<?php namespace App\Providers;

use Permission;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
	protected $policies = [
		'App\Data\Discussion' => 'App\Policies\DiscussionPolicy',
		'App\Data\Topic' => 'App\Policies\TopicPolicy',
	];

	public function boot()
	{
		$this->registerPolicies();

		// Grab all of the permissions, loop through them, and define the abilities
		$this->getPermissions()->each(function ($permission) {
			Gate::define($permission->name, function ($user) use ($permission) {
				return $user->hasRole($permission->roles->all());
			});
		});

		// Allow admins to do whatever they want
		Gate::before(function ($user) {
			if ($user->hasRole('Forum Administrator')) {
				return true;
			}
		});
	}

	protected function getPermissions()
	{
		return Permission::with('roles')->get();
	}
}

<?php namespace App\Providers;

use Permission;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
	protected $policies = [
		'App\Data\Discussion' => 'App\Policies\DiscussionPolicy',
		'App\Data\Reply' => 'App\Policies\ReplyPolicy',
		'App\Data\Topic' => 'App\Policies\TopicPolicy',
	];

	public function boot()
	{
		$this->registerPolicies();

		// Grab all of the permissions, loop through them, and define the abilities
		$this->getPermissions()->each(function ($permission) {
			Gate::define($permission->name, function ($user) use ($permission) {
				return $user->hasRole($permission->roles->all());
			});
		});

		// Allow admins to do whatever they want
		Gate::before(function ($user) {
			if ($user->hasRole('Forum Administrator')) {
				return true;
			}
		});
	}

	protected function getPermissions()
	{
		return Permission::with('roles')->get();
	}
}

Add the reply policy to the auth SP

Add the reply policy to the auth SP


<?php declare(strict_types=1);

namespace Becklyn\RadBundle\Exception;

/**
 * Generic exception that marks, that the entity removal may be blocked by database (foreign keys, etc..) or
 * semantic constraints (e.g. "can't remove main category").
 */
class EntityRemovalBlockedException extends \DomainException
{
    /**
     * @var object
     */
    private $entity;

    /**
     * @inheritDoc
     *
     * @param object Entity
     */
    public function __construct ($entity, string $message, \Throwable $previous = null)
    {
        parent::__construct($message, 0, $previous);
        $this->entity = $entity;
    }

    /**
     * @return object
     */
    public function getEntity ()
    {
        return $this->entity;
    }
}

<?php declare(strict_types=1);

namespace Becklyn\RadBundle\Exception;

/**
 * Generic exception that marks, that the entity removal may be blocked by database (foreign keys, etc..) or
 * semantic constraints (e.g. "can't remove main category").
 */
class EntityRemovalBlockedException extends \DomainException
{
    /**
     * @var object[]
     */
    private $entities;

    /**
     * @inheritDoc
     *
     * @param object|object[] Entity
     */
    public function __construct ($entities, string $message, \Throwable $previous = null)
    {
        parent::__construct($message, 0, $previous);
        $this->entities = \is_array($entities) ? $entities : [$entities];
    }

    /**
     * @return object
     */
    public function getEntities ()
    {
        return $this->entities;
    }
}

Allow to pass multiple entities to the RemovalBlocked exception


<?php

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

return [
    'plural' => function ($count) {
        if ($count >= 0 AND $count < 2) {
            return 'one';
        }
        else {
            return 'other';
        }
    }
];

<?php

/*
 * This file is part of the German Extension for Flarum.
 *
 * (c) Marcel Ehrlich <marcelehrlich@hotmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

return [
    'plural' => function ($count) {
        return $count == 1 ? 'one' : 'other';
    }
];

Fix plural rule and change copyright notice.


<?php namespace Laraplus\Form\DataStores;

use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Laraplus\Form\Contracts\DataStore;

class LaravelDataStore implements DataStore
{
    use RetrievesModelValues;

    /**
     * @var Request
     */
    private $request;

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

    /**
     * @param string $name
     * @return string
     */
    public function getError($name)
    {
        $errors = $this->request->session()->get('errors', new MessageBag);

        if ($errors->has($name)) {
            return $errors->first($name);
        }

        return null;
    }

    /**
     * @param string $name
     * @return null|string
     */
    public function getOldValue($name)
    {
        $current = $this->request->input($name);
        $old = $this->request->old($name);

        if(isset($current)) return $current;

        if(isset($old)) return $old;

        return null;
    }

    /**
     * @return string
     */
    public function getUrl()
    {
        $query = $this->request->getQueryString();

        return '/' . trim($this->request->path(), '/') . ($query ? '?' . $query : '');
    }

    /**
     * @return string
     */
    public function getToken()
    {
        return $this->request->session()->getToken();
    }
}

<?php namespace Laraplus\Form\DataStores;

use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Laraplus\Form\Contracts\DataStore;

class LaravelDataStore implements DataStore
{
    use RetrievesModelValues;

    /**
     * @var Request
     */
    private $request;

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

    /**
     * @param string $name
     * @return string
     */
    public function getError($name)
    {
        $name = str_replace(['[', ']'], ['.', ''], $name);

        $errors = $this->request->session()->get('errors', new MessageBag);

        if ($errors->has($name)) {
            return $errors->first($name);
        }

        return null;
    }

    /**
     * @param string $name
     * @return null|string
     */
    public function getOldValue($name)
    {
        $name = str_replace(['[', ']'], ['.', ''], $name);

        $current = $this->request->input($name);
        $old = $this->request->old($name);

        if(isset($current)) return $current;

        if(isset($old)) return $old;

        return null;
    }

    /**
     * @return string
     */
    public function getUrl()
    {
        $query = $this->request->getQueryString();

        return '/' . trim($this->request->path(), '/') . ($query ? '?' . $query : '');
    }

    /**
     * @return string
     */
    public function getToken()
    {
        return $this->request->session()->getToken();
    }
}

Fix old values & errors for array fields


<?php

namespace OrcaServices\Heartbeat\Heartbeat\Sensor;

use Cake\Core\Plugin;
use Migrations\Migrations;
use OrcaServices\Heartbeat\Heartbeat\Sensor;

/**
 * DB Up to Date Sensor
 */
class DBUpToDate extends Sensor
{
    /**
     * Migration status indicating the migration was executed successfully
     */
    const MIGRATION_STATUS_UP = 'up';

    /**
     * @inheritdoc
     */
    protected function _getStatus()
    {
        if (!Plugin::loaded('Migrations')) {
            Plugin::load('Migrations');
        }

        $dbMigrated = true;
        try {
            $migrations = new Migrations();
            $status = $migrations->status();
            $lastStatus = array_pop($status);
            if ($lastStatus['status'] !== self::MIGRATION_STATUS_UP) {
                $dbMigrated = false;
            }
        } catch (\Exception $e) {
            $dbMigrated = false;
        }

        return $dbMigrated;
    }

}

<?php

namespace OrcaServices\Heartbeat\Heartbeat\Sensor;

use Cake\Core\Plugin;
use Migrations\Migrations;
use OrcaServices\Heartbeat\Heartbeat\Sensor;

/**
 * DB Up to Date Sensor
 *
 * This sensor depends on the CakePHP Migrations plugin
 *
 * @link https://github.com/cakephp/migrations/
 */
class DBUpToDate extends Sensor
{
    /**
     * Migration status indicating the migration was executed successfully
     */
    const MIGRATION_STATUS_UP = 'up';

    /**
     * @inheritdoc
     */
    protected function _getStatus()
    {
        if (!Plugin::loaded('Migrations')) {
            Plugin::load('Migrations');
        }

        $dbMigrated = true;
        try {
            $migrations = new Migrations();
            $status = $migrations->status();
            $lastStatus = array_pop($status);
            if ($lastStatus['status'] !== self::MIGRATION_STATUS_UP) {
                $dbMigrated = false;
            }
        } catch (\Exception $e) {
            $dbMigrated = false;
        }

        return $dbMigrated;
    }

}

Document dependency on CakePHP Migration plugin


<?php

namespace Spatie\MediaLibrary;

use Illuminate\Support\ServiceProvider;
use Spatie\MediaLibrary\Commands\RegenerateCommand;

class MediaLibraryServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     */
    public function boot()
    {
        $mediaClass = config('laravel-medialibrary.media_model');
        $mediaClass::observe(new MediaObserver());

        $this->publishes([
            __DIR__.'/../resources/config/laravel-medialibrary.php' => $this->app->configPath().'/'.'laravel-medialibrary.php',
        ], 'config');

        if (!class_exists('CreateMediaTable')) {

            // Publish the migration
            $timestamp = date('Y_m_d_His', time());

            $this->publishes([
                __DIR__.'/../resources/migrations/create_media_table.php.stub' => $this->app->basePath().'/'.'database/migrations/'.$timestamp.'_create_media_table.php',
            ], 'migrations');
        }
    }

    /**
     * Register the service provider.
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../resources/config/laravel-medialibrary.php', 'laravel-medialibrary');

        $this->app->singleton(MediaRepository::class);

        $this->app->bind('command.medialibrary:regenerate', RegenerateCommand::class);

        $this->commands(['command.medialibrary:regenerate']);
    }
}

<?php

namespace Spatie\MediaLibrary;

use Illuminate\Support\ServiceProvider;
use Spatie\MediaLibrary\Commands\RegenerateCommand;

class MediaLibraryServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     */
    public function boot()
    {
        $mediaClass = config('laravel-medialibrary.media_model');
        $mediaClass::observe(new MediaObserver());

        $this->publishes([
            __DIR__.'/../resources/config/laravel-medialibrary.php' => $this->app->configPath().'/'.'laravel-medialibrary.php',
        ], 'config');

        if (!class_exists('CreateMediaTable')) {

            // Publish the migration
            $timestamp = date('Y_m_d_His', time());

            $this->publishes([
                __DIR__.'/../resources/migrations/create_media_table.php.stub' => database_path('migrations/'.$timestamp.'_create_media_table.php'),
            ], 'migrations');
        }
    }

    /**
     * Register the service provider.
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../resources/config/laravel-medialibrary.php', 'laravel-medialibrary');

        $this->app->singleton(MediaRepository::class);

        $this->app->bind('command.medialibrary:regenerate', RegenerateCommand::class);

        $this->commands(['command.medialibrary:regenerate']);
    }
}

Use Database Path for Publishing Migrations.


<?php

use iansltx\DialogflowBridge\{Question, Answer, Middleware\DoublePass, Router};

return function(\Pimple\Container $c, $env) {
    $c[DoublePass::class] = function() {
        return new DoublePass(Router::buildFromClosureArray([
            // no skills yet
        ], function(Question $question, Answer $answer) : Answer {
            return $answer->withSpeechAndText("Sorry, I don't know how to help you with that.");
        }));
    };
};

<?php

use iansltx\DialogflowBridge\{Question, Answer, Middleware\DoublePass, Router};

return function(\Pimple\Container $c, $env) {
    $c[DoublePass::class] = function() {
        return new DoublePass(Router::buildFromClosureArray([
            'schedule' => function(Question $question, Answer $answer) {
                date_default_timezone_set('America/New_York');
                $date = $question->getParam('date', date('Y-m-d'));

                $whatsHappening = "what's happening";

                if ($date === date('Y-m-d')) {
                    $relative = 'today';
                } elseif ($date === date('Y-m-d', time() - 86400)) {
                    $relative = 'yesterday';
                } elseif ($date === date('Y-m-d', time() + 86400)) {
                    $relative = 'tomorrow';
                } elseif (strtotime($date) > time() && strtotime($date) <= time() + 86400 * 7) {
                    $relative = 'on ' . date('l', strtotime($date)); // day of week
                } else {
                    if (strtotime($date) < time()) {
                        $whatsHappening = 'what happened';
                    }
                    $relative = 'on the ' . date('jS', strtotime($date)); // e.g. the 13th
                }

                return $answer->withSpeechAndText("Sorry, but I'm not sure $whatsHappening $relative quite yet.");
            }
        ], function(Question $question, Answer $answer) : Answer {
            return $answer->withSpeechAndText("Sorry, I don't know how to help you with that.");
        }));
    };
};

Add "I don't know anything" schedule action handler, using date param


<?php

class CM_FormField_Email extends CM_FormField_Text {

	public function __construct($name = 'email') {
		parent::__construct($name);
	}

	public function validate($userInput) {
		$userInput = parent::validate($userInput);

		if (!preg_match("/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i", $userInput)) {
			throw new CM_Exception_FormFieldValidation('Invalid email address');
		}

		return $userInput;
	}
}

<?php

class CM_FormField_Email extends CM_FormField_Text {

	public function __construct($name = 'email') {
		parent::__construct($name);
	}

	public function validate($userInput) {
		$userInput = parent::validate($userInput);

		if (false === filter_var($userInput, FILTER_VALIDATE_EMAIL)) {
			throw new CM_Exception_FormFieldValidation('Invalid email address');
		}

		return $userInput;
	}
}

Fix email validation; Use php's filter_var() for email field validation


<?php

declare(strict_types=1);

use Doctrine\Common\Annotations\AnnotationRegistry;
use JMS\Serializer\Tests\Util\DeprecationLogger;

(static function () {
    if (!is_file($autoloadFile = __DIR__ . '/../vendor/autoload.php')) {
        throw new RuntimeException('Did not find vendor/autoload.php. Did you run "composer install --dev"?');
    }

    $loader = require $autoloadFile;
    $loader->add('JMS\Serializer\Tests', __DIR__);

    AnnotationRegistry::registerLoader('class_exists');
})();

DeprecationLogger::register();

<?php

declare(strict_types=1);

use Doctrine\Common\Annotations\AnnotationRegistry;
use JMS\Serializer\Tests\Util\DeprecationLogger;

(static function () {
    if (!is_file($autoloadFile = __DIR__ . '/../vendor/autoload.php')) {
        throw new RuntimeException('Did not find vendor/autoload.php. Did you run "composer install --dev"?');
    }

    require $autoloadFile;

    AnnotationRegistry::registerLoader('class_exists');
})();

DeprecationLogger::register();

Remove PSR-0 autoloading for tests

Remove PSR-0 autoloading for tests


	<?php echo $l->t('You have no contacts in your addressbook.') ?>

		<input type="button" value="<?php echo $l->t('Add contact') ?>" onclick="Contacts.UI.Card.editNew()" />
		<input type="button" value="<?php echo $l->t('Configure addressbooks') ?>" onclick="Contacts.UI.Addressbooks.overview()" />

	<?php echo $l->t('You have no contacts in your addressbook.') ?>

		<input type="button" value="<?php echo $l->t('Add contact') ?>" onclick="OC.Contacts.Card.editNew()" />

Use correct js class in first-run template.


<?php namespace Anomaly\SelectFieldType;

use Anomaly\Streams\Platform\Addon\FieldType\FieldTypePresenter;

/**
 * Class SelectFieldTypePresenter
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 * @package       Anomaly\SelectFieldType
 */
class SelectFieldTypePresenter extends FieldTypePresenter
{

    /**
     * The decorated object.
     * This is for IDE support.
     *
     * @var SelectFieldType
     */
    protected $object;

    /**
     * Return the selection key.
     *
     * @return string|null
     */
    public function key()
    {
        return $this->object->getValue();
    }

    /**
     * Return the selection value.
     *
     * @return string|null
     */
    public function value()
    {
        $options = $this->object->getOptions();

        if (!$key = $this->object->getValue()) {
            return null;
        }

        return trans(array_get($options, $key));
    }
}

<?php namespace Anomaly\SelectFieldType;

use Anomaly\Streams\Platform\Addon\FieldType\FieldTypePresenter;

/**
 * Class SelectFieldTypePresenter
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 * @package       Anomaly\SelectFieldType
 */
class SelectFieldTypePresenter extends FieldTypePresenter
{

    /**
     * The decorated object.
     * This is for IDE support.
     *
     * @var SelectFieldType
     */
    protected $object;

    /**
     * Return the selection key.
     *
     * @return string|null
     */
    public function key()
    {
        return $this->object->getValue();
    }

    /**
     * Return the selection value.
     *
     * @return string|null
     */
    public function value()
    {
        $options = $this->object->getOptions();

        if (($key = $this->object->getValue()) === null) {
            return null;
        }

        return trans(array_get($options, $key));
    }
}

Fix issue where 0 is treated as null

Fix issue where 0 is treated as null


<?php
use Symfony\Component\Debug\Debug;
$filename = __DIR__.preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
    return false;
}

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '83.86.115.104', 'fe80::1', '::1'))
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

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

Debug::enable();

$app = require __DIR__.'/../src/app.php';
require __DIR__.'/../config/dev.php';
require __DIR__.'/../src/controllers.php';
$app->run();

<?php
use Symfony\Component\Debug\Debug;
$filename = __DIR__.preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
    return false;
}

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

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

Debug::enable();

$app = require __DIR__.'/../src/app.php';
require __DIR__.'/../config/dev.php';
require __DIR__.'/../src/controllers.php';
$app->run();

Revert "Added ip address in order to access the debug toolbar"

This reverts commit 59832b211b7ddefe84f723bac08849a4feda0798.


<?php

Route::group(['prefix' => Config::get('core::core.admin-prefix'), 'namespace' => 'Modules\Workshop\Http\Controllers'],
    function () {
        Route::get('modules', ['as' => 'dashboard.modules.index', 'uses' => 'ModulesController@index']);
        Route::post('modules', ['as' => 'dashboard.modules.store', 'uses' => 'ModulesController@store']);
        # Workbench
        Route::get('workbench', ['as' => 'dashboard.workbench.index', 'uses' => 'WorkbenchController@index']);
        Route::post('generate', ['as' => 'dashboard.workbench.generate.index', 'uses' => 'WorkbenchController@generate']);
        Route::post('migrate', ['as' => 'dashboard.workbench.migrate.index', 'uses' => 'WorkbenchController@migrate']);
        Route::post('install', ['as' => 'dashboard.workbench.install.index', 'uses' => 'WorkbenchController@install']);
        Route::post('seed', ['as' => 'dashboard.workbench.seed.index', 'uses' => 'WorkbenchController@seed']);
    }
);

<?php

Route::group(['prefix' => LaravelLocalization::setLocale(), 'before' => 'LaravelLocalizationRedirectFilter'], function()
    {
        Route::group(['prefix' => Config::get('core::core.admin-prefix'), 'namespace' => 'Modules\Workshop\Http\Controllers'],
            function () {
                Route::get('modules', ['as' => 'dashboard.modules.index', 'uses' => 'ModulesController@index']);
                Route::post('modules', ['as' => 'dashboard.modules.store', 'uses' => 'ModulesController@store']);
                # Workbench
                Route::get('workbench', ['as' => 'dashboard.workbench.index', 'uses' => 'WorkbenchController@index']);
                Route::post('generate', ['as' => 'dashboard.workbench.generate.index', 'uses' => 'WorkbenchController@generate']);
                Route::post('migrate', ['as' => 'dashboard.workbench.migrate.index', 'uses' => 'WorkbenchController@migrate']);
                Route::post('install', ['as' => 'dashboard.workbench.install.index', 'uses' => 'WorkbenchController@install']);
                Route::post('seed', ['as' => 'dashboard.workbench.seed.index', 'uses' => 'WorkbenchController@seed']);
            }
        );
});

Add i18n route and route filter

Add i18n route and route filter


<?php

namespace Concise\Services;

class TimeFormatter
{
    protected function pluralize($number, $word)
    {
        return "{$number} {$word}" . (($number == 1) ? '' : 's');
    }

    protected function part(array &$r, &$seconds, $size, $word)
    {
        if ($seconds >= $size) {
            $x = floor($seconds / $size);
            $r[] = $this->pluralize($x, $word);
            $seconds -= $x * $size;
        }
    }

    public function format($seconds)
    {
        if (0 == $seconds) {
            return '0 seconds';
        }

        $r = [];
        $this->part($r, $seconds, 3600, 'hour');
        $this->part($r, $seconds, 60, 'minute');
        $this->part($r, $seconds, 1, 'second');
        return implode(' ', $r);
    }
}

<?php

namespace Concise\Services;

class TimeFormatter
{
    protected function pluralize($number, $word)
    {
        return "{$number} {$word}" . (($number == 1) ? '' : 's');
    }

    protected function part(array &$r, &$seconds, $size, $word)
    {
        if ($seconds >= $size) {
            $x = floor($seconds / $size);
            $r[] = $this->pluralize($x, $word);
            $seconds -= $x * $size;
        }
    }

    public function format($seconds)
    {
        if (0 == $seconds) {
            return '0 seconds';
        }

        $r = array();
        $this->part($r, $seconds, 3600, 'hour');
        $this->part($r, $seconds, 60, 'minute');
        $this->part($r, $seconds, 1, 'second');
        return implode(' ', $r);
    }
}

Fix syntax error for PHP 5.3

Fix syntax error for PHP 5.3


<?php

use OrcaServices\Datatrans\Xml\Api\Factory;

$merchantId = 1000011011;
$uppTransactionId = 522061;

$authorisationRequest = Factory::authorisation($merchantId, $uppTransactionId);
$authorisationRequest->execute();

Remove non functioning example code

Remove non functioning example code


<?php
function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

$c = new Memcached();
$c->addServer("localhost", 11211);
foreach($c->getAllKeys() as $key) {
	if(startsWith($key, "qreport_")) {
		echo substr($key, 0, strlen("qreport_"));
	}

}
// var_dump( $c->getAllKeys() );
?>

<?php
function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

$c = new Memcached();
$c->addServer("localhost", 11211);
foreach($c->getAllKeys() as $key) {
	if(startsWith($key, "qreport_")) {
		echo substr($key, strlen("qreport_")) . "\n";
	}

}
// var_dump( $c->getAllKeys() );
?>

Update server site for osmlive reports

Update server site for osmlive reports


<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * This is used by Laravel authentication to redirect users after login.
     *
     * @var string
     */
    public const HOME = '/home';

    /**
     * The controller namespace for the application.
     *
     * When present, controller route declarations will automatically be prefixed with this namespace.
     *
     * @var string|null
     */
    // protected $namespace = 'App\\Http\\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));
        });
    }

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60);
        });
    }
}

<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * This is used by Laravel authentication to redirect users after login.
     *
     * @var string
     */
    public const HOME = '/home';

    /**
     * The controller namespace for the application.
     *
     * When present, controller route declarations will automatically be prefixed with this namespace.
     *
     * @var string|null
     */
    // protected $namespace = 'App\\Http\\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));
        });
    }

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->ip());
        });
    }
}

Revert per user API rate limit

Revert per user API rate limit

It was changed from per user to per application in ced3e50bca279f5a499a6d513fcdfd2a020c28ce


<?php snippet_detect('html_head', array(
	'criticalcss' => false,
	'prev_next' => false,
	'prerender' => false
)); ?>

	<?php snippet('banner'); ?>

<?php echo $page->title()->smartypants()->widont(); ?>

		<?php if($page->date($format=true)): ?>
			<?php snippet('datetime'); ?>
		<?php endif; ?>

		<?php echo $page->intro()->kirbytext(); ?>
		<?php echo $page->text()->kirbytext(); ?>

		<?php if($page->hasImages()) : ?>

Photo(s) form page

			<?php foreach($page->images() as $image): ?>

				<?php if($image->caption()=='') {
					$imageAlt = $image->title();
				} else {
					$imageAlt = '';
				} ?>
				<?php echo thumb($image, array('width' => 450, 'height' => 450, 'hd' => false, 'crop' => true, 'alt' => $imageAlt)); ?>

				<?php if($image->caption()!='') : ?>

<?php echo $image->caption(); ?>

				<?php endif; ?>

			<?php endforeach; ?>

		<?php endif; ?>

		<?php snippet('nav_sub'); ?>

<?php snippet_detect('footer'); ?>

<?php snippet_detect('html_head', array(
	'criticalcss' => false,
	'prev_next' => false,
	'prerender' => false
)); ?>

	<?php snippet('banner'); ?>

<?php echo $page->title()->smartypants()->widont(); ?>

		<?php if($page->date($format=true)): ?>
			<?php snippet('datetime'); ?>
		<?php endif; ?>

		<?php echo $page->intro()->kirbytext(); ?>
		<?php echo $page->text()->kirbytext(); ?>

		<?php snippet('nav_sub'); ?>

<?php snippet_detect('footer'); ?>

Remove ‘loading photos from folder’ tempalte code.


<?php

use App\Models\Country;

class UsersControllerTest extends TestCase
{
    /**
     * Checks whether an OK status is returned when the
     * profile order update request is valid.
     */
    public function testStore()
    {
        config()->set('osu.user.allow_registration', true);

        $this
            ->json('POST', route('users.store'), [
                'user' => [
                    'username' => 'user1',
                    'user_email' => 'user1@example.com',
                    'password' => 'hunter22',
                ],
            ], [
                'HTTP_USER_AGENT' => config('osu.client.user_agent'),
            ])->assertJsonFragment([
                'username' => 'user1',
            ]);
    }

    public function testStoreWithCountry()
    {
        config()->set('osu.user.allow_registration', true);

        $country = factory(Country::class)->create();

        $this
            ->json('POST', route('users.store'), [
                'user' => [
                    'username' => 'user1',
                    'user_email' => 'user1@example.com',
                    'password' => 'hunter22',
                ],
            ], [
                'HTTP_USER_AGENT' => config('osu.client.user_agent'),
                'HTTP_CF_IPCOUNTRY' => $country->getKey(),
            ])->assertJsonFragment([
                'username' => 'user1',
                'country' => [
                    'code' => $country->getKey(),
                    'name' => $country->name,
                ],
            ]);
    }
}

<?php

use App\Models\Country;

class UsersControllerTest extends TestCase
{
    /**
     * Checks whether an OK status is returned when the
     * profile order update request is valid.
     */
    public function testStore()
    {
        config()->set('osu.user.allow_registration', true);

        $this
            ->json('POST', route('users.store'), [
                'user' => [
                    'username' => 'user1',
                    'user_email' => 'user1@example.com',
                    'password' => 'hunter22',
                ],
            ], [
                'HTTP_USER_AGENT' => config('osu.client.user_agent'),
            ])->assertJsonFragment([
                'username' => 'user1',
            ]);
    }

    public function testStoreWithCountry()
    {
        config()->set('osu.user.allow_registration', true);

        $country = Country::inRandomOrder()->first() ?? factory(Country::class)->create();

        $this
            ->json('POST', route('users.store'), [
                'user' => [
                    'username' => 'user1',
                    'user_email' => 'user1@example.com',
                    'password' => 'hunter22',
                ],
            ], [
                'HTTP_USER_AGENT' => config('osu.client.user_agent'),
                'HTTP_CF_IPCOUNTRY' => $country->getKey(),
            ])->assertJsonFragment([
                'username' => 'user1',
                'country' => [
                    'code' => $country->getKey(),
                    'name' => $country->name,
                ],
            ]);
    }
}

Make test more resilient to countries already existing in test database


<?php

/**
 * This file is part of the laravel url package.
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace Benrowe\Laravel\Url;

use Illuminate\Support\ServiceProvider as LaravelServiceProvider;
use Blade;

/**
 * Url Service Provider
 * Registers the service provider into the application IOC
 *
 * @package    Benrowe\Laravel\Url
 * @author     Ben Rowe <ben.rowe.83@gmail.com>
 * @copyright  Ben Rowe <ben.rowe.83@gmail.com>
 * @link       https://github.com/benrowe/laravel-filesystem-url
 */
class ServiceProvider extends LaravelServiceProvider
{
    protected $defer;

    public function boot()
    {
        // blade directives
        Blade::directive(
            'file',
            function ($expression) {
                return '<?php
                try {
                    echo app(\'filesystem-url\')->url' . $expression . ';
                } catch (Exception $e) {
                }
                ?>';
            }
        );
    }

    public function register()
    {
        $this->app->bindShared('filesystem-url', function ($app) {
            return new UrlService(config('filesystems'), $app['request']->secure());
        });
        $this->app->alias('filesystem-url', 'Benrowe\Laravel\Url\UrlService');
    }

    public function provides()
    {
        return [
            'Benrowe\Laravel\Url\UrlService',
            'filesystem-url'
        ];
    }
}

<?php

namespace Benrowe\Laravel\Url;

use Illuminate\Support\ServiceProvider as LaravelServiceProvider;
use Blade;

/**
 * Url Service Provider
 * Registers the service provider into the application IOC
 *
 * @package    Benrowe\Laravel\Url
 */
class ServiceProvider extends LaravelServiceProvider
{
    protected $defer;

    public function boot()
    {
        // blade directives
        Blade::directive(
            'file',
            function ($expression) {
                return '<?php
                try {
                    echo app(\'filesystem-url\')->url' . $expression . ';
                } catch (Exception $e) {
                }
                ?>';
            }
        );
    }

    public function register()
    {
        $this->app->singleton('filesystem-url', function ($app) {
            return new UrlService(config('filesystems'), $app['request']->secure());
        });
        $this->app->alias('filesystem-url', 'Benrowe\Laravel\Url\UrlService');
    }

    public function provides()
    {
        return [
            'Benrowe\Laravel\Url\UrlService',
            'filesystem-url'
        ];
    }
}

Update package serviceprovider to support laravel 5.2


<?php
define('AJXP_EXEC', 1);

parse_str(implode('&', array_slice($argv, 1)), $_GET);

#$utils_path = "/opt/pydio/core/classes";
$utils_path = "/home/toilal/IdeaProjects/pydio-core/core/src/core/classes";

require($utils_path . "/class.AJXP_Utils.php");

print(AJXP_Utils::pbkdf2_create_hash($_GET["password"]));
?>

<?php
define('AJXP_EXEC', 1);

parse_str(implode('&', array_slice($argv, 1)), $_GET);

$utils_path = "/opt/pydio/core/classes";
require($utils_path . "/class.AJXP_Utils.php");

print(AJXP_Utils::pbkdf2_create_hash($_GET["password"]));
?>

Fix require path for Pydio password tool


<?php

namespace Face;
use Face\Core\InstancesKeeper;
use Face\Sql\Result\ResultSet;
use Face\Util\OOPUtils;

/**
 * Face\ORM is a class that interfaces comon calls of the Face API
 *
 * This abstract is made to be call everywhere in the application.
 * An alternative for dependency injection lives at Face\DiOrm
 *
 * @author sghzal
 */
abstract class ORM {

    /**
     * Prepare a query
     * @param string|Core\EntityFaceElement|\Face\Traits\EntityFaceTrait $what it can be a classname, a face object, or an entity that uses EntityFaceTrait
     * @return \Face\Sql\Query\FQuery the query for the entity we asked
     * @throws Exception\FacelessException if the entity we asked doesnt exist
     */
    public static function Query($what){

        if(is_string($what)){
            $baseFace=  Core\FacePool::getFace($what);
        }else if(is_a($what,'Face\Core\EntityFaceElement')){
            $baseFace=$what;
        }else if(OOPUtils::UsesTrait($what, 'Face\Traits\EntityFaceTrait')){
            $baseFace=$what->getEntityFace();
        }else{
            throw new Exception\FacelessException("You asked a query for something that has no face");
        }

        return new Sql\Query\SelectBuilder($baseFace);
    }

    /**
     *
     * @param \Face\Sql\Query\FQuery $fQuery
     * @param \PDO $pdo
     * @return Sql\Result\ResultSet
     */
    public static function execute(Sql\Query\FQuery $fQuery, \PDO $pdo){
        $j=$fQuery->execute($pdo);

        if(!$j->rowCount()){
            return new ResultSet($fQuery->getBaseFace(), new InstancesKeeper());
        }

        $reader=new \Face\Sql\Reader\QueryArrayReader($fQuery);

        $rs=$reader->read($j);

        return $rs;
    }

}

<?php

namespace Face;
use Face\Core\InstancesKeeper;
use Face\Sql\Result\ResultSet;
use Face\Util\OOPUtils;

/**
 * Face\ORM is a class that interfaces comon calls of the Face API
 *
 * This abstract is made to be call everywhere in the application.
 * An alternative for dependency injection lives at Face\DiOrm
 *
 * @author sghzal
 */
abstract class ORM {

    /**
     *
     * @param \Face\Sql\Query\FQuery $fQuery
     * @param \PDO $pdo
     * @return Sql\Result\ResultSet
     */
    public static function execute(Sql\Query\FQuery $fQuery, \PDO $pdo){
        $j=$fQuery->execute($pdo);

        if(!$j->rowCount()){
            return new ResultSet($fQuery->getBaseFace(), new InstancesKeeper());
        }

        $reader=new \Face\Sql\Reader\QueryArrayReader($fQuery);

        $rs=$reader->read($j);

        return $rs;
    }

}

Remove the useless function Orm::query

Remove the useless function Orm::query


<?php

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

namespace Symfony\Bundle\FrameworkBundle\Routing;

use Symfony\Component\Routing\Loader\AnnotationClassLoader;
use Symfony\Component\Routing\Route;

/**
 * AnnotatedRouteControllerLoader is an implementation of AnnotationClassLoader
 * that sets the '_controller' default based on the class and method names.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class AnnotatedRouteControllerLoader extends AnnotationClassLoader
{
    /**
     * Configures the _controller default parameter of a given Route instance.
     *
     * @param mixed $annot The annotation class instance
     */
    protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot)
    {
        $route->setDefault('_controller', $class->getName().'::'.$method->getName());
    }

    /**
     * Makes the default route name more sane by removing common keywords.
     *
     * @return string
     */
    protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method)
    {
        return preg_replace(array(
            '/(bundle|controller)_/',
            '/action(_\d+)?$/',
            '/__/',
        ), array(
            '_',
            '\\1',
            '_',
        ), parent::getDefaultRouteName($class, $method));
    }
}

<?php

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

namespace Symfony\Bundle\FrameworkBundle\Routing;

use Symfony\Component\Routing\Loader\AnnotationClassLoader;
use Symfony\Component\Routing\Route;

/**
 * AnnotatedRouteControllerLoader is an implementation of AnnotationClassLoader
 * that sets the '_controller' default based on the class and method names.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class AnnotatedRouteControllerLoader extends AnnotationClassLoader
{
    /**
     * Configures the _controller default parameter of a given Route instance.
     *
     * @param mixed $annot The annotation class instance
     */
    protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot)
    {
        if ('__invoke' === $method->getName()) {
            $route->setDefault('_controller', $class->getName());
        } else {
            $route->setDefault('_controller', $class->getName().'::'.$method->getName());
        }
    }

    /**
     * Makes the default route name more sane by removing common keywords.
     *
     * @return string
     */
    protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method)
    {
        return preg_replace(array(
            '/(bundle|controller)_/',
            '/action(_\d+)?$/',
            '/__/',
        ), array(
            '_',
            '\\1',
            '_',
        ), parent::getDefaultRouteName($class, $method));
    }
}

Set controller without __invoke method from invokable class


<?php

namespace PragmaRX\Google2FALaravel\Support;

class Constants
{
    const CONFIG_PACKAGE_NAME = 'google2fa';

    const SESSION_AUTH_PASSED = 'auth_passed';

    const SESSION_AUTH_TIME = 'auth_time';

    const SESSION_OTP_TIMESTAMP = 'otp_timestamp';

    const QRCODE_IMAGE_BACKEND_EPS = 'eps';

    const QRCODE_IMAGE_BACKEND_SVG = 'svg';

    const QRCODE_IMAGE_BACKEND_IMAGEMAGICK = 'imagemagick';
}

<?php

namespace PragmaRX\Google2FALaravel\Support;

class Constants
{
    const CONFIG_PACKAGE_NAME = 'google2fa';

    const SESSION_AUTH_PASSED = 'auth_passed';

    const SESSION_AUTH_TIME = 'auth_time';

    const SESSION_OTP_TIMESTAMP = 'otp_timestamp';

    const QRCODE_IMAGE_BACKEND_EPS = 'eps';

    const QRCODE_IMAGE_BACKEND_SVG = 'svg';

    const QRCODE_IMAGE_BACKEND_IMAGEMAGICK = 'imagemagick';

    const OTP_EMPTY = 'empty';

    const OTP_VALID = 'valid';

    const OTP_INVALID = 'invalid';
}

Add new constants for One Time Password validation


<?php
namespace vsc\application\controllers;

use vsc\presentation\requests\HttpRequestA;
use vsc\presentation\views\ExceptionView;
use vsc\presentation\views\ViewA;

class ContentTypeController extends FrontControllerA {

	public function isValidContentType($sContentType) {}

	public function getAvailableContentTypes() {}

	public function getController() {}

	/**
	 * @returns ViewA
	 */
	public function getDefaultView() {
	}

	/**
	 * @param HttpRequestA $oRequest
	 * @param null $oProcessor
	 * @return \vsc\presentation\responses\HttpResponseA
	 */
	public function getResponse(HttpRequestA $oRequest, $oProcessor = null) {
	}

	/**
	 * @param HttpRequestA $oRequest
	 * @param null $oProcessor
	 * @return \vsc\presentation\responses\HttpResponse|\vsc\presentation\responses\HttpResponseA
	 */
	public function getErrorResponse(HttpRequestA $oRequest, $oProcessor = null) {
	}

	/**
	 * @returns ViewA
	 * @throws ExceptionView
	 */
	public function getView() {
	}
}

<?php
namespace vsc\application\controllers;

use vsc\presentation\requests\HttpRequestA;
use vsc\presentation\views\ExceptionView;
use vsc\presentation\views\ViewA;

class ContentTypeController extends FrontControllerA {

	public static function isValidContentType($sContentType) {}

	public function getAvailableContentTypes() {}

	public function getController() {}

	/**
	 * @returns ViewA
	 */
	public function getDefaultView() {
	}

	/**
	 * @param HttpRequestA $oRequest
	 * @param null $oProcessor
	 * @return \vsc\presentation\responses\HttpResponseA
	 */
	public function getResponse(HttpRequestA $oRequest, $oProcessor = null) {
	}

	/**
	 * @param HttpRequestA $oRequest
	 * @param null $oProcessor
	 * @return \vsc\presentation\responses\HttpResponse|\vsc\presentation\responses\HttpResponseA
	 */
	public function getErrorResponse(HttpRequestA $oRequest, $oProcessor = null) {
	}

	/**
	 * @returns ViewA
	 * @throws ExceptionView
	 */
	public function getView() {
	}
}

Fix for calling a static method

Fix for calling a static method


<?php
/*
Plugin Name:  Site Specific Functionality
Description:  Custom post types, taxonomies, metaboxes and shortcodes
*/

require_once(dirname(__FILE__) . '/lib/post-types.php');
require_once(dirname(__FILE__) . '/lib/meta-boxes.php');
require_once(dirname(__FILE__) . '/lib/shortcodes.php');

<?php
/*
Plugin Name:  Site Specific Functionality
Description:  Custom post types, taxonomies, metaboxes and shortcodes
*/

// require_once(dirname(__FILE__) . '/lib/post-types.php');
// require_once(dirname(__FILE__) . '/lib/meta-boxes.php');
// require_once(dirname(__FILE__) . '/lib/shortcodes.php');

Comment out site specific functionality by default

Post types, meta boxes, and shortcodes can be uncommented after
they've been customized for first use


<?php
namespace Craft;

class FeedMeHelper
{
    // Public Methods
    // =========================================================================

    public static function parseBoolean($value)
    {
        $result = filter_var($value, FILTER_VALIDATE_BOOLEAN);

        // Also check for translated values of boolean-like terms
        if (strtolower($value) === Craft::t('yes')) {
            $result = true;
        }

        if (strtolower($value) === Craft::t('on')) {
            $result = true;
        }

        if (strtolower($value) === Craft::t('open')) {
            $result = true;
        }

        if (strtolower($value) === Craft::t('no')) {
            $result = false;
        }

        if (strtolower($value) === Craft::t('off')) {
            $result = false;
        }

        if (strtolower($value) === Craft::t('closed')) {
            $result = false;
        }

        return $result;
    }

}

<?php
namespace Craft;

class FeedMeHelper
{
    // Public Methods
    // =========================================================================

    public static function parseBoolean($value)
    {
        $result = filter_var($value, FILTER_VALIDATE_BOOLEAN);

        // Also check for translated values of boolean-like terms
        if (strtolower($value) === Craft::t('yes')) {
            $result = true;
        }

        if (strtolower($value) === Craft::t('on')) {
            $result = true;
        }

        if (strtolower($value) === Craft::t('open')) {
            $result = true;
        }

        if (strtolower($value) === Craft::t('enabled')) {
            $result = true;
        }

        if (strtolower($value) === Craft::t('live')) {
            $result = true;
        }

        if (strtolower($value) === Craft::t('no')) {
            $result = false;
        }

        if (strtolower($value) === Craft::t('off')) {
            $result = false;
        }

        if (strtolower($value) === Craft::t('closed')) {
            $result = false;
        }

        if (strtolower($value) === Craft::t('disabled')) {
            $result = false;
        }

        return $result;
    }

}

Add extra truthy detections for ‘live’ and ‘enabled’


<?php
/**
 * Yii2 FancyBox Extension
 * @author Paul P <bigpaulie25ro@yahoo.com>
 * @license MIT
 */
namespace bigpaulie\fancybox;

use yii\web\AssetBundle;

class FancyBoxAsset extends AssetBundle{

    public $sourcePath = '@bower/fancybox';

    public $css = [
        'source/jquery.fancybox.css',
        'source/helpers/jquery.fancybox-buttons.css',
        'source/helpers/jquery.fancybox-thumbs.css',
    ];

    public $js = [
        'source/jquery.fancybox.js',
        'lib/jquery.mousewheel-3.0.6.pack.js',
        'source/helpers/jquery.fancybox-buttons.js',
        'source/helpers/jquery.fancybox-thumbs.js',
    ];

    public $depends = [
        'yii\web\JqueryAsset',
    ];

}

<?php
/**
 * Yii2 FancyBox Extension
 * @author Paul P <bigpaulie25ro@yahoo.com>
 * @license MIT
 */
namespace bigpaulie\fancybox;

use yii\web\AssetBundle;

class FancyBoxAsset extends AssetBundle{

    public $sourcePath = '@bower/fancybox';

    public $css = [
        'source/jquery.fancybox.css',
        'source/helpers/jquery.fancybox-buttons.css',
        'source/helpers/jquery.fancybox-thumbs.css',
    ];

    public $js = [
        'source/jquery.fancybox.js',
        'lib/jquery.mousewheel-3.0.6.pack.js',
        'source/helpers/jquery.fancybox-buttons.js',
        'source/helpers/jquery.fancybox-thumbs.js',
        'source/helpers/jquery.fancybox-media.js',
    ];

    public $depends = [
        'yii\web\JqueryAsset',
    ];

}

Fix adding missing helper library

Fix adding missing helper library


<?php

namespace PhpToZephir\Converter\Printer\Expr;

use PhpParser\Node\Expr;
use PhpToZephir\Converter\SimplePrinter;

class NewPrinter extends SimplePrinter
{
    public static function getType()
    {
        return "pExpr_New";
    }

    public function convert(Expr\New_ $node)
    {
        return 'new '.$this->dispatcher->p($node->class).'('.$this->dispatcher->pCommaSeparated($node->args).')';
    }
}

<?php

namespace PhpToZephir\Converter\Printer\Expr;

use PhpParser\Node\Expr;
use PhpToZephir\Converter\SimplePrinter;

class NewPrinter extends SimplePrinter
{
    public static function getType()
    {
        return "pExpr_New";
    }

    public function convert(Expr\New_ $node)
    {
        if ($node->class instanceof \PhpParser\Node\Expr\Variable) {
            return 'new {' . $this->dispatcher->p($node->class) . '}(' . $this->dispatcher->pCommaSeparated($node->args) . ')';
        }
        return 'new ' . $this->dispatcher->p($node->class) . '(' . $this->dispatcher->pCommaSeparated($node->args) . ')';
    }
}

Fix New object from variable name

Fix New object from variable name


@extends('app')

@section('content')

Register an Account

    {!! Form::open() !!}
        @include('partials/form/text', ['name' => 'name', 'label' => 'Username', 'placeholder' => 'Your login name'])
        @include('partials/form/text', ['name' => 'email', 'label' => 'Email address', 'placeholder' => 'Your email'])
        @include('partials/form/password', ['name' => 'password', 'label' => 'Password', 'placeholder' => 'A strong password'])
        @include('partials/form/password', ['name' => 'password_confirmation', 'label' => 'Confirm Password', 'placeholder' => 'Type your password again'])

        <button type="submit" class="btn btn-primary">Submit</button>
    {!! Form::close() !!}
@endsection

@extends('app')

@section('content')

Register an Account

    {!! Form::open() !!}
        @include('partials/form/text', ['name' => 'name', 'label' => 'Username', 'placeholder' => 'Your login name'])
        @include('partials/form/text', ['name' => 'email', 'label' => 'Email address', 'placeholder' => 'Your email'])
        @include('partials/form/password', ['name' => 'password', 'label' => 'Password', 'placeholder' => 'A strong password'])
        @include('partials/form/password', ['name' => 'password_confirmation', 'label' => 'Confirm Password', 'placeholder' => 'Type your password again'])

        <button type="submit" class="btn btn-primary">Submit</button>
    {!! Form::close() !!}

        Already registered? Login Here!

        Forgot your password? Reset it!

@endsection

Add login and forgot links in the user register view

Make is easy for users to get to the login and forgot view
if they already registered.

Signed-off-by: Marc Jones <bb1304e98184a66f7e15848bfbd0ff1c09583089@gmail.com>


<?php
namespace tomlib\object;

function try_get_property($object, $name, $default = null) {
		if(property_exists($object, $name))
				return $object->$name;
		else
				return $default;
}

function to_indexed_array($object, $properties, $reference = false) {
		if($reference) {
				foreach($properties as $property) {
						$result[] =& try_get_property($object, $property);
				}
		} else {
				foreach($properties as $property) {
						$result[] = try_get_property($object, $property);
				}
		}

		return $result;
}

<?php
namespace tomlib\object;

function try_get_property($object, $name, $default = null) {
		if(property_exists($object, $name))
				return $object->$name;
		else
				return $default;
}

function to_indexed_array($object, $properties, $reference = false) {
		if($reference) {
				foreach($properties as $property) {
						$result[$property] =& try_get_property($object, $property);
				}
		} else {
				foreach($properties as $property) {
						$result[$property] = try_get_property($object, $property);
				}
		}

		return $result;
}

Add index assignments to to_indexed_array

Beforehand, to_indexed_array wouldn't return an indexed array, instead it would just push the values into the array.


<?php
/**
 * AmChartsPHP
 *
 * @link      http://github.com/neeckeloo/AmChartsPHP
 * @copyright Copyright (c) 2012 Nicolas Eeckeloo
 */
namespace AmCharts\Chart\Axis;

use AmCharts\Chart\Exception;

class Category extends AbstractAxis
{
    const POSITION_START = 'start';

    const POSITION_MIDDLE = 'middle';

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

    /**
     * Sets grid position
     *
     * @param type $position
     * @return Category
     */
    public function setGridPosition($position)
    {
        if ($position != self::POSITION_START && $position != self::POSITION_MIDDLE) {
            throw new Exception\InvalidArgumentException('The grid position provided is not valid.');
        }

        $this->gridPosition = (string) $position;

        return $this;
    }

    /**
     * Returns grid position
     *
     * @return string
     */
    public function getGridPosition()
    {
        return $this->gridPosition;
    }

    /**
     * Returns object properties as array
     *
     * @return array
     */
    public function toArray()
    {
        $options = parent::toArray();

        if ($options) {
            $keys = array_keys($options);
            array_walk($keys, function (&$value, $key) {
                $value = 'categoryAxis.' . $value;
            });
            $options = array_combine($keys, array_values($options));
        }

        return $options;
    }
}

<?php
/**
 * AmChartsPHP
 *
 * @link      http://github.com/neeckeloo/AmChartsPHP
 * @copyright Copyright (c) 2012 Nicolas Eeckeloo
 */
namespace AmCharts\Chart\Axis;

use AmCharts\Chart\Exception;

class Category extends AbstractAxis
{
    const POSITION_START = 'start';

    const POSITION_MIDDLE = 'middle';

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

    /**
     * Sets grid position
     *
     * @param string $position
     * @return Category
     */
    public function setGridPosition($position)
    {
        if ($position != self::POSITION_START && $position != self::POSITION_MIDDLE) {
            throw new Exception\InvalidArgumentException('The grid position provided is not valid.');
        }

        $this->gridPosition = (string) $position;

        return $this;
    }

    /**
     * Returns grid position
     *
     * @return string
     */
    public function getGridPosition()
    {
        return $this->gridPosition;
    }

    /**
     * Returns object properties as array
     *
     * @return array
     */
    public function toArray()
    {
        $options = parent::toArray();

        if ($options) {
            $keys = array_keys($options);
            array_walk($keys, function (&$value, $key) {
                $value = 'categoryAxis.' . $value;
            });
            $options = array_combine($keys, array_values($options));
        }

        return $options;
    }
}

Fix param type in doc block

Fix param type in doc block


<?php

namespace PhpAbac\Manager;

use PhpAbac\Loader\YamlAbacLoader;

use Symfony\Component\Config\FileLocatorInterface;

class ConfigurationManager {
    /** @var FileLocatorInterface **/
    protected $locator;
    /** @var string **/
    protected $format;
    /** @var array **/
    protected $loaders;
    /** @var array **/
    protected $rules;
    /** @var array **/
    protected $attributes;

    /**
     * @param FileLocatorInterface $locator
     * @param string $format
     */
    public function __construct(FileLocatorInterface $locator, $format = 'yaml') {
        $this->locator = $locator;
        $this->format = $format;
        $this->attributes = [];
        $this->rules = [];
        $this->loaders['yaml'] = new YamlAbacLoader($locator);
    }

    /**
     * @param array $configurationFiles
     */
    public function parseConfigurationFile($configurationFiles) {
        foreach($configurationFiles as $configurationFile) {
            $config = $this->loaders[$this->format]->load($configurationFile);
            $this->attributes = array_merge($this->attributes, $config['attributes']);
            $this->rules = array_merge($this->rules, $config['rules']);
        }
    }

    /**
     * @return array
     */
    public function getAttributes() {
        return $this->attributes;
    }

    /**
     * @return array
     */
    public function getRules() {
        return $this->rules;
    }
}

<?php

namespace PhpAbac\Manager;

use PhpAbac\Loader\YamlAbacLoader;

use Symfony\Component\Config\FileLocatorInterface;

class ConfigurationManager {
    /** @var FileLocatorInterface **/
    protected $locator;
    /** @var string **/
    protected $format;
    /** @var array **/
    protected $loaders;
    /** @var array **/
    protected $rules;
    /** @var array **/
    protected $attributes;

    /**
     * @param FileLocatorInterface $locator
     * @param string $format
     */
    public function __construct(FileLocatorInterface $locator, $format = 'yaml') {
        $this->locator = $locator;
        $this->format = $format;
        $this->attributes = [];
        $this->rules = [];
        $this->loaders['yaml'] = new YamlAbacLoader($locator);
    }

    /**
     * @param array $configurationFiles
     */
    public function parseConfigurationFile($configurationFiles) {
        foreach($configurationFiles as $configurationFile) {
            $config = $this->loaders[$this->format]->load($configurationFile);
            if(isset($config['attributes'])) {
                $this->attributes = array_merge($this->attributes, $config['attributes']);
            }
            if(isset($config['rules'])) {
                $this->rules = array_merge($this->rules, $config['rules']);
            }
        }
    }

    /**
     * @return array
     */
    public function getAttributes() {
        return $this->attributes;
    }

    /**
     * @return array
     */
    public function getRules() {
        return $this->rules;
    }
}

Allow multiple configuration files for both rules and attributes


Authentication Required

			In order to continue, please enter your group's password below.

	This password should have been provided by your group in a bulletin, mail, etc.

			<?php if( $wrongPass == true ): ?>

You have entered an incorrect password!

			<?php endif; ?>
			<form action='<?php echo URL::base(TRUE, TRUE);?>/access/group_password' method='POST' class="center-text">
				<input type='password' name='group_password' />

				<input type='submit' value='Submit' style="padding:10px" />
			</form>

Authentication Required

			In order to continue, please enter your group's password below.

	This password should have been provided by your group in a bulletin, mail, etc.

			<?php if( $wrongPass == true ): ?>

You have entered an incorrect password!

			<?php endif; ?>
			<form action='<?php echo URL::base(TRUE, TRUE);?>access/group_password' method='POST' class="center-text">
				<input type='password' name='group_password' />

				<input type='submit' value='Submit' style="padding:10px" />
			</form>

Remove extra slash from group password form


<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect('/home');
        }

        return $next($request);
    }
}

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect('/');
        }

        return $next($request);
    }
}

Change where to redirect if authenticated


Welcome

        <?php if(isset($_SESSION['error'])) {
            if ($_SESSION['error'] > 1) {
                foreach ($_SESSION['error'] as $item) {
                    ?>
 <?php echo $item; ?>
 <?php
                    echo '

';
                }
            } else {
                ?>
 <?php echo $_SESSION['error']; ?>
 <?php
            }
        } else {
        }
        ?>

        <form class="form" autocomplete="off" method="post" action="<?php echo base_url("user/doLogin") ?>">
            <input type="text" name='username' placeholder="Username" placeholder="Email Address" required="" autofocus="" >
            <input type="password" name="password" placeholder="Password" required="">
            <button type="submit" id="login-button">Login</button>
        </form>

Welcome

        <?php if(isset($_SESSION['error'])) {
            if ($_SESSION['error'] > 1) {
                foreach ($_SESSION['error'] as $item) {
                    ?>
 <?php echo $item; ?>
 <?php
                    echo '

';
                }
            } else {
                ?>
 <?php echo $_SESSION['error']; ?>
 <?php
            }
        } else {
        }
        unset($_SESSION['error']);
        ?>

        <form class="form" autocomplete="off" method="post" action="<?php echo base_url("user/doLogin") ?>">
            <input type="text" name='username' placeholder="Username" placeholder="Email Address" required="" autofocus="" >
            <input type="password" name="password" placeholder="Password" required="">
            <button type="submit" id="login-button">Login</button>
        </form>

Make the error goes away

Make the error goes away


<?php
  namespace ActiveCollab\Insight\Test;

  use ActiveCollab\Insight\Utilities\Timestamp;
  use Redis, RedisCluster;

  /**
   * @package ActiveCollab\Insight\Test
   */
  abstract class TestCase extends \PHPUnit_Framework_TestCase
  {
    /**
     * @var int
     */
    protected $current_timestamp;

    /**
     * @var Redis|RedisCluster
     */
    protected $redis_client;

    /**
     * Switch to test database
     */
    public function setUp()
    {
      $this->current_timestamp = Timestamp::lock();

      $this->redis_client = new Redis();
      $this->redis_client->connect('127.0.0.1', 6379);
      $this->redis_client->select(15);
      $this->redis_client->flushdb();
    }

    /**
     * Tear down test database
     */
    public function tearDown()
    {
      Timestamp::unlock();
      $this->current_timestamp = null;

      $this->redis_client->flushdb();
    }
  }

<?php
  namespace ActiveCollab\Insight\Test;

  use ActiveCollab\Insight\Utilities\Timestamp;
  use Redis, RedisCluster;

  /**
   * @package ActiveCollab\Insight\Test
   */
  abstract class TestCase extends \PHPUnit_Framework_TestCase
  {
    /**
     * @var int
     */
    protected $current_timestamp;

    /**
     * @var Redis|RedisCluster
     */
    protected $redis_client;

    /**
     * Switch to test database
     */
    public function setUp()
    {
      $this->current_timestamp = Timestamp::lock();

      if (getenv('TEST_REDIS_CLUSTER')) {
        $this->redis_client = new RedisCluster(null, [ '127.0.0.1:30001', '127.0.0.1:30002', '127.0.0.1:30003' ]);
      } else {
        $this->redis_client = new Redis();
        $this->redis_client->connect('127.0.0.1');
      }

      $this->flushData();
    }

    /**
     * Tear down test database
     */
    public function tearDown()
    {
      Timestamp::unlock();
      $this->current_timestamp = null;

      $this->flushData();
    }

    /**
     * Flush data
     */
    private function flushData()
    {
      if ($this->redis_client instanceof RedisCluster) {
        foreach($this->redis_client->_masters() as $master) {
          $this->redis_client->flushAll($master);
        }
      } else if ($this->redis_client instanceof Redis) {
        $this->redis_client->flushdb();
      }
    }
  }

Test agains cluster as well

Test agains cluster as well


<?php

namespace RichanFongdasen\EloquentBlameableTest;

class HelperTests extends TestCase
{
    /** @test */
    public function it_returns_current_user_identifier_correctly1()
    {
        $this->assertNull(blameable_user());
    }

    /** @test */
    public function it_returns_current_user_identifier_correctly2()
    {
        $this->impersonateUser();

        $this->assertEquals($this->user->getKey(), blameable_user());
    }

    /** @test */
    public function it_returns_current_user_identifier_correctly3()
    {
        $this->impersonateOtherUser();

        $this->assertEquals($this->otherUser->getKey(), blameable_user());
    }
}

<?php

namespace RichanFongdasen\EloquentBlameableTest;

use RichanFongdasen\EloquentBlameableTest\Models\Post;
use RichanFongdasen\EloquentBlameableTest\Models\PostWithoutAttributes;

use RichanFongdasen\EloquentBlameable\BlameableService;

class HelperTests extends TestCase
{

    /**
     * The Eloquent model to test the helper function on
     *
     * @var Post
     */
    protected $post;

    /**
     * Set up the test
     */
    public function setUp()
    {
        parent::setUp();

        $this->post = factory(Post::class)->make();
    }

    /** @test */
    public function it_returns_current_user_identifier_correctly1()
    {
        $this->assertNull(blameable_user($this->post));
    }

    /** @test */
    public function it_returns_current_user_identifier_correctly2()
    {
        $this->impersonateUser();

        $this->assertEquals($this->user->getKey(), blameable_user($this->post));
    }

    /** @test */
    public function it_returns_current_user_identifier_correctly3()
    {
        $this->impersonateOtherUser();

        $this->assertEquals($this->otherUser->getKey(), blameable_user($this->post));
    }
}

Update the tests for the helper.

Update the tests for the helper.


<?php

require_once('MongoQueue.php');
require_once('MongoFunctor.php');

abstract class MongoJob
{
	public static function later($delay = 0, $batch = false)
	{
		return self::at(time() + $delay, $batch);
	}

	public static function at($time = null, $batch = false)
	{
		if (!$time) $time = time();
		$className = get_called_class();
		return new MongoFunctor($className, $time, $batch);
	}

	public static function batchLater($delay = 0)
	{
		return self::later($delay, true);
	}

	public static function batchAt($time = null)
	{
		return self::at($time, true);
	}

	public static function run()
	{
		return MongoQueue::run(get_called_class());
	}

	public static function count()
	{
		return MongoQueue::count(get_called_class());
	}
}

<?php

require_once('MongoQueue.php');
require_once('MongoFunctor.php');

abstract class MongoJob
{
	public static function later($delay = 0, $batch = false)
	{
		return self::at(time() + $delay, $batch);
	}

	public static function at($time = null, $batch = false)
	{
		if ($time === null) $time = time();
		$className = get_called_class();
		return new MongoFunctor($className, $time, $batch);
	}

	public static function batchLater($delay = 0)
	{
		return self::later($delay, true);
	}

	public static function batchAt($time = null)
	{
		return self::at($time, true);
	}

	public static function run()
	{
		return MongoQueue::run(get_called_class());
	}

	public static function count()
	{
		return MongoQueue::count(get_called_class());
	}
}

Check specifically for null before overriding the timestamp


<?php

namespace AdamWathan\Form;

use AdamWathan\Form\ErrorStore\IlluminateErrorStore;
use AdamWathan\Form\OldInput\IlluminateOldInputProvider;
use Illuminate\Support\ServiceProvider;

class FormServiceProvider extends ServiceProvider
{
    protected $defer = false;

    public function register()
    {
        $this->registerErrorStore();
        $this->registerOldInput();
        $this->registerFormBuilder();
    }

    protected function registerErrorStore()
    {
        $this->app->singleton('adamwathan.form.errorstore', function ($app) {
            return new IlluminateErrorStore($app['session.store']);
        });
    }

    protected function registerOldInput()
    {
        $this->app->singleton('adamwathan.form.oldinput', function ($app) {
            return new IlluminateOldInputProvider($app['session.store']);
        });
    }

    protected function registerFormBuilder()
    {
        $this->app->singleton('adamwathan.form', function ($app) {
            $formBuilder = new FormBuilder;
            $formBuilder->setErrorStore($app['adamwathan.form.errorstore']);
            $formBuilder->setOldInputProvider($app['adamwathan.form.oldinput']);
            $formBuilder->setToken($app['session.store']->getToken());

            return $formBuilder;
        });
    }

    public function provides()
    {
        return ['adamwathan.form'];
    }
}

<?php

namespace AdamWathan\Form;

use AdamWathan\Form\ErrorStore\IlluminateErrorStore;
use AdamWathan\Form\OldInput\IlluminateOldInputProvider;
use Illuminate\Support\ServiceProvider;

class FormServiceProvider extends ServiceProvider
{
    protected $defer = false;

    public function register()
    {
        $this->registerErrorStore();
        $this->registerOldInput();
        $this->registerFormBuilder();
    }

    protected function registerErrorStore()
    {
        $this->app->singleton('adamwathan.form.errorstore', function ($app) {
            return new IlluminateErrorStore($app['session.store']);
        });
    }

    protected function registerOldInput()
    {
        $this->app->singleton('adamwathan.form.oldinput', function ($app) {
            return new IlluminateOldInputProvider($app['session.store']);
        });
    }

    protected function registerFormBuilder()
    {
        $this->app->singleton('adamwathan.form', function ($app) {
            $formBuilder = new FormBuilder;
            $formBuilder->setErrorStore($app['adamwathan.form.errorstore']);
            $formBuilder->setOldInputProvider($app['adamwathan.form.oldinput']);
            $formBuilder->setToken($app['session.store']->token());

            return $formBuilder;
        });
    }

    public function provides()
    {
        return ['adamwathan.form'];
    }
}

Use token instead of getToken

Use token instead of getToken


<?php  namespace Flarum\Core\Seeders;

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

class PermissionsTableSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
        Permission::truncate();

		$permissions = [

            // Guests can view the forum
            ['group.2' , 'forum'          , 'view'],
            ['group.2' , 'forum'          , 'register'],

            // Members can create and reply to discussions + edit their own stuff
            ['group.3' , 'forum'          , 'startDiscussion'],
            ['group.3' , 'discussion'     , 'editOwn'],
            ['group.3' , 'discussion'     , 'reply'],
            ['group.3' , 'post'           , 'editOwn'],

            // Moderators can edit + delete stuff and suspend users
            ['group.4' , 'discussion'     , 'delete'],
            ['group.4' , 'discussion'     , 'edit'],
            ['group.4' , 'post'           , 'delete'],
            ['group.4' , 'post'           , 'edit'],
            ['group.4' , 'user'           , 'suspend'],

        ];
        foreach ($permissions as &$permission) {
            $permission = [
                'grantee'    => $permission[0],
                'entity'     => $permission[1],
                'permission' => $permission[2]
            ];
        }
        Permission::insert($permissions);
	}

}

<?php  namespace Flarum\Core\Seeders;

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

class PermissionsTableSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
        Permission::truncate();

		$permissions = [

            // Guests can view the forum
            [2, 'forum.view'],

            // Members can create and reply to discussions + edit their own stuff
            [3, 'forum.startDiscussion'],
            [3, 'discussion.reply'],

            // Moderators can edit + delete stuff and suspend users
            [4, 'discussion.delete'],
            [4, 'discussion.rename'],
            [4, 'post.delete'],
            [4, 'post.edit'],
            [4, 'user.suspend'],

        ];
        foreach ($permissions as &$permission) {
            $permission = [
                'group_id'   => $permission[0],
                'permission' => $permission[1]
            ];
        }
        Permission::insert($permissions);
	}

}

Update permissions table seeder with new structure


<?php namespace Responsiv\Uploader;

use System\Classes\PluginBase;

/**
 * Uploader Plugin Information File
 */
class Plugin extends PluginBase
{

    /**
     * Returns information about this plugin.
     *
     * @return array
     */
    public function pluginDetails()
    {
        return [
            'name'        => 'Uploader',
            'description' => 'Tools for uploading files and photos',
            'author'      => 'Responsiv Internet',
            'icon'        => 'icon-leaf'
        ];
    }

    public function registerComponents()
    {
        return [
           'Responsiv\Uploader\Components\FileUploader'  => 'fileUploader',
           'Responsiv\Uploader\Components\ImageUploader' => 'imageUploader',
        ];
    }

}

<?php namespace Responsiv\Uploader;

use System\Classes\PluginBase;

/**
 * Uploader Plugin Information File
 */
class Plugin extends PluginBase
{
    /**
     * Returns information about this plugin.
     *
     * @return array
     */
    public function pluginDetails()
    {
        return [
            'name'        => 'Uploader',
            'description' => 'Tools for uploading files and photos',
            'author'      => 'Responsiv Internet',
            'icon'        => 'icon-leaf',
            'homepage'    => 'https://github.com/responsiv/uploader-plugin'
        ];
    }

    public function registerComponents()
    {
        return [
           'Responsiv\Uploader\Components\FileUploader'  => 'fileUploader',
           'Responsiv\Uploader\Components\ImageUploader' => 'imageUploader',
        ];
    }
}

Add homepage to plugin details

Add homepage to plugin details


<?php

namespace Plugin\Theme;

use Core\PluginBase;

class Plugin extends PluginBase
{
    public function initialize()
    {
        $this->template->hook->attach('template:layout:head', 'theme:layout/head');
        $this->template->hook->attach('template:layout:top', 'theme:layout/top');
        $this->template->setTemplateOverride('template:header', 'theme:layout/header');
    }
}

<?php

namespace Plugin\Theme;

use Core\Plugin\Base;

class Plugin extends Base
{
    public function initialize()
    {
        $this->template->hook->attach('template:layout:head', 'theme:layout/head');
        $this->template->hook->attach('template:layout:top', 'theme:layout/top');
        $this->template->setTemplateOverride('header', 'theme:layout/header');
    }
}

Fix namespace missing backslash / wrong class


<?php

namespace Barryvdh\Debugbar\DataCollector;

use Barryvdh\Debugbar\DataFormatter\SimpleFormatter;
use DebugBar\DataCollector\MessagesCollector;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Str;

/**
 * Collector for Models.
 */
class ModelsCollector extends MessagesCollector
{
    public $models = [];

    /**
     * @param Dispatcher $events
     */
    public function __construct(Dispatcher $events)
    {
        parent::__construct('models');
        $this->setDataFormatter(new SimpleFormatter());

        $events->listen('eloquent.*', function ($event, $models) {
            if (Str::contains($event, 'eloquent.retrieved')) {
                foreach (array_filter($models) as $model) {
                    $class = get_class($model);
                    $this->models[$class] = ($this->models[$class] ?? 0) + 1;
                }
            }
        });
    }

    public function collect()
    {
        foreach ($this->models as $type => $count) {
            $this->addMessage($count, $type);
        }

        return [
            'count' => array_sum($this->models),
            'messages' => $this->getMessages(),
        ];
    }

    public function getWidgets()
    {
        $widgets = parent::getWidgets();
        $widgets['models']['icon'] = 'cubes';

        return $widgets;
    }
}

<?php

namespace Barryvdh\Debugbar\DataCollector;

use DebugBar\DataCollector\DataCollector;
use DebugBar\DataCollector\DataCollectorInterface;
use DebugBar\DataCollector\Renderable;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Str;

/**
 * Collector for Models.
 */
class ModelsCollector extends DataCollector implements DataCollectorInterface, Renderable
{
    public $models = [];

    /**
     * @param Dispatcher $events
     */
    public function __construct(Dispatcher $events)
    {
        $events->listen('eloquent.*', function ($event, $models) {
            if (Str::contains($event, 'eloquent.retrieved')) {
                foreach (array_filter($models) as $model) {
                    $class = get_class($model);
                    $this->models[$class] = ($this->models[$class] ?? 0) + 1;
                }
            }
        });
    }

    public function collect()
    {
        ksort($this->models, SORT_NUMERIC);

        return array_reverse($this->models);
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'models';
    }

    /**
     * {@inheritDoc}
     */
    public function getWidgets()
    {
        return [
            "models" => [
                "icon" => "cubes",
                "widget" => "PhpDebugBar.Widgets.HtmlVariableListWidget",
                "map" => "models",
                "default" => "{}"
            ]
        ];
    }
}

Use list for Models collector + sort

Use list for Models collector + sort


<?php namespace Nwidart\MoneyFormatterLaravel;

use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
use Nwidart\MoneyFormatter\MoneyFormatter;

class MoneyFormatterServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->registerConfiguration();
        $this->registerAlias();

        $this->app->bindShared('Nwidart\MoneyFormatter\MoneyFormatter', function () {
            return new MoneyFormatter(config('money-formatter.locale', 'en_UK'));
        });
    }

    /**
     * Register the configuration file so Laravel can publish them
     * Also merges the published config file with original
     */
    private function registerConfiguration()
    {
        $configPath = __DIR__ . '/../config/money-formatter.php';
        $this->mergeConfigFrom($configPath, 'money-formatter');
        $this->publishes([$configPath => config_path('money-formatter.php')]);
    }

    /**
     * Register the MoneyFormatter laravel alias.
     */
    private function registerAlias()
    {
        $aliasLoader = AliasLoader::getInstance();
        $aliasLoader->alias('MoneyFormatter', 'Nwidart\MoneyFormatterLaravel\MoneyFormatter');
    }
}

<?php namespace Nwidart\MoneyFormatterLaravel;

use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
use Nwidart\MoneyFormatter\MoneyFormatter;

class MoneyFormatterServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->registerConfiguration();
        $this->registerAlias();

        $this->app->singleton('Nwidart\MoneyFormatter\MoneyFormatter', function () {
            return new MoneyFormatter(config('money-formatter.locale', 'en_UK'));
        });
    }

    /**
     * Register the configuration file so Laravel can publish them
     * Also merges the published config file with original
     */
    private function registerConfiguration()
    {
        $configPath = __DIR__ . '/../config/money-formatter.php';
        $this->mergeConfigFrom($configPath, 'money-formatter');
        $this->publishes([$configPath => config_path('money-formatter.php')]);
    }

    /**
     * Register the MoneyFormatter laravel alias.
     */
    private function registerAlias()
    {
        $aliasLoader = AliasLoader::getInstance();
        $aliasLoader->alias('MoneyFormatter', 'Nwidart\MoneyFormatterLaravel\MoneyFormatter');
    }
}

Add support for laravel 5.3

Add support for laravel 5.3


<?php
namespace Bolt\Storage\Mapping;

/**
 * Taxonomy mapping.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class TaxonomyValue implements \ArrayAccess
{
    /** @var string */
    protected $name;
    /** @var string */
    protected $value;
    /** @var array */
    protected $data;

    /**
     * Constructor.
     *
     * @param array $data
     */
    public function __construct($name, $value, array $data)
    {
        $this->name = $name;
        $this->value = $value;
        $this->data = $data;
    }

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

    public function offsetSet($offset, $value)
    {
        $this->data[$offset] = $value;
    }

    public function offsetExists($offset)
    {
        return isset($this->data[$offset]);
    }

    public function offsetUnset($offset)
    {
        unset($this->data[$offset]);
    }

    public function offsetGet($offset)
    {
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
    }
}

<?php
namespace Bolt\Storage\Mapping;

use Bolt\Exception\StorageException;

/**
 * Taxonomy mapping.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class TaxonomyValue implements \ArrayAccess
{
    /** @var string */
    protected $name;
    /** @var string */
    protected $value;
    /** @var array */
    protected $data;

    /**
     * Constructor.
     *
     * @throws StorageException
     *
     * @param array $data
     */
    public function __construct($name, $value, array $data)
    {
        if (empty($value)) {
            throw new StorageException('Taxonomy value can not be empty!');
        }

        $this->name = $name;
        $this->value = $value;
        $this->data = $data;
    }

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

    public function offsetSet($offset, $value)
    {
        $this->data[$offset] = $value;
    }

    public function offsetExists($offset)
    {
        return isset($this->data[$offset]);
    }

    public function offsetUnset($offset)
    {
        unset($this->data[$offset]);
    }

    public function offsetGet($offset)
    {
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
    }
}

Throw an exception if passed an empty value


<?php

namespace Common\EventListener;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class ResponseSecurer
{
    /**
     * Add some headers to the response to make our application more secure
     * see https://www.owasp.org/index.php/List_of_useful_HTTP_headers
     *
     * @param FilterResponseEvent $event
     */
    public function onKernelResponse(FilterResponseEvent $event)
    {
        // provides clickjacking protection
        $event->getResponse()->headers->set('X-Frame-Options', 'deny');

        // enables the XSS filter built into most recent browsers
        $event->getResponse()->headers->set('X-XSS-Protection', '1; mode=block');

        // prevents IE and Chrome from MIME-sniffing
        $event->getResponse()->headers->set('X-Content-Type-Options', 'nosniff');
    }
}

<?php

namespace Common\EventListener;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class ResponseSecurer
{
    /**
     * Add some headers to the response to make our application more secure
     * see https://www.owasp.org/index.php/List_of_useful_HTTP_headers
     *
     * @param FilterResponseEvent $event
     */
    public function onKernelResponse(FilterResponseEvent $event)
    {
        $headers = [
            'X-Frame-Options' => 'deny',
            'X-XSS-Protection' => '1; mode=block',
            'X-Content-Type-Options' => 'nosniff',
        ];

        foreach ($headers as $header => $value) {
            if (!$event->getResponse()->headers->has($header)) {
                $event->getResponse()->headers->set($header, $value);
            }
        }
    }
}

Make it possible to define other values for the headers X-Frame-Options, X-XSS-Protection, X-Content-Type-Options if you realy want to

The current implementation uses an iframe this change makes it possible to use that again


<?php

namespace hiapi\Core\Http\Psr15\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class CorsMiddleware implements MiddlewareInterface
{
    protected $headers = [
        'Access-Control-Allow-Origin' => ['*'],
        'Access-Control-Request-Method' => ['GET POST'],
    ];

    public function addHeader($name, $value): self
    {
        $this->headers[$name] = array_merge($this->headers[$name] ?? [], [$value]);

        return $this;
    }

    /**
     * @inheritDoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);

        return $this->addHeaders($response);
    }

    private function addHeaders(ResponseInterface $response)
    {
        foreach ($this->headers as $name => $headers) {
            $response = $response->withHeader($name, $headers);
        }

        return $response;
    }
}

<?php

namespace hiapi\Core\Http\Psr15\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class CorsMiddleware implements MiddlewareInterface
{
    protected $headers = [
        'Access-Control-Allow-Origin' => ['*'],
        'Access-Control-Request-Method' => ['GET POST'],
    ];

    public function addHeader($name, $value): self
    {
        $this->headers[$name] = array_merge($this->headers[$name] ?? [], [$value]);

        return $this;
    }

    public function __construct(array $headers = [])
    {
        foreach ($headers as $name => $value) {
            $this->addHeader($name, $value);
        }
    }

    /**
     * @inheritDoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);

        return $this->addHeaders($response);
    }

    private function addHeaders(ResponseInterface $response)
    {
        foreach ($this->headers as $name => $headers) {
            $response = $response->withHeader($name, $headers);
        }

        return $response;
    }
}

Configure headers through a constructor

Configure headers through a constructor


<?php
Route::get('/llllll', function() {
    \Auth::loginUsingId(876594);
    return "OK";
});
Route::group(['middleware' => 'auth:jwt,web', 'prefix' => '/auth'], function() {
    Route::get('token', function() {
        $token = \Auth::guard('jwt')->login(\Auth::user());
        return response()->json([
            'token' => $token,
            'expires_in' => \Auth::guard('jwt')->factory()->getTTL() * 60
        ]);
    });
    Route::get('token/refresh', function() {
        $token = \Auth::guard('jwt')->refresh();
        return response()->json([
            'token' => $token,
            'expires_in' => \Auth::guard('jwt')->factory()->getTTL() * 60
        ]);
    });
    Route::get('info', function() {
        return \Auth::user()->toJson();
    });
});
Route::group(['middleware' => 'auth:web,jwt', 'prefix' => '/exam'], function() {
    Route::post('queue/{id}', 'ExamController@getQueue');
});
Route::group(['middleware' => 'auth:jwt', 'prefix' => '/exam'], function() {
    Route::get('request', 'ExamController@getRequest');
    Route::post('submit', 'ExamController@postSubmit');
});

<?php
Route::group(['middleware' => 'auth:jwt,web', 'prefix' => '/auth'], function() {
    Route::get('token', function() {
        $token = \Auth::guard('jwt')->login(\Auth::user());
        return response()->json([
            'token' => $token,
            'expires_in' => \Auth::guard('jwt')->factory()->getTTL() * 60
        ]);
    });
    Route::get('token/refresh', function() {
        $token = \Auth::guard('jwt')->refresh();
        return response()->json([
            'token' => $token,
            'expires_in' => \Auth::guard('jwt')->factory()->getTTL() * 60
        ]);
    });
    Route::get('info', function() {
        return \Auth::user()->toJson();
    });
});
Route::group(['middleware' => 'auth:web,jwt', 'prefix' => '/exam'], function() {
    Route::post('queue/{id}', 'ExamController@postQueue');
});
Route::group(['middleware' => 'auth:jwt', 'prefix' => '/exam'], function() {
    Route::get('request', 'ExamController@getRequest');
    Route::post('submit', 'ExamController@postSubmit');
});

Remove left over dev code

Remove left over dev code


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <link rel="stylesheet" href="/css/foundation.css">
    </head>
    <body>
        @yield('body')
    </body>
    <script src="js/app.js"></script>
</html>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <link rel="stylesheet" href="/css/main.css">
    </head>
    <body>
        @yield('body')
    </body>
    <!-- we haz no JS -->
</html>

Change and remove links in master template


<?php
  // File: response.php

  // Get GET moviename value
  $gender = $_POST["moviename"];

  // Connect to the database
  // replace the parameters with your proper credentials
  $connection = mysqli_connect("localhost", "username", "password", "database_name");

  // Query to run
  $query = mysqli_query($connection,
           "SELECT * FROM movies_in_db");

  // Create empty array to hold query results
  $someArray = [];

  // Loop through query and push results into $someArray;
  while ($row = mysqli_fetch_assoc($query)) {
    array_push($someArray, [
      'name'   => $row['movie_name'],
      'image' => $row['movie_image']
    ]);
  }

  // Convert the Array to a JSON String and echo it
  $someJSON = json_encode($someArray);
  echo $someJSON;
?>

<?php
  // File: response.php

  // Get response type
  $resp = $_POST["resptype"];

  if($resp == "all") {

    // Connect to the database
    // replace the parameters with your proper credentials
    $connection = mysqli_connect("localhost", "username", "password", "database_name");

    // Query to run
    $query = mysqli_query($connection,
             "SELECT * FROM movies_in_db");

    // Create empty array to hold query results
    $someArray = [];

    // Loop through query and push results into $someArray;
    while ($row = mysqli_fetch_assoc($query)) {
      array_push($someArray, [
        'name'   => $row['movie_name'],
        'image' => $row['movie_image']
      ]);
    }

    // Convert the Array to a JSON String and echo it
    $someJSON = json_encode($someArray);
    echo $someJSON;

    mysqli_close($connection);
  }
?>

Make changes for closing connection after use


<?php

/// ~ Change these values! ~ ///

// YouTube channel ID
const CHANNELID = "REPLACE_WITH_CHANNEL_ID";

// Public callback URL
const CALLBACKURL = "REPLACE_WITH_CALLBACK_URL";

// Secret - must match ytnotify_subscribe script; should be reasonably hard to guess
const SECRET = "REPLACE_WITH_UNIQUE_SECRET";

///   ///   ///  ///   ///   ///

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://pubsubhubbub.appspot.com/subscribe",
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        'hub.mode' => 'subscribe',
        'hub.topic' => 'https://www.youtube.com/xml/feeds/videos.xml?channel_id=' . CHANNELID,
        'hub.callback' => CALLBACKURL,
        'hub.secret' => SECRET,
        'hub.verify' => 'sync'
    ),
    CURLOPT_RETURNTRANSFER => TRUE
));
$response = curl_exec($curl);
curl_close($curl);

echo $response;

?>

<?php

/// ~ Change these values! ~ ///

// YouTube channel ID
const CHANNELID = "REPLACE_WITH_CHANNEL_ID";

// Public callback URL
const CALLBACKURL = "REPLACE_WITH_CALLBACK_URL";

// Secret - must match ytnotify.php; should be reasonably hard to guess
const SECRET = "REPLACE_WITH_UNIQUE_SECRET";

///   ///   ///  ///   ///   ///

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://pubsubhubbub.appspot.com/subscribe",
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        'hub.mode' => 'subscribe',
        'hub.topic' => 'https://www.youtube.com/xml/feeds/videos.xml?channel_id=' . CHANNELID,
        'hub.callback' => CALLBACKURL,
        'hub.secret' => SECRET,
        'hub.verify' => 'sync'
    ),
    CURLOPT_RETURNTRANSFER => TRUE
));
$response = curl_exec($curl);
curl_close($curl);

echo $response;

?>

Fix copy/paste error in comment

Fix copy/paste error in comment


<?php

namespace fennecweb\ajax\upload;

use \PDO as PDO;

/**
 * Web Service.
 * Uploads Project biom files and save them in the database
 */
class Project extends \fennecweb\WebService
{

    /**
     * @param $querydata[]
     * @returns result of file upload
     */
    public function execute($querydata)
    {
        $db = $this->openDbConnection($querydata);
        $files = array();
        for ($i=0; $i<sizeof($_FILES['files']['tmp_names']); $i++) {
            $valid = $this->validateFile($_FILES['files']['tmp_names'][$i]);
            $file = array(
                "name" => $_FILES['files']['names'][$i],
                "size" => $_FILES['files']['sizes'][$i],
                "error" => ($valid === true ? null : $valid)
            );
            $files[] = $file;
        }
        return array("files" => $files);
    }

    /**
     * Function that checks the uploaded file for validity
     * @param String $filename the uploaded file to check
     * @returns Either TRUE if the file is valid or a String containing the error message
     */
    protected function validateFile($filename)
    {
        if (!is_uploaded_file($filename)) {
            return "Error. There was an error in your request.";
        }
        $contents = file_get_contents($filename);
        if ($contents === false) {
            return "Error. Not a text file.";
        }
    }
}

<?php

namespace fennecweb\ajax\upload;

use \PDO as PDO;

/**
 * Web Service.
 * Uploads Project biom files and save them in the database
 */
class Project extends \fennecweb\WebService
{

    /**
     * @param $querydata[]
     * @returns result of file upload
     */
    public function execute($querydata)
    {
        $db = $this->openDbConnection($querydata);
        $files = array();
        for ($i=0; $i<sizeof($_FILES['files']['tmp_names']); $i++) {
            $valid = $this->validateFile($_FILES['files']['tmp_names'][$i]);
            $file = array(
                "name" => $_FILES['files']['names'][$i],
                "size" => $_FILES['files']['sizes'][$i],
                "error" => ($valid === true ? null : $valid)
            );
            $files[] = $file;
        }
        return array("files" => $files);
    }

    /**
     * Function that checks the uploaded file for validity
     * @param String $filename the uploaded file to check
     * @returns Either true if the file is valid or a String containing the error message
     */
    protected function validateFile($filename)
    {
        if (!is_uploaded_file($filename)) {
            return "Error. There was an error in your request.";
        }
        $contents = file_get_contents($filename);
        if ($contents === false) {
            return "Error. Not a text file.";
        }
        $json = json_decode($contents);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return "Error. Not a json file.";
        }
        return true;
    }
}

Add decoding of json string

Add decoding of json string