<?php namespace Orchestra\Auth;

class AuthServiceProvider extends \Illuminate\Auth\AuthServiceProvider {

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['auth'] = $this->app->share(function($app)
		{
			// Once the authentication service has actually been requested by the developer
			// we will set a variable in the application indicating such. This helps us
			// know that we need to set any queued cookies in the after event later.
			$app['auth.loaded'] = true;

			return new AuthManager($app);
		});

		$this->app['orchestra.acl'] = $this->app->share(function($app)
		{
			return new Acl\Environment;
		});
	}

}

<?php namespace Orchestra\Auth;

class AuthServiceProvider extends \Illuminate\Auth\AuthServiceProvider {

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['auth'] = $this->app->share(function($app)
		{
			// Once the authentication service has actually been requested by the developer
			// we will set a variable in the application indicating such. This helps us
			// know that we need to set any queued cookies in the after event later.
			$app['auth.loaded'] = true;

			return new AuthManager($app);
		});

		$this->app['orchestra.acl'] = $this->app->share(function($app)
		{
			return new Acl\Environment;
		});
	}

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

}

Add provides since this service is deferred.

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

/*
 * NOTICE OF LICENSE
 *
 * Part of the Cortex Foundation Module.
 *
 * This source file is subject to The MIT License (MIT)
 * that is bundled with this package in the LICENSE file.
 *
 * Package: Cortex Foundation Module
 * License: The MIT License (MIT)
 * Link:    https://rinvex.com
 */

namespace Cortex\Foundation\Providers;

use Rinvex\Module\ModuleServiceProvider;
use Illuminate\Foundation\Providers\ConsoleSupportServiceProvider;
use Illuminate\Support\AggregateServiceProvider as BaseAggregateServiceProvider;

class AggregateServiceProvider extends BaseAggregateServiceProvider
{
    /**
     * The provider class names.
     *
     * @var array
     */
    protected $providers = [
        ModuleServiceProvider::class,
        FoundationServiceProvider::class,
        ConsoleSupportServiceProvider::class,
        FortServiceProvider::class,
    ];
}

<?php

/*
 * NOTICE OF LICENSE
 *
 * Part of the Cortex Foundation Module.
 *
 * This source file is subject to The MIT License (MIT)
 * that is bundled with this package in the LICENSE file.
 *
 * Package: Cortex Foundation Module
 * License: The MIT License (MIT)
 * Link:    https://rinvex.com
 */

namespace Cortex\Foundation\Providers;

use Rinvex\Module\ModuleServiceProvider;
use Illuminate\Support\AggregateServiceProvider as BaseAggregateServiceProvider;

class AggregateServiceProvider extends BaseAggregateServiceProvider
{
    /**
     * The provider class names.
     *
     * @var array
     */
    protected $providers = [
        ModuleServiceProvider::class,
        FoundationServiceProvider::class,
        ConsoleSupportServiceProvider::class,
        FortServiceProvider::class,
    ];
}

Use our own custom ConsoleSupportServiceProvider


<?php
/**
 * Language file for mentions
 *
 * @author Shitiz Garg <mail@dragooon.net>
 * @copyright 2014 Shitiz Garg
 * @license Simplified BSD (2-Clause) License
 */

global $txt, $context;

$txt['mentions_subject'] = 'MENTIONNAME, you have been mentioned at a post in ' . $context['forum_name'];
$txt['mentions_body'] = 'Hello MENTIONNAME!

MEMBERNAME mentioned you in the post "POSTNAME", you can view the post at POSTLINK

Regards,
' . $context['forum_name'];
$txt['mentions'] = 'Mentions';
$txt['mentions_profile_title'] = 'Posts mentioning %s';
$txt['mentions_post_subject'] = 'Subject';
$txt['mentions_member'] = 'Mentioned By';
$txt['mentions_post_time'] = 'Mentioned Time';
$txt['permissionname_mention_member'] = 'Mention members';
$txt['permissionhelp_mention_member'] = 'Allow members to tag other members and alert them via mentioning them via @username syntax';
$txt['email_mentions'] = 'E-mail mention notifications';
$txt['scheduled_task_removeMentions'] = 'Remove seen mentions';
$txt['scheduled_task_desc_removeMentions'] = 'Automatically removes seen mentions older than the specified days';

Add language strings for mention's scheduled task


<?php

namespace React\Socket;

use Evenement\EventEmitter;
use React\EventLoop\LoopInterface;
use React\Stream\WritableStreamInterface;
use React\Stream\Buffer;
use React\Stream\Stream;
use React\Stream\Util;

class Connection extends Stream implements ConnectionInterface
{
    public function handleData($stream)
    {
        $data = fread($stream, $this->bufferSize);
        if ('' === $data || false === $data) {
            $this->end();
        } else {
            $this->emit('data', array($data, $this));
        }
    }

    public function handleClose()
    {
        if (is_resource($this->stream)) {
            stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR);
            fclose($this->stream);
        }
    }

    public function getRemoteAddress()
    {
        return $this->parseAddress(stream_socket_get_name($this->stream, true));
    }

    private function parseAddress($address)
    {
        return trim(substr($address, 0, strrpos($address, ':')), '[]');
    }
}

<?php

namespace React\Socket;

use React\Stream\Stream;

class Connection extends Stream implements ConnectionInterface
{
    public function handleData($stream)
    {
        $data = stream_socket_recvfrom($stream, $this->bufferSize);
        if ('' === $data || false === $data || feof($stream)) {
            $this->end();
        } else {
            $this->emit('data', array($data, $this));
        }
    }

    public function handleClose()
    {
        if (is_resource($this->stream)) {
            stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR);
            fclose($this->stream);
        }
    }

    public function getRemoteAddress()
    {
        return $this->parseAddress(stream_socket_get_name($this->stream, true));
    }

    private function parseAddress($address)
    {
        return trim(substr($address, 0, strrpos($address, ':')), '[]');
    }
}

[Socket] Read raw stream when using Socket server (no stream)


<?php

/**
 * Landing CMS
 *
 * A simple CMS for Landing Pages.
 *
 * @package    Landing CMS
 * @author     Ilia Chernykh <landingcms@yahoo.com>
 * @copyright  2017, Landing CMS (https://github.com/Elias-Black/Landing-CMS)
 * @license    https://opensource.org/licenses/LGPL-2.1  LGPL-2.1
 * @version    Release: 0.0.4
 * @link       https://github.com/Elias-Black/Landing-CMS
 */

$public_db_path = 'cms/_db/public.php';

$public_db_content = file_get_contents($public_db_path);

$get = unserialize($public_db_content);

<?php

/**
 * Landing CMS
 *
 * A simple CMS for Landing Pages.
 *
 * @package    Landing CMS
 * @author     Ilia Chernykh <landingcms@yahoo.com>
 * @copyright  2017, Landing CMS (https://github.com/Elias-Black/Landing-CMS)
 * @license    https://opensource.org/licenses/LGPL-2.1  LGPL-2.1
 * @version    Release: 0.0.4
 * @link       https://github.com/Elias-Black/Landing-CMS
 */

$public_db_path = 'cms/_db/public.php';

$controller_file_nesting = 1;

$root_path = realpath( dirname(__FILE__) . str_repeat('/..', $controller_file_nesting) ) . '/';

$public_db_path = $root_path . $public_db_path;

$public_db_content = file_get_contents($public_db_path);

$get = unserialize($public_db_content);

Fix for path to Public DB in controller. Now you can include the controller everywhere.


<?php

namespace Oro\Bundle\ChartBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

use Oro\Component\Config\Loader\CumulativeConfigLoader;
use Oro\Component\Config\Loader\YamlCumulativeFileLoader;

class OroChartExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $chartConfigs = array();

        $configLoader = new CumulativeConfigLoader(
            'oro_chart',
            new YamlCumulativeFileLoader('Resources/config/oro/chart.yml')
        );

        $resources = $configLoader->load($container);
        foreach ($resources as $resource) {
            $chartConfigs[] = $resource->data['oro_chart'];
        }

        foreach ($configs as $config) {
            $chartConfigs[] = $config;
        }

        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $chartConfigs);

        $container->getDefinition('oro_chart.config_provider')->replaceArgument(0, $config);
    }
}

<?php

namespace Oro\Bundle\ChartBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\Config\FileLocator;

use Oro\Component\Config\Loader\CumulativeConfigLoader;
use Oro\Component\Config\Loader\YamlCumulativeFileLoader;

class OroChartExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        $chartConfigs = array();

        $configLoader = new CumulativeConfigLoader(
            'oro_chart',
            new YamlCumulativeFileLoader('Resources/config/oro/chart.yml')
        );

        $resources = $configLoader->load($container);
        foreach ($resources as $resource) {
            $chartConfigs[] = $resource->data['oro_chart'];
        }

        foreach ($configs as $config) {
            $chartConfigs[] = $config;
        }

        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $chartConfigs);

        $container->getDefinition('oro_chart.config_provider')->replaceArgument(0, $config);
    }
}

BAP-3230: Add chart configuration
- add missed loading of services.yml


<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new AppBundle\AppBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
    public function getCacheDir()
    {
        return '/tmp/symfony/ukmdelta/cache/';
    }
	public function getLogDir()
    {
        return '/tmp/symfony/ukmdelta/log/';
    }
}

<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new AppBundle\AppBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
    public function getCacheDir()
    {
        return '/tmp/symfony/ukmrundown/cache/';
    }
	public function getLogDir()
    {
        return '/tmp/symfony/ukmrundown/log/';
    }
}

Fix cache dir in Kernel

Fix cache dir in Kernel


<?php namespace JamylBot\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use JamylBot\Group;

class MustBeAdmin {

    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect('/home')->with('auth_message', 'Must be logged in.');
            }
        }
        /** @var \JamylBot\User $user */
        $user = $this->auth->user();
        if ($user->admin) {
            return $next($request);
        }
        $groupId = $request->group ? $request->group : $request->groups;
        if ($groupId) {
            /** @var Group $group */
            $group = Group::find($groupId);
            if ($group->isOwner($user->id)) {
                return $next($request);
            }
        }

        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect('/home')->with('auth_message', 'Access Denied');
        }

    }

}

<?php namespace JamylBot\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use JamylBot\Group;

class MustBeAdmin {

    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect('/home')->with('auth_message', 'Must be logged in.');
            }
        }
        /** @var \JamylBot\User $user */
        $user = $this->auth->user();
        if ($user->admin) {
            return $next($request);
        }
        $groupId = $request->groupId ? $request->groupId : $request->group;
        if ($groupId) {
            /** @var Group $group */
            $group = Group::find($groupId);
            if ($group->isOwner($user->id)) {
                return $next($request);
            }
        }

        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect('/home')->with('auth_message', 'Access Denied');
        }

    }

}

Update admin middleware to fix permissions for adding users etc

Changed the wrong variable in the last fix.


<?php

namespace Laravel\Lumen\Testing;

trait DatabaseTransactions
{
    /**
     * Handle database transactions on the specified connections.
     *
     * @return void
     */
    public function beginDatabaseTransaction()
    {
        $database = $this->app->make('db');

        foreach ($this->connectionsToTransact() as $name) {
            $database->connection($name)->beginTransaction();
        }

        $this->beforeApplicationDestroyed(function () use ($database) {
            foreach ($this->connectionsToTransact() as $name) {
                $database->connection($name)->rollBack();
            }
        });
    }

    /**
     * The database connections that should have transactions.
     *
     * @return array
     */
    protected function connectionsToTransact()
    {
        return property_exists($this, 'connectionsToTransact')
            ? $this->connectionsToTransact : [null];
    }
}

<?php

namespace Laravel\Lumen\Testing;

trait DatabaseTransactions
{
    /**
     * Handle database transactions on the specified connections.
     *
     * @return void
     */
    public function beginDatabaseTransaction()
    {
        $database = $this->app->make('db');

        foreach ($this->connectionsToTransact() as $name) {
            $database->connection($name)->beginTransaction();
        }

        $this->beforeApplicationDestroyed(function () use ($database) {
            foreach ($this->connectionsToTransact() as $name) {
                $connection = $database->connection($name);

                $connection->rollBack();
                $connection->disconnect();
            }
        });
    }

    /**
     * The database connections that should have transactions.
     *
     * @return array
     */
    protected function connectionsToTransact()
    {
        return property_exists($this, 'connectionsToTransact')
            ? $this->connectionsToTransact : [null];
    }
}

Fix "Too Many Connections" error during testing

See laravel/framework#20340


<div class="panel <?php echo (isset($single)?'single':''); ?>">

        My Reading History

    <div class="<?php echo (isset($single)?'':'warp'); ?>">
    <?php while ($row = $history->row()): ?>
        <div <?php echo (isset($single)?'class="list"':''); ?>>
            <a href="<?php echo baseUrl().
                "manga/$row->fmanga/chapter/$row->fchapter" ?>"
                <?php echo (isset($single)?'class="clearfix"':''); ?>>
            <?php if (isset($single)): ?>

                    <?php echo $row->chapter; ?>

                    <?php echo page()->date->relative($row->update_at); ?>

            <?php else: ?>
                <?php echo $row->chapter;?>
            <?php endif; ?>

    <?php endwhile; ?>

<div class="panel <?php echo (isset($single)?'single':''); ?>">

        <?php if (isset($single)): ?>
            Last Read
        <?php else: ?>
            My Reading History
        <?php endif; ?>

    <div class="<?php echo (isset($single)?'':'warp'); ?>">
    <?php while ($row = $history->row()): ?>
        <div <?php echo (isset($single)?'class="list"':''); ?>>
            <a href="<?php echo baseUrl().
                "manga/$row->fmanga/chapter/$row->fchapter" ?>"
                <?php echo (isset($single)?'class="clearfix"':''); ?>>
            <?php if (isset($single)): ?>

                    <?php echo $row->chapter; ?>

                    <?php echo page()->date->relative($row->update_at); ?>

            <?php else: ?>
                <?php echo $row->chapter;?>
            <?php endif; ?>

    <?php endwhile; ?>

Change title of history page depend on the current page


@section('title')
Searching for {{$search}} - Cataclysm: Dark Days Ahead Item Browser
@stop

Search: {{ $search }}

@if (!empty($items))

Items matches:

@foreach ($items as $item)

  {{$item->symbol}} $item->id)) }}">{{$item->name}}
  {{ $item->featureLabels }}

@endforeach
@endif

@if (!empty($monsters))

Monster matches:

@foreach($monsters as $monster)

{{ link_to_route("monster.view", $monster->name, array($monster->id)) }}
@endforeach

@endif

@section('title')
Searching for {{$search}} - Cataclysm: Dark Days Ahead Item Browser
@stop

Search: {{ $search }}

@if (!empty($items))

Items matches:

@foreach ($items as $item)

  {{$item->symbol}} $item->id)) }}">{{$item->name}}
  {{ $item->featureLabels }}

@endforeach
@endif

@if (!empty($monsters))

Monster matches:

@foreach($monsters as $monster)

{{$monster->symbol}} {{ link_to_route("monster.view", $monster->name, array($monster->id)) }}
@endforeach

@endif

Add monster symbols on the search results.


<?php

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

class JadePHPTest extends PHPUnit_Framework_TestCase {

    static private $skipped = array(
        // Here is the remain to implement list
        'inheritance.extend.mixins',
        'mixin.attrs',
        'mixin.block-tag-behaviour',
        'mixin.blocks',
        'mixin.merge',
        'tag.interpolation'
    );

    public function caseProvider() {
        static $rawResults = null;
        if(is_null($rawResults)) {
            $rawResults = get_tests_results();
            $rawResults = $rawResults['results'];
        }
        return $rawResults;
    }

    /**
     * @dataProvider caseProvider
     */
    public function testStringGeneration($name, $input, $expected) {
        if(! in_array($name, static::$skipped)) {
            $this->assertSame($input, $expected, $name);
        }
    }
}

<?php

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

class JadePHPTest extends PHPUnit_Framework_TestCase {

    static private $skipped = array(
        // Here is the remain to implement list
        'inheritance.extend.mixins',
        'mixin.attrs',
        'mixin.block-tag-behaviour',
        'mixin.blocks',
        'mixin.merge',
        'tag.interpolation'
    );

    public function caseProvider() {
        static $rawResults = null;
        if(is_null($rawResults)) {
            $rawResults = get_tests_results();
            $rawResults = $rawResults['results'];
        }
        return $rawResults;
    }

    /**
     * @dataProvider caseProvider
     */
    public function testStringGeneration($name, $input, $expected) {
        if(! in_array($name, static::$skipped)) {
            $this->assertSame($input, $expected, $name);
        }
    }
}

Use __DIR__ as PHP < 5.3 is not supported


<?php
/**
 * This helper package makes a database connection for package Kola\PotatoOrm\Model.
 *
 * @package Kola\PotatoOrm\Helper\DbConn
 * @author  Kolawole ERINOSO <kola.erinoso@gmail.com>
 * @license MIT <https://opensource.org/licenses/MIT>
 */

namespace Kola\PotatoOrm\Helper;

use Kola\PotatoOrm\Exception\UnsuccessfulDbConnException as ConnEx;
use \PDO;

final class DbConn extends PDO implements DbConnInterface
{
    /**
     * Override the parent class PDO constructor to prevent instantiation-argument requirement
     */
    public function __construct()
    {
    }

    /**
     * Make a database connection
     *
     * @return PDO|string
     */
    public static function connect()
    {
        self::loadDotenv();

        try {
            $dbConn = new PDO(getenv('DB_ENGINE') . ':host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_DATABASE'), getenv('DB_USERNAME'), getenv('DB_PASSWORD'));
            $dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (ConnEx $e) {
            return $e->message();
        }

        return $dbConn;
    }

    /**
     * Load Dotenv to grant getenv() access to environment variables in .env file
     */
    private static function loadDotenv()
    {
        $dotenv = new \Dotenv\Dotenv($_SERVER['DOCUMENT_ROOT']);
        $dotenv->load();
    }
}

<?php
/**
 * This helper package makes a database connection for package Kola\PotatoOrm\Model.
 *
 * @package Kola\PotatoOrm\Helper\DbConn
 * @author  Kolawole ERINOSO <kola.erinoso@gmail.com>
 * @license MIT <https://opensource.org/licenses/MIT>
 */

namespace Kola\PotatoOrm\Helper;

use Kola\PotatoOrm\Exception\UnsuccessfulDbConnException as ConnEx;
use \PDO;

final class DbConn extends PDO implements DbConnInterface
{
    /**
     * Override the parent class PDO constructor to prevent instantiation-argument requirement
     */
    public function __construct()
    {
    }

    /**
     * Make a database connection
     *
     * @return PDO|string
     */
    public static function connect()
    {
        self::loadDotenv();

        try {
            $dbConn = new PDO(getenv('DB_ENGINE') . ':host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_DATABASE') . ';charset=utf8mb4', getenv('DB_USERNAME'), getenv('DB_PASSWORD'), [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
				PDO::ATTR_PERSISTENT => false]);
        } catch (ConnEx $e) {
            return $e->message();
        }

        return $dbConn;
    }

    /**
     * Load Dotenv to grant getenv() access to environment variables in .env file
     */
    private static function loadDotenv()
    {
        $dotenv = new \Dotenv\Dotenv($_SERVER['DOCUMENT_ROOT']);
        $dotenv->load();
    }
}

Add UTF-8 charset to the db connection

Add UTF-8 charset to the db connection


<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * This file defines the admin settings for this plugin
 *
 * @package   assignsubmission_comments
 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

$settings->add(new admin_setting_configcheckbox('assignfeedback_comments/default',
                   new lang_string('default', 'assignfeedback_comments'),
                   new lang_string('default_help', 'assignfeedback_comments'), 0));

<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * This file defines the admin settings for this plugin
 *
 * @package   assignsubmission_comments
 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

$settings->add(new admin_setting_configcheckbox('assignfeedback_comments/default',
                   new lang_string('default', 'assignfeedback_comments'),
                   new lang_string('default_help', 'assignfeedback_comments'), 1));

MDL-34067: Change default to on for text feedback comments in assignment

This is the "default default" setting.


<?

namespace iFixit\TokenBucket;

use \InvalidArgumentException;

/**
 * Defines a rate of tokens per second. Specify the tokens you want to
 * allow for a given number of seconds.
 */
class TokenRate {
   private $rate;

   public function __construct($tokens, $seconds) {
      if (!is_int($tokens)) {
         throw new InvalidArgumentException("Tokens must be an int");
      }
      if (!is_numeric($seconds)) {
         throw new InvalidArgumentException("Seconds must be an int");
      }

      $this->tokens = $tokens;
      $this->seconds = $seconds;

      if ($this->tokens == 0 || $this->seconds == 0) {
         $this->rate = 0;
      } else {
         $this->rate = (double)$this->tokens / (double)$this->seconds;
      }
   }

   /**
    * @return double rate of token regeneration
    */
   public function getRate() {
      return $this->rate;
   }

   public function getTokens() {
      return $this->tokens;
   }

   public function getSeconds() {
      return $this->seconds();
   }
}

<?

namespace iFixit\TokenBucket;

use \InvalidArgumentException;

/**
 * Defines a rate of tokens per second. Specify the tokens you want to
 * allow for a given number of seconds.
 */
class TokenRate {
   private $rate;
   private $tokens;
   private $seconds;

   public function __construct($tokens, $seconds) {
      if (!is_int($tokens)) {
         throw new InvalidArgumentException("Tokens must be an int");
      }
      if (!is_numeric($seconds)) {
         throw new InvalidArgumentException("Seconds must be an int");
      }

      $this->tokens = $tokens;
      $this->seconds = $seconds;

      if ($this->tokens == 0 || $this->seconds == 0) {
         $this->rate = 0;
      } else {
         $this->rate = (double)$this->tokens / (double)$this->seconds;
      }
   }

   /**
    * @return double rate of token regeneration
    */
   public function getRate() {
      return $this->rate;
   }

   public function getTokens() {
      return $this->tokens;
   }

   public function getSeconds() {
      return $this->seconds();
   }
}

Add tokens and seconds as private members

These members shouldn't be accessible other than being specified in the
constructor. If they were updated after the fact then the rate wouldn't
represent the chnage.


<?php

namespace Frozone;

/**
 * Trait implementing Freezable.
 *
 * Include in your classes for sweet, chilly magic.
 */
trait Freeze /* implements FreezableInterface */ {

  /**
   * State flag indicating whether or not this object is frozen.
   *
   * Named oddly to help avoid naming collisions.
   *
   * @var bool
   */
  protected $_tfrozen = FALSE;

  /**
   * {@inheritdoc}
   */
  public function freeze() {
    $this->_tfrozen = TRUE;

    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isFrozen() {
    return $this->_tfrozen;
  }

  /**
   * Checks if the asset collection is frozen, throws an exception if it is.
   *
   * @param string $method
   *   The name of the method that was originally called.
   *
   * @throws FrozenObjectException
   */
  protected function attemptWrite($method) {
    if ($this->isFrozen()) {
      throw new FrozenObjectException(sprintf('State-changing method %s::%s called on a frozen object instance.', __CLASS__, $method));
    }
  }
}

<?php

namespace Frozone;

/**
 * Trait implementing Freezable.
 *
 * Make sure to begin any state-mutating method in the composed class with
 * a call to $this->attemptWrite(__METHOD__).
 */
trait Freeze /* implements FreezableInterface */ {

  /**
   * State flag indicating whether or not this object is frozen.
   *
   * Named oddly to help avoid naming collisions.
   *
   * @var bool
   */
  protected $_tfrozen = FALSE;

  public function freeze() {
    $this->attemptWrite('', 'Object is already frozen.');
    $this->_tfrozen = TRUE;

    return $this;
  }

  public function isFrozen() {
    return $this->_tfrozen;
  }

  /**
   * Checks if the object is frozen and throws an exception if it is.
   *
   * @throws FrozenObjectException
   */
  protected function attemptWrite() {
    if ($this->isFrozen()) {
      throw new FrozenObjectException(sprintf('State-changing method called on instance of %s.', __CLASS__));
    }
  }

  /**
   * Checks if the object is frozen and throws an exception if it is.
   *
   * @param string $method
   *   The name of the method that was originally called.
   *
   * @throws FrozenObjectException
   */
  protected function attemptWriteWithMethod($method) {
    if ($this->isFrozen()) {
      throw new FrozenObjectException(sprintf('State-changing method %s::%s called on a frozen object instance.', __CLASS__, $method));
    }
  }

  /**
   * Checks if the object is frozen and throws an exception if it is.
   *
   * @param string $msg
   *   The message to use in the exception, if frozen.
   *
   * @throws FrozenObjectException
   */
  protected function attemptWriteWithMessage($msg) {
    if ($this->isFrozen()) {
      throw new FrozenObjectException($msg);
    }
  }
}

Add two more AttemptWrite*() methods, for convenience.


<?php
namespace Staf\Generator;

use Illuminate\Console\Command;

class PublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'generator:build {definition=default}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Builds the static site';

    /**
     * The static site builder instance
     *
     * @var Builder
     */
    protected $builder;

    /**
     * Set the instance of the builder upon instantiation.
     *
     * @param Builder $builder
     */
    public function __construct(Builder $builder)
    {
        $this->builder = $builder;
    }

    /**
     *
     */
    public function handle()
    {
        $definitionName = $this->argument('definition');

        $definition = array_get(config('generator.definitions'), $definitionName);

        if ($definition === null) {
            $this->error('Invalid site definition provided.');

            return;
        }

        $this->builder->build($definition);

        $this->info("Static site '$definitionName' built!");
    }
}

<?php
namespace Staf\Generator;

use Illuminate\Console\Command;

class PublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'generator:build {definition=default}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Builds the static site';

    /**
     * The static site builder instance
     *
     * @var Builder
     */
    protected $builder;

    /**
     * Set the instance of the builder upon instantiation.
     *
     * @param Builder $builder
     */
    public function __construct(Builder $builder)
    {
        $this->builder = $builder;

        parent::__construct();
    }

    /**
     *
     */
    public function handle()
    {
        $definitionName = $this->argument('definition');

        $definition = array_get(config('generator.definitions'), $definitionName);

        if ($definition === null) {
            $this->error('Invalid site definition provided.');

            return;
        }

        $this->builder->build($definition);

        $this->info("Static site '$definitionName' built!");
    }
}

Call parent::__construct(); in the command.


<?php

/**
 * This model contains all methods for interacting with user emails.
 *
 * @package    Nails
 * @subpackage module-auth
 * @category   Model
 * @author     Nails Dev Team
 */

namespace Nails\Auth\Model\User;

use Nails\Auth\Constants;
use Nails\Common\Model\Base;

/**
 * Class Email
 *
 * @package Nails\Auth\Model\User
 */
class Email extends Base
{
    /**
     * The table this model represents
     *
     * @var string
     */
    const TABLE = NAILS_DB_PREFIX . 'user_email';

    /**
     * The name of the resource to use (as passed to \Nails\Factory::resource())
     *
     * @var string
     */
    const RESOURCE_NAME = 'UserEmail';

    /**
     * The provider of the resource to use (as passed to \Nails\Factory::resource())
     *
     * @var string
     */
    const RESOURCE_PROVIDER = Constants::MODULE_SLUG;
}

<?php

/**
 * This model contains all methods for interacting with user emails.
 *
 * @package    Nails
 * @subpackage module-auth
 * @category   Model
 * @author     Nails Dev Team
 */

namespace Nails\Auth\Model\User;

use Nails\Auth\Constants;
use Nails\Common\Model\Base;

/**
 * Class Email
 *
 * @package Nails\Auth\Model\User
 */
class Email extends Base
{
    /**
     * The table this model represents
     *
     * @var string
     */
    const TABLE = NAILS_DB_PREFIX . 'user_email';

    /**
     * The name of the resource to use (as passed to \Nails\Factory::resource())
     *
     * @var string
     */
    const RESOURCE_NAME = 'UserEmail';

    /**
     * The provider of the resource to use (as passed to \Nails\Factory::resource())
     *
     * @var string
     */
    const RESOURCE_PROVIDER = Constants::MODULE_SLUG;

    /**
     * Disable setting of created_by and modified_by columns
     *
     * @var bool
     */
    const AUTO_SET_USER = false;
}

Disable automatic setting of created and modified by columns


<?php

use Allsop\ObjectMap;

/**
 * Theme initialization.
 */

/**
 * Hide the 'Custom Fields' menu in production mode.
 */
if (defined('USE_PRODUCTION_ACF'))
{
    define('ACF_LITE', true);
}

/**
 * Load the classmap.
 */
require_once(FULL_PATH . 'vendor/autoload.php');

/**
 * Load helper functions.
 */
foreach (glob(FULL_PATH . 'app/helpers/*.php') as $filename)
{
    include $filename;
}

/**
 * Configure the site.
 */
require_once(FULL_PATH . 'config/init.php');

/**
 * Bind instances of each post type to the app so we can call them easily.
 * Simply add more by creating a new custom post-type class and
 * adding the full class path to the array below.
 */
ObjectMap::bind([
    'pages' => new Allsop\PostTypes\Page()),
    'posts' => new Allsop\PostTypes\Post())
]);

<?php

use Allsop\App;

/**
 * Theme initialization.
 */

/**
 * Hide the 'Custom Fields' menu in production mode.
 */
if (defined('USE_PRODUCTION_ACF'))
{
    define('ACF_LITE', true);
}

/**
 * Load the classmap.
 */
require_once(FULL_PATH . 'vendor/autoload.php');

/**
 * Load helper functions.
 */
foreach (glob(FULL_PATH . 'app/helpers/*.php') as $filename)
{
    include $filename;
}

/**
 * Configure the site.
 */
require_once(FULL_PATH . 'config/init.php');

/**
 * Bind instances of each post type to the app so we can call them easily.
 * Simply add more by creating a new custom post-type class and
 * adding the full class path to the array below.
 */
App::bind([
    'pages' => new Allsop\PostTypes\Page()),
    'posts' => new Allsop\PostTypes\Post())
]);

Change ObjectMap to new class name

Change ObjectMap to new class name


<?php

namespace App\Http\Requests\Api;

use Illuminate\Foundation\Http\FormRequest;

class InstallationModel extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return auth()->check() && auth()->user()->isAdmin();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'active' => 'required|integer',
        ];
    }
}

<?php

namespace App\Http\Requests\Api;

use Illuminate\Foundation\Http\FormRequest;

class InstallationModel extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return auth()->check() && auth()->user()->isAdmin();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'active' => 'required|boolean',
        ];
    }
}

Change active input to a boolean format instead of integer


<?php

namespace ZF2FileUploadExamples\Form;

use Zend\InputFilter;
use Zend\Form\Form;
use Zend\Form\Element;

class ProgressUpload extends Form
{
    public function __construct($name = null, $options = array())
    {
        parent::__construct($name, $options);
        $this->addElements();
        $this->setInputFilter($this->createInputFilter());
    }

    public function addElements()
    {
        // File Input
        $file = new Element\File('file');
        $file
            ->setLabel('File Input')
            ->setAttributes(array(
                'id' => 'file',
                'multiple' => true
            ));
        $this->add($file);

        // Progress ID
        $progressId = new Element\File\UploadProgress();
        $this->add($progressId);
        $this->byName['progressId'] = $progressId; // Add an alias for the view
    }

    public function createInputFilter()
    {
        $inputFilter = new InputFilter\InputFilter();

        // File Input
        $file = new InputFilter\FileInput('file');
        $file->setRequired(true);
        $inputFilter->add($file);

        return $inputFilter;
    }
}

<?php

namespace ZF2FileUploadExamples\Form;

use Zend\InputFilter;
use Zend\Form\Form;
use Zend\Form\Element;

class ProgressUpload extends Form
{
    public function __construct($name = null, $options = array())
    {
        parent::__construct($name, $options);
        $this->addElements();
        $this->setInputFilter($this->createInputFilter());
    }

    public function addElements()
    {
        // File Input
        $file = new Element\File('file');
        $file
            ->setLabel('File Input')
            ->setAttributes(array(
                'id' => 'file',
                'multiple' => true
            ));
        $this->add($file);

        // Progress ID
        $progressId = new Element\File\SessionProgress();
        $this->add($progressId);
        $this->byName['progressId'] = $progressId; // Add an alias for the view
    }

    public function createInputFilter()
    {
        $inputFilter = new InputFilter\InputFilter();

        // File Input
        $file = new InputFilter\FileInput('file');
        $file->setRequired(true);
        $inputFilter->add($file);

        return $inputFilter;
    }
}

Fix to use proper file element for session uploads


<?php

/*
 * Show debug code.
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

/*
 * Establish our routing table.
 */
$router = array();
$router['registrars'] = 'registrars';
$router['validator'] = 'validator';
$router['submit'] = 'submit';
$router['bounce'] = 'bounce';

/*
 * Identify which method is being requested, and whether any parameters are being passed to that
 * method.
 */
$url_components = parse_url($_SERVER['REQUEST_URI']);
$method = str_replace('/api/', '', $url_components['path']);
if (strpos($method, '/') !== FALSE)
{

	$tmp = explode('/', $method);
	$method = $tmp[0];
	if (!empty($tmp[1]))
	{
		$parameter = $tmp[1];
	}

}

/*
 * If our method is invalid, fail with a 404.
 */
if ( ($method === FALSE) || !isset($router[$method]) )
{
	header("HTTP/1.0 404 Not Found");
	echo '404 Not Found';
}

include $router[$method] . '.php';
/*
 * Enable cross-origin resource sharing (CORS).
 */
header("Access-Control-Allow-Origin: *");

<?php

/*
 * Show debug code.
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

/*
 * Establish our routing table.
 */
$router = array();
$router['registrars'] = 'registrars';
$router['validator'] = 'validator';
$router['submit'] = 'submit';
$router['bounce'] = 'bounce';

/*
 * Identify which method is being requested, and whether any parameters are being passed to that
 * method.
 */
$url_components = parse_url($_SERVER['REQUEST_URI']);
$method = str_replace('/api/', '', $url_components['path']);
if (strpos($method, '/') !== FALSE)
{

	$tmp = explode('/', $method);
	$method = $tmp[0];
	if (!empty($tmp[1]))
	{
		$parameter = $tmp[1];
	}

}

/*
 * If our method is invalid, fail with a 404.
 */
if ( ($method === FALSE) || !isset($router[$method]) )
{

	header("HTTP/1.0 404 Not Found");
	echo '404 Not Found';
	exit();

}

include $router[$method] . '.php';
/*
 * Enable cross-origin resource sharing (CORS).
 */
header("Access-Control-Allow-Origin: *");

Exit after sending a 404

Exit after sending a 404


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

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsViolations = $phpcsCLI->process(array('standard' => array('PSR1'), 'files' => array('src', '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(array('standard' => array('PSR1'), 'files' => array('bin', 'src', '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");

Check coding standard against bin directory as well.


<?php

/**
 * Container for multiple TwitterRequestTokenModel objects, also handles
 * collection metadata such as pagination
 */
class TwitterRequestTokenModelCollection extends AbstractModelCollection
{
    /** @var int */
    protected $total;

    /** @var array */
    protected $list;
    /**
     * Take arrays of data and create a collection of models; store metadata
     *
     * @param array $data
     * @param int $total
     */
    public function __construct(array $data, $total = 0)
    {
        $this->total = $total;
        $this->list = [];

        // hydrate the model objects
        foreach ($data as $item) {
            $this->list[] = new TwitterRequestTokenModel($item);
        }
    }

    /**
     * Present this collection ready for the output handlers
     *
     * This creates the expected output structure, converting each resource
     * to it's presentable representation and adding the meta fields for totals
     * and pagination
     *
     * @param Request $request
     * @param bool $verbose
     *
     * @return array
     */
    public function getOutputView(Request $request, $verbose = false)
    {
        // handle the collection first
        $retval                           = array();
        $retval['twitter_request_tokens'] = array();
        foreach ($this->list as $item) {
            $retval['twitter_request_tokens'][] = $item->getOutputView($request, $verbose);
        }

        // add other fields
        $retval['meta'] = $this->addPaginationLinks($request);

        return $retval;
    }
}

<?php

/**
 * Container for multiple TwitterRequestTokenModel objects, also handles
 * collection metadata such as pagination
 */
class TwitterRequestTokenModelCollection extends AbstractModelCollection
{
    /**
     * Take arrays of data and create a collection of models; store metadata
     *
     * @param array $data
     * @param int $total
     */
    public function __construct(array $data, $total = 0)
    {
        $this->total = $total;

        // hydrate the model objects
        foreach ($data as $item) {
            $this->list[] = new TwitterRequestTokenModel($item);
        }
    }

    /**
     * Present this collection ready for the output handlers
     *
     * This creates the expected output structure, converting each resource
     * to it's presentable representation and adding the meta fields for totals
     * and pagination
     *
     * @param Request $request
     * @param bool $verbose
     *
     * @return array
     */
    public function getOutputView(Request $request, $verbose = false)
    {
        // handle the collection first
        $retval                           = array();
        $retval['twitter_request_tokens'] = array();
        foreach ($this->list as $item) {
            $retval['twitter_request_tokens'][] = $item->getOutputView($request, $verbose);
        }

        // add other fields
        $retval['meta'] = $this->addPaginationLinks($request);

        return $retval;
    }
}

Undo ctor changes to derived class of AbstractModelCollection

These will be moved to a different branch


    <?php echo $savvy->render($context->getMonthWidget()); ?>

    Subscribe to this calendar

<a href="<?php echo $frontend->getUpcomingURL(); ?>?format=rss&limit=100" title="RSS feed of upcoming events" class="eventicon-rss">RSS

<a href="<?php echo $frontend->getUpcomingURL(); ?>?format=ics&limit=100" title="ICS format of upcoming events" class="wdn-icon-calendar">ICS

    <?php echo $savvy->render($context->getMonthWidget()); ?>

    Subscribe to this calendar

<a href="<?php echo $frontend->getUpcomingURL(); ?>?format=rss&limit=100" class="eventicon-rss">RSS

<a href="<?php echo $frontend->getUpcomingURL(); ?>?format=ics&limit=100" class="wdn-icon-calendar">ICS

Remove title attribute from Subscribe links


<?php
return [
    'vendor'    => 'Log viewer by Arcanedev',
    'menu' => [
        'category'  => "Logs",
        'stats'     => 'Statistics',
        'reports'   => 'Reports'
    ],
    'stats' => [
        'entries'   => ':count entries - :percent %'
    ],
    'list' => [
        'title'     => 'Logs list',
        'actions'   => 'Actions',
        'deletequestion'    => 'Are you sure you want to delete this log file ?',
    ],
    'show' => [
        'title'         => ':date report',
        'file'          => ':date log',
        'backtolist'    => 'Liste des fichiers',
        'download'      => 'Download',
        'delete'        => 'Delete log file',
        'levels'        => 'Levels',
        'loginfo'       => 'Log info',
        'filepath'      => 'File path',
        'logentries'    => 'Log entries',
        'size'          => 'Size',
        'createdat'     => 'Created at',
        'updatedat'     => 'Updated at',
        'page'          => 'Page :current of :last',
        'env'           => 'Env',
        'level'         => 'Level',
        'time'          => 'Time',
        'header'        => 'Header'
    ]
];

<?php
return [
    'vendor'    => 'Log viewer by Arcanedev',
    'menu' => [
        'category'  => "Logs",
        'stats'     => 'Statistics',
        'reports'   => 'Reports'
    ],
    'stats' => [
        'entries'   => ':count entries - :percent %'
    ],
    'list' => [
        'title'     => 'Logs list',
        'actions'   => 'Actions',
        'deletequestion'    => 'Are you sure you want to delete this log file ?',
    ],
    'show' => [
        'title'         => ':date report',
        'file'          => ':date log',
        'backtolist'    => 'List of logs',
        'download'      => 'Download',
        'delete'        => 'Delete log file',
        'levels'        => 'Levels',
        'loginfo'       => 'Log info',
        'filepath'      => 'File path',
        'logentries'    => 'Log entries',
        'size'          => 'Size',
        'createdat'     => 'Created at',
        'updatedat'     => 'Updated at',
        'page'          => 'Page :current of :last',
        'env'           => 'Env',
        'level'         => 'Level',
        'time'          => 'Time',
        'header'        => 'Header'
    ]
];

Fix french sentence in en lang file

Fix french sentence in en lang file


<?php
/**
 * Plugin Name: Example Success
 * Plugin URI:
 * Description: An example with wordpress-validator
 * Version: 1.0.0
 * Author: labodudev
 * Author URI: http://labodudev.fr
 * Requires at least: 4.1
 * Tested up to: 4.4
 */
if ( !defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

add_action( 'wp_ajax_add_github', 'ajax_add_github' );

function ajax_add_github() {
  // Check nonce
  $_wpnonce = sanitize_key( $_POST['_wpnonce'] );
  if ( wp_verify_nonce( $_wpnonce, 'ajax_add_github' ) )
    wp_send_json_error();

  // Securize email
  $email = sanitize_email( $_POST['email'] );

  wp_send_json_success( array( 'All data is securized!' ) );
}

?>

<?php
/**
 * Plugin Name: Example Success
 * Plugin URI:
 * Description: An example with wordpress-validator
 * Version: 1.0.0
 * Author: labodudev
 * Author URI: http://labodudev.fr
 * Requires at least: 4.1
 * Tested up to: 4.4
 */
if ( !defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

include_once( 'test/nonce.test.php');
include_once( 'test/request.test.php');

add_action( 'wp_ajax_add_github', 'ajax_add_github' );

function ajax_add_github() {
  // Check nonce
  $_wpnonce = sanitize_key( $_POST['_wpnonce'] );
  if ( wp_verify_nonce( $_wpnonce, 'ajax_add_github' ) )
    wp_send_json_error();

  // Securize email
  $email = sanitize_email( $_POST['email'] );

  wp_send_json_success( array( 'All data is securized!' ) );
}

?>

Include request and nonce test

Include request and nonce test


<?php

namespace App\Form\Type;

use App\Entity\Framework\AdditionalField;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class AdditionalFieldType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('displayName')
            ->add('appliesTo', null, ['data' => 'lsitem'])
            ->add('type')
            ->add('typeInfo', null, ['required' => false])
            ->add('save', SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => AdditionalField::class,
        ]);
    }
}

<?php

namespace App\Form\Type;

use App\Entity\Framework\AdditionalField;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

class AdditionalFieldType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $appliesToChoices = array(
            'LsItem' => 'lsitem',
            'LsAssociation' => 'lsassociation',
            'LsDoc' => 'LsDoc',
        );
        $builder
            ->add('name')
            ->add('displayName')
            ->add('appliesTo', ChoiceType::class, array('choices' => $appliesToChoices))
            ->add('type', null, ['data' => 'string'])
            ->add('typeInfo', null, ['required' => false])
            ->add('save', SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => AdditionalField::class,
        ]);
    }
}

Update the additonal fields form so the appliesto field is a select with the values lsitem, lsassociation, and lsdoc.


<?php
namespace MangoPay;

/**
 * Class represents direct debit type for mean of payment in PayIn entity
 */
class PayInPaymentDetailsDirectDebit extends Libraries\Dto implements PayInPaymentDetails
{
    /**
     * Direct debit type {SOFORT, ELV, GIROPAY}
     * @var string
     */
    public $DirectDebitType;

     /**
      * Mandate Id
      * @var string
      */
     public $MandateId;
}

<?php
namespace MangoPay;

/**
 * Class represents direct debit type for mean of payment in PayIn entity
 */
class PayInPaymentDetailsDirectDebit extends Libraries\Dto implements PayInPaymentDetails
{
    /**
     * Direct debit type {SOFORT, ELV, GIROPAY}
     * @var string
     */
    public $DirectDebitType;

     /**
      * Mandate Id
      * @var string
      */
     public $MandateId;

	 /**
     * StatementDescriptor
     * @var string
     */
     public $StatementDescriptor;
}

Add StatementDescriptor field for direct debits

Closes #138


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Beanstalkd UI Configuration
    |--------------------------------------------------------------------------
    |
    | This file stores the configuration parameters to connect to our
    | Beanstalkd Server. By default the default Beanstalkd server
    | parameters are used. But feel free to override then below.
    |
    */

    'host' => '127.0.0.1',

    'port' => '11300',

    /*
    |--------------------------------------------------------------------------
    | Route Middleware
    |--------------------------------------------------------------------------
    |
    | Here you can specify the route middleware that should be applied the
    | Admin UI routes. By default we simply require the user to be
    | logged in. If you have any additional authorization to
    | perform, this would be the place to specify it.
    |
    */

    'middleware' => ['web', 'auth'],

    /*
    |--------------------------------------------------------------------------
    | Failed Jobs
    |--------------------------------------------------------------------------
    |
    | If you do not want to be able to manage your failed jobs through
    | the UI as well, simply change this setting to `false`.
    |
    */

    'failed_jobs' => true,

    'failed_jobs_table' => 'failed_jobs',
];

Add setting to set the failed table

Add setting to set the failed table


                            {{ $title = config('app.name') }}

                        {{ $subtitle }}

Add a subtle gradient to the header

Add a subtle gradient to the header


<?php

$aFilesDelete = array(
    'inc/classes/BxDolConfig.php',
    'inc/js/editor.cleditor.js',
    'modules/base/text/template/entry-location.html',
    'plugins/OAuth/OAuth1/Service/Dolphin.php',
    'plugins_public/elementQuery.min.js',
    'studio/template/register.html',
    'template/scripts/BxBaseCmtsMenu.php',
    'template/bx_div.html',
    'template/bx_span.html',
    'plugins/lessphp/LICENSE',
    'plugins/lessphp/lessc.inc.php',
);

<?php

$aFilesDelete = array(
    'inc/js/editor.cleditor.js',
    'modules/base/text/template/entry-location.html',
    'plugins/OAuth/OAuth1/Service/Dolphin.php',
    'plugins_public/elementQuery.min.js',
    'studio/template/register.html',
    'template/scripts/BxBaseCmtsMenu.php',
    'template/bx_div.html',
    'template/bx_span.html',
    'plugins/lessphp/LICENSE',
    'plugins/lessphp/lessc.inc.php',
);

Upgrade Patch 8.0.0-A9 to 8.0.0-A10

Upgrade Patch 8.0.0-A9 to 8.0.0-A10


<?php

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

use Symfony\Polyfill\Intl\Normalizer as p;

if (!function_exists('normalizer_is_normalized')) {
    function normalizer_is_normalized($s, $form = p\Normalizer::NFC) { return p\Normalizer::isNormalized($s, $form); }
}
if (!function_exists('normalizer_normalize')) {
    function normalizer_normalize($s, $form = p\Normalizer::NFC) { return p\Normalizer::normalize($s, $form); }
}

<?php

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

use Symfony\Polyfill\Intl\Normalizer as p;

if (!function_exists('normalizer_is_normalized')) {
    function normalizer_is_normalized($input, $form = p\Normalizer::NFC) { return p\Normalizer::isNormalized($input, $form); }
}
if (!function_exists('normalizer_normalize')) {
    function normalizer_normalize($input, $form = p\Normalizer::NFC) { return p\Normalizer::normalize($input, $form); }
}

Fix the name of arguments for PHP 8

Fix the name of arguments for PHP 8


<?php
class RandomIntTest extends PHPUnit_Framework_TestCase
{
    public function testFuncExists()
    {
        $this->assertTrue(function_exists('random_int'));
    }

    public function testOutput()
    {
        $integers = [
            random_int(0, 1000),
            random_int(1001,2000)
        ];

        $this->assertFalse($integers[0] === $integers[1]);
        $this->assertTrue($integers[0] <= 1000 && $integers[0] >= 0);
        $this->assertTrue($integers[1] < 2001 && $integers[1] > 1000);
    }
}

<?php
class RandomIntTest extends PHPUnit_Framework_TestCase
{
    public function testFuncExists()
    {
        $this->assertTrue(function_exists('random_int'));
    }

    public function testOutput()
    {
        $integers = [
            random_int(0, 1000),
            random_int(1001,2000)
        ];

        $this->assertFalse($integers[0] === $integers[1]);
        $this->assertTrue($integers[0] <= 1000 && $integers[0] >= 0);
        $this->assertTrue($integers[1] < 2001 && $integers[1] > 1000);
    }

    public function testDistribution()
    {
        $integers = array_fill(0, 100, 0);
        for ($i = 0; $i < 10000; ++$i) {
            ++$integers[random_int(0,99)];
        }
        for ($i = 0; $i < 100; ++$i) {
            $this->assertFalse($integers[$i] < 30);
            $this->assertFalse($integers[$i] > 170);
        }
    }
}

Add some tests on the distribution of random values.


<?php

namespace Bernard\Tests\Fixtures;

class Service
{
    public $importUsers = false;

    public function failSendNewsletter()
    {
        throw new \Exception();
    }

    public function importUsers()
    {
        $this->importUsers = true;
    }

    public function createFile()
    {
        touch(__DIR__ . '/create_file.test');
    }
}

<?php

namespace Bernard\Tests\Fixtures;

class Service
{
    public $importUsers = false;

    public function failSendNewsletter()
    {
        throw new \Exception();
    }

    public function importUsers()
    {
        $this->importUsers = true;
    }

    public function createFile()
    {
        touch(__DIR__ . '/create_file.test');
    }

    public function importReport(Report $report)
    {
        // note: the class hinted on this method does not exist on purpose, as calling this method should cause a
        //       Throwable to be thrown
    }
}

Test asset that causes a `TypeError` to be raised (on purpose)


<?php

namespace Fogs\TaggingBundle\Entity;

use \FPN\TagBundle\Entity\Tagging as BaseTagging;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\UniqueConstraint;

/**
 * Fogs\TaggingBundle\Entity\Tagging
 *
 * @ORM\Table(uniqueConstraints={@UniqueConstraint(name="tagging_idx", columns={"tag_id", "resource_type", "resource_id"})})
 * @ORM\Entity
 */
class Tagging extends BaseTagging
{
	/**
	 * @var integer $id
	 *
	 * @ORM\Column(name="id", type="integer")
	 * @ORM\Id
	 * @ORM\GeneratedValue(strategy="AUTO")
	 */
	protected $id;

	/**
	 * @ORM\ManyToOne(targetEntity="Tag")
	 * @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
	 **/
	protected $tag;
}

<?php

namespace Fogs\TaggingBundle\Entity;

use \FPN\TagBundle\Entity\Tagging as BaseTagging;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\UniqueConstraint;

/**
 * Fogs\TaggingBundle\Entity\Tagging
 *
 * @ORM\Table(uniqueConstraints={@UniqueConstraint(name="tagging_idx", columns={"tag_id", "resource_type", "resource_id"})})
 * @ORM\Entity
 */
class Tagging extends BaseTagging
{
	/**
	 * @var integer $id
	 *
	 * @ORM\Column(name="id", type="integer")
	 * @ORM\Id
	 * @ORM\GeneratedValue(strategy="AUTO")
	 */
	protected $id;

	/**
	 * @ORM\ManyToOne(targetEntity="Tag", inversedBy="tagging")
	 * @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
	 **/
	protected $tag;
}

Add 'inversedBy' attribute on ManyToOne association with Tag entity

Without this attribute the entity mapping information won't be considered valid.


<?php
/*
 * Copyright (c) 2015, Dalenys
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

namespace OctoSend;

class SpoolerBatch
{
        function __construct($ctx, $token)
        {
                $this->_ctx    = $ctx;
                $this->_token  = $token;
                $this->_mails = [];
        }

        function mail($email)
        {
                $m = new Mail($this->_ctx, $this->_token, $email);
                array_push($this->_mails, $m);
                return $m;
        }

        function spool()
        {
                return $this->_ctx->spooler_spool_batch($this->_token, $this->_mails);
        }
}

?>

<?php
/*
 * Copyright (c) 2015, Dalenys
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

namespace OctoSend;

class SpoolerBatch
{
    function __construct($ctx, $token)
    {
        $this->_ctx    = $ctx;
        $this->_token  = $token;
        $this->_mails  = [];
    }

    function mail($email)
    {
        $m = new Mail($this->_ctx, $this->_token, $email);
        array_push($this->_mails, $m);
        return $m;
    }

    function spool()
    {
        return $this->_ctx->spooler_spool_batch($this->_token, $this->_mails);
    }

    function draft()
    {
        return $this->_ctx->spooler_spool_draft($this->_token, $this->_mails);
    }
}

Add a draft method on spoolerbatch to draft to several email in one call


    @if (!$hideTitle && !empty($post_title))

{!! apply_filters('the_title', $post_title) !!}

    @endif

    @foreach ($items as $item)

            @if ($item['thumbnail'])

            @endif

{{ $item['title'] }}

                {!! $item['lead'] !!}

    @endforeach

    @if (!$hideTitle && !empty($post_title))

            @typography([
                'element' => 'h2'
            ])
                {!! apply_filters('the_title', $post_title) !!}
            @endtypography

    @endif

    @foreach ($items as $item)

            @link([
                'href' => $item['permalink'],
                'classList' => [$classes],
                'attributeList' => ['data-equal-item' => '']
            ])
                @if ($item['thumbnail'])
                    @image([
                        'src'=> $item['thumbnail'][0],
                        'alt' => $item['title'],
                        'classList' => ['box-image']
                    ])
                    @endimage
                @endif

                    @typography([
                        'element' => 'h5',
                        'variant' => 'h5',
                        'classList' => ['box-index-title link-item']
                    ])
                        {{ $item['title'] }}
                    @endtypography

                    {!! $item['lead'] !!}

            @endlink

    @endforeach

Index module - add use of components in index module


<?php
/**
 * Copyright (c) 2014 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Licensed under the MIT license:
 * http://opensource.org/licenses/MIT
 */

namespace Icewind\SMB\Exception;

class InvalidRequestException extends Exception {
	/**
	 * @var string
	 */
	protected $path;

	/**
	 * @param string $path
	 * @param int $code
	 */
	public function __construct($path, $code = 0) {
		parent::__construct('Invalid request for ' . $path, $code);
		$this->path = $path;
	}

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

<?php
/**
 * Copyright (c) 2014 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Licensed under the MIT license:
 * http://opensource.org/licenses/MIT
 */

namespace Icewind\SMB\Exception;

class InvalidRequestException extends Exception {
	/**
	 * @var string
	 */
	protected $path;

	/**
	 * @param string $path
	 * @param int $code
	 */
	public function __construct($path, $code = 0) {
		$class = get_class($this);
		$parts = explode('\\', $class);
		$baseName = array_pop($parts);
		parent::__construct('Invalid request for ' . $path . ' (' . $baseName . ')', $code);
		$this->path = $path;
	}

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

Put exception class in message

Put exception class in message


<?php

namespace Backend\Core\Tests;

use Common\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

abstract class BackendWebTestCase extends WebTestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Backend');
        }
    }

    protected function assertAuthenticationIsNeeded(Client $client, string $url, string $method = 'GET'): void
    {
        // make sure we aren't logged in with the client
        $this->logout($client);

        $this->assertGetsRedirected(
            $client,
            $url,
            '/private/en/authentication?querystring=' . rawurlencode($url),
            $method
        );
    }
}

<?php

namespace Backend\Core\Tests;

use Backend\Core\Engine\Authentication as Authentication;
use Common\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

abstract class BackendWebTestCase extends WebTestCase
{
    /**
     * Make sure we are no longer logged-in
     */
    protected function tearDown(): void
    {
        $client = $this->getProvidedData()[0] ?? null;
        if ($client instanceof Client) {
            $this->logout($client);
        }
    }

    protected function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Backend');
        }
    }

    protected function assertAuthenticationIsNeeded(Client $client, string $url, string $method = 'GET'): void
    {
        // make sure we aren't logged in with the client
        $this->logout($client);

        $this->assertGetsRedirected(
            $client,
            $url,
            '/private/en/authentication?querystring=' . rawurlencode($url),
            $method
        );
    }
}

Make sure that you are logged out at the end of a backend test


<?php
namespace Nubs\PwMan;

use Exception;

/**
 * Manage the collection of passwords.
 */
class PasswordManager
{
    /** @type array<array> The passwords. */
    private $_passwords;

    /**
     * Initialize the password manager.
     *
     * @param array<array> The passwords.
     */
    public function __construct(array $passwords)
    {
        $this->_passwords = $passwords;
    }

    /**
     * Find all the passwords that match the given application name.
     *
     * The application name is used as a regex.
     *
     * @param string $application The application name.
     * @return array<array> The passwords for the applications that match the
     *     application.
     */
    public function matchingApplication($application)
    {
        $result = [];
        foreach ($this->_passwords as $key => $value) {
            if (preg_match("/{$application}/i", $key)) {
                $result[$key] = $value;
            }
        }

        return $result;
    }

    /**
     * Add the new application to the password list.
     *
     * @param array $newApplication The application information.
     * @return void
     */
    public function addPassword($name, array $newApplication)
    {
        if (isset($this->_passwords[$name])) {
            throw new Exception("Password already exists for {$name}");
        }

        $this->_passwords[$name] = $newApplication;
    }

    /**
     * Get the passwords.
     *
     * @return array<array> The passwords.
     */
    public function getPasswords()
    {
        return $this->_passwords;
    }
}

<?php
namespace Nubs\PwMan;

use Exception;

/**
 * Manage the collection of passwords.
 */
class PasswordManager
{
    /** @type array<array> The passwords. */
    private $_passwords;

    /**
     * Initialize the password manager.
     *
     * @param array<array> The passwords.
     */
    public function __construct(array $passwords)
    {
        $this->_passwords = $passwords;
    }

    /**
     * Find all the passwords that match the given application name.
     *
     * The application name is used as a regex.
     *
     * @param string $application The application name.
     * @return array<array> The passwords for the applications that match the
     *     application.
     */
    public function matchingApplication($application)
    {
        $result = [];
        foreach ($this->_passwords as $key => $value) {
            if (preg_match("/{$application}/i", $key)) {
                $result[$key] = $value;
            }
        }

        return $result;
    }

    /**
     * Add the new application to the password list.
     *
     * @param string $name The unique application name.
     * @param array $newApplication The application information.
     * @return void
     */
    public function addPassword($name, array $newApplication)
    {
        if (isset($this->_passwords[$name])) {
            throw new Exception("Password already exists for {$name}");
        }

        $this->_passwords[$name] = $newApplication;
    }

    /**
     * Get the passwords.
     *
     * @return array<array> The passwords.
     */
    public function getPasswords()
    {
        return $this->_passwords;
    }
}

Document the application name parameter.


<?php

namespace Sandertv\BlockSniper\events;

use pocketmine\event\plugin\PluginEvent;
use Sandertv\BlockSniper\Loader;

abstract class BaseEvent extends PluginEvent {

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

	public function getOwner() {
		return $this->owner;
	}
}

<?php

namespace Sandertv\BlockSniper\events;

use pocketmine\event\plugin\PluginEvent;

abstract class BaseEvent extends PluginEvent {

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

	public function getOwner() {
		return $this->owner;
	}
}

Fix events with wrong constructor.

Fix events with wrong constructor.


<?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 Closure to execute when that URI is requested.
|
*/

Route::get('/', 'HomeController@showWelcome');

Route::get('trigger', 'HomeController@trigger');

<?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 Closure to execute when that URI is requested.
|
*/

Route::get('/', 'HomeController@showClient');

Route::get('trigger', 'HomeController@trigger');

Check your damn code before you commit it. Fixes home route


<?php

namespace Burgov\Bundle\KeyValueFormBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('burgov_key_value_form');

        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}

<?php

namespace Burgov\Bundle\KeyValueFormBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('burgov_key_value_form');

        if (method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->getRootNode();
        } else {
            // BC layer for symfony/config 4.1 and older
            $rootNode = $treeBuilder->root('burgov_key_value_form');
        }

        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}

Fix Symfony 4.2 deprecations for TreeBuilder


<?php

use PHPUnit\Framework\TestCase;

class ArrayableNodeCollectionTest extends TestCase
{
    /** @test */
    function it_can_count_the_values()
    {
        $collection = $this->getCollection();

        $this->assertCount(2,$collection);
    }

    /** @test */
    function it_can_get_value_by_key()
    {
        $collection = $this->getCollection();

        $this->assertInstanceOf(\Vine\Node::class,$collection[1]);
    }

    /** @test */
    function it_can_set_value_by_key()
    {
        $collection = $this->getCollection();
        $collection[2] = 'foobar';

        $this->assertCount(3,$collection);
        $this->assertEquals('foobar',$collection[2]);
    }

    /** @test */
    function it_can_unset_a_value()
    {
        $collection = $this->getCollection();

        $this->assertCount(2,$collection);
        unset($collection[1]);

        $this->assertCount(1,$collection);
    }

    /** @test */
    function it_can_check_if_key_exists()
    {
        $collection = $this->getCollection();

        $this->assertTrue(isset($collection[1]));
        $this->assertFalse(isset($collection[2]));
    }

    /** @test */
    function it_can_loop_over_collection()
    {
        $collection = $this->getCollection();

        $flag = 0;
        foreach($collection as $node){ $flag++; }

        $this->assertEquals(2,$flag);
    }

    /**
     * @return \Vine\NodeCollection
     */
    private function getCollection(): \Vine\NodeCollection
    {
        $collection = new \Vine\NodeCollection(
            new \Vine\Node(null),
            new \Vine\Node(null)
        );

        return $collection;
    }
}

Test native array behaviour of collection


<?php
/**
 * This file is part of the Zimbra API in PHP library.
 *
 * © Nguyen Van Nguyen <nguyennv1981@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Zimbra\Soap\Request;

use Zimbra\Soap\Request;
use Zimbra\Struct\AttrsImplTrait;

/**
 * Attr class in Zimbra API PHP, not to be instantiated.
 *
 * @package   Zimbra
 * @category  API
 * @author    Nguyen Van Nguyen - nguyennv1981@gmail.com
 * @copyright Copyright © 2013 by Nguyen Van Nguyen.
 */
abstract class Attr extends Request
{
    use AttrsImplTrait;
}

<?php
/**
 * This file is part of the Zimbra API in PHP library.
 *
 * © Nguyen Van Nguyen <nguyennv1981@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Zimbra\Soap\Request;

use Zimbra\Soap\Request;
use Zimbra\Struct\AttrsImplTrait;

/**
 * Attr class in Zimbra API PHP, not to be instantiated.
 *
 * @package   Zimbra
 * @category  API
 * @author    Nguyen Van Nguyen - nguyennv1981@gmail.com
 * @copyright Copyright © 2013 by Nguyen Van Nguyen.
 */
abstract class Attr extends Request
{
    use AttrsImplTrait {
        AttrsImplTrait::__construct as private __attrConstruct;
    }

    /**
     * Constructor method for AttrsImpl
     * @param array $attrs
     * @return self
     */
    public function __construct(array $attrs = [])
    {
        $this->__attrConstruct($attrs);
    }
}

Fix has colliding constructor definitions coming from traits


<?php
/**
 * Trait Google\Site_Kit\Core\Util\Requires_Javascript_Trait
 *
 * @package   Google\Site_Kit\Core\Util
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Core\Util;

/**
 * Trait to display no javascript fallback message.
 *
 * @since n.e.x.t
 * @access private
 * @ignore
 */
trait Requires_Javascript_Trait {

	/**
	 * Display fallback message when Javascript is disabled
	 *
	 * @since n.e.x.t
	 *
	 * @return string noscript HTML tag,
	 */
	protected function get_noscript_html() {

		ob_start();

		?>

									<?php
										esc_html_e( 'The Site Kit by Google plugin requires JavaScript to be enabled in your browser.', 'google-site-kit' )
									?>

		<?php

		return ob_get_clean();
	}
}

<?php
/**
 * Trait Google\Site_Kit\Core\Util\Requires_Javascript_Trait
 *
 * @package   Google\Site_Kit\Core\Util
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Core\Util;

/**
 * Trait to display no javascript fallback message.
 *
 * @since n.e.x.t
 * @access private
 * @ignore
 */
trait Requires_Javascript_Trait {

	/**
	 * Outputs a fallback message when Javascript is disabled.
	 *
	 * @since n.e.x.t
	 */
	protected function render_noscript_html() {
		?>

									<?php
										esc_html_e( 'The Site Kit by Google plugin requires JavaScript to be enabled in your browser.', 'google-site-kit' )
									?>

		<?php
	}
}

Update noscript method to output rather than return.


<?php

use Enzyme\Loopy\Filters\SkipNulls;

class SkipNullsFilterTest extends PHPUnit_Framework_TestCase
{
    public function testPassesThroughFilterSuccess()
    {
        $filter = new SkipNulls;
        $expected = true;

        $key = 1;
        $value = 1;
        $this->assertEquals($expected, $filter->passes($key, $value));

        $key = null;
        $value = 1;
        $this->assertEquals($expected, $filter->passes($key, $value));
    }

    public function testPassesThroughFilterFailure()
    {
        $filter = new SkipNulls;
        $expected = false;

        $key = 1;
        $value = null;
        $this->assertEquals($expected, $filter->passes($key, $value));

        $key = null;
        $value = null;
        $this->assertEquals($expected, $filter->passes($key, $value));
    }
}

<?php

use Enzyme\Loopy\Each;
use Enzyme\Loopy\Filters\SkipNulls;

class SkipNullsFilterTest extends PHPUnit_Framework_TestCase
{
    public function testPassesThroughFilterSuccess()
    {
        $filter = new SkipNulls;
        $expected = true;

        $key = 1;
        $value = 1;
        $this->assertEquals($expected, $filter->passes($key, $value));

        $key = null;
        $value = 1;
        $this->assertEquals($expected, $filter->passes($key, $value));
    }

    public function testPassesThroughFilterFailure()
    {
        $filter = new SkipNulls;
        $expected = false;

        $key = 1;
        $value = null;
        $this->assertEquals($expected, $filter->passes($key, $value));

        $key = null;
        $value = null;
        $this->assertEquals($expected, $filter->passes($key, $value));
    }

    public function testFilterWorksAsExpected()
    {
        $filter = new SkipNulls;
        $expected = [1, 2, 4];
        $array = [1, 2, null, 4];

        $actual = [];

        Each::shallow($filter)->begin($array, function($bag) use(&$actual) {
            $actual[] = $bag->value();
        });

        $this->assertEquals($expected, $actual);
    }
}

Add futher tests to SkipNulls filter.

Add futher tests to SkipNulls filter.


<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Http\Controllers;

class FallbackController extends Controller
{
    public function __construct()
    {
        if (is_api_request()) {
            $this->middleware('api');
        } else {
            $this->middleware('web');
        }

        parent::__construct();
    }

    public function index()
    {
        if (is_json_request()) {
            return error_popup(trans('errors.missing_route'), 404);
        }

        return ext_view('layout.error', ['statusCode' => 404], 'html', 404);
    }
}

<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Http\Controllers;

class FallbackController extends Controller
{
    public function __construct()
    {
        if (is_api_request()) {
            $this->middleware('api');
        } else {
            $this->middleware('web');
        }

        parent::__construct();
    }

    public function index()
    {
        app('route-section')->setError(404);

        if (is_json_request()) {
            return error_popup(trans('errors.missing_route'), 404);
        }

        return ext_view('layout.error', ['statusCode' => 404], 'html', 404);
    }
}

Put back set error (now in correct place)


<?php

namespace Doctrine\Search\Serializer;

use Doctrine\Search\SerializerInterface;
use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\Naming\IdenticalPropertyNamingStrategy;

class JMSSerializer implements SerializerInterface
{
    protected $serializer;
    protected $context;

    public function __construct(SerializationContext $context = null)
    {
        $this->context = $context;
        $this->serializer = SerializerBuilder::create()
            ->setPropertyNamingStrategy(new IdenticalPropertyNamingStrategy())
            ->addDefaultHandlers()
       	   ->build();
    }

    public function serialize($object)
    {
        $context = $this->context ? clone $this->context : null;
        return json_decode($this->serializer->serialize($object, 'json', $context), true);
    }
}

<?php

namespace Doctrine\Search\Serializer;

use Doctrine\Search\SerializerInterface;
use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\Naming\SerializedNameAnnotationStrategy;
use JMS\Serializer\Naming\IdenticalPropertyNamingStrategy;

class JMSSerializer implements SerializerInterface
{
    protected $serializer;
    protected $context;

    public function __construct(SerializationContext $context = null)
    {
        $this->context = $context;
        $this->serializer = SerializerBuilder::create()
            ->setPropertyNamingStrategy(new SerializedNameAnnotationStrategy(new IdenticalPropertyNamingStrategy()))
            ->addDefaultHandlers()
       	   ->build();
    }

    public function serialize($object)
    {
        $context = $this->context ? clone $this->context : null;
        return json_decode($this->serializer->serialize($object, 'json', $context), true);
    }
}

Update to JMS Serializer to allow manual override


<?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\Inventory\Factory;

use Doctrine\Common\Collections\ArrayCollection;
use Sylius\Component\Inventory\Model\InventoryUnitInterface;
use Sylius\Component\Inventory\Model\StockableInterface;
use Sylius\Component\Resource\Factory\Factory;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * Default inventory operator.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class InventoryUnitFactory extends Factory implements InventoryUnitFactoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function createForStockable(StockableInterface $stockable, $quantity, $state = InventoryUnitInterface::STATE_SOLD)
    {
        if ($quantity < 1) {
            throw new \InvalidArgumentException('Quantity of units must be greater than 1.');
        }

        $units = new ArrayCollection();

        for ($i = 0; $i < $quantity; $i++) {
            $inventoryUnit = parent::createNew();
            $inventoryUnit->setStockable($stockable);
            $inventoryUnit->setInventoryState($state);

            $units->add($inventoryUnit);
        }

        return $units;
    }
}

<?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\Inventory\Factory;

use Doctrine\Common\Collections\ArrayCollection;
use Sylius\Component\Inventory\Model\InventoryUnitInterface;
use Sylius\Component\Inventory\Model\StockableInterface;
use Sylius\Component\Resource\Factory\Factory;

/**
 * Default inventory operator.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class InventoryUnitFactory extends Factory implements InventoryUnitFactoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function createForStockable(StockableInterface $stockable, $quantity, $state = InventoryUnitInterface::STATE_SOLD)
    {
        if ($quantity < 1) {
            throw new \InvalidArgumentException('Quantity of units must be greater than 1.');
        }

        $units = new ArrayCollection();

        for ($i = 0; $i < $quantity; $i++) {
            $inventoryUnit = parent::createNew();
            $inventoryUnit->setStockable($stockable);
            $inventoryUnit->setInventoryState($state);

            $units->add($inventoryUnit);
        }

        return $units;
    }
}

Update all configurations to include factories


<?php
require_once('vendor/autoload.php');

if (!PRODUCTION)
{
  error_reporting(E_ALL);
  ini_set('display_errors','On');
}

function phoxy_conf()
{
  $ret = phoxy_default_conf();
  $ret["api_xss_prevent"] = PRODUCTION;

  return $ret;
}

function default_addons()
{
  $ret =
  [
    "cache" => PRODUCTION ? ['global' => '10m'] : "no",
    "result" => "canvas",
  ];
  return $ret;
}

include('phoxy/phoxy_return_worker.php');
phoxy_return_worker::$add_hook_cb = function($that)
{
  global $USER_SENSITIVE;

  if ($USER_SENSITIVE)
    $that->obj['cache'] = 'no';
};

phpsql\OneLineConfig(conf()->db->connection_string);

include('phoxy/load.php');

<?php
require_once('vendor/autoload.php');

if (!PRODUCTION)
{
  error_reporting(E_ALL);
  ini_set('display_errors','On');
}

function phoxy_conf()
{
  $ret = phoxy_default_conf();
  $ret["api_xss_prevent"] = PRODUCTION;

  return $ret;
}

function default_addons()
{
  $ret =
  [
    "cache" => PRODUCTION ? ['global' => '10m'] : "no",
    "result" => "canvas",
  ];
  return $ret;
}

include('phoxy/phoxy_return_worker.php');
phoxy_return_worker::$add_hook_cb = function($that)
{
  global $USER_SENSITIVE;

  if ($USER_SENSITIVE)
    $that->obj['cache'] = 'no';
};

phpsql\OneLineConfig(conf()->db->connection_string);

db::Query("INSERT INTO requests(url, get, post, headers, server) VALUES ($1, $2, $3, $4, $5)",
  [
    $_SERVER['QUERY_STRING'],
    json_encode($_GET),
    json_encode($_POST),
    json_encode(getallheaders()),
    json_encode($_SERVER),
  ]);

include('phoxy/load.php');

Store every single request for debug and security purposes


<?php

/**
 *  @link    http://foundationize.com
 *  @package foundationize/yii2-foundation
 *  @version dev
 */

namespace foundationize\foundation;

use Yii;
use yii\helpers\Html;

class FnActiveForm extends \yii\widgets\ActiveForm {

    public $fieldClass = 'foundationize\foundation\FnActiveField';
    public $layout = 'default';

    /**
     * Override default settings for form
     */
    //public $errorCssClass = 'form-error';

    /**
     * @inheritdoc
     */
    public function init() {
        if (!in_array($this->layout, ['default', 'inline'])) {
            throw new InvalidConfigException('Invalid layout type: ' . $this->layout);
        }

        if ($this->layout !== 'default') {
            Html::addCssClass($this->options, 'form-' . $this->layout);
        }
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function run() {
        parent::run();
        $view = $this->getView();
        ActiveFormAsset::register($view);
    }

}

<?php

/**
 *  @link    http://foundationize.com
 *  @package foundationize/yii2-foundation
 *  @version dev
 */

namespace foundationize\foundation;

use Yii;
use yii\helpers\Html;

class FnActiveForm extends \yii\widgets\ActiveForm {

    public $fieldClass = 'foundationize\foundation\FnActiveField';
    public $layout = 'default';

    /**
     * Override default settings for form
     */
    //public $errorCssClass = 'form-error';

    /**
     * @inheritdoc
     */
    public function init() {
        if (!in_array($this->layout, ['default', 'inline'])) {
            throw new InvalidConfigException('Invalid layout type: ' . $this->layout);
        }

        if ($this->layout !== 'default') {
            Html::addCssClass($this->options, 'form-' . $this->layout);
        }
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function run() {
        $view = $this->getView();
        ActiveFormAsset::register($view);

        return parent::run();
    }

}

Upgrade to yii2 version 2.0.16

Upgrade to yii2 version 2.0.16

see https://github.com/yiisoft/yii2/blob/2.0.16/framework/UPGRADE.md#upgrade-from-yii-207


<?php

$REGISTER_LTI2 = array(
"name" => "Peer-Graded Dropbox",
"FontAwesome" => "fa-code-fork",
"short_name" => "Peer Grader",
"description" => "This tool provides a structured dropbox that can take images, URLs, text and code.  These tools can be peer-graded, instructor graded, or a blend of peer and instructor graded assignments."
);

<?php

$REGISTER_LTI2 = array(
"name" => "Peer-Graded Dropbox",
"FontAwesome" => "fa-code-fork",
"short_name" => "Peer Grader",
"description" => "This tool provides a structured dropbox that can take images, URLs, text and code.  These tools can be peer-graded, instructor graded, or a blend of peer and instructor graded assignments.",
"messages" => array("launch", "launch_grade")
);

Add a bunch of things for ContentItem support