<?php

namespace PHPLegends\Routes;
use PHPLegends\Routes\Exceptions\RouteException;

class Dispatcher extends AbstractDispatcher
{
	public function __construct($uri, $verbs)
	{
		$this->uri = $uri;
		$this->verbs = $verbs;
	}

	public function dispatch()
	{
		$routes = $this->getRouter()->getCollection()->filterByUri($this->uri);

		if ($routes->isEmpty())
		{
			throw new RouteException("Unable to find '{$this->uri}'");
		}

		$route = $routes->findByVerb($this->verbs);

		if ($route === null)
		{
			throw new RouteException('Unable to find');
		}

		$result = $this->getRouter()->processRouteFilters($route);

		if ($result !== null) return $result;

		return call_user_func_array(
			$route->getActionAsCallable(), $route->match($this->uri)
		);

	}
}

<?php

namespace PHPLegends\Routes;
use PHPLegends\Routes\Exceptions\NotFoundException;
use PHPLegends\Routes\Exceptions\InvalidVerbException;

class Dispatcher extends AbstractDispatcher
{
	public function __construct($uri, $verbs)
	{
		$this->uri = $uri;
		$this->verbs = $verbs;
	}

	public function dispatch()
	{
		$routes = $this->getRouter()->getCollection()->filterByUri($this->uri);

		if ($routes->isEmpty())
		{
			throw new NotFoundException("Unable to find '{$this->uri}'");
		}

		$route = $routes->findByVerb($this->verbs);

		if ($route === null)
		{
			throw new InvalidVerbException(
				sprintf('Invalid verb for route "%s"', $this->uri)
			);
		}

		$result = $this->getRouter()->processRouteFilters($route);

		if ($result !== null) return $result;

		return call_user_func_array(
			$route->getActionAsCallable(), $route->match($this->uri)
		);

	}
}

Change messages and exceptions throws in dispatch method


<?php

namespace Galahad\LaravelAddressing;

use Illuminate\Http\Request;

class Controller extends \Illuminate\Routing\Controller
{
	public function getAdministrativeAreas($countryCode, Request $request)
	{

	}
}

<?php

namespace Galahad\LaravelAddressing;

use Exception;
use Illuminate\Http\Request;

/**
 * Class Controller
 *
 * @package Galahad\LaravelAddressing
 * @author Chris Morrell
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class Controller extends \Illuminate\Routing\Controller
{
    /**
     * @var LaravelAddressing
     */
    protected $addressing;

    /**
     * The construct method
     *
     * @param LaravelAddressing $addressing
     */
    public function __construct()
    {
        $this->addressing = new LaravelAddressing();
    }

    /**
     * Get a json with all the administrative areas by a given country code
     *
     * @param string $countryCode
     * @param string $format
     * @param Request $request
     */
    public function getAdministrativeAreas($countryCode, $format = 'json', Request $request)
	{
		$this->validateAjaxRequest($request);
        $this->checkQueryParameters($request);
        $format = $this->filterFormat($format);
        $country = $this->addressing->getCountryByCode($countryCode);
        if ($country instanceof Country) {
            $admAreas = $country->getAdministrativeAreas();
            if ($format == 'json') {
                echo json_encode([
                    'label' => 'State',
                    'expected_length' => 2,
                    'country' => $countryCode,
                    'options' => $admAreas->toList(),
                    'status' => 200,
                ]);
            }
        } else {
            echo json_encode([
                'error' => true,
                'status' => 404,
                'message' => "Country not found [$countryCode]",
            ]);
        }
	}

    /**
     * Filter a response format
     *
     * @param string $format
     * @return string
     */
    protected function filterFormat($format)
	{
        $format = strtolower(trim($format, '.'));
        $allowed = ['json'];

        return in_array($format, $allowed) ? $format : 'json';
	}

    /**
     * Validate if is a AJAX request
     *
     * @param Request $request
     * @throws Exception
     */
    public function validateAjaxRequest(Request $request)
	{
        if (! $request->isXmlHttpRequest()) {
            throw new Exception('This URL only accepts AJAX requests');
        }
	}

    /**
     * Parse some query parameters from the request
     *
     * @param Request $request
     */
    protected function checkQueryParameters(Request $request)
	{
        $locale = $request->get('locale', 'en');
        $this->addressing->setLocale($locale);
	}
}

Add basic logic the package controller when getting admin areas


<?php

/**
 * @file
 * Sample script for launching Wind as a REST server.
 *
 * This script launches a sample Wind server and stores all log request
 * to a file called log.log. This script requires the Monolog library.
 *
 * (c) Wouter Admiraal <wad@wadmiraal.net>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require dirname(__FILE__) . '/../../vendor/autoload.php';

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Wind\Server\EndPoint;
use Wind\Server\Router;

try {
    $logger = new Logger('name');
    $logger->pushHandler(new StreamHandler(dirname(__FILE__) . '/log.log', Logger::DEBUG));
} catch (Exception $e) {
    die("This example script requires Monolog. Aborting.");
}

$wind = new Endpoint($logger, new Router());
$wind->run();

<?php

/**
 * @file
 * Sample script for launching Wind as a REST server.
 *
 * This script launches a sample Wind server and stores all log request
 * to a file called log.log. This script requires the Monolog library.
 *
 * (c) Wouter Admiraal <wad@wadmiraal.net>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Wind\Server\EndPoint;
use Wind\Server\Router;

try {
    $logger = new Logger('name');
    $logger->pushHandler(new StreamHandler('./log.log', Logger::DEBUG));
} catch (Exception $e) {
    die("This example script requires Monolog. Aborting.");
}

$wind = new Endpoint($logger, new Router());
$wind->run();

Update bin scripts to function when installed through composer as well.


<?php

// Database configuration.
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'host' => 'localhost',
  'username' => '',
  'password' => '',
  'database' => '',
  'prefix' => '',
);

// Salt for one-time login links, cancel links, form tokens, etc.
// You should modify this.
$settings['hash_salt'] = '4946c1912834b8477cc70af309a2c30dcfc24c2103c724ff30bf13b4c10efd82';

$config_directories = array();

// Custom configuration directories.
// Unfortunately, this appears to prevent installs of Drupal 8.0.0-beta9.
//
// $config_directories = array(
//   CONFIG_ACTIVE_DIRECTORY => '../../config/active',
//   CONFIG_STAGING_DIRECTORY => '../../config/staging',
// );

<?php

// Database configuration.
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'host' => 'localhost',
  'username' => '',
  'password' => '',
  'database' => '',
  'prefix' => '',
);

// Salt for one-time login links, cancel links, form tokens, etc.
// You should modify this.
$settings['hash_salt'] = '4946c1912834b8477cc70af309a2c30dcfc24c2103c724ff30bf13b4c10efd82';

// Configuration directories.
$config_directories = array(
  CONFIG_ACTIVE_DIRECTORY => '../shared/config/active',
  CONFIG_STAGING_DIRECTORY => '../shared/config/staging',
);

Revert "Custom $config_directories break beta9"

This reverts commit 56f8bdccb46b3b9a6ffe768235fece0341a63568.

Pending answer to core issue: https://www.drupal.org/node/2461341


<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Sauna</title>
<script src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script>
	$(document).ready(function(e) {
       $.ajax({
			url:"Sauna.php",
			dataType:"html",
			success: function(html) {
				$('body').html(html);
			}
		});
    });
</script>
</head>

<body>
</body>
</html>

<?php

header('Location: Sauna.php');
?>

Revert "Revert "Revert "Index aangepast zodat deze via ajax Sauna.php ophaalt"""

This reverts commit c5d3a9fdd2d9df477213acc0b0bbf8c88c6d50d3.


@extends('layouts/app')

@section('title')
   Teams | {{ config('app.name') }}
@endsection

@section('content')
    @component('layouts/title')
        Teams
    @endcomponent

        @foreach (\App\Team::visible()->orderBy('name', 'asc')->get() as $team)

{{ $team->name }}

{{ $team->short_description }}

                        id) }}" class="btn btn-primary">More Info

        @endforeach

@endsection

@extends('layouts/app')

@section('title')
   Teams | {{ config('app.name') }}
@endsection

@section('content')
    @component('layouts/title')
        Teams
    @endcomponent

        @foreach ($teams as $team)

{{ $team->name }}

{{ $team->short_description }}

                        name)) }}" class="btn btn-primary">More Info

        @endforeach

@endsection

Use data from controller instead of querying in the view; Lowercase team name for detail page


<?php

namespace App;

use Layer\Blog\BlogPlugin;
use Layer\Pages\PagesPlugin;

class Application extends \Layer\Application {

	public function __construct() {

		parent::__construct();

		$app = $this;

		/**
		 * Set the app name
		 */
		$app['name'] = 'Layer Skeleton App';

		/**
		 * Register plugins
		 */
		$app
			->register(new PagesPlugin())
			->register(new BlogPlugin())
		;

	}

	protected function initializeAssets() {

		parent::initializeAssets();

		$this['assets.register_scss']('app', ['scss/app.scss']);

	}

}

<?php

namespace App;

use Layer\Blog\BlogPlugin;
use Layer\Pages\PagesPlugin;

class Application extends \Layer\Application {

	protected function initialize() {

		$app = $this;

		/**
		 * Set the app name
		 */
		$app['name'] = 'Layer Skeleton App';

		/**
		 * Register plugins
		 */
		$app
			->register(new PagesPlugin())
			->register(new BlogPlugin())
		;

		$app['assets.register_scss']('app', ['scss/app.scss']);

	}

}

Use initialize method instead of constructor


<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Appointment extends Model {

	protected $fillable = ['contact_id', 'business_id', 'date', 'time', 'duration', 'comments'];

	public function contact()
	{
		return $this->belongsTo('\App\Contact');
	}

}

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

use Carbon\Carbon;

class Appointment extends Model {

	protected $fillable = ['contact_id', 'business_id', 'date', 'time', 'duration', 'comments'];

	const STATUS_RESERVED  = 'R';
	const STATUS_CONFIRMED = 'C';
	const STATUS_ANNULATED = 'A';
	const STATUS_SERVED    = 'S';

	public function contact()
	{
		return $this->belongsTo('\App\Contact');
	}

	public function getFinishTimeAttribute()
	{
		if (is_numeric($this->duration)) {
			$carbon = new Carbon("{$this->date} {$this->time}");
			return $carbon->addMinutes($this->duration);
		}
	}

	public function getStatusLabelAttribute()
	{
		switch ($this->status) {
			case Self::STATUS_RESERVED:
				$label = trans('appointments.status.reserved');
				break;
			case Self::STATUS_CONFIRMED:
				$label = trans('appointments.status.confirmed');
				break;
			case Self::STATUS_ANNULATED:
				$label = trans('appointments.status.annulated');
				break;
			case Self::STATUS_SERVED:
				$label = trans('appointments.status.annulated');
				break;
			default:
				$label = '?';
				break;
		}
		return $label;
	}

}

Add appointment finishTime and statusLabel attributes


<?php

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

// PHPUnit >= 6.0 compatibility
if (!class_exists('PHPUnit_Framework_TestSuite') && class_exists('PHPUnit\Framework\TestSuite')) {
    /** @noinspection PhpIgnoredClassAliasDeclaration */
    class_alias('PHPUnit\Framework\TestSuite', 'PHPUnit_Framework_TestSuite');
}

if (!class_exists('PHPUnit_Framework_TestCase') && class_exists('PHPUnit\Framework\TestCase')) {
    /** @noinspection PhpIgnoredClassAliasDeclaration */
    class_alias('PHPUnit\Framework\TestCase', 'PHPUnit_Framework_TestCase');
}

require_once __DIR__ . '/BaseTestCase.php';
require_once __DIR__ . '/AttrDefTestCase.php';

echo "HTMLPurifier version: ", HTMLPurifier::VERSION, "\n";
echo "libxml version:       ", constant('LIBXML_DOTTED_VERSION'), "\n";
echo "PHP memory limit:     ", ini_get('memory_limit'), "\n";
echo "\n";

if (getenv('TRAVIS_PHP_VERSION')) {
    // Fixes /home/travis/.travis/functions: line 109:  4773 Segmentation fault (core dumped)
    gc_disable();
}

Fix segmentation fault on PHP 5.6 on Travis CI

Segmentation fault started occuring after adding test case related to issue #51


<?php

namespace Redports\Master;

/**
 * Configuration class to store various static settings.
 *
 * @author     Bernhard Froehlich <decke@bluelife.at>
 * @copyright  2015 Bernhard Froehlich
 * @license    BSD License (2 Clause)
 *
 * @link       https://freebsd.github.io/redports/
 */
class Config
{
    protected static $settings = array(
      'debug'          => true,
      'datasource'     => '/var/run/redis/redis.sock',
      'logdir'         => __DIR__.'/../../../logs',
      'https_only'     => true,
      'ircbridgetoken' => '',
      'userconfig'     => array(
          'jails'   => array('10.1-RELEASE-amd64', '10.1-RELEASE-i386'),
          'notify'  => 'commit', /* commit, email, none */
      ),
   );

    public static function get($property)
    {
        if (isset(self::$settings[$property])) {
            return self::$settings[$property];
        }

        return false;
    }

    public static function getDatabaseHandle()
    {
        if (isset($GLOBALS['redis'])) {
            return $GLOBALS['redis'];
        }

        return false;
    }
}

<?php

namespace Redports\Master;

/**
 * Configuration class to store various static settings.
 *
 * @author     Bernhard Froehlich <decke@bluelife.at>
 * @copyright  2015 Bernhard Froehlich
 * @license    BSD License (2 Clause)
 *
 * @link       https://freebsd.github.io/redports/
 */
class Config
{
    protected static $settings = array(
      'debug'          => true,
      'datasource'     => '/var/run/redis/redis.sock',
      'logdir'         => __DIR__.'/../../../logs',
      'https_only'     => true,
      'ircbridgetoken' => '',
      'userconfig'     => array(
          'jails'   => array('10.1-RELEASE-amd64', '10.1-RELEASE-i386'),
          'notify'  => 'commit', /* commit, email, none */
      ),
   );

    public static function get($property)
    {
        if (isset(self::$settings[$property])) {
            return self::$settings[$property];
        }

        return false;
    }

    public static function getDatabaseHandle()
    {
        if (isset($GLOBALS['redis'])) {
            return $GLOBALS['redis'];
        }
        else {
            $GLOBALS['redis'] = new \Redis();
            $GLOBALS['redis']->pconnect(Config::get('datasource'));
            return $GLOBALS['redis'];
        }

        return false;
    }
}

Fix getDatabaseHandle() when running inside a resque job without our regular environment.


<?php

return array(
     'controllers' => array(
         'invokables' => array(
             'Album\Controller\Album' => 'Album\Controller\AlbumController',
         ),
     ),
     // The following section is new and should be added to your file
     'router' => array(
         'routes' => array(
             'album' => array(
                 'type'    => 'segment',
                 'options' => array(
                     'route'    => '/album[/][:action][/:id]',
                     'constraints' => array(
                         'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                         'id'     => '[0-9]+',
                     ),
                     'defaults' => array(
                         'controller' => 'Album\Controller\Album',
                         'action'     => 'index',
                     ),
                 ),
             ),
         ),
     ),
     'view_manager' => array(
         'template_path_stack' => array(
             'album' => __DIR__ . '/../view',
         ),
     ),
 );

<?php

namespace Album;

return array(
     'controllers' => array(
         'invokables' => array(
             'Album\Controller\Album' => 'Album\Controller\AlbumController',
         ),
     ),
     // The following section is new and should be added to your file
     'router' => array(
         'routes' => array(
             'album' => array(
                 'type'    => 'segment',
                 'options' => array(
                     'route'    => '/album[/][:action][/:id]',
                     'constraints' => array(
                         'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                         'id'     => '[0-9]+',
                     ),
                     'defaults' => array(
                         'controller' => 'Album\Controller\Album',
                         'action'     => 'index',
                     ),
                 ),
             ),
         ),
     ),
     'view_manager' => array(
         'template_path_stack' => array(
             'album' => __DIR__ . '/../view',
         ),
     ),
    // Doctrine config
    'doctrine' => array(
        'driver' => array(
            __NAMESPACE__ . '_driver' => array(
                'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
                'cache' => 'array',
                'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity')
            ),
            'orm_default' => array(
                'drivers' => array(
                    __NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
                )
            )
        )
    )
 );

Update for current version of ZF2 tutorial.


<?php

namespace SecucardConnect\Product\Payment;

use SecucardConnect\Product\Payment\Service\PaymentService;

/**
 * Operations for the payment.secupaycreditcard resource.
 * @package SecucardConnect\Product\Payment
 */
class SecupayCreditcardsService extends PaymentService
{
    /**
     * @deprecated v1.1.0 Use now onStatusChange($fn).
     */
    public function onSecupayCreditcardChanged($fn)
    {
        $this->onStatusChange($fn);
    }
}

<?php

namespace SecucardConnect\Product\Payment;

use SecucardConnect\Product\Payment\Service\PaymentService;

/**
 * Operations for the payment.secupaycreditcard resource.
 * @package SecucardConnect\Product\Payment
 */
class SecupayCreditcardsService extends PaymentService
{
}

CHANGE remove deprecated function in new code


<?php
// define available loader list
$loaderList = ['Front', 'Admin', 'Api', 'Install'];

// set error level
error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);

// define document root as project root folder
define('root', __DIR__);

// get current URI path
$uriRequest = $_SERVER['REQUEST_URI'];

// get configs to prepare posible route to switch environment
$configs = require(root . '/Private/Config/Default.php');
// remove base path
$uriRequest = substr($uriRequest, strlen($configs['basePath']));
$uriArray = explode('/', $uriRequest);

// extract 1st element
$uriLoader = array_shift($uriArray);
// prepare path to default filesystem type
$uriLoader = ucfirst(strtolower(str_replace('.', '', $uriLoader)));

// if loader of interface is available - require it
if (in_array($uriLoader, $loaderList, true) && file_exists(root . '/Loader/' . $uriLoader . '/index.php')) {
    require_once (root . '/Loader/' . $uriLoader . '/index.php');
} else { // else - try to load default interface
    require_once (root . '/Loader/Front/index.php');
}

<?php
// define available loader list
$loaderList = ['Front', 'Admin', 'Api', 'Install'];

// set error level
error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);

// define document root as project root folder
define('root', __DIR__);

// get current URI path
$uriRequest = $_SERVER['REQUEST_URI'];

// check if SAPI client == cli (php built-in dev server)
if (php_sapi_name() === 'cli-server') {
    $path = root . DIRECTORY_SEPARATOR . ltrim($uriRequest, '/');
    // if static file exist
    if (is_file($path)) {
        // check if it looks like standalone php script
        if (strtolower(substr($path, -4)) == '.php') {
            include($path);
            return true;
        }
        return false;
    }
}

// get configs to prepare posible route to switch environment
$configs = require(root . '/Private/Config/Default.php');
// remove base path
$uriRequest = substr($uriRequest, strlen($configs['basePath']));
$uriArray = explode('/', $uriRequest);

// extract 1st element
$uriLoader = array_shift($uriArray);
// prepare path to default filesystem type
$uriLoader = ucfirst(strtolower(str_replace('.', '', $uriLoader)));

// if loader of interface is available - require it
if (in_array($uriLoader, $loaderList, true) && file_exists(root . '/Loader/' . $uriLoader . '/index.php')) {
    require_once (root . '/Loader/' . $uriLoader . '/index.php');
} else { // else - try to load default interface
    require_once (root . '/Loader/Front/index.php');
}

Add support for built-in php server

Add support for built-in php server

Now allow to run with success rewrite: php -S 127.0.0.1:8000 index.php


<?php

require 'Slim/Slim.php';

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->get('/', function(){
    echo "
We're counting...
";
});

$app->get('/event/:code', function(){
    //Query if event exists & is between open and close date
    //If yes, add click to database
});

$app->run();

<?php

require 'Slim/Slim.php';

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->get('/', function(){
    echo "
We're counting...
";
});

$app->get('/event/:code', function() use ($app) {
    $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
    if ($mysqli->connect_errno) {
        error_log("Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error);
        $app->request->setStatus(500);
        return;
    }

    if (!($stmt = $mysqli->prepare('SELECT event_id FROM `events` WHERE CODE=(?) AND open<=CURDATE() AND close>=CURDATE()))'))) {
        error_log("Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error);
        $app->request->setStatus(500);
        return;
    }

    if (!$stmt->bind_param("s", $code)) {
        error_log("Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error);
        $app->request->setStatus(500);
        return;
    }

    if (!$stmt->execute()) {
        error_log("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
        $app->request->setStatus(500);
        return;
    }

    if (!($res = $stmt->get_result())) {
        error_log("Getting result set failed: (" . $stmt->errno . ") " . $stmt->error);
        $app->request->setStatus(500);
        return;
    }

    var_dump($res->fetch_all());

    $stmt->close();

    //Query if event exists & is between open and close date
    //If yes, add click to database
});

$app->run();

Check if event exists and is open

Check if event exists and is open


<?php

namespace SilverStripe\UserForms\Model;

use Page;

use SilverStripe\UserForms\UserForm;
use SilverStripe\UserForms\Control\UserDefinedFormController;

/**
 * @package userforms
 */
class UserDefinedForm extends Page
{
    use UserForm;

    /**
     * @var string
     */
    private static $icon_class = 'font-icon-p-list';

    /**
     * @var string
     */
    private static $description = 'Adds a customizable form.';

    /**
     * @var string
     */
    private static $table_name = 'UserDefinedForm';

    public function getControllerName()
    {
        return UserDefinedFormController::class;
    }
}

<?php

namespace SilverStripe\UserForms\Model;

use Page;

use SilverStripe\UserForms\UserForm;
use SilverStripe\UserForms\Control\UserDefinedFormController;

/**
 * @package userforms
 */
class UserDefinedForm extends Page
{
    use UserForm;

    /**
     * @var string
     */
    private static $icon_class = 'font-icon-p-list';

    /**
     * @var string
     */
    private static $description = 'Adds a customizable form.';

    /**
     * @var string
     */
    private static $table_name = 'UserDefinedForm';

    /**
     * @var string
     */
    private static $controller_name =  UserDefinedFormController::class;
}

Use controller_name static config instead of method for better inheritance


<?
	/*
		Uplodius
		Multiple image file upload using PHP
		https://github.com/RDmitriev/Uplodius
	*/

	include 'lib/uplodius.php';

	if(isset($_POST['images_add']))
	{
		$Uplodius = new Uplodius;

		$result = $Uplodius->Upload(
			$_FILES['files'],
			(object) array(
				'dir' 			=> '../upload/',
				'name' 			=> $structure['path'],
				'width' 		=> 1000,
				'height' 		=> 0,
				'prevWidth' 	=> 200,
				'prevHeight' 	=> 0
			)
		);

		var_dump($result);
	}
?>

Upload images

<form method="post" enctype="multipart/form-data" class="form">
	<input type="file" name="files[]" multiple="multiple">
	<input type="submit" name="images_add" value="Загрузить">
</form>

<?
	/*
		Uplodius
		Multiple image file upload using PHP
		https://github.com/RDmitriev/Uplodius
	*/

	include 'lib/uplodius.php';

	if(isset($_POST['images_add']))
	{
		$Uplodius = new Uplodius;

		$result = $Uplodius->Upload(
			$_FILES['files'],
			(object) array(
				'dir' 			=> '../upload/',
				'name' 			=> 'example',
				'width' 		=> 1000,
				'height' 		=> 0,
				'prevWidth' 	=> 200,
				'prevHeight' 	=> 0
			)
		);

		var_dump($result);
	}
?>

Upload images

<form method="post" enctype="multipart/form-data" class="form">
	<input type="file" name="files[]" multiple="multiple">
	<input type="submit" name="images_add" value="Upload">
</form>

Fix name and value name

Fix name and value name


<?php

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

require 'vendor/autoload.php';

$app = new Silex\Application();

$app->get('/', function() {
    return "Main application!";
});

$blog = new Silex\Application();

$blog->get('/', function() {
    return "This is the blog!";
});

$stack = (new Stack\Stack)
    ->push('Stack\UrlMap', ['/blog' => $blog]);

$app = $stack->resolve($app);

$request = Request::createFromGlobals();
$response = $app->handle($request)->send();

$app->terminate($request, $response);

<?php

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

require 'vendor/autoload.php';

$app = new Silex\Application();

$app->get('/', function () {
    return "Main application!";
});

$blog = new Silex\Application();

$blog->get('/', function () {
    return "This is the blog!";
});

$stack = (new Stack\Stack)
    ->push('Stack\UrlMap', ['/blog' => $blog]);

$app = $stack->resolve($app);

$request = Request::createFromGlobals();
$response = $app->handle($request)->send();

$app->terminate($request, $response);

Add a space between function keyword and '()'


<?php
define('LAN_MENTIONS_TAG_CHATBOX', 'chatbox');
define('LAN_MENTIONS_TAG_COMMENT', 'comment');
define('LAN_MENTIONS_TAG_FORUM', 'forum');

define('LAN_MENTIONS_EMAIL_VERSE_CHATBOX', '[user] mentioned you in a [tag] post on [date].');
define('LAN_MENTIONS_EMAIL_VERSE_COMMENT', '[user] mentioned you in a [tag] post for the [type] item titled \'[title]\' on [date].');
define('LAN_MENTIONS_EMAIL_VERSE_FORUM', '[user] mentioned you in a [tag] post on [date].');
define('LAN_MENTIONS_EMAIL_VERSE_UNRESOLVED', '[x] mentioned you in an un-resolvable post!');

<?php
define('LAN_MENTIONS_TAG_CHATBOX', 'chatbox');
define('LAN_MENTIONS_TAG_COMMENT', 'comment');
define('LAN_MENTIONS_TAG_FORUM', 'forum');

define('LAN_MENTIONS_EMAIL_HELLO', 'Hello');

define('LAN_MENTIONS_EMAIL_VERSE_CHATBOX', '[user] mentioned you in a [tag] post on [date].');
define('LAN_MENTIONS_EMAIL_VERSE_COMMENT', '[user] mentioned you in a [tag] post for the [type] item titled \'[title]\' on [date].');
define('LAN_MENTIONS_EMAIL_VERSE_FORUM', '[user] mentioned you in a [tag] post on [date].');
define('LAN_MENTIONS_EMAIL_VERSE_UNRESOLVED', '[x] mentioned you in an un-resolvable post!');

Add LAN constant for email 'Hello'

Add LAN constant for email 'Hello'


<?php
/**
 * Created by PhpStorm.
 * User: stas
 * Date: 13.01.16
 * Time: 23:55
 */

namespace ApiBundle\Controller;

use CoreBundle\Model\Request\Game\GameGetListRequest;
use CoreBundle\Model\Request\Game\GameGetRequest;
use CoreBundle\Model\Request\Game\GamePostPgnRequest;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use CoreBundle\Processor\GameProcessorInterface;

/**
 * Class GameController
 * @package ApiBundle\Controller
 * @RouteResource("Game", pluralize=false)
 */
class GameController extends BaseController
{
    public function getListAction(Request $request)
    {
        return $this->process($request, new GameGetListRequest());
    }

    public function getAction(Request $request, $id)
    {
        return $this->process($request, new GameGetRequest());
    }

    public function postPgnAction(Request $request, $id)
    {
        return $this->process($request, new GamePostPgnRequest());
    }

    /**
     * @return GameProcessorInterface
     */
    protected function getProcessor()
    {
        return $this->container->get("core.handler.game");
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: stas
 * Date: 13.01.16
 * Time: 23:55
 */

namespace ApiBundle\Controller;

use CoreBundle\Model\Request\Game\GameGetListRequest;
use CoreBundle\Model\Request\Game\GameGetRequest;
use CoreBundle\Model\Request\Game\GamePostPgnRequest;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use CoreBundle\Processor\GameProcessorInterface;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;

/**
 * Class GameController
 * @package ApiBundle\Controller
 * @RouteResource("Game", pluralize=false)
 */
class GameController extends BaseController
{
    public function getListAction(Request $request)
    {
        return $this->process($request, new GameGetListRequest());
    }

    public function getAction(Request $request, $id)
    {
        return $this->process($request, new GameGetRequest());
    }

    /**
     * @ApiDoc(
     *  resource=true,
     *  description="Save pgn",
     *  filters={
     *      {"name"="login", "dataType"="string", "description"="Your name"},
     *      {"name"="token", "dataType"="string", "description"="Your token"},
     *      {"name"="pgn", "dataType"="string"}
     *  }
     * )
     *
     * @param Request $request
     * @param $id
     * @return Response
     */
    public function postPgnAction(Request $request, $id)
    {
        return $this->process($request, new GamePostPgnRequest());
    }

    /**
     * @return GameProcessorInterface
     */
    protected function getProcessor()
    {
        return $this->container->get("core.handler.game");
    }
}

Add api doc to saving pgn.

docs(backend): Add api doc to saving pgn.


<?
	# $Id: logout.php,v 1.1.2.12 2003-07-04 14:59:16 dan Exp $
	#
	# Copyright (c) 1998-2003 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');

	freshports_CookieClear();

	if (IsSet($_GET['origin'])) {
		$origin = $_GET['origin'];
	} else {
		$origin = '/';
	}

	if ($origin == '/index.php') {
		$origin = '/';
	}

	header('Location: http://' . $_SERVER['HTTP_HOST'] . "/$origin");  /* Redirect browser to PHP web site */
	exit;  /* Make sure that code below does not get executed when we redirect. */
?>

<html>

<head>
<title></title>
</head

<body>
</body>
</html>

<?
	# $Id: logout.php,v 1.1.2.13 2003-09-25 10:46:14 dan Exp $
	#
	# Copyright (c) 1998-2003 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');

	freshports_CookieClear();

	if (IsSet($_GET['origin'])) {
		$origin = $_GET['origin'];
	} else {
		$origin = '';
	}

	if ($origin == '/index.php') {
		$origin = '';
	}

	header("Location: /$origin");  /* Redirect browser to PHP web site */
	exit;  /* Make sure that code below does not get executed when we redirect. */
?>

<html>

<head>
<title></title>
</head

<body>
</body>
</html>

Fix the redirect via origin so we don't get a //

git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@2482 46e82423-29d8-e211-989e-002590a4cdd4


<?php
namespace Vanderbilt\EmailTriggerExternalModule;

use ExternalModules\AbstractExternalModule;
use ExternalModules\ExternalModules;

require_once 'EmailTriggerExternalModule.php';

$passthruData = $module->resetSurveyAndGetCodes($_REQUEST['pid'], $_REQUEST['record'], $_REQUEST['instrument'], $_REQUEST['event']);

$returnCode = $passthruData['return_code'];
$hash = $passthruData['hash'];
if($returnCode == $_REQUEST['returnCode']){

    $surveyLink = APP_PATH_SURVEY_FULL."?s=".$hash;
    $link = ($_REQUEST['returnCode'] == "NULL")? "":"<input type='hidden' value='".$returnCode."' name='__code'/>";
    ?>

    <html>
    <body>
    <form id='passthruform' name='passthruform' action='<?=$surveyLink?>' method='post' enctype='multipart/form-data'>
             <?=$link?>
            <input type='hidden' value='1' name='__prefill' />
    </form>
        <script type='text/javascript'>
        window.onload = function(){
            document.passthruform.submit();
        }

    </script>
    </body>
    </html>
<?php }
else {
	echo "Error: Incorrect return code specified";
}?>

<?php
namespace Vanderbilt\EmailTriggerExternalModule;

use ExternalModules\AbstractExternalModule;
use ExternalModules\ExternalModules;

require_once 'EmailTriggerExternalModule.php';

$passthruData = $module->resetSurveyAndGetCodes($_REQUEST['pid'], $_REQUEST['record'], $_REQUEST['instrument'], $_REQUEST['event']);

$returnCode = $passthruData['return_code'];
$hash = $passthruData['hash'];
if($returnCode == $_REQUEST['returnCode']){

    $surveyLink = APP_PATH_SURVEY_FULL."?s=".$hash;
    $link = ($_REQUEST['returnCode'] == "NULL")? "":"<input type='hidden' value='".$returnCode."' name='__code'/>";
    ?>

    <form id='passthruform' name='passthruform' action='<?=$surveyLink?>' method='post' enctype='multipart/form-data'>
             <?=$link?>
            <input type='hidden' value='1' name='__prefill' />
    </form>

<?php }
else {
	echo "Error: Incorrect return code specified.

This error can also be caused by using an outdated version of the External Modules framework with a longitudinal study project. You may be able to correct this error by updating to a version of REDCap above 8.7.0";
}?>

Expand the error message to recommend updating REDCap versions


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for clean Mimic library function.
 *
 * @since 0.1.0
 */
class CleanFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array(array(1, 2, 3, 4), array(1, false, 0, 2, 3, 4, '')),
			array(array('something', 'else', 'hello'), array('something', 'else', false, 0, '', 'hello')),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\clean
	 */
	public function testResults($expected, $collection) {
		$this->assertEquals($expected, F\clean($collection));
	}
}

<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for clean Mimic library function.
 *
 * @since 0.1.0
 */
class CleanFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array(array(0 => 1, 3 => 2, 4 => 3, 5 => 4), array(1, false, 0, 2, 3, 4, '')),
			array(array(0 => 'something', 1 => 'else', 5 => 'hello'), array('something', 'else', false, 0, '', 'hello')),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\clean
	 */
	public function testResults($expected, $collection) {
		$this->assertEquals($expected, F\clean($collection));
	}
}

Fix tests: filter preserves indexes.

Fix tests: filter preserves indexes.


<?php
namespace PhakeBuilder\Tests;

class SamiTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testUpdateException()
    {
        $sami = new \PhakeBuilder\Sami('foobar');
        $sami->update('blah');
    }

    public function testUpdate()
    {
        $sami = new \PhakeBuilder\Sami('foobar');
        $result = $sami->update(__FILE__);
        $this->assertEquals('foobar update ' . __FILE__, $result, "Invalid sami command [$result]");
    }

    public function testUpdateDefaultConfig()
    {
        $sami = new \PhakeBuilder\Sami('foobar');
        $result = $sami->update();
        $this->assertEquals('foobar update etc/sami.config.php', $result, "Invalid sami command [$result]");
    }
}

<?php
namespace PhakeBuilder\Tests;

class SamiTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testUpdateException()
    {
        $sami = new \PhakeBuilder\Sami('foobar');
        $sami->update('blah');
    }

    public function testUpdate()
    {
        $sami = new \PhakeBuilder\Sami('foobar');
        $result = $sami->update(__FILE__);
        $this->assertEquals('foobar update ' . __FILE__, $result, "Invalid sami command [$result]");
    }

    public function testUpdateDefaultConfig()
    {
        $sami = new \PhakeBuilder\Sami('foobar');
        $result = $sami->update();
        $this->assertEquals('foobar update etc/sami.config.php', $result, "Invalid sami command [$result]");
    }

    public function testUpdateEmptyConfig()
    {
        $sami = new \PhakeBuilder\Sami('foobar');
        $result = $sami->update(array());
        $this->assertEquals('foobar update etc/sami.config.php', $result, "Invalid sami command [$result]");
    }
}

Test Sami with empty config

Test Sami with empty config


<?php

/**
 * @file
 * Contains CultuurNet\UDB3\Event\Events\OrganizerUpdated.
 */

namespace CultuurNet\UDB3\Event\Events;

use CultuurNet\UDB3\Event\EventEvent;

/**
 * Description of DescriptionUpdated
 */
class OrganizerUpdated extends EventEvent
{
    use \CultuurNet\UDB3\OrganizerUpdatedTrait;

    /**
     * @param string $id
     * @param string $organizerId
     */
    public function __construct($id, $organizerId)
    {
        parent::__construct($id);
        $this->organizerId = $organizerId;
    }

    /**
     * @return mixed The object instance
     */
    public static function deserialize(array $data)
    {
        return new static($data['event_id'], $data['organizerId']);
    }
}

<?php

/**
 * @file
 * Contains CultuurNet\UDB3\Event\Events\OrganizerUpdated.
 */

namespace CultuurNet\UDB3\Event\Events;

use CultuurNet\UDB3\Event\EventEvent;

class OrganizerUpdated extends EventEvent
{
    use \CultuurNet\UDB3\OrganizerUpdatedTrait;

    /**
     * @param string $id
     * @param string $organizerId
     */
    public function __construct($id, $organizerId)
    {
        parent::__construct($id);
        $this->organizerId = $organizerId;
    }

    /**
     * @return mixed The object instance
     */
    public static function deserialize(array $data)
    {
        return new static($data['event_id'], $data['organizerId']);
    }
}

Remove useless, wrong class description

III-473: Remove useless, wrong class description


<?php
/**
 * Plugin to remove component which uses cookie when user has chosen to opt-out from cookies
 *
 * Needs to used in conjunction with Kwc_Statistics_CookieBeforePlugin
 *
 * @see Kwc_Statistics_Analytics_Component
 */
class Kwc_Statistics_CookieAfterPlugin extends Kwf_Component_Plugin_Abstract
    implements Kwf_Component_Plugin_Interface_ViewBeforeChildRender
{
    public function processOutput($output, $renderer)
    {
        $pos = strpos($output, '{/kwcOptType}');
        if ($pos) {
            $optType = substr($output, 12, $pos - 12);
            if (
                (!Kwf_Statistics::issetUserOptValue() && $optType == Kwf_Statistics::OPT_OUT) ||
                Kwf_Statistics::getUserOptValue() == Kwf_Statistics::OPT_IN
            ) {
                return substr($output, $pos + 13);
            }
        }
        return '';
    }
}

<?php
/**
 * Plugin to remove component which uses cookie when user has chosen to opt-out from cookies
 *
 * Needs to used in conjunction with Kwc_Statistics_CookieBeforePlugin
 *
 * @see Kwc_Statistics_Analytics_Component
 */
class Kwc_Statistics_CookieAfterPlugin extends Kwf_Component_Plugin_Abstract
    implements Kwf_Component_Plugin_Interface_ViewBeforeChildRender
{
    public function processOutput($output, $renderer)
    {
        $pos = strpos($output, '{/kwcOptType}');
        if ($pos) {
            $defaultOptValue = substr($output, 12, $pos - 12);
            if (
                (!Kwf_Statistics::issetUserOptValue() && $defaultOptValue == Kwf_Statistics::OPT_IN) ||
                Kwf_Statistics::getUserOptValue() == Kwf_Statistics::OPT_IN
            ) {
                return substr($output, $pos + 13);
            }
        }
        return '';
    }
}

Fix wrong default behaviour for analytics opt out


<?php
namespace app\models;

use yii\base\Model;

/**
 * Signup form
 */
class SignupForm extends Model
{
    public $email;
    public $signup_token;
    public $password;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['signup_token', 'trim'],
            ['email', 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => '\app\models\User', 'message' => 'You are already an existing user. Proceed to login'],
            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if (!$this->validate()) {
            return null;
        }

        $user = new User();
        $user->email = $this->email;
        $user->setPassword($this->password);
        $user->generateAuthKey();

        return $user->save() ? $user : null;
    }
}

<?php
namespace app\models;

use yii\base\Model;

/**
 * Signup form
 */
class SignupForm extends Model
{
    public $email;
    public $signup_token;
    public $password;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['signup_token', 'trim'],
            ['email', 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => '\app\models\User', 'message' => 'You are already an existing user. Proceed to login'],
            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if (!$this->validate()) {
            return null;
        }

        $user = new User();
        $user->email = $this->email;
        $user->role = SignupLinks::findByEmail($this->email)->role;
        $user->setPassword($this->password);
        $user->generateAuthKey();

        return $user->save() ? $user : null;
    }
}

Save user role when signing up

Save user role when signing up


<?php
/**
 * Bootstrap handler - perform the Nova Framework's bootstrap stage.
 *
 * @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
 * @version 3.0
 * @date December 15th, 2015
 */

use Nova\Modules\Manager as Modules;
use Nova\Events\Manager as Events;
use Nova\Net\Session;
use Nova\Net\Router;
use Nova\Config;
use Nova\Logger;

// The current configuration files directory.
$configDir = dirname(__FILE__) .DS;

/**
 * Turn on output buffering.
 */
ob_start();

require $configDir .'constants.php';
require $configDir .'functions.php';
require $configDir .'config.php';

/**
 * Turn on custom error handling.
 */

Logger::initialize();

set_exception_handler('Nova\Logger::ExceptionHandler');
set_error_handler('Nova\Logger::ErrorHandler');

/**
 * Set timezone.
 */
date_default_timezone_set(Config::get('timezone'));

/**
 * Start sessions.
 */
Session::initialize();

/** Get the Router instance. */
$router = Router::getInstance();

/** load routes */
require $configDir .'routes.php';

/** bootstrap the active modules (and their associated routes) */
Modules::bootstrap();

/** initialize the Events */
Events::initialize();

/** Execute matched routes. */
$router->dispatch();

<?php
/**
 * Bootstrap handler - perform the Nova Framework's bootstrap stage.
 *
 * @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
 * @version 3.0
 * @date December 15th, 2015
 */

use Nova\Modules\Manager as Modules;
use Nova\Events\Manager as Events;
use Nova\Net\Session;
use Nova\Net\Router;
use Nova\Config;
use Nova\Logger;

// The current configuration files directory.
$configDir = dirname(__FILE__) .DS;

/**
 * Turn on output buffering.
 */
ob_start();

require $configDir .'constants.php';
require $configDir .'functions.php';
require $configDir .'config.php';

/**
 * Turn on custom error handling.
 */

Logger::initialize();

set_exception_handler('Nova\Logger::ExceptionHandler');
set_error_handler('Nova\Logger::ErrorHandler');

/**
 * Set timezone.
 */
date_default_timezone_set(Config::get('timezone'));

/**
 * Start sessions.
 */
Session::initialize();

/** Get the Router instance. */
$router = Router::getInstance();

/** bootstrap the active modules (and their associated routes) */
Modules::bootstrap();

/** initialize the Events */
Events::initialize();

/** load routes */
require $configDir .'routes.php';

/** Execute matched routes. */
$router->dispatch();

Move the App's Routes config file inclusion right before Router's dispatching; this way, the Routes defined by Modules taking precedence


<?php

namespace Kunstmaan\FormBundle\Tests\DependencyInjection;

use Kunstmaan\FormBundle\DependencyInjection\Configuration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

/**
 * Class ConfigurationTest
 */
class ConfigurationTest extends TestCase
{
    public function testConfiguration()
    {
        $object = new Configuration();
        $tree = $object->getConfigTreeBuilder();

        $this->assertInstanceOf(TreeBuilder::class, $tree);

        $node = $tree->root('hosts');
        $this->assertInstanceOf(ArrayNodeDefinition::class, $node);
    }
}

<?php

namespace Kunstmaan\FormBundle\Tests\DependencyInjection;

use Kunstmaan\FormBundle\DependencyInjection\Configuration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

/**
 * Class ConfigurationTest
 */
class ConfigurationTest extends TestCase
{
    public function testConfiguration()
    {
        $object = new Configuration();
        $tree = $object->getConfigTreeBuilder();

        $this->assertInstanceOf(TreeBuilder::class, $tree);

        if (method_exists($tree, 'getRootNode')) {
            $node = $tree->getRootNode();
        } else {
            // BC layer for symfony/config 4.1 and older
            $node = $tree->root('kunstmaan_form');
        }
        $this->assertInstanceOf(ArrayNodeDefinition::class, $node);
    }
}

[FormBundle] Use the root method on the configuration class is deprecated


<?php

/**
 * Setup global configuration variable.
 */
$config = require 'config.php';

/**
 * Register the Composer autoloader.
 */
require WP_CONTENT_DIR.'/../vendor/autoload.php';

/**
 * Load Framework Components.
 */
require get_template_directory().'/library/cleanup.php';
require get_template_directory().'/library/editor.php';
require get_template_directory().'/library/login.php';
require get_template_directory().'/library/pages.php';
require get_template_directory().'/library/updates.php';
require get_template_directory().'/library/utils.php';

/**
 * Enable Gzip if available.
 */
if (extension_loaded('zlib') && (ini_get('output_handler') !== 'ob_gzhandler'))
{
	add_action('wp', create_function('', '@ob_end_clean();@ini_set("zlib.output_compression", 1);'));
}

/**
 * Speed up page load in WordPress 3.8+.
 */
define('WP_HTTP_BLOCK_EXTERNAL', $config['http_block_external']);

/**
 * Prevent file edit from WordPress administrator dashboard.
 */
define('DISALLOW_FILE_EDIT', $config['disallow_file_edit']);

/**
 * Custom footer text.
 *
 * @return string
 */
add_filter('admin_footer_text', function() use ($config)
{
	return $config['footer_text'];
});

<?php

/**
 * Setup global configuration variable.
 */
$config = require 'config.php';

/**
 * Register the Composer autoloader.
 */
require WP_CONTENT_DIR.'/../vendor/autoload.php';

/**
 * Load Framework Components.
 */
require get_template_directory().'/library/cleanup.php';
require get_template_directory().'/library/editor.php';
require get_template_directory().'/library/login.php';
require get_template_directory().'/library/pages.php';
require get_template_directory().'/library/updates.php';
require get_template_directory().'/library/utils.php';

/**
 * Enable Gzip if available.
 */
if (extension_loaded('zlib') && (ini_get('output_handler') !== 'ob_gzhandler'))
{
	add_action('wp', create_function('', '@ob_end_clean();@ini_set("zlib.output_compression", 1);'));
}

/**
 * Speed up page load in WordPress 3.8+.
 */
if (!defined('WP_HTTP_BLOCK_EXTERNAL'))
{
	define('WP_HTTP_BLOCK_EXTERNAL', $config['http_block_external']);
}

/**
 * Prevent file edit from WordPress administrator dashboard.
 */
if (!defined('DISALLOW_FILE_EDIT'))
{
	define('DISALLOW_FILE_EDIT', $config['disallow_file_edit']);
}

/**
 * Custom footer text.
 *
 * @return string
 */
add_filter('admin_footer_text', function() use ($config)
{
	return $config['footer_text'];
});

Check if constants are defined before.

Check if constants are defined before.


<?php

namespace base;

class Controller{

	private $_views = array();
	private $_res = null;
	private $_req = null;
	public $currentPath = null;

	protected function getRequest()
	{
		return Request::getInstance();
	}

	protected function getResponse()
	{
		if(empty($this->_res)){
			$this->_res = new Response();
		}
		return $this->_res;
	}

	protected function getView($tplName, $isNew = false)
	{
		if(!$isNew && !empty($this->_views[$tplName])) {
			return $this->_views[$tplName];
		} else {
			if(empty($this->currentPath) || empty($this->className)) {
				$class_info = new \ReflectionClass($this);
				$this->currentPath = dirname($class_info->getFileName());
				$this->className = $class_info->getShortName();
			}
			$ds = DIRECTORY_SEPARATOR;
			$tplName = $this->currentPath.$ds.$this->className.'.Views'.$ds."{$tplName}.php";
			$this->_views[$tplName] = new View($tplName);
			return $this->_views[$tplName];
		}
	}
}

<?php

namespace base;

class Controller{

	private $_views = array();
	private $_res = null;
	private $_req = null;
	public $currentPath = null;

	protected function getRequest()
	{
		return Request::getInstance();
	}

	protected function getResponse()
	{
		if(empty($this->_res)){
			$this->_res = new Response();
		}
		return $this->_res;
	}

	protected function getView($tplName, $isNew = false)
	{
		if(!$isNew && !empty($this->_views[$tplName])) {
			return $this->_views[$tplName];
		} else {
			if(empty($this->currentPath) || empty($this->className)) {
				$class_info = new \ReflectionClass($this);
				$this->currentPath = dirname($class_info->getFileName());
				$this->className = $class_info->getShortName();
			}
			$ds = DIRECTORY_SEPARATOR;
			$tplName = $this->currentPath.$ds.$this->className.'.Views'.$ds."{$tplName}.php";
			$this->_views[$tplName] = new View($tplName);
			return $this->_views[$tplName];
		}
	}

	public function getProfile()
	{
		return "Profile";
	}
}

Add public getProfile method to base controller


<?php

namespace Symfony\Component\Validator\Mapping\Cache;

use Symfony\Component\Validator\Mapping\ClassMetadata;

class ApcCache implements CacheInterface
{
    private $prefix;

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

    public function has($class)
    {
        return apc_exists($this->prefix.$class);
    }

    public function read($class)
    {
        return apc_fetch($this->prefix.$class);
    }

    public function write(ClassMetadata $metadata)
    {
        apc_store($this->prefix.$metadata->getClassName(), $metadata);
    }
}

<?php

namespace Symfony\Component\Validator\Mapping\Cache;

use Symfony\Component\Validator\Mapping\ClassMetadata;

class ApcCache implements CacheInterface
{
    private $prefix;

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

    public function has($class)
    {
        if (!function_exists('apc_exists')) {
            $exists = false;

            apc_fetch($this->prefix.$class, $exists);

            return $exists;
        }

        return apc_exists($this->prefix.$class);
    }

    public function read($class)
    {
        return apc_fetch($this->prefix.$class);
    }

    public function write(ClassMetadata $metadata)
    {
        apc_store($this->prefix.$metadata->getClassName(), $metadata);
    }
}

Fix for bug when using APC in version 3.1.4


<?php namespace Mitch\LaravelDoctrine\Configuration;

class SqliteMapper implements Mapper
{
	/**
	 * Map the L4 configuration array to a sqlite-friendly doctrine configuration.
	 *
	 * @param array $configuration
	 * @return array
	 */
	public function map(array $configuration)
	{
		$sqliteConfig = [
			'driver' => 'pdo_sqlite',
			'user' => @$configuration['username'],
			'password' => @$configuration['password']
		];
		$this->databaseLocation($configuration, $sqliteConfig);
		return $sqliteConfig;
	}

	/**
	 * Is only suitable for sqlite configuration mapping.
	 *
	 * @param array $configuration
	 * @return bool
	 */
	public function isAppropriateFor(array $configuration)
	{
		return $configuration['driver'] == 'sqlite';
	}

	/**
	 * Determines the location of the database and appends this to the sqlite configuration.
	 *
	 * @param $configuration
	 * @param $sqliteConfig
	 */
	private function databaseLocation($configuration, &$sqliteConfig)
	{
		if ($configuration['database'] == ':memory:')
			$sqliteConfig['memory'] = true;
		else
			$sqliteConfig['path'] = app_path('database').'/'.$configuration['database'].'.sqlite';
	}
}

<?php namespace Mitch\LaravelDoctrine\Configuration;

class SqliteMapper implements Mapper
{
	/**
	 * Map the L4 configuration array to a sqlite-friendly doctrine configuration.
	 *
	 * @param array $configuration
	 * @return array
	 */
	public function map(array $configuration)
	{
		$sqliteConfig = [
			'driver' => 'pdo_sqlite',
			'user' => @$configuration['username'],
			'password' => @$configuration['password']
		];
		$this->databaseLocation($configuration, $sqliteConfig);
		return $sqliteConfig;
	}

	/**
	 * Is only suitable for sqlite configuration mapping.
	 *
	 * @param array $configuration
	 * @return bool
	 */
	public function isAppropriateFor(array $configuration)
	{
		return $configuration['driver'] == 'sqlite';
	}

	/**
	 * Determines the location of the database and appends this to the sqlite configuration.
	 *
	 * @param $configuration
	 * @param $sqliteConfig
	 */
	private function databaseLocation($configuration, &$sqliteConfig)
	{
		if ($configuration['database'] == ':memory:')
			$sqliteConfig['memory'] = true;
		else
			$sqliteConfig['path'] = $configuration['database'];
	}
}

Maintain laravel database path for sqlite.


<?php

namespace App\Controller;

use Chadicus\Slim\OAuth2\Http\RequestBridge;
use Chadicus\Slim\OAuth2\Http\ResponseBridge;
use Slim\Http\Request;
use Slim\Http\Response;

class TokenController extends Controller
{
    public function token(Request $request)
    {
        $oauthRequest = RequestBridge::toOAuth2($request);

        $oauthResponse = $this->oauth->handleTokenRequest($oauthRequest);

        return ResponseBridge::fromOauth2($oauthResponse);
    }

    public function user(Request $request, Response $response)
    {
        return $this->ok($response, $this->getUser());
    }
}

<?php

namespace App\Controller;

use Chadicus\Slim\OAuth2\Http\RequestBridge;
use Chadicus\Slim\OAuth2\Http\ResponseBridge;
use Slim\Http\Request;
use Slim\Http\Response;

class TokenController extends Controller
{
    public function token(Request $request)
    {
        $oauthRequest = RequestBridge::toOAuth2($request);

        $oauthResponse = $this->oauth->handleTokenRequest($oauthRequest);

        return ResponseBridge::fromOauth2($oauthResponse);
    }

    public function user(Request $request, Response $response)
    {
        return $this->ok($response, $this->sentinel->getUser());
    }
}

Call getUser from sentinel instead of Controller


<?php
namespace Grav\Plugin;

use Grav\Common\Plugin;
use Grav\Common\Grav;
use Grav\Common\Page\Page;
use Grav\Common\Page\Pages;
use Grav\Component\EventDispatcher\Event;

class ErrorPlugin extends Plugin
{
    /**
     * @return array
     */
    public static function getSubscribedEvents() {
        return [
            'onPageNotFound' => ['onPageNotFound', 0]
        ];
    }

    /**
     * Display error page if no page was found for the current route.
     *
     * @param Event $event
     */
    public function onPageNotFound(Event $event)
    {
        $this->enable([
            'onTwigTemplatePaths' => ['onTwigTemplatePaths', -10]
        ]);

        /** @var Pages $pages */
        $pages = $this->grav['pages'];

        // Try to load user error page.
        $page = $pages->dispatch($this->config->get('plugins.error.routes.404', '/error'), true);

        if (!$page) {
            // If none provided use built in error page.
            $page = new Page;
            $page->init(new \SplFileInfo(__DIR__ . '/pages/error.md'));
        }

        $event->page = $page;
        $event->stopPropagation();
    }

    /**
     * Add current directory to twig lookup paths.
     */
    public function onTwigTemplatePaths()
    {
        $this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
    }
}

<?php
namespace Grav\Plugin;

use Grav\Common\Plugin;
use Grav\Common\Grav;
use Grav\Common\Page\Page;
use Grav\Common\Page\Pages;
use RocketTheme\Toolbox\Event\Event;

class ErrorPlugin extends Plugin
{
    /**
     * @return array
     */
    public static function getSubscribedEvents() {
        return [
            'onPageNotFound' => ['onPageNotFound', 0]
        ];
    }

    /**
     * Display error page if no page was found for the current route.
     *
     * @param Event $event
     */
    public function onPageNotFound(Event $event)
    {
        $this->enable([
            'onTwigTemplatePaths' => ['onTwigTemplatePaths', -10]
        ]);

        /** @var Pages $pages */
        $pages = $this->grav['pages'];

        // Try to load user error page.
        $page = $pages->dispatch($this->config->get('plugins.error.routes.404', '/error'), true);

        if (!$page) {
            // If none provided use built in error page.
            $page = new Page;
            $page->init(new \SplFileInfo(__DIR__ . '/pages/error.md'));
        }

        $event->page = $page;
        $event->stopPropagation();
    }

    /**
     * Add current directory to twig lookup paths.
     */
    public function onTwigTemplatePaths()
    {
        $this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
    }
}

Update code to use new classes

Update code to use new classes


<?php declare(strict_types=1);

namespace Room11\Jeeves\Chat\Message;

class Factory
{
    public function build(array $data): Message
    {
        $message = reset($data);

        if (isset($message['e'])) {
            return $this->buildEventMessage($message['e'][0]);
        }

        return new Heartbeat($message);
    }

    private function buildEventMessage(array $message): Message
    {
        switch ($message['event_type']) {
            case 1:
                return new NewMessage($message);

            case 2:
                return new EditMessage($message);

            case 3:
                return new UserEnter($message);

            case 4:
                return new UserLeave($message);

            case 6:
                return new StarMessage($message);

            case 10:
                return new DeleteMessage($message);

            default:
                return new Unknown($message);
        }
    }
}

<?php declare(strict_types=1);

namespace Room11\Jeeves\Chat\Message;

class Factory
{
    public function build(array $data): Message
    {
        $message = reset($data);

        if (isset($message['e'])) {
            return $this->buildEventMessage(reset($message['e']));
        }

        return new Heartbeat($message);
    }

    private function buildEventMessage(array $message): Message
    {
        switch ($message['event_type']) {
            case 1:
                return new NewMessage($message);

            case 2:
                return new EditMessage($message);

            case 3:
                return new UserEnter($message);

            case 4:
                return new UserLeave($message);

            case 6:
                return new StarMessage($message);

            case 10:
                return new DeleteMessage($message);

            default:
                return new Unknown($message);
        }
    }
}

Discard other messages when multiple are added

Not sure whether this can also happen when multiple messages are
actually sent


<?php
namespace wcf\system\database\table\column;

/**
 * Represents a `varbinary` database table column.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2019 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Database\Table\Column
 * @since	5.2
 */
class VarbinaryDatabaseTableColumn extends AbstractDatabaseTableColumn implements ILengthDatabaseTableColumn {
	use TLengthDatabaseTableColumn;

	/**
	 * @inheritDoc
	 */
	protected $type = 'varbinary';

	/**
	 * @inheritDoc
	 */
	public function getMaximumLength() {
		return 65535;
	}
}

<?php
namespace wcf\system\database\table\column;

/**
 * Represents a `varbinary` database table column.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2019 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Database\Table\Column
 * @since	5.2
 */
class VarbinaryDatabaseTableColumn extends AbstractDatabaseTableColumn implements ILengthDatabaseTableColumn {
	use TLengthDatabaseTableColumn;

	/**
	 * @inheritDoc
	 */
	protected $type = 'varbinary';

	/**
	 * @inheritDoc
	 */
	public function getLength() {
		if ($this->length === null) {
			throw new \LogicException('The length of varbinary fields must be explicitly set.');
		}

		return $this->traitGetLength();
	}

	/**
	 * @inheritDoc
	 */
	public function getMaximumLength() {
		return 65535;
	}
}

Throw exception for VARBINARY columns without length

Close #3827


<?php

namespace Cache;

use Cache\CacheManager;
use Support\ServiceProvider;

class CacheServiceProvider extends ServiceProvider
{
    /**
     * Register the Service Provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bindShared('cache', function($app)
        {
            return new CacheManager($app);
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array('cache');
    }

}

<?php

namespace Cache;

use Cache\CacheManager;
use Support\ServiceProvider;

class CacheServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the Provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Register the Service Provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bindShared('cache', function($app)
        {
            return new CacheManager($app);
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array('cache');
    }

}

Make deferred the Cache Service Provider


<?php
// ==========================================
// Ideamart : PHP SMS API Logger Class
// ==========================================
// Author : Pasindu De Silva
// Licence : MIT License
// http://opensource.org/licenses/MIT
// ==========================================

class Logger{
	public function WriteLog($logStream){
		$_LOGFILE = 'LogData.log';

		$file = fopen($_LOGFILE, 'a');
		fwrite($file, '['.date('D M j G:i:s T Y').'] '.$logStream.'\n');
		fclose($file);
	}
}
?>

<?php
// ==========================================
// Ideamart : PHP SMS API Logger Class
// ==========================================
// Author : Pasindu De Silva
// Licence : MIT License
// http://opensource.org/licenses/MIT
// ==========================================

class Logger{
	public function WriteLog($logStream){
		date_default_timezone_set('Asia/Colombo');
		$_LOGFILE = 'LogData.log';

		$file = fopen($_LOGFILE, 'a');
		fwrite($file, '['.date('D M j G:i:s T Y').'] '.$logStream.'\n');
		fclose($file);
	}
}
?>

Add timezone to remove the warning for time zone


<?php

/*
 * This file is part of Zippy.
 *
 * (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 Alchemy\Zippy\Parser;

interface ParserInterface
{
    /**
     * Parses a file listing
     *
     * @param String $output The string to parse
     *
     * @return Array An array of Members
     */
    public function parseFileListing($output);

    /**
     * Parses a version
     *
     * @param String $output
     *
     * @return String The version
     */
    public function parseVersion($output);
}

<?php

/*
 * This file is part of Zippy.
 *
 * (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 Alchemy\Zippy\Parser;

interface ParserInterface
{
    /**
     * Parses a file listing
     *
     * @param String $output The string to parse
     *
     * @return Array An array of Members
     */
    public function parseFileListing($output);

    /**
     * Parses the inflator binary version
     *
     * @param String $output
     *
     * @return String The version
     */
    public function parseInflatorVersion($output);

    /**
     * Parses the deflator binary version
     *
     * @param String $output
     *
     * @return String The version
     */
    public function parsedeflatorVersion($output);
}

Update parser interface to fetch version from inflator & deflator binary


<?php
namespace Freeagent\Invoice;

/**
 * Class InvoiceItem
 *
 * @package Freeagent\Invoice
 */
class InvoiceItem
{
    /**
     * @var string
     */
    public $item_type;

    /**
     * @var int
     */
    public $quantity;

    /**
     * @var float
     */
    public $price;

    /**
     * @var string
     */
    public $description;

    /**
     * @var string
     */
    public $sales_tax_rate;

    /**
     * @var int
     */
    public $position;

    /**
     * @var string
     */
    public $second_sales_tax_rate;

    /**
     * @var string
     */
    public $category;

    /**
     * @return array
     */
    public function toArray()
    {
        return array(
            'item_type'      => $this->item_type,
            'quantity'       => $this->quantity,
            'price'          => $this->price,
            'description'    => $this->description,
            'sales_tax_rate' => $this->sales_tax_rate,
            'position'       => $this->position,
            'second_sales_tax_rate' => $this->second_sales_tax_rate,
            'category'       => $this->category
        );
    }
}

<?php
namespace Freeagent\Invoice;

/**
 * Class InvoiceItem
 *
 * @package Freeagent\Invoice
 */
class InvoiceItem
{
    /**
     * @var string
     */
    public $item_type;

    /**
     * @var int
     */
    public $quantity;

    /**
     * @var float
     */
    public $price;

    /**
     * @var string
     */
    public $description;

    /**
     * @var string
     */
    public $sales_tax_rate = 0;

    /**
     * @var int
     */
    public $position;

    /**
     * @var int
     */
    public $second_sales_tax_rate = 0;

    /**
     * @var string
     */
    public $category;

    /**
     * @return array
     */
    public function toArray()
    {
        return array(
            'item_type'      => $this->item_type,
            'quantity'       => $this->quantity,
            'price'          => $this->price,
            'description'    => $this->description,
            'sales_tax_rate' => $this->sales_tax_rate,
            'position'       => $this->position,
            'second_sales_tax_rate' => $this->second_sales_tax_rate,
            'category'       => $this->category
        );
    }
}

Set default sales tax rates

Set default sales tax rates


<?php

namespace Ilex\Base\Model\db;

use Ilex\Core\Loader;

/**
 * Class Base
 * @package Ilex\Base\Model\db
 *
 * @property string $collectionName
 * @property \MongoCollection $collection
 */
class Base extends \Ilex\Base\Model\Base
{
    protected $collectionName;
    public $collection; // todo: Do NOT expose this

    public function __construct()
    {
        $this->collection = Loader::db()->selectCollection($this->collectionName);
    }
}

<?php

namespace Ilex\Base\Model\db;

use Ilex\Core\Loader;

/**
 * Class Base
 * @package Ilex\Base\Model\db
 *
 * @property string $collectionName
 * @property \MongoCollection $collection
 */
class Base extends \Ilex\Base\Model\Base
{
    protected $collectionName;
    public $collection; // todo: Do NOT expose this

    public function __construct()
    {
        $this->collection = Loader::db()->selectCollection($this->collectionName);
    }

    protected function getId($id)
    {
        if (is_string($id)) {
            try {
                return new \MongoId($id);
            } catch (\Exception $e) {
                return $id;
            }
        } else {
            return $id;
        }
    }

    protected function setRetractId($object)
    {
        if (isset($object['_id'])) {
            $object['_id'] = $this->getId($object['_id']);
        }
        return $object;
    }

    public function find($criterion = [], $projection = [], $toArray = TRUE)
    {
        $criterion = $this->setRetractId($criterion);
        $cursor = $this->collection->find($criterion, $projection);
        return $toArray ? array_values(iterator_to_array($cursor)) : $cursor;
    }

}

Add kit functions for database mongo

Add kit functions for database mongo


<?php
declare(strict_types=1);

namespace zauberfisch\SerializedDataObject\Form;

class FormExtension extends \Extension {
	private static $allowed_actions = [
		'handleFieldArrayList',
	];
//	private static $url_handlers = [
//		'field/$FieldName!' => 'handleFieldArrayList',
//	];

	/**
	 * @param \SS_HTTPRequest $request
	 * @return \FormField
	 */
	public function handleFieldArrayList($request) {
		$field = $this->owner->handleField($request);
		if (!$field) {
			$fieldName = $request->param('FieldName');
			foreach ($this->owner->Fields()->dataFields() as $dataField) {
				/** @var \FormField|ArrayListField $dataField */
				if ($dataField->is_a(ArrayListField::class)) {
					if (strpos($fieldName, $dataField->getName()) == 0) {
						$field = $dataField->handleSubField($fieldName);
						break;
					}
				}
			}
		}
		return $field;
	}
}

<?php
declare(strict_types=1);

namespace zauberfisch\SerializedDataObject\Form;

class FormExtension extends \Extension {
	private static $allowed_actions = [
		'handleFieldArrayList',
	];
//	private static $url_handlers = [
//		'field/$FieldName!' => 'handleFieldArrayList',
//	];

	/**
	 * @param \SS_HTTPRequest $request
	 * @return \FormField
	 */
	public function handleFieldArrayList($request) {
		$field = $this->owner->handleField($request);
		if (!$field) {
			$fieldName = $request->param('FieldName');
			foreach ($this->owner->Fields()->dataFields() as $dataField) {
				/** @var \FormField|ArrayListField $dataField */
				if ($dataField->is_a(ArrayListField::class)) {
					if (strpos($fieldName, $dataField->getName()) === 0) {
						$field = $dataField->handleSubField($fieldName);
						break;
					}
				}
			}
		}
		return $field;
	}
}

FIX handleFieldArrayList only handling first ArrayListField


<?php

namespace League\Tactician;

use League\Tactician\Exception\CommandWasNotHandledException;
use Closure;

/**
 * Receives a command and modifies or dispatches it to a handler in some way
 */
class StandardCommandBus implements CommandBus
{
    /**
     * @var Closure
     */
    private $middlewareChain;

    /**
     * @param Middleware[] $middleware
     */
    public function __construct(array $middleware)
    {
        $this->middlewareChain = $this->createExecutionChain($middleware);
    }

    /**
     * Executes the given command and optionally returns a value
     *
     * @param Command $command
     * @return mixed
     */
    public function execute(Command $command)
    {
        $middlewareChain = $this->middlewareChain;
        return $middlewareChain($command);
    }

    /**
     * @param Middleware[] $middlewareList
     * @return Closure
     */
    protected function createExecutionChain($middlewareList)
    {
        $lastCallable = function (Command $command) {
            // the final callable is a no-op
        };

        while ($middleware = array_pop($middlewareList)) {
            $lastCallable = function (Command $command) use ($middleware, $lastCallable) {
                return $middleware->execute($command, $lastCallable);
            };
        }

        return $lastCallable;
    }
}

<?php

namespace League\Tactician;

use Closure;

/**
 * Receives a command and modifies or dispatches it to a handler in some way
 */
class StandardCommandBus implements CommandBus
{
    /**
     * @var Closure
     */
    private $middlewareChain;

    /**
     * @param Middleware[] $middleware
     */
    public function __construct(array $middleware)
    {
        $this->middlewareChain = $this->createExecutionChain($middleware);
    }

    /**
     * Executes the given command and optionally returns a value
     *
     * @param Command $command
     * @return mixed
     */
    public function execute(Command $command)
    {
        $middlewareChain = $this->middlewareChain;
        return $middlewareChain($command);
    }

    /**
     * @param Middleware[] $middlewareList
     * @return Closure
     */
    protected function createExecutionChain($middlewareList)
    {
        $lastCallable = function (Command $command) {
            // the final callable is a no-op
        };

        while ($middleware = array_pop($middlewareList)) {
            $lastCallable = function (Command $command) use ($middleware, $lastCallable) {
                return $middleware->execute($command, $lastCallable);
            };
        }

        return $lastCallable;
    }
}

Remove use statement for deleted class

Remove use statement for deleted class


#!/usr/bin/env php
<?php

set_time_limit(0);

$vendorDir = __DIR__;
$deps = array(
    array('symfony', 'http://github.com/symfony/symfony', isset($_SERVER['SYMFONY_VERSION']) ? $_SERVER['SYMFONY_VERSION'] : 'origin/master'),
    array('knp-menu', 'http://github.com/knplabs/KnpMenu.git', 'origin/master'),
);

foreach ($deps as $dep) {
    list($name, $url, $rev) = $dep;

    echo "> Installing/Updating $name\n";

    $installDir = $vendorDir.'/'.$name;
    if (!is_dir($installDir)) {
        system(sprintf('git clone -q %s %s', escapeshellarg($url), escapeshellarg($installDir)));
    }

    system(sprintf('cd %s && git fetch -q origin && git reset --hard %s', escapeshellarg($installDir), escapeshellarg($rev)));
}

#!/usr/bin/env php
<?php

set_time_limit(0);

$vendorDir = __DIR__;
$deps = array(
    array('symfony', 'http://github.com/symfony/symfony', isset($_SERVER['SYMFONY_VERSION']) ? $_SERVER['SYMFONY_VERSION'] : 'origin/master'),
    array('knp-menu', 'http://github.com/KnpLabs/KnpMenu.git', 'origin/master'),
);

foreach ($deps as $dep) {
    list($name, $url, $rev) = $dep;

    echo "> Installing/Updating $name\n";

    $installDir = $vendorDir.'/'.$name;
    if (!is_dir($installDir)) {
        system(sprintf('git clone -q %s %s', escapeshellarg($url), escapeshellarg($installDir)));
    }

    system(sprintf('cd %s && git fetch -q origin && git reset --hard %s', escapeshellarg($installDir), escapeshellarg($rev)));
}

Fix case in repo urls

Fix case in repo urls


<?php echo $title; ?>

Page under construction

<?= $title; ?>

Online purchase functionality is under construction

To purchase items, pleae contact <?= EMAIL ?>

Add email to temp purchase page.

Add email to temp purchase page.


<?php
namespace Chamilo\Core\Repository\Workspace\Table\Workspace\Shared;

use Chamilo\Core\Repository\Workspace\Table\Workspace\WorkspaceTableCellRenderer;

/**
 *
 * @package Chamilo\Core\Repository\Workspace\Table\Workspace\Shared
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 * @author Magali Gillard <magali.gillard@ehb.be>
 * @author Eduard Vossen <eduard.vossen@ehb.be>
 */
class SharedWorkspaceTableCellRenderer extends WorkspaceTableCellRenderer
{
}

<?php
namespace Chamilo\Core\Repository\Workspace\Table\Workspace\Shared;

use Chamilo\Libraries\Platform\Translation;
use Chamilo\Libraries\Utilities\Utilities;
use Chamilo\Libraries\Format\Structure\ToolbarItem;
use Chamilo\Libraries\Format\Theme;
use Chamilo\Core\Repository\Workspace\Table\Workspace\WorkspaceTableCellRenderer;
use Chamilo\Core\Repository\Workspace\Manager;

/**
 *
 * @package Chamilo\Core\Repository\Workspace\Table\Workspace\Shared
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 * @author Magali Gillard <magali.gillard@ehb.be>
 * @author Eduard Vossen <eduard.vossen@ehb.be>
 */
class SharedWorkspaceTableCellRenderer extends WorkspaceTableCellRenderer
{

    public function get_actions($workspace)
    {
        $toolbar = $this->getToolbar($workspace);

        $toolbar->prepend_item(
            new ToolbarItem(
                Translation :: get('Favourite', null, Utilities :: COMMON_LIBRARIES),
                Theme :: getInstance()->getImagePath(Manager :: context(), 'Action/Favourite'),
                $this->get_component()->get_url(
                    array(
                        Manager :: PARAM_ACTION => Manager :: ACTION_FAVOURITE,
                        \Chamilo\Core\Repository\Workspace\Favourite\Manager :: PARAM_ACTION => \Chamilo\Core\Repository\Workspace\Favourite\Manager :: ACTION_CREATE,
                        Manager :: PARAM_WORKSPACE_ID => $workspace->get_id())),
                ToolbarItem :: DISPLAY_ICON));

        return $toolbar->as_html();
    }
}

Fix: Allow setting a shared workspace as a favourite


<?php

namespace SimplyTestable\WorkerBundle\Tests\Integration\Command\Task\Perform\LinkIntegrity;

use SimplyTestable\WorkerBundle\Tests\Command\ConsoleCommandBaseTestCase;

class BugFixTest extends ConsoleCommandBaseTestCase {

    public static function setUpBeforeClass() {
        self::setupDatabase();
    }

    public function testBugFix() {
        $this->assertTrue(true);
        return;

//        $taskObject = $this->createTask('http://www.joelonsoftware.com/articles/fog0000000017.html', 'Link integrity');
//        $taskObject = $this->createTask('http://www.boxuk.com/blog/dark-patterns-in-ux/', 'Link integrity');
//        $taskObject = $this->createTask('http://www.joelonsoftware.com/', 'Link integrity');
        $taskObject = $this->createTask('http://www.boxuk.com/news/box-uk-to-showcase-digital-solutions-at-tfma-exhibition/', 'Link integrity');

        $task = $this->getTaskService()->getById($taskObject->id);

        $this->assertEquals(0, $this->runConsole('simplytestable:task:perform', array(
            $task->getId() => true
        )));

        var_dump(json_decode($task->getOutput()->getOutput()));
    }
}

<?php

namespace SimplyTestable\WorkerBundle\Tests\Integration\Command\Task\Perform\LinkIntegrity;

use SimplyTestable\WorkerBundle\Tests\Command\ConsoleCommandBaseTestCase;

class BugFixTest extends ConsoleCommandBaseTestCase {

    public static function setUpBeforeClass() {
        self::setupDatabase();
    }

    public function testBugFix() {
        $this->assertTrue(true);
        return;

        $this->getHttpClientService()->getMemcacheCache()->deleteAll();

//        $taskObject = $this->createTask('http://www.joelonsoftware.com/articles/fog0000000017.html', 'Link integrity');
//        $taskObject = $this->createTask('http://www.boxuk.com/blog/dark-patterns-in-ux/', 'Link integrity');
//        $taskObject = $this->createTask('http://www.joelonsoftware.com/', 'Link integrity');
//        $taskObject = $this->createTask('http://www.boxuk.com/news/box-uk-to-showcase-digital-solutions-at-tfma-exhibition/', 'Link integrity');

        $urls = array(
            'http://www.hnp.dk/'
        );

        foreach ($urls as $url) {
            $taskObject = $this->createTask($url, 'Link integrity');

            $task = $this->getTaskService()->getById($taskObject->id);

            $this->assertEquals(0, $this->runConsole('simplytestable:task:perform', array(
                $task->getId() => true
            )));

            var_dump($task->getOutput()->getOutput());

            echo "\n\n";
        }

        //var_dump(json_decode($task->getOutput()->getOutput()));
    }
}

Fix link integrity no referer tests

Fix link integrity no referer tests


<?php

// If subsites is installed
if(class_exists('Subsite')) {
    CatalogueProduct::add_extension('SubsiteCatalogueExtension');
    CatalogueCategory::add_extension('SubsiteCatalogueExtension');
    TaxRate::add_extension('SubsiteCatalogueExtension');
    CatalogueAdmin::add_extension('SubsiteMenuExtension');
}

// Setup google sitemaps
$catalogue_enabled = Catalogue::config()->enable_frontend;

if($catalogue_enabled && class_exists("GoogleSitemap")) {
    GoogleSitemap::register_dataobject('CatalogueProduct');
    GoogleSitemap::register_dataobject('CatalogueCategory');
}

<?php

// If subsites is installed
if(class_exists('Subsite')) {
    CatalogueProduct::add_extension('SubsiteCatalogueExtension');
    CatalogueCategory::add_extension('SubsiteCatalogueExtension');
    TaxRate::add_extension('SubsiteCatalogueExtension');
    CatalogueAdmin::add_extension('SubsiteMenuExtension');
}

// Setup google sitemaps
$catalogue_enabled = Catalogue::config()->enable_frontend;

if($catalogue_enabled && class_exists("GoogleSitemap")) {
    // Ensure compatibility with PHP 7.2 ("object" is a reserved word),
    // with SilverStripe 3.6 (using Object) and SilverStripe 3.7 (using SS_Object)
    if (!class_exists('SS_Object')) {
        class_alias('Object', 'SS_Object');
    }

    GoogleSitemap::register_dataobject('CatalogueProduct');
    GoogleSitemap::register_dataobject('CatalogueCategory');
}

Add shic for SS3.7 support

Add shic for SS3.7 support


<?php declare(strict_types=1);

namespace Symplify\ChangelogLinker\ChangeTree\Resolver;

use Nette\Utils\Strings;
use Symplify\ChangelogLinker\Configuration\Package;

final class PackageResolver
{
    /**
     * @var string
     *
     * It assumes that tere is space after the package name.
     *
     * It covers:
     * - "[package-name] "Message => package-name
     * - "[aliased-package-name] "Message => aliased-package-name
     * - "[Aliased\PackageName] "Message => Aliased\PackageName
     */
    public const PACKAGE_NAME_PATTERN = '#\[(?<package>[-\w\\\\]+)\]( )#';

    /**
     * @var string[]
     */
    private $packageAliases = [];

    /**
     * @param string[] $packageAliases
     */
    public function __construct(array $packageAliases)
    {
        $this->packageAliases = $packageAliases;
    }

    /**
     * E.g. "[ChangelogLinker] Add feature XY" => "ChangelogLinker"
     */
    public function resolvePackage(string $message): ?string
    {
        $match = Strings::match($message, self::PACKAGE_NAME_PATTERN);
        if (! isset($match['package'])) {
            return Package::UNKNOWN;
        }

        return $this->packageAliases[$match['package']] ?? $match['package'];
    }
}

<?php declare(strict_types=1);

namespace Symplify\ChangelogLinker\ChangeTree\Resolver;

use Nette\Utils\Strings;
use Symplify\ChangelogLinker\Configuration\Package;

final class PackageResolver
{
    /**
     * @var string
     *
     * It assumes that there is at least one space after the package name.
     *
     * It covers:
     * - "[package-name] "Message => package-name
     * - "[aliased-package-name] "Message => aliased-package-name
     * - "[Aliased\PackageName] "Message => Aliased\PackageName
     * - "[Aliased\PackageName]      "Message => Aliased\PackageName
     */
    public const PACKAGE_NAME_PATTERN = '#\[(?<package>[-\w\\\\]+)\]( ){1,}#';

    /**
     * @var string[]
     */
    private $packageAliases = [];

    /**
     * @param string[] $packageAliases
     */
    public function __construct(array $packageAliases)
    {
        $this->packageAliases = $packageAliases;
    }

    /**
     * E.g. "[ChangelogLinker] Add feature XY" => "ChangelogLinker"
     */
    public function resolvePackage(string $message): ?string
    {
        $match = Strings::match($message, self::PACKAGE_NAME_PATTERN);
        if (! isset($match['package'])) {
            return Package::UNKNOWN;
        }

        return $this->packageAliases[$match['package']] ?? $match['package'];
    }
}

[ChangelogLinker] Remove extra spaces from message without package


<?php defined('SYSPATH') or die('No direct script access.');

class MustacheView
{
	protected $values;
	public $name;

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

	public function __get($key)
	{
		if (empty($this->values[$key])) return false;
		return $this->values[$key];
	}

	public function __set($key, $value)
	{
		if (is_object($value) && method_exists($value, '__toString'))
		{
			$value = $value->__toString();
		}
		$this->values[$key] = $value;
	}

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

	public function __isset($key)
	{
		return (isset($this->values[$key]));
	}

	public function render()
	{
		$m = new Mustache;
		return $m->render($this->markup(), $this);
	}

	protected function markup()
	{
		return file_get_contents(APPPATH . 'views/' . $this->name . '.ms');
	}

	public static function factory($name)
	{
		return new self($name);
	}
}

<?php defined('SYSPATH') or die('No direct script access.');

class MustacheView
{
	protected $values;
	public $name;

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

	public function __get($key)
	{
		if (!isset($this->values[$key])) return false;
		return $this->values[$key];
	}

	public function __set($key, $value)
	{
		if (is_object($value) && method_exists($value, '__toString'))
		{
			$value = $value->__toString();
		}
		$this->values[$key] = $value;
	}

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

	public function __isset($key)
	{
		return (isset($this->values[$key]));
	}

	public function render()
	{
		$m = new Mustache;
		return $m->render($this->markup(), $this);
	}

	protected function markup()
	{
		return file_get_contents(APPPATH . 'views/' . $this->name . '.ms');
	}

	public static function factory($name)
	{
		return new self($name);
	}
}

Use isset instead of empty

Use isset instead of empty


<?php

namespace humhub\modules\twitter;

return [
    'id' => 'twitter',
    'class' => 'humhub\modules\twitter\Module',
    'namespace' => 'humhub\modules\twitter',
    'events' => [
        [
            'class' => \humhub\modules\dashboard\widgets\Sidebar::className(),
            'event' => \humhub\modules\dashboard\widgets\Sidebar::EVENT_INIT,
            'callback' => [
                'humhub\modules\twitter\Events',
                'addTwitterFrame'
            ]
        ],
        [
            'class' => \humhub\modules\space\widgets\Sidebar::className(),
            'event' => \humhub\modules\space\widgets\Sidebar::EVENT_INIT,
            'callback' => [
                'humhub\modules\twitter\Events',
                'addTwitterFrame'
            ]
        ],
        [
            'class' => \humhub\modules\admin\widgets\AdminMenu::className(),
            'event' => \humhub\modules\admin\widgets\AdminMenu::EVENT_INIT,
            'callback' => [
                'humhub\modules\twitter\Events',
                'onAdminMenuInit'
            ]
        ]
    ]
];
?>

<?php

namespace humhub\modules\twitter;

return [
    'id' => 'twitter',
    'class' => 'humhub\modules\twitter\Module',
    'namespace' => 'humhub\modules\twitter',
    'events' => [
        [
            'class' => \humhub\modules\dashboard\widgets\Sidebar::className(),
            'event' => \humhub\modules\dashboard\widgets\Sidebar::EVENT_INIT,
            'callback' => [
                'humhub\modules\twitter\Events',
                'addTwitterFrame'
            ]
        ],
//        [
//            'class' => \humhub\modules\space\widgets\Sidebar::className(),
//            'event' => \humhub\modules\space\widgets\Sidebar::EVENT_INIT,
//            'callback' => [
//                'humhub\modules\twitter\Events',
//                'addTwitterFrame'
//            ]
//        ],
        [
            'class' => \humhub\modules\admin\widgets\AdminMenu::className(),
            'event' => \humhub\modules\admin\widgets\AdminMenu::EVENT_INIT,
            'callback' => [
                'humhub\modules\twitter\Events',
                'onAdminMenuInit'
            ]
        ]
    ]
];
?>

Remove from Spaces till implement toggle switch


<?php

abstract class Media_Compiler {

	/**
	 * Add contents to the file specified, while
	 * also recursively creating the directory the
	 * file should be located in if it doesn't exist
	 *
	 * @param string $filepath The file location
	 * @param string $contents The file contents
	 */
	public function put_contents($filepath, $contents)
	{
		// Genearte the directory tree
		$this->make_missing_directories($filepath);

		// Create the file with the contents
		file_put_contents($filepath, $contents);
	}

	/**
	 * Recursively create a directory path in the
	 * filesysystem if the path doesn't exist
	 *
	 * @param string $filepath The file path to create
	 */
	public function make_missing_directories($filepath)
	{
		// Get the real directory path
		$directory = pathinfo($filepath, PATHINFO_DIRNAME);

		// Create missing directories recursively
		if ( ! is_dir($directory))
		{
			mkdir($directory, 0777, TRUE);
		}
	}

	/**
	 * Compile a type of media source and place
	 * the compiled file(s) into the configured
	 * location in the applications media directory
	 *
	 * @param array $filepaths Files to compile
	 * @param array $options Compiler options
	 */
	abstract public function compile(array $filepaths, array $options);

}

<?php

abstract class Media_Compiler {

	/**
	 * Add contents to the file specified, while
	 * also recursively creating the directory the
	 * file should be located in if it doesn't exist
	 *
	 * @param string $filepath The file location
	 * @param string $contents The file contents
	 */
	public function put_contents($filepath, $contents)
	{
		// Genearte the directory tree
		$this->make_missing_directories($filepath);

		// Create the file with the contents
		file_put_contents($filepath, $contents);
	}

	/**
	 * Recursively create a directory path in the
	 * filesysystem if the path doesn't exist
	 *
	 * @param string $filepath The file path to create
	 */
	public function make_missing_directories($filepath)
	{
		// Get the real directory path
		$directory = pathinfo($filepath, PATHINFO_DIRNAME);

		// Create missing directories recursively
		if ( ! is_dir($directory))
		{
			mkdir($directory, 0777, TRUE);
		}
	}

	/**
	 * Compile a type of media source and place
	 * the compiled file(s) into the configured
	 * location in the applications media directory
	 *
	 * @param array $paths Associative array of source => compiled file
	 * @param array $options Compiler options
	 */
	abstract public function compile(array $paths, array $options);

}

Rename the first parameter for the compile mthod


<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\models\CttStaticdataDocsources */

$this->title = Yii::t('app/ctt_staticdata_docsource', 'Update Ctt Staticdata Docsources') . ' ' . $model->name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app/ctt_staticdata_docsource', 'Ctt Staticdata Docsources'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => Yii::t('app/ctt_staticdata_docsource', 'Ctt Staticdata Countrys(Language List)'),
                                    'url' => ['lang-list', 'id' => $model->id]];
$this->params['breadcrumbs'][] = Yii::t('app/frontend', 'Update');
?>
<div class="ctt-staticdata-docsources-update">

    <?= $this->render('_form', [
        'title' => Html::encode($this->title),
        'model' => $model,
        'mode' => 'edit',
    ]) ?>

</div>

<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\models\CttStaticdataDocsources */

$this->title = Yii::t('app/ctt_staticdata_docsource', 'Update Ctt Staticdata Docsources') . ': ' . $model->name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app/ctt_staticdata_docsource', 'Ctt Staticdata Docsources'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => Yii::t('app/ctt_staticdata_docsource', 'Ctt Staticdata Countrys(Language List)'),
                                    'url' => ['lang-list', 'id' => $model->id]];
$this->params['breadcrumbs'][] = Yii::t('app/frontend', 'Update');
?>
<div class="ctt-staticdata-docsources-update">

    <?= $this->render('_form', [
        'title' => Html::encode($this->title),
        'model' => $model,
        'mode' => 'edit',
    ]) ?>

</div>

Edit a wording of breadcrums.

Edit a wording of breadcrums.

:)


<?php

declare (strict_types = 1); // @codeCoverageIgnore

use Evenement\EventEmitterInterface;
use Peridot\Console\Environment;
use Peridot\Reporter\CodeCoverage\AbstractCodeCoverageReporter;
use Peridot\Reporter\CodeCoverageReporters;

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

return function (EventEmitterInterface $emitter) {
    (new CodeCoverageReporters($emitter))->register();

    $emitter->on('peridot.start', function (Environment $environment) {
        $environment->getDefinition()->getArgument('path')->setDefault('test/suite');
    });

    $emitter->on('code-coverage.start', function (AbstractCodeCoverageReporter $reporter) {
        $reporter->addDirectoryToWhitelist(__DIR__ . '/src');
        $reporter->addDirectoryToWhitelist(__DIR__ . '/src-internal');
    });
};

<?php

declare (strict_types = 1); // @codeCoverageIgnore

use Evenement\EventEmitterInterface;
use Peridot\Console\Environment;
use Peridot\Reporter\CodeCoverage\AbstractCodeCoverageReporter;
use Peridot\Reporter\CodeCoverageReporters;

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

return function (EventEmitterInterface $emitter) {
    (new CodeCoverageReporters($emitter))->register();

    $emitter->on('peridot.start', function (Environment $environment) {
        $environment->getDefinition()->getArgument('path')->setDefault('test/suite');
    });

    $emitter->on('code-coverage.start', function (AbstractCodeCoverageReporter $reporter) {
        $reporter->addDirectoryToWhitelist(__DIR__ . '/src');
    });
};

Remove non-existant src-internal directory from coverage whitelist.


<?php

namespace ProjectBundle\Repository;

/**
 * PlayerRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PlayerRepository extends \Doctrine\ORM\EntityRepository
{
	public function listAndTestLinkPlayers($entryInput)
	{
		$listOfPlayers = $this->findAll();

		foreach($listOfPlayers as $player){

			$playerLinkExample = $player->getlinkExample();

			if($this->testBetweenToLinks($playerLinkExample, $entryInput))
				return array('type' => $player->getId(), 'name' =>$player->getName());

		}

		return null;
	}

	private function testBetweenToLinks($databaseLink, $entryLink){

		$entry = parse_url($entryLink);
		$entry = preg_replace('#^www\.(.+\.)#i', '$1',  $entry["host"]);

		if($databaseLink == $entry){
			return true;
		}

		return false;

	}

	// prefer domain name method
//	private function testBetweenToLinks($databaseLink, $entryLink){
//
//		similar_text($databaseLink, $entryLink, $percent);
//
//		if($percent > 30){
//			return true;
//		}
//
//		return false;
//
//	}
}

<?php

namespace ProjectBundle\Repository;

/**
 * PlayerRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PlayerRepository extends \Doctrine\ORM\EntityRepository
{
	public function listAndTestLinkPlayers($entryInput)
	{
		if (filter_var($entryInput, FILTER_VALIDATE_URL) === FALSE) {
			return null;
		}

		$listOfPlayers = $this->findAll();

		foreach($listOfPlayers as $player){

			$playerLinkExample = $player->getlinkExample();

			if($this->testBetweenToLinks($playerLinkExample, $entryInput))
				return array('type' => $player->getId(), 'name' =>$player->getName());

		}

		return null;
	}

	private function testBetweenToLinks($databaseLink, $entryLink){

		$entry = parse_url($entryLink);
		$entry = preg_replace('#^www\.(.+\.)#i', '$1',  $entry["host"]);

		if($databaseLink == $entry){
			return true;
		}

		return false;

	}

	// prefer domain name method
//	private function testBetweenToLinks($databaseLink, $entryLink){
//
//		similar_text($databaseLink, $entryLink, $percent);
//
//		if($percent > 30){
//			return true;
//		}
//
//		return false;
//
//	}
}

Check if url or not

Check if url or not