<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

use Faker\Generator;
use Rhumsaa\Uuid\Uuid;

class SecretTest extends TestCase
{

    use DatabaseTransactions;

    /**
     * Test secret creation.
     *
     * @return void
     */
    public function testCreateSecret()
    {
        $this->visit('/create')
             ->type('a secret', 'secret')
             ->press('Submit')
             ->see('/show/')
             ->seePageIs('/store');
    }

    /**
     * Test secret retrieval.
     *
     * @return void
     */
    public function testRetrieveSecret()
    {
        $faker = Faker\Factory::create();

        $secret_intermediate = $faker->word(32);
        $secret = Crypt::encrypt($secret_intermediate);
        $uuid4_intermediate = Uuid::uuid4();
        $uuid4 = Hash::make($uuid4_intermediate);

        $secret = factory(App\Secret::class)->create([
            'uuid4' => $uuid4,
            'secret' => $secret
        ]);

        $this->visit('/show/' . $uuid4_intermediate)
             ->see($secret_intermediate);
    }
}

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

use Faker\Generator;
use Rhumsaa\Uuid\Uuid;

class SecretTest extends TestCase
{

    use DatabaseTransactions;

    /**
     * Test secret creation.
     *
     * @return void
     */
    public function testCreateSecret()
    {
        $this->visit('/create')
             ->type('a secret', 'secret')
             ->press('Submit')
             ->see('/show/')
             ->seePageIs('/store');
    }

    /**
     * Test secret retrieval.
     *
     * @return void
     */
    public function testRetrieveSecret()
    {
        $faker = Faker\Factory::create();

        $secret_intermediate = $faker->word(32);
        $secret = Crypt::encrypt($secret_intermediate);
        $uuid4_intermediate = Uuid::uuid4();
        $uuid4 = Hash::make($uuid4_intermediate);

        $secret = factory(App\Secret::class)->create([
            'uuid4' => $uuid4,
            'secret' => $secret
        ]);

        $this->visit('/show/' . $uuid4_intermediate)
             ->see($secret_intermediate);
    }

    /**
     * Test views-expired secret retrieval.
     *
     * @return void
     */
    public function testRetrieveViewsExpiredSecret()
    {
        $faker = Faker\Factory::create();

        $secret_intermediate = $faker->word(32);
        $secret = Crypt::encrypt($secret_intermediate);
        $uuid4_intermediate = Uuid::uuid4();
        $uuid4 = Hash::make($uuid4_intermediate);
        $count_views = $faker->numberBetween(5,1000);

        $secret = factory(App\Secret::class)->create([
            'uuid4' => $uuid4,
            'secret' => $secret,
            'expires_views' => $count_views,
            'count_views' => $count_views
        ]);

        $this->visit('/show/' . $uuid4_intermediate)
             ->see('Secret not found.');
    }
}

Test added for retrieval under views-expired scenario.


<?php

/**
 * Bootstrap command line application
 */

date_default_timezone_set('UTC');

defined('APP_PATH') or define('APP_PATH', dirname(dirname(__DIR__)));

require APP_PATH . '/vendor/autoload.php';

use Symfony\Component\Console\Application;

$application = new Application('ID', '1.0');//TODO select version

foreach (new DirectoryIterator(APP_PATH . '/src/Commands') as $file) {
    if ($file->isFile() && $file->getExtension() == 'php') {
        $class_name = ('\\ActiveCollab\\JobQueue\\Commands\\' . $file->getBasename('.php'));

        if (!(new ReflectionClass($class_name))->isAbstract()) {

            $command = new $class_name;
            $application->add($command);
        }
    }
}
$application->run();

<?php

/**
 * Bootstrap command line application
 */

date_default_timezone_set('UTC');

defined('APP_PATH') or define('APP_PATH', dirname(dirname(__DIR__)));
define('ACTIVECOLLAB_JOBS_CONSUMER_SCRIPT_TIME', microtime(true));

require APP_PATH . '/vendor/autoload.php';

use Symfony\Component\Console\Application;

$application = new Application('ID', '1.0');//TODO select version

foreach (new DirectoryIterator(APP_PATH . '/src/Commands') as $file) {
    if ($file->isFile() && $file->getExtension() == 'php') {
        $class_name = ('\\ActiveCollab\\JobQueue\\Commands\\' . $file->getBasename('.php'));

        if (!(new ReflectionClass($class_name))->isAbstract()) {

            $command = new $class_name;
            $application->add($command);
        }
    }
}
$application->run();

Add missing global var. ACTIVECOLLAB_JOBS_CONSUMER_SCRIPT_TIME


<?
require_once(dirname(__FILE__).'/config.php');
require_once(dirname(__FILE__).'/User.php');

include(dirname(__FILE__).'/view/account/account_details.php');
# this yields Smarty onbject as $smarty
if (preg_match("/^Smarty-3/",$smarty->_version)) {
  $smarty->setTemplateDir(UserConfig::$smarty_templates.'/account');
  $smarty->setCompileDir(UserConfig::$smarty_compile);
  $smarty->setCacheDir(UserConfig::$smarty_cache);
} elseif (preg_match("/^2\./",$smarty->_version)) {
  $smarty->template_dir(UserConfig::$smarty_templates.'/account');
  $smarty->compile_dir(UserConfig::$smarty_compile);
  $smarty->cache_dir(UserConfig::$smarty_cache);
} else {
  die("Cannot handle smarty version ".$smarty->_version);
}

require_once(UserConfig::$header);

$smarty->display('account_details.tpl');

require_once(UserConfig::$footer);

<?
require_once(dirname(__FILE__).'/config.php');
require_once(dirname(__FILE__).'/User.php');

include(dirname(__FILE__).'/view/account/account_details.php');
# this yields Smarty onbject as $smarty
if (preg_match("/^Smarty-3/",$smarty->_version)) {
  $smarty->setTemplateDir(UserConfig::$smarty_templates.'/account');
  $smarty->setCompileDir(UserConfig::$smarty_compile);
  $smarty->setCacheDir(UserConfig::$smarty_cache);
} elseif (preg_match("/^2\./",$smarty->_version)) {
  $smarty->template_dir = UserConfig::$smarty_templates.'/account';
  $smarty->compile_dir = UserConfig::$smarty_compile;
  $smarty->cache_dir = UserConfig::$smarty_cache;
} else {
  die("Cannot handle smarty version ".$smarty->_version);
}

require_once(UserConfig::$header);

$smarty->display('account_details.tpl');

require_once(UserConfig::$footer);

Fix in smarty v2 support

Fix in smarty v2 support


<?php
/**
 * This code is free software; you can redistribute it and/or modify it under
 * the terms of the new BSD License.
 *
 * Copyright (c) 2009-2011, Sebastian Staudt
 *
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */

require_once STEAM_CONDENSER_PATH . 'exceptions/SteamCondenserException.php';

/**
 * This class is used to streamline access to XML-based data resources
 *
 * @author     Sebastian Staudt
 * @package    steam-condenser
 * @subpackage community
 */
abstract class XMLData {

    /**
     * Loads XML data from the given URL and returns it parsed into a
     * <var>SimpleXMLElement</var>
     *
     * @param string $url The URL to load the data from
     * @return SimpleXMLElement The parsed XML data
     * @throws SteamCondenserException if the data cannot be parsed
     */
    protected function getData($url) {
        try {
            return @new SimpleXMLElement($url, 0, true);
        } catch (Exception $e) {
            throw new SteamCondenserException("XML could not be parsed", 0, $e);
        }
    }

}

<?php
/**
 * This code is free software; you can redistribute it and/or modify it under
 * the terms of the new BSD License.
 *
 * Copyright (c) 2009-2013, Sebastian Staudt
 *
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */

require_once STEAM_CONDENSER_PATH . 'exceptions/SteamCondenserException.php';

/**
 * This class is used to streamline access to XML-based data resources
 *
 * @author     Sebastian Staudt
 * @package    steam-condenser
 * @subpackage community
 */
abstract class XMLData {

    /**
     * Loads XML data from the given URL and returns it parsed into a
     * <var>SimpleXMLElement</var>
     *
     * @param string $url The URL to load the data from
     * @return SimpleXMLElement The parsed XML data
     * @throws SteamCondenserException if the data cannot be parsed
     */
    protected function getData($url) {
        try {
            return @new SimpleXMLElement($url, 0, true);
        } catch (Exception $e) {
            $errorMessage = "XML could not be parsed: " . $e->getMessage();
            if ((float) phpversion() < 5.3) {
                throw new SteamCondenserException($errorMessage, 0);
            } else {
                throw new SteamCondenserException($errorMessage, 0, $e);
            }
        }
    }

}

Improve error handling while parsing XML data

Fixes koraktor/steam-condenser#224


<?php

namespace Integrated\Bundle\ContentBundle\Form\Registry;

use Integrated\Common\ContentType\Form\Custom\Type;
use Integrated\Common\ContentType\Form\Custom\Type\Registry;

/**
 * Simple factory for Registry
 *
 * @author Jeroen van Leeuwen <jeroen@e-active.nl>
 */
class RegistryFactory
{
    /**
     * @return Registry
     */
    public static function create()
    {
        $registry = new Registry();

        // Todo this must be configurable
        $text  = new Type();
        $text
            ->setType('text')
            ->setName('Text')
        ;

        $textarea = new Type();
        $textarea
            ->setType('textarea')
            ->setName('Textarea')
        ;

        $registry
            ->add($text)
            ->add($textarea)
        ;

        return $registry;
    }
}

<?php

namespace Integrated\Bundle\ContentBundle\Form\Registry;

use Integrated\Common\ContentType\Form\Custom\Type;
use Integrated\Common\ContentType\Form\Custom\Type\Registry;

use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

/**
 * Simple factory for Registry
 *
 * @author Jeroen van Leeuwen <jeroen@e-active.nl>
 */
class RegistryFactory
{
    /**
     * @return Registry
     */
    public static function create()
    {
        $registry = new Registry();

        // Todo this must be configurable
        $text  = new Type();
        $text
            ->setType(TextType::class)
            ->setName('Text')
        ;

        $textarea = new Type();
        $textarea
            ->setType(TextareaType::class)
            ->setName('Textarea')
        ;

        $registry
            ->add($text)
            ->add($textarea)
        ;

        return $registry;
    }
}

Use the full class name in the registry

Use the full class name in the registry


<?php
include ('header.php');

echo "
Messaging Statistics

";

if ($a != 2){
  echo "No data available";

}
echo "
";

$output = shell_exec('cat /var/log/ecelerity/mainlog.ec |grep "@D@" |grep wc -l');
if ($output < 1){$output = 0;}
echo "Deliveries today: $output
";

$output = shell_exec('bzcat /var/log/ecelerity/mainlog.ec.1.bz2 |grep "@D@" |grep wc -l');
if ($output < 1){$output = 0;}
echo "Deliveries yesterday: $output
";

include ('footer.php');
?>

<?php
include ('header.php');

echo "
Messaging Statistics
";

$output1 = shell_exec('cat /var/log/ecelerity/mainlog.ec |grep "@R@" |grep wc -l');
$output2 = shell_exec('cat /var/log/ecelerity/mainlog.ec |grep "@D@" |grep wc -l');
$output3 = shell_exec('cat /var/log/ecelerity/mainlog.ec |grep "@P@" |grep wc -l');
if ($output1 < 1){$output1 = 0;}
if ($output2 < 1){$output2 = 0;}
if ($output3 < 1){$output3 = 0;}
echo "

 	Deliveries	Receptions	Bounces
";
echo "
Today: 	$output1	$output2	$output3
";

$output1 = shell_exec('bzcat /var/log/ecelerity/mainlog.ec.1.bz2 |grep "@R@" |grep wc -l');
$output2 = shell_exec('bzcat /var/log/ecelerity/mainlog.ec.1.bz2 |grep "@D@" |grep wc -l');
$output3 = shell_exec('bzcat /var/log/ecelerity/mainlog.ec.1.bz2 |grep "@P@" |grep wc -l');
if ($output1 < 1){$output1 = 0;}
if ($output2 < 1){$output2 = 0;}
if ($output3 < 1){$output3 = 0;}
echo "
Yesterday: 	$output1	$output2	$output3
";
echo "
";

include ('footer.php');
?>

Rebuild to show a table

Rebuild to show a table


@extends('layout.emails')

@section('preheader')
{!! trans('cachet.subscriber.email.maintenance.html-preheader', ['app_name' => Setting::get('app_name')]) !!}
@stop

@section('content')
    {!! trans('cachet.subscriber.email.maintenance.html', ['app_name' => Setting::get('app_name')]) !!}

        {!! $status !!}

        {!! $htmlContent !!}

    @if(Setting::get('show_support'))

{!! trans('cachet.powered_by', ['app' => Setting::get('app_name')]) !!}

    @endif

        {!! trans('cachet.subscriber.email.unsubscribe') !!}

@stop

@extends('layout.emails')

@section('preheader')
{!! trans('cachet.subscriber.email.maintenance.html-preheader', ['app_name' => Setting::get('app_name')]) !!}
@stop

@section('content')

            {!! trans('cachet.subscriber.email.maintenance.html', ['app_name' => Setting::get('app_name')]) !!}

        {!! $status !!}

        {!! $htmlContent !!}

        {!! trans('cachet.subscriber.email.unsubscribe') !!}

@stop

Apply style changes to maintenance emails


<?php

require '../autoloader.php';

$redis = new Yampee_Redis_Client();

$redis->set('key', 'value');

if ($redis->has('key')) {
	$redis->get('key');
}

<?php

require '../autoloader.php';

$redis = new Yampee_Redis_Client();

// Getters/Setters
$redis->set('key', 'value');

if ($redis->has('key')) {
	$redis->get('key');
}

$redis->remove('key');

// You can authenticate on the server:
$redis->authenticate('password');

// You can remove an expiration on a value
$redis->persist('key');

// You can find keys that match a given pattern
$redis->findKeys('pattern');

// You can flush the database (delete all keys)
$redis->flush();

// You can get server stats
$redis->getStats();

// You can configure the server
$redis->getParameter('parameterName');
$redis->setParameter('parameterName', 'parameterValue');

// You can get the database size
$redis->getSize();

// And for each more specific command, you can use send()
$redis->send($command, $arguments);

Update demo to add all possibilities.

Update demo to add all possibilities.


<?php

namespace App;

use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class BelongsToManyOrOne extends BelongsToMany
{
    /**
     * Whether this relation should return a collection.
     *
     * @var boolean
     */
    protected $isMany = true;

    /**
     * Get the results of the relationship.
     *
     * @return mixed
     */
    public function getResults()
    {
        $results = $this->get();

        return $this->isMany ? $results : $results->first();
    }

    /**
     * Declare that a single result should be returned.
     *
     * @return $this
     */
    public function expectOne()
    {
        $this->isMany = false;

        return $this;
    }

    /**
     * Declare that a collection of results should be returned.
     *
     * @return $this
     */
    public function expectMany()
    {
        $this->isMany = true;

        return $this;
    }

    /**
     * Convenience method for only getting the preferred item.
     *
     * @return $this
     */
    public function isPreferred()
    {

        return $this->wherePivot('preferred', '=', true)->expectOne();

    }

    /**
     * Convenience method for only getting the alternative items.
     *
     * @return $this
     */
    public function isAlternative()
    {

        return $this->wherePivot('preferred', '=', false)->expectMany();

    }

}

<?php

namespace App;

use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class BelongsToManyOrOne extends BelongsToMany
{
    /**
     * Whether this relation should return a collection.
     *
     * @var boolean
     */
    protected $isMany = true;

    /**
     * Get the results of the relationship.
     *
     * @return mixed
     */
    public function getResults()
    {
        $results = $this->get();

        return $this->isMany ? $results : $results->first();
    }

    /**
     * Declare that a single result should be returned.
     *
     * @return $this
     */
    public function expectOne()
    {
        $this->isMany = false;

        return $this;
    }

    /**
     * Declare that a collection of results should be returned.
     *
     * @return $this
     */
    public function expectMany()
    {
        $this->isMany = true;

        return $this;
    }

    /**
     * Convenience method for only getting the preferred item.
     *
     * @return $this
     */
    public function isPreferred()
    {

        return $this->wherePivot('preferred', '=', true)->expectOne();

    }

    /**
     * Convenience method for only getting the alternative items.
     *
     * @return $this
     */
    public function isAlternative()
    {

        return $this->wherePivotIn('preferred', [false, null], 'or')->expectMany();

    }

}

Fix blank alt fields by accepting preferred null

Definitely feeling the slowdown on `/artworks`. Might need to change
API to be a facade on Elasticsearch for speed, if we can figure out
`include` functionality on search.


<?php

function amp_get_permalink( $post_id ) {
	if ( '' != get_option( 'permalink_structure' ) ) {
		$amp_url = trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( AMP_QUERY_VAR, 'single_amp' );
	} else {
		$amp_url = add_query_arg( AMP_QUERY_VAR, absint( $post_id ), home_url() );
	}

	return apply_filters( 'amp_get_permalink', $amp_url, $post_id );
}

function post_supports_amp( $post ) {
	// Because `add_rewrite_endpoint` doesn't let us target specific post_types :(
	if ( ! post_type_supports( $post->post_type, AMP_QUERY_VAR ) ) {
		return false;
	}

	if ( true === apply_filters( 'amp_skip_post', false, $post->ID ) ) {
		return false;
	}

	return true;
}

/**
 * Are we currently on an AMP URL?
 *
 * Note: will always return `false` if called before the `parse_query` hook.
 */
function is_amp_endpoint() {
	return false !== get_query_var( AMP_QUERY_VAR, false );
}

function amp_get_asset_url( $file ) {
	return plugins_url( sprintf( 'assets/%s', $file ), AMP__FILE__ );
}

<?php

function amp_get_permalink( $post_id ) {
	if ( '' != get_option( 'permalink_structure' ) ) {
		$amp_url = trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( AMP_QUERY_VAR, 'single_amp' );
	} else {
		$amp_url = add_query_arg( AMP_QUERY_VAR, absint( $post_id ), home_url() );
	}

	return apply_filters( 'amp_get_permalink', $amp_url, $post_id );
}

function post_supports_amp( $post ) {
	// Because `add_rewrite_endpoint` doesn't let us target specific post_types :(
	if ( ! post_type_supports( $post->post_type, AMP_QUERY_VAR ) ) {
		return false;
	}

	if ( true === apply_filters( 'amp_skip_post', false, $post->ID, $post ) ) {
		return false;
	}

	return true;
}

/**
 * Are we currently on an AMP URL?
 *
 * Note: will always return `false` if called before the `parse_query` hook.
 */
function is_amp_endpoint() {
	return false !== get_query_var( AMP_QUERY_VAR, false );
}

function amp_get_asset_url( $file ) {
	return plugins_url( sprintf( 'assets/%s', $file ), AMP__FILE__ );
}

Add full post to amp_skip_post filter

Add full post to amp_skip_post filter


<?php

namespace Meng\Soap\HttpBinding;

use Meng\Soap\Interpreter;
use Psr\Http\Message\RequestInterface;
use Zend\Diactoros\Stream;

class HttpBinding
{
    private $interpreter;
    private $builder;

    public function __construct(Interpreter $interpreter, RequestBuilder $builder)
    {
        $this->interpreter = $interpreter;
        $this->builder = $builder;
    }

    /**
     * @return RequestInterface
     */
    public function toHttpRequest($name, array $arguments, array $options = null, $inputHeaders = null)
    {
        $soapRequest = $this->interpreter->request($name, $arguments, $options, $inputHeaders);
        if ($soapRequest->getSoapVersion() == '1') {
            $this->builder->isSOAP11();
        } else {
            $this->builder->isSOAP12();
        }
        $this->builder->setEndpoint($soapRequest->getEndpoint());
        $this->builder->setSoapAction($soapRequest->getSoapAction());
        $stream = fopen('php://temp', 'r');
        fwrite($stream, $soapRequest->getSoapMessage());
        fseek($stream, 0);
        $this->builder->setSoapMessage(new Stream($stream));
        return $this->builder->getSoapHttpRequest();
    }

    /**
     * @return mixed
     */
    public function fromHttpResponse($response, $name, &$output_headers = null)
    {
        return $this->interpreter->response($response, $name, $output_headers);
    }
}

<?php

namespace Meng\Soap\HttpBinding;

use Meng\Soap\Interpreter;
use Psr\Http\Message\RequestInterface;
use Zend\Diactoros\Stream;

class HttpBinding
{
    private $interpreter;
    private $builder;

    public function __construct(Interpreter $interpreter, RequestBuilder $builder)
    {
        $this->interpreter = $interpreter;
        $this->builder = $builder;
    }

    /**
     * @return RequestInterface
     */
    public function toHttpRequest($name, array $arguments, array $options = null, $inputHeaders = null)
    {
        $soapRequest = $this->interpreter->request($name, $arguments, $options, $inputHeaders);
        if ($soapRequest->getSoapVersion() == '1') {
            $this->builder->isSOAP11();
        } else {
            $this->builder->isSOAP12();
        }
        $this->builder->setEndpoint($soapRequest->getEndpoint());
        $this->builder->setSoapAction($soapRequest->getSoapAction());
        $stream = fopen('php://temp', 'r+');
        fwrite($stream, $soapRequest->getSoapMessage());
        fseek($stream, 0);
        $this->builder->setSoapMessage(new Stream($stream));
        return $this->builder->getSoapHttpRequest();
    }

    /**
     * @return mixed
     */
    public function fromHttpResponse($response, $name, &$output_headers = null)
    {
        return $this->interpreter->response($response, $name, $output_headers);
    }
}

Make sure request body stream is writable.


<?php

namespace Pterodactyl\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies;

    /**
     * The current proxy header mappings.
     *
     * @var array
     */
    protected $headers = [
        Request::HEADER_FORWARDED => 'FORWARDED',
        Request::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
        Request::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
        Request::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
        Request::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
    ];
}

<?php

namespace Pterodactyl\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies;

    /**
     * The current proxy header mappings.
     *
     * @var array
     */
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
}

Make sure this trust proxies is also changed


<?php

namespace UserControlSkeleton\Models\Database;

use PDO;
use UserControlSkeleton\Interfaces\AdapterInterface;

class MysqlAdapter implements AdapterInterface
{
    protected $user;

    protected $pass;

    protected $host;

    protected $port;

    protected $name;

    protected $driver;

    public function __construct()
    {
        $this->user = getenv('DATABASE_USER');
        $this->pass = getenv('DATABASE_PASS');
        $this->host = getenv('DATABASE_HOST');
        $this->port = getenv('DATABASE_PORT');
        $this->name = getenv('DATABASE_NAME');
        $this->driver = getenv('DATABASE_DRIVER');
    }

    public function connect()
    {
        try {
            $link = new PDO($this->driver.':host='.$this->host.';port='.$this->port.';dbname='.$this->name.';charset=UTF8;', $this->user, $this->pass);

            return $link;
        } catch (\PDOException $e) {
            echo $e->getMessage();
            die();
        }
    }

    public function getColumns()
    {
        $statement = $this->connect();
        $statement = $statement->prepare('SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = "user_control_skeleton" AND TABLE_NAME = "users"');

        $statement->execute();
        $statement->fetch(PDO::FETCH_ASSOC);

        return $statement;
    }
}

<?php

namespace UserControlSkeleton\Models\Database;

use PDO;
use UserControlSkeleton\Interfaces\AdapterInterface;

class MysqlAdapter implements AdapterInterface
{
    protected $user;

    protected $pass;

    protected $host;

    protected $port;

    protected $name;

    protected $driver;

    public function __construct()
    {
        $this->user = getenv('DATABASE_USER');
        $this->pass = getenv('DATABASE_PASS');
        $this->host = getenv('DATABASE_HOST');
        $this->port = getenv('DATABASE_PORT');
        $this->name = getenv('DATABASE_NAME');
        $this->driver = getenv('DATABASE_DRIVER');
    }

    public function connect()
    {
        try {
            $link = new PDO($this->driver.':host='.$this->host.';port='.$this->port.';dbname='.$this->name.';charset=UTF8;', $this->user, $this->pass);

            return $link;
        } catch (\PDOException $e) {
            echo $e->getMessage();
            die();
        }
    }

    public function getColumns()
    {
        $databaseName = getenv('DATABASE_NAME');

        $statement = $this->connect();
        $statement = $statement->prepare('
            SELECT COLUMN_NAME
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA = "$databaseName"
            AND TABLE_NAME = "users"
        ');

        $statement->execute();
        $statement->fetch(PDO::FETCH_ASSOC);

        return $statement;
    }
}

Add dynamic database name to getColumns()


<?php

class UrlGenerator {
    public static function generate_thumb_url($filename, $type = '', $size = '_thumb') {
        if (empty($filename)) {
            return ''; // Fallback error image
        }

        if (ENVIRONMENT === 'production') {
            $host = 'http://img.pickartyou.com/';
        } else {
            $host = '/uploads/';
        }

        if (!empty($type)) {
            $host .= $type . '/';
        }

        $path_parts = pathinfo($filename);

        if (!isset($path_parts['extension'])) {
            return ''; // Fallback error image
        }

        return $host . $path_parts['filename'] . $size . '.' . $path_parts['extension'];
    }

    public static function generate_original_image_url($filename, $type = '') {
        if (empty($filename)) {
            return ''; // Fallback error image
        }

        if (ENVIRONMENT === 'production') {
            $host = 'http://img.pickartyou.com/';
        } else {
            $host = '/uploads/';
        }

        if (!empty($type)) {
            $host .= $type . '/';
        }

        return $host . $filename;
    }

    public static function generate_static_url($filename) {
        $full_file_path = __DIR__ . '/../../static/' . $filename;
        if (file_exists($full_file_path)) {
            $filename .= '?' . filemtime($full_file_path);
        }

        if (ENVIRONMENT === 'production') {
            $host = 'http://static.pickartyou.com/';
        } else {
            $host = '../../static/';
        }

        return $host . $filename;
    }
}

<?php

class UrlGenerator {
    public static function generate_thumb_url($filename, $type = '', $size = '_thumb') {
        if (empty($filename)) {
            return ''; // Fallback error image
        }

        if (ENVIRONMENT === 'production') {
            $host = '//img.pickartyou.com/';
        } else {
            $host = '/uploads/';
        }

        if (!empty($type)) {
            $host .= $type . '/';
        }

        $path_parts = pathinfo($filename);

        if (!isset($path_parts['extension'])) {
            return ''; // Fallback error image
        }

        return $host . $path_parts['filename'] . $size . '.' . $path_parts['extension'];
    }

    public static function generate_original_image_url($filename, $type = '') {
        if (empty($filename)) {
            return ''; // Fallback error image
        }

        if (ENVIRONMENT === 'production') {
            $host = '//img.pickartyou.com/';
        } else {
            $host = '/uploads/';
        }

        if (!empty($type)) {
            $host .= $type . '/';
        }

        return $host . $filename;
    }

    public static function generate_static_url($filename) {
        $full_file_path = __DIR__ . '/../../static/' . $filename;
        if (file_exists($full_file_path)) {
            $filename .= '?' . filemtime($full_file_path);
        }

        if (ENVIRONMENT === 'production') {
            $host = '//static.pickartyou.com/';
        } else {
            $host = '../../static/';
        }

        return $host . $filename;
    }
}

Make a urlgenerator creates links protocol insensitive


<?php

/*
 * This file is part of PHP-FFmpeg.
 *
 * (c) Alchemy <info@alchemy.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FFMpeg\Format\Video;

/**
 * The X264 video format
 */
class X264 extends DefaultVideo
{
    public function __construct($audioCodec = 'libfaac', $videoCodec = 'libx264')
    {
        $this
            ->setAudioCodec($audioCodec)
            ->setVideoCodec($videoCodec);
    }

    /**
     * {@inheritDoc}
     */
    public function supportBFrames()
    {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    public function getAvailableAudioCodecs()
    {
        return array('libvo_aacenc', 'libfaac', 'libmp3lame');
    }

    /**
     * {@inheritDoc}
     */
    public function getAvailableVideoCodecs()
    {
        return array('libx264');
    }

    /**
     * {@inheritDoc}
     */
    public function getPasses()
    {
        return 2;
    }

    public function getModulus()
    {
        return 2;
    }
}

<?php

/*
 * This file is part of PHP-FFmpeg.
 *
 * (c) Alchemy <info@alchemy.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FFMpeg\Format\Video;

/**
 * The X264 video format
 */
class X264 extends DefaultVideo
{
    /** @var boolean */
    private $bframesSupport;

    public function __construct($audioCodec = 'libfaac', $videoCodec = 'libx264')
    {
        $this
            ->setAudioCodec($audioCodec)
            ->setVideoCodec($videoCodec);
        $this->bframesSupport = true;
    }

    /**
     * {@inheritDoc}
     */
    public function supportBFrames()
    {
        return $this->bframesSupport;
    }

    /**
     * @param $support
     * @return X264
     */
    public function setBFramesSupport($support)
    {
        $this->bframesSupport = $support;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function getAvailableAudioCodecs()
    {
        return array('libvo_aacenc', 'libfaac', 'libmp3lame');
    }

    /**
     * {@inheritDoc}
     */
    public function getAvailableVideoCodecs()
    {
        return array('libx264');
    }

    /**
     * {@inheritDoc}
     */
    public function getPasses()
    {
        return 2;
    }

    public function getModulus()
    {
        return 2;
    }
}

Allow to set bframe support in a format

Allow to set bframe support in a format


<?php

class ColourTest extends PHPUnit_Framework_TestCase
{
  public function testFromHex()
  {
    $colour = \Colourist\Colour::fromHex('#0A141E');
    /** @var \Colourist\Rgb $colour */
    $this->assertSame(10, $colour->red());
    $this->assertSame(20, $colour->green());
    $this->assertSame(30, $colour->blue());
  }

  /**
   * @expectedException Respect\Validation\Exceptions\AllOfException
   */
  public function testFromHexBadCode()
  {
    \Colourist\Colour::fromHex('oops, this is bad');
  }
}

<?php

class ColourTest extends PHPUnit_Framework_TestCase
{
  public function testFromHex()
  {
    $colour = \Colourist\Colour::fromHex('#0A141E');
    /** @var \Colourist\Rgb $colour */
    $this->assertSame(10, $colour->red());
    $this->assertSame(20, $colour->green());
    $this->assertSame(30, $colour->blue());
  }

  /**
   * @expectedException Respect\Validation\Exceptions\AllOfException
   */
  public function testFromHexNoHash()
  {
    \Colourist\Colour::fromHex('0A141E');
  }

  /**
   * @expectedException Respect\Validation\Exceptions\AllOfException
   */
  public function testFromHexBadCode()
  {
    \Colourist\Colour::fromHex('oops, this is bad');
  }
}

Add extra test for no hash in fromHex

Add extra test for no hash in fromHex


<?php

define('PHPUNIT_RUN', 1);

require_once __DIR__.'/../../../lib/base.php';
require_once __DIR__.'/../vendor/autoload.php';

if(!class_exists('PHPUnit_Framework_TestCase')) {
	require_once('PHPUnit/Autoload.php');
}

OC_Hook::clear();

<?php

define('PHPUNIT_RUN', 1);

require_once __DIR__.'/../../../lib/base.php';
require_once __DIR__.'/../vendor/autoload.php';
\OC::$loader->addValidRoot(OC::$SERVERROOT . '/tests');

if(!class_exists('PHPUnit_Framework_TestCase')) {
	require_once('PHPUnit/Autoload.php');
}

OC_Hook::clear();

Add tests to the list of allowed paths

Add tests to the list of allowed paths


<?php
    class BotController extends AuthenticatedController {
        public function update( $boturl = '' ) {
            $this->requireLogin();

            require_once 'models/grader/bot.php';

            if ( empty( $boturl ) ) {
                go( 'bot', 'update', [ 'boturl_empty' => true ] );
            }
            if ( !filter_var( $boturl, FILTER_VALIDATE_URL ) ) {
                go( 'bot', 'update', [ 'boturl_invalid' => true ] );
            }
            $user = $_SESSION[ 'user' ];
            try {
                $user->setBoturl( $boturl );
            }
            catch ( ModelValidationException $e ) {
                go( 'bot', 'update', [ 'bot_fail' => true, 'errorid' => $e->error ] );
            }
            go( 'bot', 'update' );
        }
        public function updateView( $boturl_empty, $boturl_invalid, $bot_fail, $errorid = false ) {
            require_once 'models/error.php';

            $this->requireLogin();
            if ( $errorid !== false ) {
                $error = new Error( $errorid );
                if ( $error->user->id !== $_SESSION[ 'user' ]->id ) {
                    throw new HTTPUnauthorizedException();
                }
            }
            $user = $_SESSION[ 'user' ];

            require_once 'models/grader/bot.php';
            require_once 'views/bot/update.php';
        }
    }
?>

<?php
    class BotController extends AuthenticatedController {
        public function update( $boturl = '' ) {
            $this->requireLogin();

            require_once 'models/grader/bot.php';

            if ( empty( $boturl ) ) {
                go( 'bot', 'update', [ 'boturl_empty' => true ] );
            }
            if ( !filter_var( $boturl, FILTER_VALIDATE_URL ) ) {
                go( 'bot', 'update', [ 'boturl_invalid' => true ] );
            }
            $user = $_SESSION[ 'user' ];
            try {
                $user->setBoturl( $boturl );
            }
            catch ( ModelValidationException $e ) {
                go( 'bot', 'update', [ 'bot_fail' => true, 'errorid' => $e->error ] );
            }
            go( 'bot', 'update' );
        }
        public function updateView( $boturl_empty, $boturl_invalid, $bot_fail, $errorid = false ) {
            require_once 'models/error.php';

            $this->requireLogin();
            $user = $_SESSION[ 'user' ];
            if ( $errorid !== false ) {
                $error = new Error( $errorid );
                if ( $error->user->id !== $user->id ) {
                    throw new HTTPUnauthorizedException();
                }
            }

            require_once 'models/grader/bot.php';
            require_once 'views/bot/update.php';
        }
    }
?>

Define user earlier so it can be used more


<?php
	#
	# $Id: ports-deleted.php,v 1.2 2006-12-17 12:06:14 dan Exp $
	#
	# Copyright (c) 1998-2005 DVL Software Limited
	#

	require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/common.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/freshports.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/databaselogin.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/getvalues.php');

	require_once($_SERVER['DOCUMENT_ROOT'] . '/../include/freshports_page_list_ports.php');

	$page = new freshports_page_list_ports();

	$page->setDB($db);

	$page->setTitle('Deleted ports');
	$page->setDescription('These are the deleted ports');
	$page->setStatus('D');

	$page->setSQL('', $User->id);

	$page->display();
?>

Remove trailing ?> while investigating another page which is missing last_commit_id


View Protein

                Name
                <?php echo $prot['NAME'] ?>

                Acronym
                <?php echo $prot['ACRONYM'] ?>

                Sequence
                <?php echo $prot['SEQUENCE'] ?>

                Moecular Mass
                <?php echo $prot['MOLECULARMASS'] ?>

                    Id
                    Name
                    Protein
                    Spacegroup
                    Comment
                    Shipment
                    Dewar
                    Container
                    Snapshot
                    Data Collections

View Protein

                Name
                <?php echo $prot['NAME'] ?>

                Acronym
                <?php echo $prot['ACRONYM'] ?>

<?php echo $prot['SEQUENCE'] ?>

                Sequence

                Moecular Mass
                <?php echo $prot['MOLECULARMASS'] ?>

                    Id
                    Name
                    Protein
                    Spacegroup
                    Comment
                    Shipment
                    Dewar
                    Container
                    Snapshot
                    Data Collections

Make sequence wrap + clear li

Make sequence wrap + clear li


<?php

namespace Test\Unit;

use Test\TestCase;
use Taskforcedev\CrudApi\Helpers\CrudApi;

class CrudApiHelperTest extends TestCase
{
    public function testGetRelatedFieldForUserId()
    {
        $crudApi = new CrudApi(['namespace' => null]);
        $related_field = $crudApi->getRelatedField('user_id');
        $this->assertEquals('user', $related_field);
    }

    public function testGetRelatedFieldForOrganisationId()
    {
        $crudApi = new CrudApi(['namespace' => null]);
        $related_field = $crudApi->getRelatedField('organisation_id');
        $this->assertEquals('organisation', $related_field);
    }

    public function testGetModelDisplayNameWithoutAnInstance()
    {
        $options = [
            'namespace' => null,
            'model' => 'User'
        ];
        $crudApi = new CrudApi($options);
        $display = $crudApi->getModelDisplayName();
        $this->assertEquals('User', $display);
    }
}

<?php

namespace Test\Unit;

use Test\TestCase;
use Taskforcedev\CrudApi\Helpers\CrudApi;

class CrudApiHelperTest extends TestCase
{
    public function testGetRelatedFieldForUserId()
    {
        $crudApi = new CrudApi(['namespace' => null]);
        $related_field = $crudApi->getRelatedField('user_id');
        $this->assertEquals('user', $related_field);
    }

    public function testGetRelatedFieldForOrganisationId()
    {
        $crudApi = new CrudApi(['namespace' => null]);
        $related_field = $crudApi->getRelatedField('organisation_id');
        $this->assertEquals('organisation', $related_field);
    }

    public function testGetModelDisplayNameWithoutAnInstance()
    {
        $options = [
            'namespace' => null,
            'model' => 'User'
        ];
        $crudApi = new CrudApi($options);
        $display = $crudApi->getModelDisplayName();
        $this->assertEquals('User', $display);
    }

    public function testAuthorUserModelBinding()
    {
        $crudApi = new CrudApi(['namespace' => 'Test\\Models\\', 'model' => 'Post']);
        $related_field = $crudApi->getRelatedField('author_id');
        $this->assertEquals('author', $related_field);
        $relation = $crudApi->getRelatedModel($related_field);
        $class = get_class($relation);
        $this->assertEquals('Test\\Models\\User', $class);
    }
}

Test model aliasing for author => user.

Test model aliasing for author => user.


<?php

# Copyright 2015 Wayne D Grant (www.waynedgrant.com)
# Licensed under the MIT License

abstract class BaseSource
{
	const SERVICE_VERSION = 1.4;

    protected $clientRaw;

    public function __construct($clientRaw)
    {
        $this->clientRaw = $clientRaw;
    }

    protected function createBase()
    {
        return array(
            "endpoint" => $this->createEndpoint(),
            "station" => $this->createStation($clientRaw),
            "time" => $this->clientRaw->getCurrentDateAndTime()->getAllValues());
    }

    private function createEndpoint()
    {
        return array(
            "url" => $this->createServiceUrl(),
            "version" => self::SERVICE_VERSION);
    }

    private function createStation()
    {
        return array(
            "name" => $this->clientRaw->getStationName(),
            "latitude" => $this->clientRaw->getLatitude(),
            "longitude" => $this->clientRaw->getLongitude(),
            "wd_version" => $this->clientRaw->getWdVersion());
    }

    private function createServiceUrl()
    {
        return "http".(!empty($_SERVER['HTTPS'])?"s":"")."://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    }
}

?>

<?php

# Copyright 2015 Wayne D Grant (www.waynedgrant.com)
# Licensed under the MIT License

abstract class BaseSource
{
	const SERVICE_VERSION = 1.4;
    const API_DOCUMENTATION_LINK = "http://www.waynedgrant.com/weather/api.html";
    const GITHUB_PROJECT_LINK = "https://github.com/waynedgrant/json-webservice-wdlive";
    const COPYRIGHT_NOTICE = "Copyright © 2015 Wayne D Grant (www.waynedgrant.com)";

    protected $clientRaw;

    public function __construct($clientRaw)
    {
        $this->clientRaw = $clientRaw;
    }

    protected function createBase()
    {
        return array(
            "endpoint" => $this->createEndpoint(),
            "station" => $this->createStation($clientRaw),
            "time" => $this->clientRaw->getCurrentDateAndTime()->getAllValues());
    }

    private function createEndpoint()
    {
        return array(
            "url" => $this->createServiceUrl(),
            "version" => self::SERVICE_VERSION,
            "api_docs" => self::API_DOCUMENTATION_LINK,
            "github_project" => self::GITHUB_PROJECT_LINK,
            "copyright" => self::COPYRIGHT_NOTICE);
    }

    private function createStation()
    {
        return array(
            "name" => $this->clientRaw->getStationName(),
            "latitude" => $this->clientRaw->getLatitude(),
            "longitude" => $this->clientRaw->getLongitude(),
            "wd_version" => $this->clientRaw->getWdVersion());
    }

    private function createServiceUrl()
    {
        return "http".(!empty($_SERVER['HTTPS'])?"s":"")."://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    }
}

?>

Add api docs and github project links to endpoint. Also add copyright


<?php

namespace Helldar\Vk\Commands;

use Carbon\Carbon;
use Helldar\Vk\Models\VkRequest;
use Illuminate\Console\Command;

class VkRequestsClear extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'vk:queue-clear';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Clear old data';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        VkRequest::onlyTrashed()->where('deleted_at', '<', Carbon::now()->addHours(2))->delete();
    }
}

<?php

namespace Helldar\Vk\Commands;

use Carbon\Carbon;
use Helldar\Vk\Models\VkRequest;
use Illuminate\Console\Command;

class VkRequestsClear extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'vk:queue-clear';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Clear old data';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        VkRequest::onlyTrashed()->where('deleted_at', '<', Carbon::now()->addHours(-2))->delete();
    }
}

Fix deleting old request to VK.

Fix deleting old request to VK.


<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Flarum\Auth\GitHub\Listener;

use Flarum\Event\ConfigureWebApp;
use Illuminate\Contracts\Events\Dispatcher;

class AddClientAssets
{
    /**
     * @param Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen(ConfigureWebApp::class, [$this, 'addAssets']);
    }

    /**
     * @param ConfigureClientView $event
     */
    public function addAssets(ConfigureWebApp $event)
    {
        if ($event->isForum()) {
            $event->addAssets([
                __DIR__.'/../../js/forum/dist/extension.js',
                __DIR__.'/../../less/forum/extension.less'
            ]);
            $event->addBootstrapper('flarum/auth/github/main');
        }

        if ($event->isAdmin()) {
            $event->addAssets([
                __DIR__.'/../../js/admin/dist/extension.js'
            ]);
            $event->addBootstrapper('flarum/auth/github/main');
        }
    }
}

<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Flarum\Auth\GitHub\Listener;

use Flarum\Frontend\Event\Rendering;
use Illuminate\Contracts\Events\Dispatcher;

class AddClientAssets
{
    /**
     * @param Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen(Rendering::class, [$this, 'addAssets']);
    }

    /**
     * @param Rendering $event
     */
    public function addAssets(Rendering $event)
    {
        if ($event->isForum()) {
            $event->addAssets([
                __DIR__.'/../../js/forum/dist/extension.js',
                __DIR__.'/../../less/forum/extension.less'
            ]);
            $event->addBootstrapper('flarum/auth/github/main');
        }

        if ($event->isAdmin()) {
            $event->addAssets([
                __DIR__.'/../../js/admin/dist/extension.js'
            ]);
            $event->addBootstrapper('flarum/auth/github/main');
        }
    }
}

Update namespaces for beta 8

Update namespaces for beta 8

Refs flarum/core#1235.


<?php

namespace ATPCms\View\Filter;

class Images extends \ATPCore\View\Filter\AbstractBlockFilter
{
	protected function _loadObject($id)
	{
		$image = new \ATPCms\Model\Image();
		$image->loadByIdentifier($id);
		return $image;
	}

	protected function _replace($image)
	{
		//Get the base path helper
		$sm = $this->getServiceManager();
		$vm = $sm->get('ViewManager');
		$hm = $vm->getHelperManager();
		$basePath = $hm->get("basepath");

		$path = $basePath($image->filePath('imageFile'));
		$alt = $image->alt;

		return "<img src=\"{$path}\" alt=\"{$alt}\" />";
	}
}

<?php

namespace ATPCms\View\Filter;

class Images extends \ATPCore\View\Filter\AbstractBlockFilter
{
	protected function _loadObject($id)
	{
		$image = new \ATPCms\Model\Image();
		$image->loadByIdentifier($id);
		if(!$image->id)
		{
			$image->loadById($id);
		}
		return $image;
	}

	protected function _replace($image)
	{
		//Get the base path helper
		$sm = $this->getServiceManager();
		$vm = $sm->get('ViewManager');
		$hm = $vm->getHelperManager();
		$basePath = $hm->get("basepath");

		$path = $basePath($image->filePath('imageFile'));
		$alt = $image->alt;

		return "<img src=\"{$path}\" alt=\"{$alt}\" />";
	}
}

Allow image filter to load by id as well as identifier


<?php
/**
 * Created by PhpStorm.
 * User: mirel
 * Date: 19.03.2015
 * Time: 11:06
 */

namespace mpf\modules\forum\controllers;

use mpf\modules\forum\components\Controller;
use mpf\modules\forum\models\ForumThread;
use mpf\modules\forum\models\ForumUser2Section;
use mpf\WebApp;

class User extends Controller{

    public function actionIndex($id, $currentPage = 1){
        $this->assign('user', ForumUser2Section::findByAttributes(['user_id' => $id, 'section_id' => $this->sectionId]));
        $this->assign("threads", ForumThread::findAllByUser($id, $this->sectionId, $currentPage));
    }

    public function actionControlPanel(){
        $user  = ForumUser2Section::findByAttributes(['user_id' => WebApp::get()->user()->id, 'section_id' => $this->sectionId]);
        $user->icon = $user->user->icon;
        if (isset($_POST['ForumUser2Section'])){
            $user->signature = $_POST['ForumUser2Section']['signature'];
            $user->save();
            $user->changeIcon();
            $user->icon = $user->user->icon;
            WebApp::get()->user()->setState('icon', $user->user->icon);
        }
        $this->assign('model', $user);
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: mirel
 * Date: 19.03.2015
 * Time: 11:06
 */

namespace mpf\modules\forum\controllers;

use mpf\modules\forum\components\Controller;
use mpf\modules\forum\models\ForumThread;
use mpf\modules\forum\models\ForumUser2Section;
use mpf\WebApp;

class User extends Controller{

    public function actionLogin(){
        WebApp::get()->request()->goToURL(WebApp::get()->request()->createURL("home", "index", [], ""));
    }

    public function actionIndex($id, $currentPage = 1){
        $this->assign('user', ForumUser2Section::findByAttributes(['user_id' => $id, 'section_id' => $this->sectionId]));
        $this->assign("threads", ForumThread::findAllByUser($id, $this->sectionId, $currentPage));
    }

    public function actionControlPanel(){
        $user  = ForumUser2Section::findByAttributes(['user_id' => WebApp::get()->user()->id, 'section_id' => $this->sectionId]);
        $user->icon = $user->user->icon;
        if (isset($_POST['ForumUser2Section'])){
            $user->signature = $_POST['ForumUser2Section']['signature'];
            $user->save();
            $user->changeIcon();
            $user->icon = $user->user->icon;
            WebApp::get()->user()->setState('icon', $user->user->icon);
        }
        $this->assign('model', $user);
    }
}

Fix redirect to login when required

Fix redirect to login when required


<?php

error_reporting(E_ALL | E_STRICT);

// include the composer autoloader
$autoloader = require __DIR__.'/../vendor/autoload.php';

// autoload abstract TestCase classes in test directory
$autoloader->add('Omnipay', __DIR__);

<?php

error_reporting(E_ALL | E_STRICT);
date_default_timezone_set('UTC');

// include the composer autoloader
$autoloader = require __DIR__.'/../vendor/autoload.php';

// autoload abstract TestCase classes in test directory
$autoloader->add('Omnipay', __DIR__);

Set default timezone to UTC in tests

Set default timezone to UTC in tests


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @since         3.0.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace TestApp\Model\Table;

use Cake\ORM\Table;

/**
 * Tag table class
 */
class TagsTable extends Table
{

    public function initialize(array $config)
    {
        $this->belongsTo('authors');
        $this->belongsToMany('articles');
        $this->hasMany('ArticlesTags', ['propertyName' => 'extraInfo']);
    }
}

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @since         3.0.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace TestApp\Model\Table;

use Cake\ORM\Table;

/**
 * Tag table class
 */
class TagsTable extends Table
{

    public function initialize(array $config)
    {
        $this->belongsTo('Authors');
        $this->belongsToMany('Articles');
        $this->hasMany('ArticlesTags', ['propertyName' => 'extraInfo']);
    }
}

Fix non-conventional aliases that cause problems sometimes.


<?php

system('sudo /etc/init.d/protherm change_mode', $ret);

<?php

if (file_exists('/etc/init.d/protherm')) {
    // Use sysvinit start/stop script to send SIGUSR1 signal.
    system('sudo /etc/init.d/protherm change_mode', $ret);
} else {
    // Uses systemd to send SIGUSR1 signal.
    system('sudo /usr/local/sbin/protherm-sigusr1', $ret);
}

Send signal to ProTherm process via sysvinit/PID or via systemd service


<?php

namespace Github\Api\Organization;

use Github\Api\AbstractApi;

/**
 * @link   http://developer.github.com/v3/orgs/members/
 * @author Joseph Bielawski <stloyd@gmail.com>
 */
class Members extends AbstractApi
{
    public function all($organization, $type = null)
    {
        if (null === $type) {
            return $this->get('orgs/'.rawurlencode($organization).'/members');
        }

        return $this->get('orgs/'.rawurlencode($organization).'/public_members');
    }

    public function show($organization, $username)
    {
        return $this->get('orgs/'.rawurlencode($organization).'/members/'.rawurlencode($username));
    }

    public function check($organization, $username)
    {
        return $this->get('orgs/'.rawurlencode($organization).'/public_members/'.rawurlencode($username));
    }

    public function publicize($organization, $username)
    {
        return $this->put('orgs/'.rawurlencode($organization).'/public_members/'.rawurlencode($username));
    }

    public function conceal($organization, $username)
    {
        return $this->delete('orgs/'.rawurlencode($organization).'/public_members/'.rawurlencode($username));
    }

    public function remove($organization, $username)
    {
        return $this->delete('orgs/'.rawurlencode($organization).'/members/'.rawurlencode($username));
    }
}

<?php

namespace Github\Api\Organization;

use Github\Api\AbstractApi;

/**
 * @link   http://developer.github.com/v3/orgs/members/
 * @author Joseph Bielawski <stloyd@gmail.com>
 */
class Members extends AbstractApi
{
    public function all($organization, $type = null, $filter = 'all')
    {
        $parameters = array();
        $path = 'orgs/'.rawurlencode($organization).'/';
        if (null === $type) {
           $path .= 'members';
           if (null !== $filter) {
               $parameters['filter'] = $filter;
           }
        } else {
            $path .= 'public_members';
        }

        return $this->get($path, $parameters);
    }

    public function show($organization, $username)
    {
        return $this->get('orgs/'.rawurlencode($organization).'/members/'.rawurlencode($username));
    }

    public function check($organization, $username)
    {
        return $this->get('orgs/'.rawurlencode($organization).'/public_members/'.rawurlencode($username));
    }

    public function publicize($organization, $username)
    {
        return $this->put('orgs/'.rawurlencode($organization).'/public_members/'.rawurlencode($username));
    }

    public function conceal($organization, $username)
    {
        return $this->delete('orgs/'.rawurlencode($organization).'/public_members/'.rawurlencode($username));
    }

    public function remove($organization, $username)
    {
        return $this->delete('orgs/'.rawurlencode($organization).'/members/'.rawurlencode($username));
    }
}

Add support for filtering organisation members by 2FA status


<?php

namespace AppBundle\Entity;

/**
 * RecipeRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class RecipeRepository extends \Doctrine\ORM\EntityRepository
{
    public function searchRecipes($categoryId, $tags)
    {
        $queryBuilder = $this->createQueryBuilder('r');
        $queryBuilder->leftJoin('r.category', 'category');
        $queryBuilder->where('category.id = :categoryId');
        $queryBuilder->setParameter(':categoryId', $categoryId);

        $queryBuilder->leftJoin('r.tags', 't');
        $queryBuilder->andWhere('t.id IN(:tags)');
        $queryBuilder->setParameter('tags', array_values($tags->toArray()));

        return $queryBuilder->getQuery()->getResult();
    }
}

<?php

namespace AppBundle\Entity;

/**
 * RecipeRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class RecipeRepository extends \Doctrine\ORM\EntityRepository
{
    public function searchRecipes($categoryId, $tags)
    {
        $queryBuilder = $this->createQueryBuilder('r');
        $queryBuilder->leftJoin('r.category', 'category');
        $queryBuilder->where('category.id = :categoryId');
        $queryBuilder->setParameter(':categoryId', $categoryId);

        $queryBuilder->leftJoin('r.tags', 't');
        $queryBuilder->andWhere('t.id IN(:tags)');
        $queryBuilder->setParameter('tags', array_values($tags->toArray()));

        $queryBuilder->having('COUNT(t) >= :nbTags');
        $queryBuilder->setParameter('nbTags', count($tags));

        return $queryBuilder->getQuery()->getResult();
    }
}

Fix query to have all tags taken into account on recipe search


<?php
class GoogleReaderKeys extends Plugin {

	private $link;
	private $host;

	function about() {
		return array(1.0,
			"Keyboard hotkeys emulate Google Reader",
			"markwaters");
	}

	function init($host) {
		$this->link = $host->get_link();
		$this->host = $host;

		$host->add_hook($host::HOOK_HOTKEY_MAP, $this);
	}

	function hook_hotkey_map($hotkeys) {

		$hotkeys["j"]		= "next_article_noscroll";
		$hotkeys["k"]		= "prev_article_noscroll";
		$hotkeys["*n"]		= "next_feed";
		$hotkeys["*p"]		= "prev_feed";
		$hotkeys["v"]		= "open_in_new_window";
		$hotkeys["r"]		= "feed_refresh";
		$hotkeys["(32)|space"]	= "next_article";
		$hotkeys["(38)|up"]	= "article_scroll_up";
		$hotkeys["(40)|down"]	= "article_scroll_down";

		return $hotkeys;

	}
}
?>

<?php
class GoogleReaderKeys extends Plugin {

	private $link;
	private $host;

	function about() {
		return array(1.0,
			"Keyboard hotkeys emulate Google Reader",
			"markwaters");
	}

	function init($host) {
		$this->link = $host->get_link();
		$this->host = $host;

		$host->add_hook($host::HOOK_HOTKEY_MAP, $this);
	}

	function hook_hotkey_map($hotkeys) {

		$hotkeys["j"]		= "next_article_noscroll";
		$hotkeys["k"]		= "prev_article_noscroll";
		$hotkeys["*n"]		= "next_feed";
		$hotkeys["*p"]		= "prev_feed";
		$hotkeys["v"]		= "open_in_new_window";
		$hotkeys["r"]		= "feed_refresh";
		$hotkeys["m"]		= "toggle_unread";
		$hotkeys["(32)|space"]	= "next_article";
		$hotkeys["(38)|up"]	= "article_scroll_up";
		$hotkeys["(40)|down"]	= "article_scroll_down";

		return $hotkeys;

	}
}
?>

Modify googlereaderkeys plugin with mark unread toggle.


<?php

use yii\helpers\Html;
use yii\widgets\ListView;

/* @var $this yii\web\View */

?>

Links Index

<?= ListView::widget([
    'dataProvider' => $data,
    'itemView' => '_linkItem',
    'options' => ['class' => 'striped'],
]); ?>

<?= Html::a('Add New', ['new'], ['class' => 'btn btn-default btn-success']); ?>

<?php

use yii\helpers\Html;
use yii\widgets\ListView;

/* @var $this yii\web\View */

?>

Links Index

<?= ListView::widget([
    'dataProvider' => $data,
    'itemView' => '_linkItem',
    'options' => ['class' => 'striped'],
]); ?>

<?php if (!Yii::$app->user->isGuest) : ?>
<?= Html::a('Add New', ['new'], ['class' => 'btn btn-default btn-success']); ?>
<?php endif; ?>

Hide "Add Link" button if user isn't logged in


<?php

require __DIR__.'/../vendor/autoload.php';
Guzzle\Tests\GuzzleTestCase::setMockBasePath(__DIR__.'/mock');

<?php

require __DIR__.'/../vendor/autoload.php';
error_reporting(-1);
Guzzle\Tests\GuzzleTestCase::setMockBasePath(__DIR__.'/mock');
Guzzle\Common\Version::$emitWarnings = true;

Enable deprecation warnings in Guzzle 3.7


<?php

$loader = require __DIR__.'/../vendor/.composer/autoload.php';
$loader->add('Igorw\Tests', __DIR__);
$loader->register();

<?php

$loader = require __DIR__.'/../vendor/autoload.php';
$loader->add('Igorw\Tests', __DIR__);
$loader->register();

Use new composer autoload filename

Use new composer autoload filename


@extends('app')

@section('content')

All Groups

                        New
                        @if (count($groups))

                                    Id
                                    Name
                                    Owners

                            @foreach ($groups as $group)

                                    {{ $group->id }}
                                    {{ $group->name }}
                                    {{ $group->owners }}

                            @endforeach

                        @else

No groups to display.

                        @endif

@endsection

@extends('app')

@section('content')

All Groups

                        New
                        @if (count($groups))

                                    Id
                                    Name
                                    Owners
                                    Channels

                            @foreach ($groups as $group)

                                    {{ $group->id }}
                                    {{ $group->name }}
                                    {{ $group->owners }}

                                        @foreach ($group->channels as $channel)

{{ $channel->name }}

                                        @endforeach

                            @endforeach

                        @else

No groups to display.

                        @endif

@endsection

Add list of channels to group index

Add list of channels to group index


<?php
    $options      = get_option('plugin_options');
    $social_media = array('facebook', 'twitter', 'google', 'mail', 'linkedin', 'xing', 'skype', 'youtube', 'vimeo', 'flickr', 'rss');
?>

        <?php foreach ($social_media as $i => $name) {
                  if (!empty( $options['vobe_' . $name . '_link'] )) {
                      echo '

';
                  }
              }
        ?>

    <?php if ( function_exists(qtrans_generateLanguageSelectCode) ) echo qtrans_generateLanguageSelectCode(); ?>

Fix social media icon links.

Fix social media icon links.


<?php
namespace App\Controller;

use App\Lib\CakeboxInfo;
use Cake\Controller\Controller;
use Cake\Datasource\ConnectionManager;

/**
 * Application Controller
 *
 * Application-wide methods inherited by all controllers.
 */
class AppController extends Controller
{

    /**
     * @var Our Controllers do not use tables
     */
    public $uses = false;

    /**
     * @var Helpers made available to all Views
     */
    public $helpers = ['Cakebox'];

    /**
     * CakeboxInfo instance available to all Controllers
     *
     * @var \App\Lib\CakeboxInfo
     */
    public $cbi;

    /**
     * Initialization hook method.
     *
     * @return void
     */
    public function initialize()
    {
        $this->loadComponent('Flash');
        $this->loadComponent('RequestHandler');
        $this->cbi = new CakeboxInfo;
    }
}

<?php
namespace App\Controller;

use App\Lib\CakeboxInfo;
use Cake\Controller\Controller;
use Cake\Datasource\ConnectionManager;
use Cake\Event\Event;
use Cake\Network\Exception\NotFoundException;

/**
 * Application Controller
 *
 * Application-wide methods inherited by all controllers.
 */
class AppController extends Controller
{

    /**
     * @var Our Controllers do not use tables
     */
    public $uses = false;

    /**
     * @var Helpers available to all views
     */
    public $helpers = ['Cakebox'];

    /**
     * CakeboxInfo instance available to all Controllers
     *
     * @var \App\Lib\CakeboxInfo
     */
    public $cbi;

    /**
     * Initialization hook method.
     *
     * @return void
     */
    public function initialize()
    {
        $this->loadComponent('Flash');
        $this->loadComponent('RequestHandler');
        $this->loadComponent('Security');
        $this->loadComponent('Csrf');
        $this->cbi = new CakeboxInfo;
    }

    /**
     * BeforeFilter
     *
     * @param \Cake\Event\Event $event
     */
    public function beforeFilter(Event $event)
    {
        // Throw 404's for non-ajax connections to ajax_ prefixed actions
        if (substr($this->request->action, 0, 5) == 'ajax_') {
            if (!$this->request->is('ajax')) {
                throw new NotFoundException;
            }
        }
    }

}

Add Security/Csrf components + protects ajax_ prefixed actions


<?php

namespace React\Tests\Dns;

use React\Tests\Dns\TestCase;
use React\EventLoop\Factory as LoopFactory;
use React\Dns\Resolver\Resolver;
use React\Dns\Resolver\Factory;

class FunctionalTest extends TestCase
{
    public function setUp()
    {
        $this->loop = LoopFactory::create();

        $factory = new Factory();
        $this->resolver = $factory->create('8.8.8.8', $this->loop);
    }

    public function testResolveGoogleResolves()
    {
        $promise = $this->resolver->resolve('google.com');
        $promise->then($this->expectCallableOnce(), $this->expectCallableNever());

        $this->loop->run();
    }

    public function testResolveInvalidRejects()
    {
        $promise = $this->resolver->resolve('example.invalid');
        $promise->then($this->expectCallableNever(), $this->expectCallableOnce());

        $this->loop->run();
    }
}

<?php

namespace React\Tests\Dns;

use React\Tests\Dns\TestCase;
use React\EventLoop\Factory as LoopFactory;
use React\Dns\Resolver\Resolver;
use React\Dns\Resolver\Factory;

class FunctionalTest extends TestCase
{
    public function setUp()
    {
        $this->loop = LoopFactory::create();

        $factory = new Factory();
        $this->resolver = $factory->create('8.8.8.8', $this->loop);
    }

    public function testResolveGoogleResolves()
    {
        $promise = $this->resolver->resolve('google.com');
        $promise->then($this->expectCallableOnce(), $this->expectCallableNever());

        $this->loop->run();
    }

    public function testResolveInvalidRejects()
    {
        $promise = $this->resolver->resolve('example.invalid');
        $promise->then($this->expectCallableNever(), $this->expectCallableOnce());

        $this->loop->run();
    }

    public function testResolveCancelledRejectsImmediately()
    {
        if (!interface_exists('React\Promise\CancellablePromiseInterface')) {
            $this->markTestSkipped();
        }

        $promise = $this->resolver->resolve('google.com');
        $promise->then($this->expectCallableNever(), $this->expectCallableOnce());
        $promise->cancel();

        $time = microtime(true);
        $this->loop->run();
        $time = microtime(true) - $time;

        $this->assertLessThan(0.1, $time);
    }
}

Add functional test for cancelling queries


<?php

namespace Enzyme\Axiom\Exceptions;

use Exception;

/**
 * Thrown when an atom cannot process the given value.
 */
class AtomException extends Exception
{
    public function __construct($atom_type, $value)
    {
        parent::__construct(
            "The atom {$atom_type} does not support the value {$value}"
        );
    }
}

<?php

namespace Enzyme\Axiom\Exceptions;

use Exception;

/**
 * Thrown when an atom cannot process the given value.
 */
class AtomException extends Exception
{
    public function __construct($atom_type, $value)
    {
        parent::__construct(
            "The atom '{$atom_type}' does not support the value '{$value}'."
        );
    }
}

Update the exception message on atom exceptions.


<?php

namespace Cvogit\LumenJWT\Http\Middleware;

use Closure;
use \InvalidArgumentException;
use \RuntimeException;
use Illuminate\Http\Request;
use Cvogit\LumenJWT\JWT;
use Cvogit\LumenJWT\Parser;

class JwtGuard
{
	/**
	 * The parsed jwt
	 *
	 */
	protected $jwt;

	/**
	 * The parser
	 *
	 */
	protected $parser;

	/**
	 * Create a new middleware instance.
	 *
	 * @param
	 * @return void
	 */
	public function __construct(JWT $jwt, Parser $parser)
	{
		$this->jwt = $jwt;
		$this->parser = $parser;
	}

	/**
	 * Run the request filter.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 *
	 * @return mixed
	 */
	public function handle(Request $request, Closure $next)
	{

		try {
			$token = $this->parser->parse($request);
		}	catch (RuntimeException $e) {
			abort(404, $e->getMessage());
    }

		try {
			$payload = $this->jwt->decode($token);
		} catch(InvalidArgumentException $e){
			abort(404, $e->getMessage());
    }

		if($payload["exp"] >= $payload["iat"])
			return $next($request);

		abort(404, "Token expired, please log in again.");
	}

}

<?php

namespace Cvogit\LumenJWT\Http\Middleware;

use Closure;
use \InvalidArgumentException;
use \RuntimeException;
use Illuminate\Http\Request;
use Cvogit\LumenJWT\JWT;
use Cvogit\LumenJWT\Parser;

class JwtGuard
{
	/**
	 * The parsed jwt
	 *
	 * @var  \Cvogit\LumenJWT\JWT  $jwt
	 */
	protected $jwt;

	/**
	 * The parser
	 *
	 * @var  \Cvogit\LumenJWT\Parser  $parser
	 */
	protected $parser;

	/**
	 * Create a new middleware instance.
	 *
	 * @param
	 * @return void
	 */
	public function __construct(JWT $jwt, Parser $parser)
	{
		$this->jwt = $jwt;
		$this->parser = $parser;
	}

	/**
	 * Run the request filter.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 *
	 * @return mixed
	 */
	public function handle(Request $request, Closure $next)
	{

		try {
			$token = $this->parser->parse($request);
		}	catch (RuntimeException $e) {
			return response()->json(['message' => $e->getMessage()], 404);
    }

		try {
			$payload = $this->jwt->decode($token);
		} catch (Exception $e) {
    	return response()->json(['message' => $e->getMessage()], 404);
    }

		return $next($request);
	}

}

Fix to return json response to invalid tokens. Fix to exception throws not being catch correctly.


<?php

Event::add_before('system.ready', current(Event::get('system.ready')), 'multisite_fetch_appname');

function multisite_fetch_appname()
{
    (PHP_SAPI == 'cli') AND $_SERVER['SERVER_NAME'] = Null;

    // Find subdomain and domain name
    preg_match('/^(?:(.*)\.)?([^.]++\.[^.]++)$/', $_SERVER['SERVER_NAME'], $appname);

    // Find appname from domain name
    $domains = Kohana::config('arag.domains');

    if (isset($domains[$appname[2]])) {
        $appname = $domains[$appname[2]];
    } else {
        $appname = ($appname[1]) ? $appname[1] : Kohana::config('arag.master_appname');
    }

    if ($appname == Kohana::config('arag.master_appname') ||
        in_array($appname, Kohana::config('arag.master_appaliases')) ||
        in_array('.*', Kohana::config('arag.master_appaliases'))) {

        define('MASTERAPP', TRUE);
        define('APPNAME', Kohana::config('arag.master_appname'));
        define('APPALIAS', $appname);

    } else {
        define('MASTERAPP', FALSE);
        define('APPNAME', $appname);
    }
}

<?php

Event::add_before('system.ready', current(Event::get('system.ready')), 'multisite_fetch_appname');

function multisite_fetch_appname()
{
    (PHP_SAPI == 'cli') AND $_SERVER['SERVER_NAME'] = Null;

    // Find subdomain and domain name
    preg_match('/^(?:(.*)\.)?([^.]++\.[^.]++)$/', $_SERVER['SERVER_NAME'], $appname);

    // Find appname from domain name
    $domains = Kohana::config('arag.domains');

    // Make sure that  $appname[1] and $appname[2] are set, in case of cli call, those are empty
    if (isset($appname[2]) && isset($domains[$appname[2]])) {
        $appname = $domains[$appname[2]];
    } else {
        $appname = (isset($appname[1]) && $appname[1]) ? $appname[1] : Kohana::config('arag.master_appname');
    }

    if ($appname == Kohana::config('arag.master_appname') ||
        in_array($appname, Kohana::config('arag.master_appaliases')) ||
        in_array('.*', Kohana::config('arag.master_appaliases'))) {

        define('MASTERAPP', TRUE);
        define('APPNAME', Kohana::config('arag.master_appname'));
        define('APPALIAS', $appname);

    } else {
        define('MASTERAPP', FALSE);
        define('APPNAME', $appname);
    }
}


<?php
/**
 * lor Standard page type view
 * @author Jon Johnson <jon.johnson@ucsf.edu>
 * @license http://jazzee.org/license.txt
 * @package jazzee
 * @subpackage lor
 */
?>

<?php print $page->getLeadingText()?>

  <?php
    $jp = $page->getApplicationPageJazzeePage();
    $jp->setController($this->controller);
    $this->renderElement('form', array('form'=> $jp->getForm()));
  ?>

<?php print $page->getTrailingText()?>

<?php
/**
 * lor Standard page type view
 * @author Jon Johnson <jon.johnson@ucsf.edu>
 * @license http://jazzee.org/license.txt
 * @package jazzee
 * @subpackage lor
 */
?>

<?php print $page->getLeadingText()?>

  <?php
    $jp = $page->getApplicationPageJazzeePage();
    $jp->setController($this->controller);
    $form = $jp->getForm();
    $element = $form->getElementByName('submit');
    $element->setValue('Submit Recommendation (Cannot be undone)');
    $this->renderElement('form', array('form'=> $form));
  ?>

<?php print $page->getTrailingText()?>

Change button text for Standard page LOR form to be clearer that recommendation is being submitted, not saved.


<?php

namespace SleepingOwl\Admin\Widgets\Messages;

use AdminTemplate;
use SleepingOwl\Admin\Widgets\Widget;

abstract class Messages extends Widget
{
    /**
     * @var string
     */
    protected static $sessionName;

    /**
     * @var string
     */
    protected $messageView;

    /**
     * Get content as a string of HTML.
     *
     * @return string
     */
    public function toHtml()
    {
        return AdminTemplate::view($this->messageView, [
            'messages' => $this->getMessage(),
        ])->render();
    }

    /**
     * @return string|array
     */
    public function template()
    {
        return AdminTemplate::getViewPath('_layout.inner');
    }

    /**
     * @return string
     */
    public function block()
    {
        return 'content.top';
    }

    /**
     * @return string
     */
    public function getMessageView()
    {
        return $this->messageView;
    }

    /**
     * @param string $messageView
     */
    public function setMessageView($messageView)
    {
        $this->messageView = $messageView;
    }

    /**
     * @return mixed
     */
    protected function getMessage()
    {
        return session(static::$sessionName);
    }

    /**
     * @param string $text
     * @return mixed
     */
    public static function addMessage($text)
    {
        session()->flash(static::$sessionName, $text);
    }
}

<?php

namespace SleepingOwl\Admin\Widgets\Messages;

use AdminTemplate;
use SleepingOwl\Admin\Widgets\Widget;

abstract class Messages extends Widget
{
    /**
     * @var string
     */
    protected static $sessionName;

    /**
     * @var string
     */
    protected $messageView;

    /**
     * Get content as a string of HTML.
     *
     * @return string
     */
    public function toHtml()
    {
        return AdminTemplate::view($this->messageView, [
            'messages' => $this->getMessage(),
        ])->render();
    }

    /**
     * @return string|array
     */
    public function template()
    {
        return AdminTemplate::getViewPath('_layout.inner');
    }

    /**
     * @return string
     */
    public function block()
    {
        return 'content.top';
    }

    /**
     * @return string
     */
    public function getMessageView()
    {
        return $this->messageView;
    }

    /**
     * @param string $messageView
     */
    public function setMessageView($messageView)
    {
        $this->messageView = $messageView;
    }

    /**
     * @return mixed
     */
    protected function getMessage()
    {
        return session(static::$sessionName);
    }

    /**
     * @param string $text
     * @return mixed
     */
    public static function addMessage($text)
    {
        return session()->flash(static::$sessionName, $text);
    }
}

Fix MessageStack for model events

Fix MessageStack for model events


<?php

namespace Core;

class Autoloader
{
    static public function load($className)
    {
        $baseDir = dirname(dirname(realpath(__FILE__)));
        $classPath = implode('/', explode('\\', $className)) . '.php';
        require_once "{$baseDir}/{$classPath}";
    }
}

spl_autoload_register(__NAMESPACE__ . '\Autoloader::load');

<?php

namespace Core;

class Autoloader
{
    static public function load($className)
    {
        $baseDir = dirname(dirname(realpath(__FILE__))) . DIRECTORY_SEPARATOR;
        if($className == 'AmazonS3') {
            require_once "$baseDir/Aws/sdk.class.php";
        }
        $classPath = implode(DIRECTORY_SEPARATOR, explode('\\', $className)) . '.php';
        if(file_exists("{$baseDir}{$classPath}")) {
            require_once "{$baseDir}{$classPath}";
        }
    }
}

spl_autoload_register(__NAMESPACE__ . '\Autoloader::load');

Fix for aws classes, fixed to S3 for now but that is fine


<?php
    $classes = 'block-' . get_row_layout();
?>
<section class="block-wrap <?=$classes?>">

        <?php cfb_template('blocks/parts/block', 'title'); ?>
        <?php cfb_template('blocks/layout', get_row_layout()); ?>

<?php

    $classes    = 'block-' . get_row_layout();

    $image = get_sub_field('background_image');

    $styles      = (get_sub_field('background_image')) ? 'background-image: url(' . $image['url'] . ');' : '';
    $styles     .= (get_sub_field('background_color')) ? 'background-color: ' . get_sub_field('background_color') . ';' : '';

?>
<section class="block-wrap <?=$classes?>" style="<?=$styles?>">

        <?php cfb_template('blocks/parts/block', 'title'); ?>
        <?php cfb_template('blocks/layout', get_row_layout()); ?>

Implement background images and colors

Implement background images and colors


<?php

namespace Tests;

use PHPUnit_Framework_TestCase;
use ReflectionClass;

class UuidResolversTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Dyrynda\Database\Support\GeneratesUuid
     */
    protected $generator;

    public function setUp()
    {
        $this->generator = $this->getMockForTrait('Dyrynda\Database\Support\GeneratesUuid');
    }

    /** @test */
    public function it_handles_uuid_version_1()
    {
        $this->generator->uuidVersion = 'uuid1';

        $this->assertSame('uuid1', $this->generator->resolveUuidVersion());
    }

    /** @test */
    public function it_handles_uuid_version_3()
    {
        $this->generator->uuidVersion = 'uuid3';

        $this->assertSame('uuid3', $this->generator->resolveUuidVersion());
    }

    /** @test */
    public function it_handles_uuid_version_4()
    {
        $this->generator->uuidVersion = 'uuid4';

        $this->assertSame('uuid4', $this->generator->resolveUuidVersion());
    }

    /** @test */
    public function it_handles_uuid_version_5()
    {
        $this->generator->uuidVersion = 'uuid5';

        $this->assertSame('uuid5', $this->generator->resolveUuidVersion());
    }

    /** @test */
    public function it_defaults_to_uuid_version_4()
    {
        $this->generator->uuidVersion = 'uuid999';

        $this->assertSame('uuid4', $this->generator->resolveUuidVersion());
    }
}

<?php

namespace Tests;

use Dyrynda\Database\Support\GeneratesUuid;
use PHPUnit_Framework_TestCase;

class UuidResolversTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Dyrynda\Database\Support\GeneratesUuid
     */
    protected $generator;

    public function setUp()
    {
        $this->generator = $this->getMockForTrait(GeneratesUuid::class);
    }

    /**
     * @see \Tests\UuidResolversTest::it_handles_uuid_versions
     * @return array
     */
    public function provider_for_it_handles_uuid_versions()
    {
        return [
            ['uuid1', 'uuid1'],
            ['uuid3', 'uuid3'],
            ['uuid4', 'uuid4'],
            ['uuid5', 'uuid5'],
            ['uuid999', 'uuid4'],
        ];
    }

    /**
     * @test
     * @param string $version
     * @param string $resolved
     *
     * @dataProvider \Tests\UuidResolversTest::provider_for_it_handles_uuid_versions
     */
    public function it_handles_uuid_versions($version, $resolved)
    {
        $this->generator->uuidVersion = $version;

        $this->assertSame($resolved, $this->generator->resolveUuidVersion());
    }
}

Use a data-provider for tests.

Use a data-provider for tests.


<?php declare(strict_types=1);

namespace Siler\Test\Unit\Config;

use PHPUnit\Framework\TestCase;
use Siler\Container;
use function Siler\Config\{all, has, load, config};
use const Siler\Config\CONFIG;

final class ConfigTest extends TestCase
{
    private $config;

    public function setUp(): void
    {
        $this->config = load(__DIR__ . '/../../fixtures/config');
    }

    public function testLoad(): void
    {
        self::assertSame($this->config, Container\get(CONFIG));
    }

    public function testConfig(): void
    {
        self::assertSame('value', config('test.config'));
        self::assertSame('another_value', config('test.another_config'));
    }

    public function testConfigDefault(): void
    {
        self::assertNull(config('invalid_key'));
        self::assertSame(123, config('invalid.key', 123));
    }

    public function testHas(): void
    {
        self::assertTrue(has('test.config'));
        self::assertFalse(has('invalid.key'));
    }

    public function testAll(): void
    {
        self::assertSame([
            'test' => [
                'another_config' => 'another_value',
                'config' => 'value',
            ]
        ], all());
    }
}

<?php declare(strict_types=1);

namespace Siler\Test\Unit\Config;

use PHPUnit\Framework\TestCase;
use Siler\Container;
use function Siler\Config\{all, has, load, config};
use const Siler\Config\CONFIG;

final class ConfigTest extends TestCase
{
    private $config;

    public function setUp(): void
    {
        $this->config = load(__DIR__ . '/../../fixtures/config');
    }

    public function testLoad(): void
    {
        self::assertSame($this->config, Container\get(CONFIG));
    }

    public function testConfig(): void
    {
        self::assertSame('value', config('test.config'));
        self::assertSame('another_value', config('test.another_config'));
    }

    public function testConfigDefault(): void
    {
        self::assertNull(config('invalid_key'));
        self::assertSame(123, config('invalid.key', 123));
    }

    public function testHas(): void
    {
        self::assertTrue(has('test.config'));
        self::assertFalse(has('invalid.key'));
    }

    public function testAll(): void
    {
        self::assertSame([
            'test' => [
                'another_config' => 'another_value',
                'config' => 'value',
            ]
        ], all());
    }

    public function testNoConfig(): void
    {
        Container\set(CONFIG, null);
        self::assertNull(config('test.config'));
        self::assertFalse(has('test.config'));
        self::assertNull(all());
    }
}

Test when there is no config

Test when there is no config


<?php

/*
 * This file is part of the HWIOAuthBundle package.
 *
 * (c) Hardware.Info <opensource@hardware.info>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

if (file_exists($file = __DIR__.'/../vendor/.composer/autoload.php')) {
    $autoload = require_once $file;
} else {
    throw new RuntimeException('Install dependencies to run test suite.');
}

spl_autoload_register(function($class) {
    if (0 === strpos($class, 'HWI\\Bundle\\OAuthBundle')) {
        $path = __DIR__.'/../'.implode('/', array_slice(explode('\\', $class), 3)).'.php';
        if (!stream_resolve_include_path($path)) {
            return false;
        }
        require_once $path;
        return true;
    }
});

<?php

/*
 * This file is part of the HWIOAuthBundle package.
 *
 * (c) Hardware.Info <opensource@hardware.info>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

if (file_exists($file = __DIR__.'/../vendor/autoload.php')) {
    $autoload = require_once $file;
} else {
    throw new RuntimeException('Install dependencies to run test suite.');
}

spl_autoload_register(function($class) {
    if (0 === strpos($class, 'HWI\\Bundle\\OAuthBundle')) {
        $path = __DIR__.'/../'.implode('/', array_slice(explode('\\', $class), 3)).'.php';
        if (!stream_resolve_include_path($path)) {
            return false;
        }
        require_once $path;
        return true;
    }
});

Fix composer setup for tests

Fix composer setup for tests


<?php

namespace Egulias\EmailValidator\Tests\EmailValidator\Validation;

use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Validation\SpoofCheckValidation;
use PHPUnit\Framework\TestCase;

class SpoofCheckValidationTest extends TestCase
{
    /**
     * @dataProvider validUTF8EmailsProvider
     */
    public function testUTF8EmailAreValid($email)
    {
        $this->markTestSkipped("Skipped for Travis CI since it is failing on this test for unknown reasons.");
        $validation = new SpoofCheckValidation();

        $this->assertTrue($validation->isValid($email, new EmailLexer()));
    }

    public function testEmailWithSpoofsIsInvalid()
    {
        $validation = new SpoofCheckValidation();

        $this->assertFalse($validation->isValid("Кириллица"."latin漢字"."ひらがな"."カタカナ", new EmailLexer()));
    }

    public function validUTF8EmailsProvider()
    {
        return [
            // Cyrillic
            ['Кириллица@Кириллица'],
            // Latin + Han + Hiragana + Katakana
            ["latin漢字"."ひらがな"."カタカナ"."@example.com"],
            // Latin + Han + Hangul
            ["latin"."漢字"."조선말"."@example.com"],
            // Latin + Han + Bopomofo
            ["latin"."漢字"."ㄅㄆㄇㄈ"."@example.com"]
        ];
    }
}

<?php

namespace Egulias\EmailValidator\Tests\EmailValidator\Validation;

use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Validation\SpoofCheckValidation;
use PHPUnit\Framework\TestCase;

class SpoofCheckValidationTest extends TestCase
{
    /**
     * @dataProvider validUTF8EmailsProvider
     */
    public function testUTF8EmailAreValid($email)
    {
        $validation = new SpoofCheckValidation();

        $this->assertTrue($validation->isValid($email, new EmailLexer()));
    }

    public function testEmailWithSpoofsIsInvalid()
    {
        $validation = new SpoofCheckValidation();

        $this->assertFalse($validation->isValid("Кириллица"."latin漢字"."ひらがな"."カタカナ", new EmailLexer()));
    }

    public function validUTF8EmailsProvider()
    {
        return [
            // Cyrillic
            ['Кириллица@Кириллица'],
            // Latin + Han + Hiragana + Katakana
            ["latin漢字"."ひらがな"."カタカナ"."@example.com"],
            // Latin + Han + Hangul
            ["latin"."漢字"."조선말"."@example.com"],
            // Latin + Han + Bopomofo
            ["latin"."漢字"."ㄅㄆㄇㄈ"."@example.com"]
        ];
    }
}

Test spoof emails in travis

Test spoof emails in travis


<?php
namespace Concrete\Controller;

class Feed extends \Concrete\Core\Controller\Controller
{
    public function get($identifier)
    {
        $feed = \Concrete\Core\Page\Feed::getByHandle($identifier);
        if (is_object($feed)) {
            //header('Content-Type: text/xml');
            $xml = $feed->getOutput($this->request);
            print $xml;
        }
        exit;
    }
}

<?php
namespace Concrete\Controller;

class Feed extends \Concrete\Core\Controller\Controller
{
    public function get($identifier=null, $defaultValue=null)
    {
        $feed = \Concrete\Core\Page\Feed::getByHandle($identifier);
        if (is_object($feed)) {
            //header('Content-Type: text/xml');
            $xml = $feed->getOutput($this->request);
            print $xml;
        }
        exit;
    }
}

Add default parameter values to method

Add default parameter values to   method

The \Concrete\Core\Controller\Controller::get method has a signature of get($identifier=null, $defaultValue=null). This signature was causing issues on PHP7.

Former-commit-id: 8174213182434f56dbd84b0180c69612422c6ade
Former-commit-id: 50dcf18f29b4ad587af4128c8966913f498966db


<?php
/**
 * Definition of class Language
 *
 * @copyright  2014-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 * @package    justso\service
 */

namespace justso\justtexts\service;

use justso\justapi\Bootstrap;
use justso\justapi\RestService;

/**
 * Class Language
 * @package justso\service
 */
class Language extends RestService
{
    public function getAction()
    {
        $config = Bootstrap::getInstance()->getConfiguration();
        $this->environment->sendJSONResult($config['languages']);
    }
}

<?php
/**
 * Definition of class Language
 *
 * @copyright  2014-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 * @package    justso\service
 */

namespace justso\justtexts\service;

use justso\justapi\RestService;

/**
 * Class Language
 * @package justso\service
 */
class Language extends RestService
{
    public function getAction()
    {
        $config = $this->environment->getBootstrap()->getConfiguration();
        $this->environment->sendJSONResult($config['languages']);
    }
}

Use bootstrap from environment instead of static instance


<?php

if (file_exists(APP . 'Config' . DS . 'croogo.php')) {
	require APP . 'Config' . DS . 'croogo.php';
} else {
	if (!defined('LOG_ERROR')) {
		define('LOG_ERROR', LOG_ERR);
	}

	Configure::write('Error', array(
		'handler' => 'ErrorHandler::handleError',
		'level' => E_ALL & ~E_DEPRECATED,
		'trace' => true
	));

	Configure::write('Exception', array(
		'handler' => 'ErrorHandler::handleException',
		'renderer' => 'ExceptionRenderer',
		'log' => true
	));
}

<?php

if (file_exists(APP . 'Config' . DS . 'croogo.php')) {
	require APP . 'Config' . DS . 'croogo.php';
} else {
	if (!defined('LOG_ERROR')) {
		define('LOG_ERROR', LOG_ERR);
	}

	Configure::write('Error', array(
		'handler' => 'ErrorHandler::handleError',
		'level' => E_ALL & ~E_DEPRECATED,
		'trace' => true
	));

	Configure::write('Exception', array(
		'handler' => 'ErrorHandler::handleException',
		'renderer' => 'ExceptionRenderer',
		'log' => true
	));

	Configure::write('Session', array(
		'defaults' => 'php',
		'ini' => array(
			'session.cookie_httponly' => 1
		)
	));
}

Fix missing default session settings prior to the installation process

Closes #440


<?php namespace Nocio\FormStore;

use System\Classes\PluginBase;

class Plugin extends PluginBase
{

    /**
     * Component details
     * @return array
     */
    public function componentDetails()
    {
        return [
            'name'        => 'nocio.formstore::lang.plugin.name',
            'description' => 'nocio.formstore::lang.plugin.description',
            'icon' => 'icon-paperclip',
            'iconSvg' => 'assets\images\logo.svg'
        ];
    }

    /**
     * Registers components
     * @return array
     */
    public function registerComponents()
    {
        return [
            'Nocio\FormStore\Components\Manager' => 'formstoreManager',
            'Nocio\FormStore\Components\Countdown' => 'formstoreCountdown'
        ];
    }

    /**
     * Registers mail templates
     * @return array
     */
    public function registerMailTemplates()
    {
        return [
            'nocio.formstore::mail.login' => 'FormStore Manager login mail'
        ];
    }
}

<?php namespace Nocio\FormStore;

use System\Classes\PluginBase;

class Plugin extends PluginBase
{
    /**
     * Component details
     * @return array
     */
    public function componentDetails()
    {
        return [
            'name'        => 'nocio.formstore::lang.plugin.name',
            'description' => 'nocio.formstore::lang.plugin.description',
            'icon'        => 'icon-paperclip',
            'iconSvg'     => 'assets\images\logo.svg',
            'homepage'    => 'https://github.com/nocio/oc-formstore-plugin'
        ];
    }

    /**
     * Registers components
     * @return array
     */
    public function registerComponents()
    {
        return [
            'Nocio\FormStore\Components\Manager'   => 'formstoreManager',
            'Nocio\FormStore\Components\Countdown' => 'formstoreCountdown'
        ];
    }

    /**
     * Registers mail templates
     * @return array
     */
    public function registerMailTemplates()
    {
        return [
            'nocio.formstore::mail.login' => 'FormStore Manager login mail'
        ];
    }
}

Add homepage for plugin details

Add homepage for plugin details


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\LoginLink;

/**
 * @author Ryan Weaver <ryan@symfonycasts.com>
 */
class LoginLinkDetails
{
    private $url;
    private $expiresAt;

    public function __construct(string $url, \DateTimeImmutable $expiresAt)
    {
        $this->url = $url;
        $this->expiresAt = $expiresAt;
    }

    public function getUrl(): string
    {
        return $this->url;
    }

    public function getExpiresAt(): \DateTimeImmutable
    {
        return $this->expiresAt;
    }

    public function __toString()
    {
        return $this->url;
    }
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\LoginLink;

/**
 * @author Ryan Weaver <ryan@symfonycasts.com>
 */
class LoginLinkDetails
{
    private $url;
    private $expiresAt;

    public function __construct(string $url, \DateTimeImmutable $expiresAt)
    {
        $this->url = $url;
        $this->expiresAt = $expiresAt;
    }

    public function getUrl(): string
    {
        return $this->url;
    }

    public function getExpiresAt(): \DateTimeImmutable
    {
        return $this->expiresAt;
    }

    public function __toString(): string
    {
        return $this->url;
    }
}

Add return type to __toString()

Add return type to __toString()


<?php
/**
 * This file is part of the Clastic package.
 *
 * (c) Dries De Peuter <dries@nousefreak.be>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Clastic\BlogBundle\Form\Module;

use Clastic\NodeBundle\Form\Extension\AbstractNodeTypeExtension;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * NodeTypeExtension
 *
 * @author Dries De Peuter <dries@nousefreak.be>
 */
class BlogFormExtension extends AbstractNodeTypeExtension
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->findTab($builder, 'general')
            ->add('introduction', 'wysiwyg')
            ->add('body', 'wysiwyg');

        $builder->get('tabs')
            ->add(
                $this->createTab($builder, 'category', array('label' => 'Category'))
                    ->add('categories', 'entity_multi_select', array(
                        'class' => 'ClasticBlogBundle:Category',
                        'property' => 'node.title',
                        'required' => false,
                    ))
            );
    }
}

<?php
/**
 * This file is part of the Clastic package.
 *
 * (c) Dries De Peuter <dries@nousefreak.be>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Clastic\BlogBundle\Form\Module;

use Clastic\NodeBundle\Form\Extension\AbstractNodeTypeExtension;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * NodeTypeExtension
 *
 * @author Dries De Peuter <dries@nousefreak.be>
 */
class BlogFormExtension extends AbstractNodeTypeExtension
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->findTab($builder, 'general')
            ->add('introduction', 'wysiwyg')
            ->add('body', 'wysiwyg');

        $builder->get('tabs')
            ->add(
                $this->createTab($builder, 'category', array('label' => 'Category'))
                    ->add('categories', 'entity_multi_select', array(
                        'class' => 'ClasticBlogBundle:Category',
                        'property' => 'node.title',
                        'required' => false,
                    ))
            );

        $builder->get('tabs')->add($this
            ->createTab($builder, 'links', array(
                'label' => 'Links',
                'position' => 'first',
            ))
            ->add('links', 'collection', array(
                'type' => 'link',
                'allow_add' => true,
                'allow_delete' => true,
                'required' => false,
                'mapped' => false,
            ))
        );
    }
}

Add meta for easy development.

[Backoffice] Add meta for easy development.