<?php
if ( function_exists( 'wfLoadExtension' ) ) {
	wfLoadExtension( 'Josa' );
	// Keep i18n globals so mergeMessageFileList.php doesn't break
	$wgMessagesDirs['Josa'] = __DIR__ . '/i18n';
	$wgExtensionMessagesFiles['JosaMagic'] = __DIR__ . '/Josa.i18n.magic.php';
	wfWarn(
		'Deprecated PHP entry point used for Josa extension. Please use wfLoadExtension instead, ' .
		'see https://www.mediawiki.org/wiki/Extension_registration for more details.'
	);
	return;
} else {
	die( 'This version of the Josa extension requires MediaWiki 1.25+' );
}

<?php
if ( function_exists( 'wfLoadExtension' ) ) {
	wfLoadExtension( 'Josa' );
	// Keep i18n globals so mergeMessageFileList.php doesn't break
	$wgMessagesDirs['Josa'] = __DIR__ . '/i18n';
	$wgExtensionMessagesFiles['JosaMagic'] = __DIR__ . '/Josa.i18n.magic.php';
	/* wfWarn(
		'Deprecated PHP entry point used for Josa extension. Please use wfLoadExtension instead, ' .
		'see https://www.mediawiki.org/wiki/Extension_registration for more details.'
	); */
	return;
} else {
	die( 'This version of the Josa extension requires MediaWiki 1.25+' );
}

Comment out deprecated PHP entry point warning for now

Until Wikimedia production switches to wfLoadExtension() directly.

Change-Id: I96d17f28181d9b21a20a4576fafb5384994b05d1


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddVerificationTokenColumnToUsersTable extends Migration {
    public function up() {
        Schema::table('users', function (Blueprint $table) {
            $table->string('verification_token', 100)->nullable()->before('remember_token');
        });
    }

    public function down() {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('verification_token');
        });
    }
}

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddVerificationTokenColumnToUsersTable extends Migration {
    public function up() {
        Schema::table('users', function (Blueprint $table) {
            $table->string('verification_token', 100)->nullable()->after('password');
        });
    }

    public function down() {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('verification_token');
        });
    }
}

Fix migration that adds verification_token column to place it in correct position


<?php namespace Milkyway\SS\FlashMessage;

use Controller as Original;

class Controller extends Original
{
    private static $allowed_actions = [
        'refresh',
    ];

    private static $url_handlers = [
        '$Area!' => 'refresh',
    ];

    /**
     * Grab available notifications
     *
     * @param $request
     * @return array|\SS_HTTPResponse|void
     * @throws \SS_HTTPResponse_Exception
     */
    public function refresh($request) {
        // Only available via AJAX
        if(!$request->isAjax()) {
            return $this->httpError(404);
        }

        $area = $request->param('Area');

        // If no area specified, do nothing
        if(!$area) {
            return [];
        }

        $response = $this->getResponse();
        $response->addHeader('Content-type', 'application/json');
        $response->setBody(json_encode(singleton('message')->$area()->get()));
        return $response;
    }

    public function Link($area = '') {
        return $this->join_links('notifications', $area);
    }
}

<?php namespace Milkyway\SS\FlashMessage;

use Controller as Original;

class Controller extends Original
{
    private static $allowed_actions = [
        'refresh',
    ];

    private static $url_handlers = [
        '$Area!' => 'refresh',
    ];

    /**
     * Grab available notifications
     *
     * @param $request
     * @return array|\SS_HTTPResponse|void
     * @throws \SS_HTTPResponse_Exception
     */
    public function refresh($request) {
        // Only available via AJAX
        if(!$request->isAjax()) {
            return $this->httpError(404);
        }

        $area = $request->param('Area');
        singleton('require')->clear();

        // If no area specified, do nothing
        if(!$area) {
            return [];
        }

        $response = $this->getResponse();
        $response->addHeader('Content-type', 'application/json');
        $response->setBody(json_encode(singleton('message')->$area()->get()));
        return $response;
    }

    public function Link($area = '') {
        return $this->join_links('notifications', $area);
    }
}

FIX: Make sure requirements are cleared before sending notifications


<?php

namespace Backend\Modules\ContentBlocks\Tests\Action;

use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

class IndexTest extends BackendWebTestCase
{
    public function testAuthenticationIsNeeded(Client $client): void
    {
        self::assertAuthenticationIsNeeded($client, '/private/en/content_blocks/index');
    }

    public function testIndexHasNoItems(Client $client): void
    {
        $this->login($client);

        self::assertPageLoadedCorrectly(
            $client,
            '/private/en/content_blocks/index',
            [
                'There are no content blocks yet.',
                'Add content block',
                'Add a content block',
            ]
        );
    }
}

<?php

namespace Backend\Modules\ContentBlocks\Tests\Action;

use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

class IndexTest extends BackendWebTestCase
{
    public function testAuthenticationIsNeeded(Client $client): void
    {
        self::assertAuthenticationIsNeeded($client, '/private/en/content_blocks/index');
    }

    public function testIndexHasNoItems(Client $client): void
    {
        $this->login($client);

        self::assertPageLoadedCorrectly(
            $client,
            '/private/en/content_blocks/index',
            [
                'There are no content blocks yet.',
                'Add content block',
            ]
        );
    }
}

Fix translation failing on github

Fix translation failing on github


<?php
return array(
    'module_layouts' => array(
        'ZfcUser' => 'layout/layout-small-header.phtml',
        'ZfModule' => 'layout/layout-small-header.phtml',
    ),
    'asset_manager' => array(
        'caching' => array(
            'default' => array(
                'cache'     => 'FilePath',  // Apc, FilePath, FileSystem etc.
                'options' => array(
                    'dir' => 'public',
                ),
            ),
        ),
    ),
    'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ),
    ),
    'db' => array(
        'driver'    => 'pdo',
        'dsn'       => 'mysql:dbname=modules;host=localhost',
        'username'  => 'modules',
        'password'  => 'modules',
    ),
);

<?php
return array(
    'module_layouts' => array(
        'ZfcUser' => 'layout/layout-small-header.phtml',
        'ZfModule' => 'layout/layout-small-header.phtml',
    ),
    'asset_manager' => array(
        'caching' => array(
            'default' => array(
                'cache'     => 'FilePath',  // Apc, FilePath, FileSystem etc.
                'options' => array(
                    'dir' => 'public',
                ),
            ),
        ),
    ),
    'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ),
        'invokables' => array(
            'Zend\Session\SessionManager' => 'Zend\Session\SessionManager',
        ),
    ),
    'db' => array(
        'driver'    => 'pdo',
        'dsn'       => 'mysql:dbname=modules;host=localhost',
        'username'  => 'modules',
        'password'  => 'modules',
    ),
);

Add session manager by default

Add session manager by default


<?php

declare(strict_types=1);

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTagsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create(config('rinvex.tags.tables.tags'), function (Blueprint $table) {
            // Columns
            $table->increments('id');
            $table->string('slug');
            $table->{$this->jsonable()}('name');
            $table->{$this->jsonable()}('description')->nullable();
            $table->mediumInteger('sort_order')->unsigned()->default(0);
            $table->string('group')->nullable();
            $table->timestamps();
            $table->softDeletes();

            // Indexes
            $table->unique('slug');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists(config('rinvex.tags.tables.tags'));
    }

    /**
     * Get jsonable column data type.
     *
     * @return string
     */
    protected function jsonable(): string
    {
        $driverName = DB::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME);
        $dbVersion = DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION);
        $isOldVersion = version_compare($dbVersion, '5.7.8', 'lt');

        return $driverName === 'mysql' && $isOldVersion ? 'text' : 'json';
    }
}

<?php

declare(strict_types=1);

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTagsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create(config('rinvex.tags.tables.tags'), function (Blueprint $table) {
            // Columns
            $table->increments('id');
            $table->string('slug');
            $table->json('name');
            $table->json('description')->nullable();
            $table->mediumInteger('sort_order')->unsigned()->default(0);
            $table->string('group')->nullable();
            $table->timestamps();
            $table->softDeletes();

            // Indexes
            $table->unique('slug');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists(config('rinvex.tags.tables.tags'));
    }
}

Drop old MySQL versions support that doesn't support json columns


<?php

	class Extension_CoreDevKit extends Extension {
	/*-------------------------------------------------------------------------
		Definition:
	-------------------------------------------------------------------------*/

		public function getSubscribedDelegates() {
			return array(
						array(
							'page'		=> '/backend/',
							'delegate'	=> 'InitaliseAdminPageHead',
							'callback'	=> 'initaliseAdminPageHead'
						),
					);
		}

		public function initaliseAdminPageHead($context) {
			error_reporting(E_ALL);
			ini_set('display_errors', 1);
		}

	}

?>

Enable Errors when extension is enabled

Enable Errors when extension is enabled


<?php

namespace Gitlist\Util;

use Silex\Application;

class Routing
{
    protected $app;

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

    public function getRepositoryRegex()
    {
        static $regex = null;

        if ($regex === null) {
            $app = $this->app;
            $quoted_paths = array_map(
                function ($repo) use ($app) {
                    return preg_quote($app['util.routing']->getRelativePath($repo['path']), '#');
                },
                $this->app['git']->getRepositories($this->app['git.repos'])
            );
            $regex = '/' . implode('|', $quoted_paths) . '/';
        }

        return $regex;
    }

    /**
     * Strips the base path from a full repository path
     *
     * @param string $repo_path Full path to the repository
     * @return string Relative path to the repository from git.repositories
     */
    public function getRelativePath($repo_path)
    {
        if (strpos($repo_path, $this->app['git.repos']) === 0) {
            $relative_path = substr($repo_path, strlen($this->app['git.repos']));
            return ltrim($relative_path, '/');
        } else {
            throw new \InvalidArgumentException(
                sprintf("Path '%s' does not match configured repository directory", $repo_path)
            );
        }
    }
}

<?php

namespace Gitlist\Util;

use Silex\Application;

class Routing
{
    protected $app;

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

    public function getRepositoryRegex()
    {
        static $regex = null;

        if ($regex === null) {
            $app = $this->app;
            $quoted_paths = array_map(
                function ($repo) use ($app) {
                    return preg_quote($app['util.routing']->getRelativePath($repo['path']), '#');
                },
                $this->app['git']->getRepositories($this->app['git.repos'])
            );
            $regex = implode('|', $quoted_paths);
        }

        return $regex;
    }

    /**
     * Strips the base path from a full repository path
     *
     * @param string $repo_path Full path to the repository
     * @return string Relative path to the repository from git.repositories
     */
    public function getRelativePath($repo_path)
    {
        if (strpos($repo_path, $this->app['git.repos']) === 0) {
            $relative_path = substr($repo_path, strlen($this->app['git.repos']));
            return ltrim($relative_path, '/');
        } else {
            throw new \InvalidArgumentException(
                sprintf("Path '%s' does not match configured repository directory", $repo_path)
            );
        }
    }
}

Remove delimiters from repository regex

Remove delimiters from repository regex


<?php

namespace Core;

class Router
{

    private $routes = array();
    private static $_instance;

    public static function getInstance()
    {
        if(is_null(self::$_instance))
        {
            self::$_instance = new Router();
        }
        return self::$_instance;
    }

    public function __construct()
    {
        $this->routes = require dirname(__DIR__) . '/config/routes.php';
    }

    public function get($key)
    {
        if(array_key_exists($key, $this->routes))
        {
            return $this->routes[$key];
        }
        else
        {
            return $this->_findWithoutArgs($key);
        }
    }

    public function getController($key)
    {
        if($this->get($key))
        {
            return $this->get($key)[0];
        }
        else
        {
            return null;
        }
    }

    public function getMethod($key)
    {
        if($this->get($key))
        {
            return $this->get($key)[1];
        }
        else
        {
            return null;
        }
    }

    private function _findWithoutArgs($key)
    {
        $next_key = substr_replace($key, '', strrpos($key, '/'));

        if(strlen($next_key) > 0)
        {
            return $this->get($next_key);
        }
        else
        {
            return null;
        }
    }

}

<?php

namespace Core;

class Router
{

    private $routes = array();

    public function __construct()
    {
        $this->routes = require dirname(__DIR__) . '/config/routes.php';
    }

    public function get($key)
    {
        if(array_key_exists($key, $this->routes))
        {
            return $this->routes[$key];
        }
        else
        {
            return $this->_findWithoutArgs($key);
        }
    }

    public function getController($key)
    {
        if($this->get($key))
        {
            return $this->get($key)[0];
        }
        else
        {
            return null;
        }
    }

    public function getMethod($key)
    {
        if($this->get($key))
        {
            return $this->get($key)[1];
        }
        else
        {
            return null;
        }
    }

    private function _findWithoutArgs($key)
    {
        $next_key = substr_replace($key, '', strrpos($key, '/'));

        if(strlen($next_key) > 0)
        {
            return $this->get($next_key);
        }
        else
        {
            return null;
        }
    }

}

Remove getInstance thanks to DI

Remove getInstance thanks to DI


<?php

$DATABASE_UNINSTALL = array(
"drop table if exists {$CFG->dbprefix}context_map"
);

$DATABASE_INSTALL = array(
array( "{$CFG->dbprefix}context_map",
"create table {$CFG->dbprefix}context_map (
    context_id  INTEGER NOT NULL,
    user_id     INTEGER NOT NULL,
    lat         FLOAT,
    lng         FLOAT,
    color       INTEGER,
    updated_at  DATETIME NOT NULL,

    CONSTRAINT `{$CFG->dbprefix}context_map_ibfk_1`
        FOREIGN KEY (`context_id`)
        REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`)
        ON DELETE CASCADE ON UPDATE CASCADE,

    CONSTRAINT `{$CFG->dbprefix}context_map_ibfk_2`
        FOREIGN KEY (`user_id`)
        REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
        ON DELETE CASCADE ON UPDATE CASCADE,

    UNIQUE(context_id, user_id, attend)
) ENGINE = InnoDB DEFAULT CHARSET=utf8")

);

<?php

$DATABASE_UNINSTALL = array(
"drop table if exists {$CFG->dbprefix}context_map"
);

$DATABASE_INSTALL = array(
array( "{$CFG->dbprefix}context_map",
"create table {$CFG->dbprefix}context_map (
    context_id  INTEGER NOT NULL,
    user_id     INTEGER NOT NULL,
    lat         FLOAT,
    lng         FLOAT,
    color       INTEGER,
    updated_at  DATETIME NOT NULL,

    CONSTRAINT `{$CFG->dbprefix}context_map_ibfk_1`
        FOREIGN KEY (`context_id`)
        REFERENCES `{$CFG->dbprefix}lti_context` (`context_id`)
        ON DELETE CASCADE ON UPDATE CASCADE,

    CONSTRAINT `{$CFG->dbprefix}context_map_ibfk_2`
        FOREIGN KEY (`user_id`)
        REFERENCES `{$CFG->dbprefix}lti_user` (`user_id`)
        ON DELETE CASCADE ON UPDATE CASCADE,

    UNIQUE(context_id, user_id)
) ENGINE = InnoDB DEFAULT CHARSET=utf8")

);

Fix the mistaken use of attend in the UNIQUE clause.


<?php

namespace Kaloa\Util\TypeSafety;

use IllegalArgumentException;

trait TypeSafetyTrait
{
    /**
     * @param string $types
     * @param array $args
     */
    private function ensure($types, array $args)
    {
        if (!is_string($types)) {
            throw new IllegalArgumentException('string expected');
        }

        $cnt = count($args);

        if (strlen($types) !== $cnt) {
            throw new IllegalArgumentException('type count does not match argument count');
        }

        for ($i = 0; $i < $cnt; $i++) {
            switch ($types[$i]) {
                case 'b':
                    if (!is_bool($args[$i])) {
                        throw new IllegalArgumentException('bool expected');
                    }
                    break;

                case 'f':
                    if (!is_float($args[$i])) {
                        throw new IllegalArgumentException('float expected');
                    }
                    break;

                case 'i':
                    if (!is_int($args[$i])) {
                        throw new IllegalArgumentException('int expected');
                    }
                    break;

                case 'r':
                    if (!is_resource($args[$i])) {
                        throw new IllegalArgumentException('resource expected');
                    }
                    break;

                case 's':
                    if (!is_string($args[$i])) {
                        throw new IllegalArgumentException('string expected');
                    }
                    break;

                case '-':
                    /* skip */
                    break;

                default:
                    throw new IllegalArgumentException('Unknown type at offset ' . $i . '. One of [bfirs-] expected');
                    break;
            }
        }
    }
}

<?php

namespace Kaloa\Util\TypeSafety;

use IllegalArgumentException;

trait TypeSafetyTrait
{
    /**
     * @param string $types
     * @param array $args
     */
    private function ensure($types, array $args)
    {
        if (!is_string($types)) {
            throw new IllegalArgumentException('Type list must be of type string');
        }

        $cnt = count($args);

        if (strlen($types) !== $cnt) {
            throw new IllegalArgumentException('Type list length does not match argument count');
        }

        $i = 0;

        foreach ($args as $arg) {
            switch ($types[$i]) {
                case 'b':
                    if (!is_bool($arg)) {
                        throw new IllegalArgumentException('bool expected');
                    }
                    break;

                case 'f':
                    if (!is_float($arg)) {
                        throw new IllegalArgumentException('float expected');
                    }
                    break;

                case 'i':
                    if (!is_int($arg)) {
                        throw new IllegalArgumentException('int expected');
                    }
                    break;

                case 'r':
                    if (!is_resource($arg)) {
                        throw new IllegalArgumentException('resource expected');
                    }
                    break;

                case 's':
                    if (!is_string($arg)) {
                        throw new IllegalArgumentException('string expected');
                    }
                    break;

                case '-':
                    /* skip */
                    break;

                default:
                    throw new IllegalArgumentException('Unknown type at offset ' . $i . '. One of [bfirs-] expected');
                    break;
            }

            $i++;
        }
    }
}

TypeSafety: Support non-zero-indexed arrays in ensure(). Improve phrasing of Exception messages


<?php

namespace Chalcedonyt\COSProcessor\Providers;
use Illuminate\Support\ServiceProvider;

class COSProcessorServiceProvider extends ServiceProvider
{
    protected $templates = [];

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $source_config = __DIR__ . '/../../config/cos_processor.php';
        $this->publishes([
            $source_config => base_path('config/cos_processor.php'),
            __DIR__.'/../views/provider.php' => base_path('app/Providers/COSProcessorServiceProvider.php')
        ]);

        // $this->loadViewsFrom(__DIR__ . '/../views', 'cos_processor');
    }

    /**
     * Register any package services.
     *
     * @return void
     */
    public function register()
    {
        $source_config = __DIR__ . '/../../config/cos_processor.php';
        $this->mergeConfigFrom($source_config, 'cos_processor');
    }
}

<?php

namespace Chalcedonyt\COSProcessor\Providers;
use Illuminate\Support\ServiceProvider;

class COSProcessorServiceProvider extends ServiceProvider
{
    protected $templates = [];

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $source_config = __DIR__ . '/../../config/cos_processor.php';
        $this->publishes([
            $source_config => base_path('config/cos_processor.php')
        ]);

        // $this->loadViewsFrom(__DIR__ . '/../views', 'cos_processor');
    }

    /**
     * Register any package services.
     *
     * @return void
     */
    public function register()
    {
        $source_config = __DIR__ . '/../../config/cos_processor.php';
        $this->mergeConfigFrom($source_config, 'cos_processor');
    }
}

Correct a typo in the service provider

Correct a typo in the service provider


<?php

namespace SlmMail\Mail\Message\Provider;

use SlmMail\Mail\Message\ProvidesOptions;
use SlmMail\Mail\Message\ProvidesTags;
use Zend\Mail\Message;

class Mailgun extends Message
{
    use ProvidesOptions;

    const TAG_LIMIT = 3;

    /**
     * @var array
     */
    protected $tags = array();

    /**
     * Get all tags for this message
     *
     * @return array
     */
    public function getTags()
    {
        return $this->tags;
    }

    /**
     * Set all tags for this message
     *
     * @param  array $tags
     * @return self
     */
    public function setTags(array $tags)
    {
        if (count($tags) > self::TAG_LIMIT) {
            throw new Exception\InvalidArgumentException(sprintf(
                'Mailgun only allows up to %s tags', self::TAG_LIMIT
            ));
        }
        $this->tags = $tags;
        return $this;
    }

    /**
     * Add a tag to this message
     *
     * @param string $tag
     */
    public function addTag($tag)
    {
        if (count($this->tags)+1 > self::TAG_LIMIT) {
            throw new Exception\InvalidArgumentException(sprintf(
                'Mailgun only allows up to %s tags', self::TAG_LIMIT
            ));
        }

        $this->tags[] = (string) $tag;
    }
}

<?php

namespace SlmMail\Mail\Message\Provider;

use SlmMail\Mail\Message\ProvidesOptions;
use SlmMail\Mail\Message\ProvidesTags;
use Zend\Mail\Message;

class Mailgun extends Message
{
    use ProvidesOptions;

    const TAG_LIMIT = 3;

    /**
     * @var array
     */
    protected $tags = array();

    /**
     * Get all tags for this message
     *
     * @return array
     */
    public function getTags()
    {
        return $this->tags;
    }

    /**
     * Set all tags for this message
     *
     * @param  array $tags
     * @return self
     */
    public function setTags(array $tags)
    {
        if (count($tags) > self::TAG_LIMIT) {
            throw new Exception\InvalidArgumentException(sprintf(
                'Mailgun only allows up to %s tags', self::TAG_LIMIT
            ));
        }
        $this->tags = $tags;
        return $this;
    }

    /**
     * Add a tag to this message
     *
     * @param string $tag
     * @return self
     */
    public function addTag($tag)
    {
        if (count($this->tags)+1 > self::TAG_LIMIT) {
            throw new Exception\InvalidArgumentException(sprintf(
                'Mailgun only allows up to %s tags', self::TAG_LIMIT
            ));
        }

        $this->tags[] = (string) $tag;
        return $this;
    }
}

Return $this after adding a tag

Return $this after adding a tag


<?php

namespace libphonenumber\prefixmapper;

/**
 * A utility which knows the data files that are available for the phone prefix mappers to use.
 * The data files contain mappings from phone number prefixes to text descriptions, and are
 * organized by country calling code and language that the text descriptions are in.
 *
 * Class MappingFileProvider
 * @package libphonenumber\prefixmapper
 */
class MappingFileProvider
{

    private $map;

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

    public function getFileName($countryCallingCode, $language, $script, $region)
    {
        if (strlen($language) == 0) {
            return "";
        }

        if ($this->inMap($language, $countryCallingCode)) {
            return $language . DIRECTORY_SEPARATOR . $countryCallingCode . '.php';
        }

        return "";
    }

    private function inMap($language, $countryCallingCode)
    {
        return (array_key_exists($language, $this->map) && in_array($countryCallingCode, $this->map[$language]));
    }

}

<?php

namespace libphonenumber\prefixmapper;

/**
 * A utility which knows the data files that are available for the phone prefix mappers to use.
 * The data files contain mappings from phone number prefixes to text descriptions, and are
 * organized by country calling code and language that the text descriptions are in.
 *
 * Class MappingFileProvider
 * @package libphonenumber\prefixmapper
 */
class MappingFileProvider
{

    private $map;

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

    public function getFileName($countryCallingCode, $language, $script, $region)
    {
        if (strlen($language) == 0) {
            return "";
        }

        if ($language === 'zh' && ($region == 'TW' || $region == 'HK' || $region == 'MO')) {
            $language = 'zh_Hant';
        }

        if ($this->inMap($language, $countryCallingCode)) {
            return $language . DIRECTORY_SEPARATOR . $countryCallingCode . '.php';
        }

        return "";
    }

    private function inMap($language, $countryCallingCode)
    {
        return (array_key_exists($language, $this->map) && in_array($countryCallingCode, $this->map[$language]));
    }

}

Fix mapping file for zh_Hant

Fix mapping file for zh_Hant


<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::post('check', [
    'middleware' => ['connection', 'auth'],
    'uses' => 'WisePayController@check'
]);

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::post('auth', [
    'middleware' => ['connection', 'auth'],
    'uses' => 'WisePayController@authUser'
]);

Route::post('check', [
    'middleware' => ['connection', 'auth'],
    'uses' => 'WisePayController@check'
]);

Add route to just authenticate user

Add route to just authenticate user


<?php
    defined('M2_MICRO') or die('Direct Access to this location is not allowed.');

    /**
      * Sef map array
      * @name $sef_map
      * @package M2 Micro Framework
      * @subpackage Library
      * @author Alexander Chaika
      * @since 0.2RC1
      */

    return array(
        '/\?module\=blog\&action\=show\&id\=(.*)/' => array(
            'table'  => 'post',
            'field'  => 'alias',
            'prefix' => '/blog/',
            'suffix' => $config['sef_suffix']
        ),
        '/\?module\=blog\&action\=category\&id\=(.*)/' => array(
            'table'  => 'category',
            'field'  => 'alias',
            'prefix' => '/category/',
            'suffix' => $config['sef_suffix']
        )
    );

<?php
    defined('M2_MICRO') or die('Direct Access to this location is not allowed.');

    /**
      * Sef map array
      * @name $sef_map
      * @package M2 Micro Framework
      * @subpackage Library
      * @author Alexander Chaika
      * @since 0.2RC1
      */

    return array(
        '/\?module\=blog\&action\=show\&id\=(.*)/' => array(
            'table'  => 'post',
            'field'  => 'alias',
            'prefix' => '/blog/',
            'suffix' => Application::$config['sef_suffix']
        ),
        '/\?module\=blog\&action\=category\&id\=(.*)/' => array(
            'table'  => 'category',
            'field'  => 'alias',
            'prefix' => '/category/',
            'suffix' => Application::$config['sef_suffix']
        )
    );

Fix sef map config provider

Fix sef map config provider


<?php
namespace Amara\Bundle\OneHydraBundle\State;

use Amara\Bundle\OneHydraBundle\Object\PageObject;

class CurrentPageState {

	/** @var PageObject */
	private $page = null;

	/**
	 * @return PageObject
	 */
	public function getPage() {
		return $this->page;
	}

	/**
	 * @param PageObject $page
	 */
	public function setPage(PageObject $page) {
		$this->page = $page;
	}
}

<?php
namespace Amara\Bundle\OneHydraBundle\State;

use Amara\OneHydra\Object\PageObject;

class CurrentPageState {

	/** @var PageObject */
	private $page = null;

	/**
	 * @return PageObject
	 */
	public function getPage() {
		return $this->page;
	}

	/**
	 * @param PageObject $page
	 */
	public function setPage(PageObject $page) {
		$this->page = $page;
	}
}

Fix current page object type

Fix current page object type


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\twig;

/**
 * Template base class
 *
 * @author Alexei Tenitski <alexei@ten.net.nz>
 */
abstract class Template extends \Twig_Template
{
    protected function getAttribute($object, $item, array $arguments = array(), $type = \Twig_Template::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false)
    {
        // Twig uses isset() to check if attribute exists which does not work when attribute exists but is null

        if ($object instanceof \yii\db\BaseActiveRecord) {
            return $object->$item;
        }

        return parent::getAttribute($object, $item, $arguments, $type, $isDefinedTest, $ignoreStrictCheck);
    }
}

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\twig;

/**
 * Template base class
 *
 * @author Alexei Tenitski <alexei@ten.net.nz>
 */
abstract class Template extends \Twig_Template
{
    protected function getAttribute($object, $item, array $arguments = array(), $type = \Twig_Template::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false)
    {
        // Twig uses isset() to check if attribute exists which does not work when attribute exists but is null

        if ($object instanceof \yii\db\BaseActiveRecord) {
            if ($type == \Twig_Template::METHOD_CALL) {
                return $object->$item();
            } else {
                return $object->$item;
            }
        }

        return parent::getAttribute($object, $item, $arguments, $type, $isDefinedTest, $ignoreStrictCheck);
    }
}

Support for method calls on models from Twig templates


@extends('layout')

@section('body')

                        @lang('general.tags')

                        @lang('actions.create')

                @foreach ($tags as $tag)

{{ $tag->name }}

                            <form class="action" method="POST" action="/tags/{{ $tag->id }}">
                                {{ method_field('delete') }}
                                {{ csrf_field() }}
                                <button>@lang('actions.delete')</button>
                            </form>

                @endforeach

@endsection

@extends('layout')

@section('body')

                        @lang('general.tags')

                        @lang('actions.create')

            @if (count($tags) > 0)

                    @foreach ($tags as $tag)

{{ $tag->name }}

                                <form class="action" method="POST" action="/tags/{{ $tag->id }}">
                                    {{ method_field('delete') }}
                                    {{ csrf_field() }}
                                    <button>@lang('actions.delete')</button>
                                </form>

                    @endforeach

            @else

You don't have any tags

            @endif

@endsection

Fix empty void when user has no tags for tags' index view


<?php
declare(strict_types=1);
namespace Onion\Framework\Controller;

use GuzzleHttp\Psr7\Stream;
use Onion\Framework\Rest\Interfaces\EntityInterface as Entity;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

abstract class RestController implements MiddlewareInterface
{
    private function getEmptyStream(string $mode = 'r'): StreamInterface
    {
        return new Stream(fopen('php://memory', $mode));
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $httpMethod = strtolower($request->getMethod());
        if ($httpMethod === 'head' && !method_exists('head')) {
            $httpMethod = 'get';
        }

        if (!method_exists($this, $httpMethod)) {
            throw new \BadMethodCallException('method not implemented');
        }

        /** @var ResponseInterface $entity */
        $response = $this->{$httpMethod}($request, $handler);

        if ($httpMethod === 'head') {
            $response = $response->withBody($this->getEmptyStream());
        }

        return $response;
    }
}

<?php
declare(strict_types=1);
namespace Onion\Framework\Controller;

use GuzzleHttp\Psr7\Stream;
use Onion\Framework\Rest\Interfaces\EntityInterface as Entity;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

abstract class RestController implements MiddlewareInterface
{
    private const HTTP_METHODS = [
        'get',
        'head',
        'post',
        'put',
        'patch',
        'options',
        'connect',
        'delete',
    ];

    private function getEmptyStream(string $mode = 'r'): StreamInterface
    {
        return new Stream(fopen('php://memory', $mode));
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $httpMethod = strtolower($request->getMethod());
        if ($httpMethod === 'head' && !method_exists('head')) {
            $httpMethod = 'get';
        }

        if (!method_exists($this, $httpMethod)) {
            throw new \BadMethodCallException('method not implemented');
        }

        /** @var ResponseInterface $response */
        $response = $this->{$httpMethod}($request, $handler);

        if ($httpMethod === 'head') {
            $response = $response->withBody($this->getEmptyStream());
        }

        if ($httpMethod === 'options') {
            $ref = new \ReflectionObject($this);
            $response = $response->withAddedHeader('allow', array_intersect(
                self::HTTP_METHODS,
                $ref->getMethods(\ReflectionMethod::IS_PUBLIC)
            ));
        }

        return $response;
    }
}

Add `Allow` header to OPTIONS requests

Add `Allow` header to OPTIONS requests


<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

Add relationship between users and roles table


<?php
class Vpc_Abstract_List_Form extends Vps_Form_NonTableForm
{
    public function __construct($name, $class)
    {
        parent::__construct($name, $class);
        $this->setProperty('class', $class);
        $this->add($this->_getMultiFields());
    }

    protected function _getMultiFields()
    {
        $multifields = new Vpc_Abstract_Field_MultiFields($this->getClass());
        $multifields->setReferences(array(
            'columns' => array('component_id'),
            'refColumns' => array('id')
        ));
        $multifields->setMinEntries(0);
        $multifields->fields->add(new Vps_Form_Field_Checkbox('visible', trlVps('Visible')));
        $multifields->setPosition(true);

        $form = Vpc_Abstract_Form::createChildComponentForm($this->getClass(), 'child');
        $form->setIdTemplate('{component_id}-{id}');
        $multifields->fields->add($form);

        return $multifields;
    }

}

<?php
class Vpc_Abstract_List_Form extends Vpc_Abstract_Form
{
    public function __construct($name, $class)
    {
        parent::__construct($name, $class);
        $this->setProperty('class', $class);
        $this->add($this->_getMultiFields());
    }

    protected function _getMultiFields()
    {
        $multifields = new Vps_Form_Field_MultiFields('Children');
        $multifields->setMinEntries(0);
        $multifields->fields->add(new Vps_Form_Field_Checkbox('visible', trlVps('Visible')));
        $multifields->setPosition(true);

        $form = Vpc_Abstract_Form::createChildComponentForm($this->getClass(), 'child');
        $form->setIdTemplate('{component_id}-{id}');
        $multifields->fields->add($form);

        return $multifields;
    }

}

Fix MultiFields admin mit unterkomponenten

statt NonTableForm Form mit OwnModel verwenden, das es ja jetzt gibt.
Macht alles viel einfacher.

problem war dass die list row _nach_ der child row gespeichert wurde und die
child row daher keine id hatte

(von niko)


<?php
define('FRESHRSS_VERSION', '0.8-dev');
define('FRESHRSS_WEBSITE', 'http://freshrss.org');

// Constantes de chemins
define('FRESHRSS_PATH', dirname(__FILE__));

	define('PUBLIC_PATH', FRESHRSS_PATH . '/p');
		define('INDEX_PATH', PUBLIC_PATH . '/i');
		define('PUBLIC_RELATIVE', '..');

	define('DATA_PATH', FRESHRSS_PATH . '/data');
		define('LOG_PATH', DATA_PATH . '/log');
		define('CACHE_PATH', DATA_PATH . '/cache');

	define('LIB_PATH', FRESHRSS_PATH . '/lib');
		define('APP_PATH', FRESHRSS_PATH . '/app');

define('TMP_PATH', sys_get_temp_dir());

<?php
define('FRESHRSS_VERSION', '0.8-dev');
define('FRESHRSS_WEBSITE', 'http://freshrss.org');

// Constantes de chemins
define('FRESHRSS_PATH', dirname(__FILE__));

	define('PUBLIC_PATH', FRESHRSS_PATH . '/p');
		define('INDEX_PATH', PUBLIC_PATH . '/i');
		define('PUBLIC_RELATIVE', '..');

	define('DATA_PATH', FRESHRSS_PATH . '/data');
		define('LOG_PATH', DATA_PATH . '/log');
		define('CACHE_PATH', DATA_PATH . '/cache');

	define('LIB_PATH', FRESHRSS_PATH . '/lib');
		define('APP_PATH', FRESHRSS_PATH . '/app');

//define('TMP_PATH', sys_get_temp_dir());  // need more tests so...
define('TMP_PATH', DATA_PATH);  // ... we use DATA_PATH for the 0.7.1

Switch TMP_PATH to DATA_PATH for the 0.7.1

See https://github.com/marienfressinaud/FreshRSS/issues/420#issuecomment-35423003


<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace Imbo\IntegrationTest\Storage;

use Imbo\Storage\S3;

/**
 * @author Christer Edvartsen <cogo@starzinger.net>
 * @package Test suite\Integration tests
 */
class S3Test extends StorageTests {
    /**
     * @see Imbo\IntegrationTest\Storage\StorageTests::getDriver()
     */
    protected function getDriver() {
        return new S3(array(
            'key' => $GLOBALS['AWS_S3_KEY'],
            'secret' => $GLOBALS['AWS_S3_SECRET'],
            'bucket' => $GLOBALS['AWS_S3_BUCKET'],
        ));
    }

    /**
     * Make sure we have the correct config available
     */
    public function setUp() {
        foreach (array('AWS_S3_KEY', 'AWS_S3_SECRET', 'AWS_S3_BUCKET') as $key) {
            if (empty($GLOBALS[$key])) {
                $this->markTestSkipped('This test needs the ' . $key . ' value to be set in phpunit.xml');
            }
        }

        parent::setUp();
    }
}

<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace Imbo\IntegrationTest\Storage;

use Imbo\Storage\S3,
    Aws\S3\S3Client;

/**
 * @author Christer Edvartsen <cogo@starzinger.net>
 * @package Test suite\Integration tests
 */
class S3Test extends StorageTests {
    /**
     * @see Imbo\IntegrationTest\Storage\StorageTests::getDriver()
     */
    protected function getDriver() {
        return new S3(array(
            'key' => $GLOBALS['AWS_S3_KEY'],
            'secret' => $GLOBALS['AWS_S3_SECRET'],
            'bucket' => $GLOBALS['AWS_S3_BUCKET'],
        ));
    }

    /**
     * Make sure we have the correct config available
     */
    public function setUp() {
        foreach (array('AWS_S3_KEY', 'AWS_S3_SECRET', 'AWS_S3_BUCKET') as $key) {
            if (empty($GLOBALS[$key])) {
                $this->markTestSkipped('This test needs the ' . $key . ' value to be set in phpunit.xml');
            }
        }

        $client = S3Client::factory(array(
            'key' => $GLOBALS['AWS_S3_KEY'],
            'secret' => $GLOBALS['AWS_S3_SECRET'],
        ));
        $client->clearBucket($GLOBALS['AWS_S3_BUCKET']);

        parent::setUp();
    }
}

Clean up before each test

Clean up before each test


<?php
\Cake\Datasource\FactoryLocator::add('Endpoint', [Muffin\Webservice\Model\EndpointRegistry::class, 'get']);

<?php
use Cake\Datasource\FactoryLocator;
use Muffin\Webservice\Model\EndpointLocator;

FactoryLocator::add('Endpoint', [new EndpointLocator(), 'get']);

Use EndpointLocator instead of EndpointRegistry.


<?
define('E_REPORTING', E_ALL & ~E_NOTICE);
error_reporting(E_REPORTING);
ini_set('display_errors', 'On');
define('TIME_START', microtime(true));
define('ROOT', dirname(dirname(__FILE__)));
define('CONFIG_ROOT', dirname(dirname(dirname(__FILE__))).'/config');
define('PROJECT', strtolower(isset($_ENV["PROJECT"]) ? $_ENV["PROJECT"] : null));
define('PROJECT_ROOT', dirname(ROOT).'/appers/'.PROJECT);
define('PROJECTS_ROOT', dirname(ROOT).'/appers');
define('EXEC_PATH', __FILE__);
require ROOT.'/lib/application/loader.php';
loader::init();
config::init();
if(config::get('restartWorkersOnChange')) {
	if(loader::isFilesChanged()) {
		bg::restartWorkers();
	}
}
cli::run(array_slice($argv,1));

<?
define('E_REPORTING', E_ALL & ~E_NOTICE);
error_reporting(E_REPORTING);
ini_set('display_errors', 'On');
define('TIME_START', microtime(true));
define('ROOT', dirname(dirname(__FILE__)));
define('CONFIG_ROOT', dirname(dirname(dirname(__FILE__))).'/config');
define('PROJECT', strtolower(isset($_ENV["PROJECT"]) ? $_ENV["PROJECT"] : null));
define('PROJECT_ROOT', PROJECT ? dirname(ROOT).'/appers/'.PROJECT : null);
define('PROJECTS_ROOT', dirname(ROOT).'/appers');
define('EXEC_PATH', __FILE__);
require ROOT.'/lib/application/loader.php';
loader::init();
config::init();
if(config::get('restartWorkersOnChange')) {
	if(loader::isFilesChanged()) {
		bg::restartWorkers();
	}
}
cli::run(array_slice($argv,1));

Fix - in cli mode PROJECT_ROOT was not empty when script was run not from project.


<?php

/**
 * If the queued jobs module is installed, this will be used for offline processing of Zip files.
 *
 * @author  Mark Guinn <mark@adaircreative.com>
 * @date    05.09.2016
 * @package shop_downloadable
 */
if (!interface_exists('QueuedJob')) {
    return;
}

class FilePrepQueuedJob extends AbstractQueuedJob implements QueuedJob
{
    /**
     * The QueuedJob queue to use when processing updates
     * @config
     * @var int
     */
    private static $reindex_queue = 2; // QueuedJob::QUEUED;

    /**
     * @param DownloadTempFile $object
     */
    public function __construct($object)
    {
        $this->setObject($object);
    }

    /**
     * Helper method
     */
    public function triggerProcessing()
    {
        singleton('QueuedJobService')->queueJob($this);
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        /** @var DownloadTempFile $obj */
        $obj = $this->getObject();
        return "Prep File For Download: " . ($obj ? $obj->getFriendlyName() : '???');
    }

    /**
     * Reprocess any needed fields
     */
    public function process()
    {
        ini_set('memory_limit', '1G');

        /** @var DownloadTempFile $obj */
        $obj = $this->getObject();
        $obj->process();
        $this->isComplete = true;
    }
}

<?php

/**
 * If the queued jobs module is installed, this will be used for offline processing of Zip files.
 *
 * @author  Mark Guinn <mark@adaircreative.com>
 * @date    05.09.2016
 * @package shop_downloadable
 */
if (!interface_exists('QueuedJob')) {
    return;
}

class FilePrepQueuedJob extends AbstractQueuedJob implements QueuedJob
{
    /**
     * The QueuedJob queue to use when processing updates
     * @config
     * @var int
     */
    private static $reindex_queue = 2; // QueuedJob::QUEUED;

    /**
     * @param DownloadTempFile $object
     */
    public function __construct($object = null)
    {
        if ($object) {
            $this->setObject($object);
        }
    }

    /**
     * Helper method
     */
    public function triggerProcessing()
    {
        singleton('QueuedJobService')->queueJob($this);
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        /** @var DownloadTempFile $obj */
        $obj = $this->getObject();
        return "Prep File For Download: " . ($obj ? $obj->getFriendlyName() : '???');
    }

    /**
     * Reprocess any needed fields
     */
    public function process()
    {
        ini_set('memory_limit', '1G');

        /** @var DownloadTempFile $obj */
        $obj = $this->getObject();
        $obj->process();
        $this->isComplete = true;
    }
}

Fix for queued job support

Fix for queued job support


<?php

/* generate a nonce which should be completely unpredictable, for use by inline script tags */
$csp_nonce = substr(base64_encode(hash("sha256", $_SERVER["UNIQUE_ID"] . $_SERVER["REQUEST_TIME_FLOAT"] . openssl_random_pseudo_bytes(6), true)), 0, 20);

$csp = "Content-Security-Policy: default-src 'none'; " .
    "connect-src 'self'; img-src 'self'; " .
    "font-src https://cdnjs.cloudflare.com https://fonts.gstatic.com; " .
    "script-src 'self' 'nonce-{$csp_nonce}'  https://cdnjs.cloudflare.com https://ajax.googleapis.com; " .
    "style-src 'self' https://cdnjs.cloudflare.com https://ajax.googleapis.com https://fonts.googleapis.com;";

header($csp);

<?php

/* generate a nonce which should be completely unpredictable, for use by inline script tags */
$csp_nonce = substr(base64_encode(hash("sha256", $_SERVER["UNIQUE_ID"] . $_SERVER["REQUEST_TIME_FLOAT"] . openssl_random_pseudo_bytes(6), true)), 0, 20);

$csp = "Content-Security-Policy: default-src 'none'; " .
    "connect-src 'self'; img-src 'self'; " .
    "font-src https://cdnjs.cloudflare.com https://fonts.gstatic.com; " .
    "script-src 'self' 'nonce-{$csp_nonce}'  https://cdnjs.cloudflare.com https://ajax.googleapis.com; " .
    "style-src 'self' https://cdnjs.cloudflare.com https://ajax.googleapis.com https://fonts.googleapis.com " .
    "'sha256-UiXlt9djFx1o7crFtCH7sUqquV6B2BX9ozY9jqs43JE=' 'sha256-UiXlt9djFx1o7crFtCH7sUqquV6B2BX9ozY9jqs43JE=' " .
    "'sha256-t6oewASd7J1vBg5mQtX4hl8bg8FeegYFM3scKLIhYUc=' 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='; ";
/* the last 2 lines above are a hack to allow inline styles such as "style='width:100%'" but need a better more scalable solution */
header($csp);

Add hashes for inline styles to CSP (temporary hack)


<?php

//require_once 'files_versions/versions.php';
OC::$CLASSPATH['OCA_Versions\Storage'] = 'apps/files_versions/lib/versions.php';
OC::$CLASSPATH['OCA_Versions\Hooks'] = 'apps/files_versions/lib/hooks.php';

OCP\App::registerAdmin('files_versions', 'settings');
OCP\App::registerPersonal('files_versions', 'settings-personal');

OCP\Util::addscript('files_versions', 'versions');

// Listen to write signals
OCP\Util::connectHook('OC_Filesystem', 'post_write', "OCA_Versions\Hooks", "write_hook");
// Listen to delete and rename signals
OCP\Util::connectHook('OC_Filesystem', 'delete', "OCA_Versions\Hooks", "remove_hook");
OCP\Util::connectHook('OC_Filesystem', 'rename', "OCA_Versions\Hooks", "rename_hook");

<?php

//require_once 'files_versions/versions.php';
OC::$CLASSPATH['OCA_Versions\Storage'] = 'apps/files_versions/lib/versions.php';
OC::$CLASSPATH['OCA_Versions\Hooks'] = 'apps/files_versions/lib/hooks.php';

OCP\App::registerAdmin('files_versions', 'settings');
OCP\App::registerPersonal('files_versions', 'settings-personal');

OCP\Util::addscript('files_versions', 'versions');

// Listen to write signals
OCP\Util::connectHook('OC_Filesystem', 'write', "OCA_Versions\Hooks", "write_hook");
// Listen to delete and rename signals
OCP\Util::connectHook('OC_Filesystem', 'delete', "OCA_Versions\Hooks", "remove_hook");
OCP\Util::connectHook('OC_Filesystem', 'rename', "OCA_Versions\Hooks", "rename_hook");

Change post_write hook to write to prevent creating a duplicate of the original file on upload


<?php

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

namespace Symfony\Bundle\DoctrineMigrationsBundle\Command;

use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\DoctrineBundle\Command\DoctrineCommand as BaseCommand;
use Doctrine\DBAL\Migrations\Configuration\Configuration;
use Doctrine\Common\Util\Inflector;

/**
 * Base class for Doctrine console commands to extend from.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 */
abstract class DoctrineCommand extends BaseCommand
{
    public static function configureMigrationsForBundle(Application $application, $bundle, Configuration $configuration)
    {
        $configuration->setMigrationsNamespace($bundle.'\DoctrineMigrations');

        $bundle = $application->getKernel()->getBundle($bundle);
        $dir = $bundle->getPath().'/DoctrineMigrations';

        $configuration->setMigrationsDirectory($dir);
        $configuration->registerMigrationsFromDirectory($dir);
        $configuration->setName($bundle->getName().' Migrations');
        $configuration->setMigrationsTableName(Inflector::tableize($bundle->getName()).'_migration_versions');
    }
}

<?php

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

namespace Symfony\Bundle\DoctrineMigrationsBundle\Command;

use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\DoctrineBundle\Command\DoctrineCommand as BaseCommand;
use Doctrine\DBAL\Migrations\Configuration\Configuration;
use Doctrine\Common\Util\Inflector;

/**
 * Base class for Doctrine console commands to extend from.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 */
abstract class DoctrineCommand extends BaseCommand
{
    public static function configureMigrationsForBundle(Application $application, $bundle, Configuration $configuration)
    {
        $bundle = $application->getKernel()->getBundle($bundle);
        $dir = $bundle->getPath().'/DoctrineMigrations';

        $configuration->setMigrationsNamespace($bundle->getNamespace().'\DoctrineMigrations');
        $configuration->setMigrationsDirectory($dir);
        $configuration->registerMigrationsFromDirectory($dir);
        $configuration->setName($bundle->getName().' Migrations');
        $configuration->setMigrationsTableName(Inflector::tableize($bundle->getName()).'_migration_versions');
    }
}

Fix Doctrine Migrations commands to work with new bundles.


<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'api/*'
    ];
}

Disable csrfToken validation on API endpoints


<?php

namespace Coosos\TagBundle\Twig;

use Symfony\Component\Form\FormView;

class TagExtension extends \Twig_Extension
{

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction("form_coosos_tag", [$this, 'tagRendering'], [
                'is_safe' => ['html'],
                'needs_environment' => true // Tell twig we need the environment
            ]),
        ];
    }

    /**
     * @param \Twig_Environment $environment
     * @param FormView          $formTag
     * @return string
     */
    public function tagRendering(\Twig_Environment $environment, FormView $formTag)
    {
        return $environment->render("CoososTagBundle::formCoososTag.html.twig", ["formTag" => $formTag]);
    }
}

<?php

namespace Coosos\TagBundle\Twig;

use Symfony\Component\Form\FormView;

class TagExtension extends \Twig_Extension
{

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction("form_coosos_tag", [$this, 'tagRendering'], [
                'is_safe' => ['html'],
                'needs_environment' => true // Tell twig we need the environment
            ]),
        ];
    }

    /**
     * @param \Twig_Environment $environment
     * @param FormView          $formTag
     * @return string
     */
    public function tagRendering(\Twig_Environment $environment, FormView $formTag): string
    {
        return $environment->render("CoososTagBundle::formCoososTag.html.twig", ["formTag" => $formTag]);
    }
}

Add return type : string

Add return type : string


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class FixUidsInArtworkCategory extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::statement("UPDATE `artwork_category`"
            . "SET `category_lake_uid`=CONCAT('PC-', `category_lake_uid`)"
            . "WHERE `category_lake_uid` NOT LIKE 'PC-%'"
        );
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement("UPDATE `artwork_category`"
            . " SET `category_lake_uid`=SUBSTR(`category_lake_uid`, 4)"
            . " WHERE `category_lake_uid` LIKE 'PC-%'"
        );
    }
}

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class FixUidsInArtworkCategory extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        // TODO: SQLite doesn't have CONCAT()
        if (App::environment('testing'))
        {
            return;
        }

        DB::statement("UPDATE `artwork_category`"
            . "SET `category_lake_uid`=CONCAT('PC-', `category_lake_uid`)"
            . "WHERE `category_lake_uid` NOT LIKE 'PC-%'"
        );

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {

        DB::statement("UPDATE `artwork_category`"
            . " SET `category_lake_uid`=SUBSTR(`category_lake_uid`, 4)"
            . " WHERE `category_lake_uid` LIKE 'PC-%'"
        );

    }
}

Fix migration for unit testing

Fix migration for unit testing

We really should consider moving off of SQLite to MySQL for testing.
Still, if the speed sacrifice is too great, it might not be worth it.


<?php

/**
 * Apply the spam protection to the comments module if it is installed
 *
 * @package spamprotection
 */

class CommentSpamProtection extends Extension {

	/**
	 * Disable the AJAX commenting and update the form
	 * with the {@link SpamProtectorField} which is enabled
	 */
	public function alterCommentForm(&$form) {
		SpamProtectorManager::update_form($form, null, array(
			'Name' => 'author_name',
			'CommenterURL' => 'author_url',
			'Comment' => 'post_body',
			'Email' => 'author_mail'
		));
	}
}

<?php

/**
 * Apply the spam protection to the comments module if it is installed
 *
 * @package spamprotection
 */

class CommentSpamProtection extends Extension {

	/**
	 * Disable the AJAX commenting and update the form
	 * with the {@link SpamProtectorField} which is enabled
	 */
	public function alterCommentForm(&$form) {
		SpamProtectorManager::update_form($form, null, array(
			'Name' => 'author_name',
			'URL' => 'author_url',
			'Comment' => 'post_body',
			'Email' => 'author_mail'
		));
	}
}

Update 'CommenterURL' field reference to 'URL'


<?php
/**
 * Initialize the basics.
 */

# Error handling
error_reporting(E_STRICT);
function report_ex($e) {
	report($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
}
function report_fatal() {
	$error = error_get_last();
	if( $error !== NULL) {
		report(
			E_CORE_ERROR, $error["message"],
			$error["file"], $error["line"]
		);
	}
}
set_error_handler("report");
set_exception_handler("report_ex");
register_shutdown_function("report_fatal");

# Encoding
mb_internal_encoding("UTF-8");

# Require path
define("ROOT", realpath(dirname(__FILE__) . "/../../../") . "/");
require BASE . 'core/Fn.php';
require BASE . 'core/MdMail.php';
require BASE . 'core/ProjectValidators.php';
require BASE . 'vendor/autoload.php';

<?php
/**
 * Initialize the basics.
 */

# Error handling
error_reporting(E_STRICT);
function report_ex($e) {
	report($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
}
function report_fatal() {
	$error = error_get_last();
	if( $error !== NULL) {
		report(
			E_CORE_ERROR, $error["message"],
			$error["file"], $error["line"]
		);
	}
}
set_error_handler("report");
set_exception_handler("report_ex");
register_shutdown_function("report_fatal");

# Encoding
mb_internal_encoding("UTF-8");

# Require path
define("ROOT", realpath(dirname(__FILE__) . "/../../../") . "/");
require ROOT . 'vendor/autoload.php';

Replace hardcoded loading by prj autoloader


#!/usr/bin/env php
<?php
// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
/**
 * Generate a config file that generates a {@link global_version} based on
 * the subversion version and it into the file specified by $1.
 *
 * This is done using the
 * {@link http://svnbook.red-bean.com/en/1.1/re57.html svnversion} command.
 *
 * @package tgiframework
 * @subpackage bootstrap
 * @copyright 2009 terry chay <tychay@php.net
 */
$latest_version = max(explode(':',exec('svnversion -n'))); //sometimes you get back a range...
$data = sprintf('<?php return array(\'global_version\'=>%d); ?>',$latest_version);
/**
 * Bootstrap tgif_file for writing
 */
include_once(dirname(dirname(__FILE__)).'/class/tgif/file.php');
tgif_file::put_contents($_SERVER['argv'][1], $data);
?>

#!/usr/bin/env php
<?php
// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
/**
 * Generate a config file that generates a {@link global_version} based on
 * the subversion version and it into the file specified by $1.
 *
 * This is done using the
 * {@link http://svnbook.red-bean.com/en/1.1/re57.html svnversion} command.
 *
 * @package tgiframework
 * @subpackage bootstrap
 * @copyright 2009 terry chay <tychay@php.net
 */
$latest_version = max(explode(':',exec('svnversion -n'))); //sometimes you get back a range...
$data = sprintf('<?php /** @package tgiframework */ return array(\'global_version\'=>%d); ?>',$latest_version);
/**
 * Bootstrap tgif_file for writing
 */
include_once(dirname(dirname(__FILE__)).'/class/tgif/file.php');
tgif_file::put_contents($_SERVER['argv'][1], $data);
?>

Write out tgif package if run.

Write out tgif package if run.


<?php

require('config.php');

$dbh = new PDO("mysql:host={$reviewhost['db_host']};dbname={$reviewhost['db_database']}", $reviewhost['db_user'], $reviewhost['db_password']);

$list = $dbh->prepare('SELECT review.checksum                            AS checksum,
                              SUBSTR(review.fingerprint, 1, 99999)       AS sample,

							  review.first_seen                          AS first_seen,
                              review.last_seen                           AS last_seen,
							  review.reviewed_by						 AS reviewed_by,
							  review.reviewed_on						 AS reviewed_on,
							  review.comments						     AS comments,

							  SUM(history.ts_cnt)                        AS count,
                              SUM(history.query_time_sum)                AS time,
							  ROUND(SUM(history.query_time_sum)/SUM(history.ts_cnt), 2) AS time_avg

                         FROM '.$reviewhost['review_table'].'            AS review
                    LEFT JOIN '.$reviewhost['review_history_table'].'    AS history
                           ON history.checksum = review.checksum
                     GROUP BY review.checksum
                           ');
$list->execute();

include('list.php');

<?php

require('config.php');

$dbh = new PDO("mysql:host={$reviewhost['db_host']};dbname={$reviewhost['db_database']}", $reviewhost['db_user'], $reviewhost['db_password']);

$list = $dbh->prepare('SELECT review.checksum                            AS checksum,
                              SUBSTR(review.fingerprint, 1, 99999)       AS sample,

							  review.first_seen                          AS first_seen,
                              review.last_seen                           AS last_seen,
							  IFNULL(review.reviewed_by, "-")      	     AS reviewed_by,
							  review.reviewed_on						 AS reviewed_on,
							  review.comments						     AS comments,

							  SUM(history.ts_cnt)                        AS count,
                              SUM(history.query_time_sum)                AS time,
							  ROUND(SUM(history.query_time_sum)/SUM(history.ts_cnt), 2) AS time_avg

                         FROM '.$reviewhost['review_table'].'            AS review
                    LEFT JOIN '.$reviewhost['review_history_table'].'    AS history
                           ON history.checksum = review.checksum
                     GROUP BY review.checksum
                           ');
$list->execute();

include('list.php');

Move to using dashes for easier filtering


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\Addressing\Model;

use Sylius\Bundle\ResourceBundle\Model\ResourceLogEntry;

/**
 * @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
 */
final class AddressLogEntry extends ResourceLogEntry
{
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\Addressing\Model;

use Sylius\Component\Resource\Model\ResourceLogEntry;

/**
 * @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
 */
final class AddressLogEntry extends ResourceLogEntry
{
}

Remove Addressing's dependency on ResourceBundle


<?php namespace Flarum\Core\Seeders;

use Illuminate\Database\Seeder;
use Flarum\Core\Models\User;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::unguard();

        $faker = \Faker\Factory::create();

        for ($i = 0; $i < 100; $i++) {
            $user = User::create([
                'username'     => $faker->userName,
                'email'        => $faker->safeEmail,
                'is_confirmed' => true,
                'is_activated' => true,
                'password'     => 'password',
                'join_time'    => $faker->dateTimeThisYear
            ]);

            // Assign the users to the 'Member' group, and possibly some others.
            $user->groups()->attach(3);
            if (rand(1, 50) == 1) {
                $user->groups()->attach(4);
            }
            if (rand(1, 20) == 1) {
                $user->groups()->attach(5);
            }
            if (rand(1, 20) == 1) {
                $user->groups()->attach(1);
            }
        }
    }
}

<?php namespace Flarum\Core\Seeders;

use Illuminate\Database\Seeder;
use Flarum\Core\Models\User;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::unguard();

        $faker = \Faker\Factory::create();

        for ($i = 0; $i < 100; $i++) {
            $user = User::create([
                'username'     => $faker->userName,
                'email'        => $faker->safeEmail,
                'is_activated' => true,
                'password'     => 'password',
                'join_time'    => $faker->dateTimeThisYear
            ]);

            // Assign the users to the 'Member' group, and possibly some others.
            $user->groups()->attach(3);
            if (rand(1, 50) == 1) {
                $user->groups()->attach(4);
            }
            if (rand(1, 20) == 1) {
                $user->groups()->attach(5);
            }
            if (rand(1, 20) == 1) {
                $user->groups()->attach(1);
            }
        }
    }
}

Remove outdated column name from user table seeder


<?php

namespace Brick\Geo\Engine;

use Brick\Geo\Exception\GeometryEngineException;

/**
 * This class holds the GeometryEngine implementation to use for calculations.
 */
final class GeometryEngineRegistry
{
    /**
     * @var GeometryEngine|null
     */
    private static $engine;

    /**
     * Returns whether a geometry engine is set.
     *
     * @return boolean
     */
    public static function has()
    {
        return self::$engine !== null;
    }

    /**
     * Sets the GeometryEngine to use for calculations.
     *
     * @param GeometryEngine $engine
     *
     * @return void
     */
    public static function set(GeometryEngine $engine)
    {
        self::$engine = $engine;
    }

    /**
     * Returns the GeometryEngine to use for calculations.
     *
     * @return GeometryEngineException
     *
     * @throws \Brick\Geo\Exception\GeometryException
     */
    public static function get()
    {
        if (self::$engine === null) {
            throw GeometryEngineException::noEngineSet();
        }

        return self::$engine;
    }
}

<?php

namespace Brick\Geo\Engine;

use Brick\Geo\Exception\GeometryEngineException;

/**
 * This class holds the GeometryEngine implementation to use for calculations.
 */
final class GeometryEngineRegistry
{
    /**
     * @var GeometryEngine|null
     */
    private static $engine;

    /**
     * Returns whether a geometry engine is set.
     *
     * @return boolean
     */
    public static function has()
    {
        return self::$engine !== null;
    }

    /**
     * Sets the GeometryEngine to use for calculations.
     *
     * @param GeometryEngine $engine
     *
     * @return void
     */
    public static function set(GeometryEngine $engine)
    {
        self::$engine = $engine;
    }

    /**
     * Returns the GeometryEngine to use for calculations.
     *
     * @return GeometryEngine
     *
     * @throws \Brick\Geo\Exception\GeometryException
     */
    public static function get()
    {
        if (self::$engine === null) {
            throw GeometryEngineException::noEngineSet();
        }

        return self::$engine;
    }
}

Fix wrongly documented return type

Fix wrongly documented return type


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

use Symfony\Component\Console\Application;

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

date_default_timezone_set('Europe/Madrid');

$loader = new \Ontic\Yaes\Loaders\SoftwarePackagesLoader();
$softwarePackages = $loader->findSoftwarePackages(
    __DIR__ . '/src/SoftwarePackages',
    'Ontic\Yaes\SoftwarePackages'
);

bindtextdomain("messages", "locale");
textdomain("messages");

$application = new Application();
foreach($softwarePackages as $package)
{
    $application->addCommands($package->getCommands());
}

$application->add(new \Ontic\Yaes\Command\IdentifyCommand($softwarePackages));
$application->add(new \Ontic\Yaes\Command\ScanCommand($softwarePackages));
$application->run();

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

use Symfony\Component\Console\Application;

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

date_default_timezone_set('Europe/Madrid');

$loader = new \Ontic\Yaes\Loaders\SoftwarePackagesLoader();
$softwarePackages = $loader->findSoftwarePackages(
    __DIR__ . '/src/SoftwarePackages',
    'Ontic\Yaes\SoftwarePackages'
);

putenv("LC_ALL=" . getenv('LANG'));
bindtextdomain("messages", "locale");
textdomain("messages");

$application = new Application();
foreach($softwarePackages as $package)
{
    $application->addCommands($package->getCommands());
}

$application->add(new \Ontic\Yaes\Command\IdentifyCommand($softwarePackages));
$application->add(new \Ontic\Yaes\Command\ScanCommand($softwarePackages));
$application->run();

Fix lang detection in the CLI

Fix lang detection in the CLI


<?php

namespace Chris\Composer\AutoregisterClassmapPlugin\Manipulator;

/**
 * Class AutoloadManipulator
 *
 * @author Christophe Chausseray <chausseray.christophe@gmail.com>
 *
 * Manipulator of the existing autoload files.
 */
class AutoloadManipulator
{
    /**
     * @var string
     */
    protected $vendorDir;

    /**
     * AutoloadManipulator constructor.
     *
     * @param string $vendorDir
     */
    public function __construct($vendorDir)
    {
        $this->vendorDir = $vendorDir;
    }

    /**
     * Rename "autoload_psr4.php" into "autoload_psr4_child.php"
     *
     * @return bool
     */
    public function moveAutoloadPsr4()
    {
        return $this->moveFile('autoload_psr4.php', 'autoload_psr4_child.php');
    }

    /**
     * Rename one autoload file into something else.
     *
     * @param $oldName
     * @param $newName
     *
     * @return bool
     */
    protected function moveFile($oldName, $newName)
    {
        return rename($this->vendorDir . '/composer/' . $oldName, $this->vendorDir . '/composer/' . $newName);
    }
}

<?php

namespace Chris\Composer\AutoregisterClassmapPlugin\Manipulator;

/**
 * Class AutoloadManipulator
 *
 * @author Christophe Chausseray <chausseray.christophe@gmail.com>
 *
 * Manipulator of the existing autoload files.
 */
class AutoloadManipulator
{
    /**
     * @var string
     */
    protected $vendorDir;

    /**
     * AutoloadManipulator constructor.
     *
     * @param string $vendorDir
     */
    public function __construct($vendorDir)
    {
        $this->vendorDir = $vendorDir;
    }

    /**
     * Rename "autoload_psr4.php" into "autoload_psr4_child.php"
     *
     * @return bool
     */
    public function moveAutoloadPsr4()
    {
        return $this->moveFile('autoload_psr4.php', 'autoload_psr4_child.php');
    }

    /**
     * Rename one autoload file into something else.
     *
     * @param string $oldName
     * @param string $newName
     *
     * @return bool
     */
    protected function moveFile($oldName, $newName)
    {
        return rename($this->vendorDir . '/composer/' . $oldName, $this->vendorDir . '/composer/' . $newName);
    }
}

Fix type of variable on PHPDoc

Fix type of variable on PHPDoc


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateSettingsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('settings', function (Blueprint $table) {
            $table->increments('id');
            $table->string('setting');
            $table->string('value')->nullable();
            $table->boolean('more')->default(NULL);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('settings');
    }
}

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateSettingsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('settings', function (Blueprint $table) {
            $table->increments('id');
            $table->string('setting')->comment("Key");
            $table->string('value',4000)->nullable()->comment("Value");
            $table->boolean('more')->default(NULL);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('settings');
    }
}

Increase value column length in settings to 4000


<?php

namespace Shivas\VersioningBundle\Twig;

use Shivas\VersioningBundle\Service\VersionManager;
use Twig_Extension;
use Twig_Extension_GlobalsInterface;

/**
 * Class VersionExtension
 */
class VersionExtension extends Twig_Extension implements Twig_Extension_GlobalsInterface
{
    /**
     * @var VersionManager
     */
    protected $manager;

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

    /**
     * @return array
     */
    public function getGlobals()
    {
        return [
            'shivas_app_version' => (string) $this->manager->getVersion(),
        ];
    }
}

<?php

namespace Shivas\VersioningBundle\Twig;

use Shivas\VersioningBundle\Service\VersionManager;
use Twig\Extension\AbstractExtension;
use Twig\Extension\GlobalsInterface;

/**
 * Class VersionExtension
 */
class VersionExtension extends AbstractExtension implements GlobalsInterface
{
    /**
     * @var VersionManager
     */
    protected $manager;

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

    /**
     * @return array
     */
    public function getGlobals()
    {
        return [
            'shivas_app_version' => (string) $this->manager->getVersion(),
        ];
    }
}

Use namespaced Twig class and interface

Use namespaced Twig class and interface


<?php

namespace Oro\Bundle\WorkflowBundle\Configuration;

use Oro\Bundle\WorkflowBundle\Entity\ProcessTrigger;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

class ProcessTriggerListConfiguration implements ConfigurationInterface
{
    /**
     * @var ProcessTriggerConfiguration
     */
    protected $triggerConfiguration;

    /**
     * @param ProcessTriggerConfiguration $triggerConfiguration
     */
    public function __construct(ProcessTriggerConfiguration $triggerConfiguration)
    {
        $this->triggerConfiguration = $triggerConfiguration;
    }

    /**
     * @param array $configs
     * @return array
     */
    public function processConfiguration(array $configs)
    {
        $processor = new Processor();
        return $processor->processConfiguration($this, array($configs));
    }

    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('configuration');
        $rootNode->useAttributeAsKey('name');
        $nodeBuilder = $rootNode
            ->prototype('array')
                ->prototype('array');
        $this->triggerConfiguration->addTriggerNodes($nodeBuilder);

        return $treeBuilder;
    }
}

<?php

namespace Oro\Bundle\WorkflowBundle\Configuration;

use Oro\Bundle\WorkflowBundle\Entity\ProcessTrigger;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

class ProcessTriggerListConfiguration implements ConfigurationInterface
{
    /**
     * @var ProcessTriggerConfiguration
     */
    protected $triggerConfiguration;

    /**
     * @param ProcessTriggerConfiguration $triggerConfiguration
     */
    public function __construct(ProcessTriggerConfiguration $triggerConfiguration)
    {
        $this->triggerConfiguration = $triggerConfiguration;
    }

    /**
     * @param array $configs
     * @return array
     */
    public function processConfiguration(array $configs)
    {
        $processor = new Processor();
        return $processor->processConfiguration($this, array($configs));
    }

    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('configuration');
        $rootNode->useAttributeAsKey('name');
        $this->triggerConfiguration->addTriggerNodes($rootNode->prototype('array')->prototype('array'));

        return $treeBuilder;
    }
}

CRM-739: Create class and command (oro.process.definition.load) to read process configuration from *.yml files to DB
 - small fix in configuration


<?php

namespace Jstewmc\Rtf\Element\Control\Word;

/**
 * The "\cxs" control word indicates an "ignored" steno group. Steno is written as a
 * series of strokes using pure steno notation with forward-slashes between them but
 * no leading- or trailing-slashes.
 *
 * The valid steno characters, in order, are STKPWHRAO*EUFRPBLGTSDZ. When the number
 * bar is used, the digits 0-9 are valid. Finally, the hyphen (-) and number sign (#)
 * are allowed.
 *
 * A hyphen is used in cases where there may be confusion between initial and final
 * consonants. For instance, to differentiate between the strokes /RBGS and /-RBGS.
 *
 * If the number bar was used in a stroke, the stroke contains a number sign to
 * indicate that. The number sign may be anywhere within the stroke, but it should
 * probably be at one end or the other. Keep in mind, most steno programs will output
 * the digit when the number bar is used to create a number, but the number sign when
 * the number bar is used to create a stroke (e.g., "/K#").
 */
class Cxs extends Word
{
    /**
     * The "\cxs" is an ignored control word
     */
    protected bool $isIgnored = true;
}

<?php

namespace Jstewmc\Rtf\Element\Control\Word;

/**
 * The "\cxs" control word indicates an "ignored" steno group. Steno is written as a
 * series of strokes using pure steno notation with forward-slashes between them but
 * no leading- or trailing-slashes.
 *
 * The valid steno characters, in order, are STKPWHRAO*EUFRPBLGTSDZ. When the number
 * bar is used, the digits 0-9 are valid. Finally, the hyphen (-) and number sign (#)
 * are allowed.
 *
 * A hyphen is used in cases where there may be confusion between initial and final
 * consonants. For instance, to differentiate between the strokes /RBGS and /-RBGS.
 *
 * If the number bar was used in a stroke, the stroke contains a number sign to
 * indicate that. The number sign may be anywhere within the stroke, but it should
 * probably be at one end or the other. Keep in mind, most steno programs will output
 * the digit when the number bar is used to create a number, but the number sign when
 * the number bar is used to create a stroke (e.g., "/K#").
 */
class Cxs extends Word
{
    /**
     * The "\cxs" is an ignored control word
     */
    protected $isIgnored = true;
}

Remove cxs property type for now

Remove cxs property type for now


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link          https://book.cakephp.org/3.0/en/development/errors.html#error-exception-configuration
 * @since         3.2.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\Console\Exception;

use Cake\Core\Exception\Exception;

/**
 * Exception class for halting errors in console tasks
 *
 * @see \Cake\Console\Shell::_stop()
 * @see \Cake\Console\Shell::error()
 */
class StopException extends Exception
{
}

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link          https://book.cakephp.org/3.0/en/development/errors.html#error-exception-configuration
 * @since         3.2.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\Console\Exception;

use Cake\Console\Command;
use Cake\Core\Exception\Exception;

/**
 * Exception class for halting errors in console tasks
 *
 * @see \Cake\Console\Shell::_stop()
 * @see \Cake\Console\Shell::error()
 * @see \Cake\Console\Command::abort()
 */
class StopException extends Exception
{
    /**
     * Default exception code
     *
     * @var int
     */
    protected $_defaultCode = Command::CODE_ERROR;
}

Fix exception to be valid error default code 1 instead of 244.


<?php
// Here you can initialize variables that will for your tests

<?php
/**
 * ZucchiModel (http://zucchi.co.uk)
 *
 * @link      http://github.com/zucchi/ZucchiModel for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zucchi Limited. (http://zucchi.co.uk)
 * @license   http://zucchi.co.uk/legals/bsd-license New BSD License
 */
// Composer autoloading
if (file_exists(__DIR__ . '/../../vendor/autoload.php')) {
    $loader = include __DIR__ . '/../../vendor/autoload.php';
}

Add autoloader to bootstrap of tests.

Add autoloader to bootstrap of tests.


<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright    Copyright 2014, Block 8 Limited.
* @license      https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link         https://www.phptesting.org/
*/

session_start();

require_once('../bootstrap.php');

$fc = new PHPCI\Application($config, new b8\Http\Request());
print $fc->handleRequest();

<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright    Copyright 2014, Block 8 Limited.
* @license      https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link         https://www.phptesting.org/
*/

session_set_cookie_params(43200); // Set session cookie to last 12 hours.
session_start();

require_once('../bootstrap.php');

$fc = new PHPCI\Application($config, new b8\Http\Request());
print $fc->handleRequest();

Update session cookie to last 12 hours.

Update session cookie to last 12 hours.


#!/usr/bin/env php
<?php
require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsViolations = $phpcsCLI->process(array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php')));
if ($phpcsViolations > 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

file_put_contents('php://stderr', "Code coverage was 100%\n");

#!/usr/bin/env php
<?php
require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsViolations = $phpcsCLI->process(['standard' => ['PSR1'], 'files' => ['src', 'tests', 'build.php']]);
if ($phpcsViolations > 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = ['coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration];
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

file_put_contents('php://stderr', "Code coverage was 100%\n");

Use PHP 5.4 short array syntax.

Use PHP 5.4 short array syntax.


 Consult advisor

                     Production

                     Military

                     Land

                     Construction

 Consult advisor

                     Production

            {{--

                     Military

--}}

                     Land

                     Construction

Comment out military advisor for now

Comment out military advisor for now


<?php
declare(strict_types=1);

namespace Fc2blog\Tests\App\Service;

use Fc2blog\Service\AccessBlock;
use Fc2blog\Web\Request;
use PHPUnit\Framework\TestCase;

class AccessBlockTest extends TestCase
{
    public function testAccessBlock(): void
    {
        $jp_ip_address = "133.0.0.1"; // Some JP address https://www.nic.ad.jp/ja/dns/jp-addr-block.html
        $r = new Request(null, null, null, null, null, null, [
            'REMOTE_ADDR' => $jp_ip_address
        ]);

        $ab = new AccessBlock("JP");
        $this->assertTrue($ab->isUserBlockIp($r));

        $ab = new AccessBlock("JP,US");
        $this->assertTrue($ab->isUserBlockIp($r));

        $ab = new AccessBlock("US,JP");
        $this->assertTrue($ab->isUserBlockIp($r));

        $ab = new AccessBlock("US");
        $this->assertFalse($ab->isUserBlockIp($r));

        $ab = new AccessBlock();
        $this->assertFalse($ab->isUserBlockIp($r));
    }
}

<?php
declare(strict_types=1);

namespace Fc2blog\Tests\App\Service;

use Fc2blog\Service\AccessBlock;
use Fc2blog\Web\Request;
use PHPUnit\Framework\TestCase;

class AccessBlockTest extends TestCase
{
    public function testAccessBlock(): void
    {
        if (!file_exists(AccessBlock::MMDB_FILE_PATH)) {
            $this->markTestSkipped();
            return;
        }

        $jp_ip_address = "133.0.0.1"; // Some JP address https://www.nic.ad.jp/ja/dns/jp-addr-block.html
        $r = new Request(null, null, null, null, null, null, [
            'REMOTE_ADDR' => $jp_ip_address
        ]);

        $ab = new AccessBlock("JP");
        $this->assertTrue($ab->isUserBlockIp($r));

        $ab = new AccessBlock("JP,US");
        $this->assertTrue($ab->isUserBlockIp($r));

        $ab = new AccessBlock("US,JP");
        $this->assertTrue($ab->isUserBlockIp($r));

        $ab = new AccessBlock("US");
        $this->assertFalse($ab->isUserBlockIp($r));

        $ab = new AccessBlock();
        $this->assertFalse($ab->isUserBlockIp($r));
    }
}

Improve test. skip access block test when not exists mmdb file.


<?php
/* (c) Anton Medvedev <anton@elfet.ru>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Deployer\Server;

use Symfony\Component\Process\Process;

class Local implements ServerInterface
{
    /**
     * {@inheritdoc}
     */
    public function connect()
    {
        // We do not need to connect to local server.
    }

    /**
     * {@inheritdoc}
     */
    public function run($command)
    {
        $process = new Process($command);
        $process->run();

        if (!$process->isSuccessful()) {
            throw new \RuntimeException($process->getErrorOutput());
        }

        return $process->getOutput();
    }

    /**
     * {@inheritdoc}
     */
    public function upload($local, $remote)
    {
        copy($local, $remote);
    }

    /**
     * {@inheritdoc}
     */
    public function download($local, $remote)
    {
        copy($remote, $local);
    }
}

<?php
/* (c) Anton Medvedev <anton@elfet.ru>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Deployer\Server;

use Symfony\Component\Process\Process;

class Local implements ServerInterface
{
    /**
     * {@inheritdoc}
     */
    public function connect()
    {
        // We do not need to connect to local server.
    }

    /**
     * {@inheritdoc}
     */
    public function run($command)
    {
        $process = new Process($command);
        $process->mustRun();

        return $process->getOutput();
    }

    /**
     * {@inheritdoc}
     */
    public function upload($local, $remote)
    {
        copy($local, $remote);
    }

    /**
     * {@inheritdoc}
     */
    public function download($local, $remote)
    {
        copy($remote, $local);
    }
}

Use mustRun instead of run and catch exception

It does the same thing but it gives out a better exception object.


<?php
/*************************************************************************************
 *  Copyright (C) 2014 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program is free software; you can redistribute it and/or                    *
 *  modify it under the terms of the GNU Affero General Public License               *
 *  as published by the Free Software Foundation; either version 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  This program is distributed in the hope that it will be useful,                  *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *
 *  GNU General Public License for more details.                                     *
 *                                                                                *
 *  You should have received a copy of the GNU Affero General Public License         *
 *  along with this program; if not, write to the Free Software                      *
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *
 *************************************************************************************/

namespace AFiestas\ProtectFont;
interface iPrinter
{
    public function printFont($path);
}

<?php
/*************************************************************************************
 *  Copyright (C) 2014 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program is free software; you can redistribute it and/or                    *
 *  modify it under the terms of the GNU Affero General Public License               *
 *  as published by the Free Software Foundation; either version 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  This program is distributed in the hope that it will be useful,                  *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *
 *  GNU General Public License for more details.                                     *
 *                                                                                *
 *  You should have received a copy of the GNU Affero General Public License         *
 *  along with this program; if not, write to the Free Software                      *
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *
 *************************************************************************************/

namespace AFiestas\ProtectFont;
interface iPrinter
{
    /**
     * @return void
     */
    public function printFont($path);
}

Add docblock to help IDE

Add docblock to help IDE


<?php
$sidebars = array('Sidebar');
foreach ($sidebars as $sidebar) {
    register_sidebar(array('name'=> $sidebar,
        'before_widget' => '

',
        'after_widget' => '

',
        'before_title' => '
',
        'after_title' => '
'
    ));
}
$sidebars = array('Footer');
foreach ($sidebars as $sidebar) {
    register_sidebar(array('name'=> $sidebar,
        'before_widget' => '
',
        'after_widget' => '
',
        'before_title' => '
',
        'after_title' => '
'
    ));
}
?>

<?php
function foundationpress_sidebars_widgets() {
    $sidebars = array('Sidebar');
    foreach ($sidebars as $sidebar) {
        register_sidebar(array(
            'name'=> $sidebar,
            'id'=> 'foundationpress_sidebar',
            'before_widget' => '

',
            'after_widget' => '

',
            'before_title' => '
',
            'after_title' => '
'
        ));
    }
    do_action('framework_sidebars');
}
add_action( 'widgets_init', 'foundationpress_sidebars_widgets' );

function foundationpress_footer_widgets() {
    $sidebars = array('Footer');
    foreach ($sidebars as $sidebar) {
        register_sidebar(array(
            'name'=> $sidebar,
            'id'=> 'foundationpress_footer',
            'before_widget' => '
',
            'after_widget' => '
',
            'before_title' => '
',
            'after_title' => '
'
        ));
    }
    do_action('framework_footerwidget');
}
add_action( 'widgets_init', 'foundationpress_footer_widgets' );
?>

Add hooks to FoundationPress widgets registration

Add hooks to FoundationPress widget registration so that it is easy to unregister them from child theme function.php.