<?php

namespace Tests\AppBundle\API\Details;

use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;

class OrganismTest extends WebserviceTestCase
{

    public function testExecute()
    {
        $default_db = $this->default_db;
        $session = null;
        $organisms = $this->webservice->factory('details', 'organism');
        $parameterBag = new ParameterBag(array('dbversion' => $default_db, 'id' => 42));
        $results = $organisms->execute($parameterBag, $session);
        $expected = array(
            "fennec_id" => 42,
            "scientific_name" => "Trebouxiophyceae sp. TP-2016a",
            "eol_identifier" => "",
            "ncbi_identifier" => "3083"
        );
        $this->assertEquals($expected, $results);
    }
}

<?php

namespace Tests\AppBundle\API\Details;

use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;

class OrganismTest extends WebserviceTestCase
{

    public function testExecute()
    {
        $default_db = $this->default_db;
        $session = null;
        $organisms = $this->webservice->factory('details', 'organism');
        $parameterBag = new ParameterBag(array('dbversion' => $default_db, 'id' => 42));
        $results = $organisms->execute($parameterBag, $session);
        $expected = array(
            "fennec_id" => 42,
            "scientific_name" => "Trebouxiophyceae sp. TP-2016a",
            "eol_identifier" => "909148",
            "ncbi_identifier" => "3083"
        );
        $this->assertEquals($expected, $results);
    }
}

Add eol id to expectation

Add eol id to expectation


<?php

namespace Kunstmaan\FixturesBundle\Populator;

use Doctrine\Common\Collections\ArrayCollection;
use Kunstmaan\FixturesBundle\Populator\Methods\MethodInterface;

class Populator
{
    /**
     * @var MethodInterface[]
     */
    private $populators;

    public function __construct()
    {
        $this->populators = new ArrayCollection();
    }

    public function populate($entity, $data)
    {
        foreach ($data as $property => $value) {
            foreach ($this->populators as $populator) {
                if ($populator->canSet($entity, $property, $value)) {
                    if ($value instanceof \Kunstmaan\FixturesBundle\Loader\Fixture) {
                        $populator->set($entity, $property, $value->getEntity());
                    } else {
                        $populator->set($entity, $property, $value);
                    }
                    break;
                }
            }
        }
    }

    public function addPopulator(MethodInterface $populator, $alias)
    {
        $this->populators->set($alias, $populator);

        return $this;
    }
}

<?php

namespace Kunstmaan\FixturesBundle\Populator;

use Doctrine\Common\Collections\ArrayCollection;
use Kunstmaan\FixturesBundle\Populator\Methods\MethodInterface;

class Populator
{
    /**
     * @var MethodInterface[]
     */
    private $populators;

    public function __construct()
    {
        $this->populators = new ArrayCollection();
    }

    public function populate($entity, $data)
    {
        foreach ($data as $property => $value) {
            foreach ($this->populators as $populator) {
                if ($populator->canSet($entity, $property, $value)) {
                    if ($value instanceof \Kunstmaan\FixturesBundle\Loader\Fixture) {
                        $populator->set($entity, $property, $value->getEntity());
                    } elseif(is_array($value)) {
                        foreach($value as &$item) {
                            if($item instanceof \Kunstmaan\FixturesBundle\Loader\Fixture) {
                                $item = $item->getEntity();
                            }
                        }
                        $populator->set($entity, $property, $value);
                    } else {
                        $populator->set($entity, $property, $value);
                    }
                    break;
                }
            }
        }
    }

    public function addPopulator(MethodInterface $populator, $alias)
    {
        $this->populators->set($alias, $populator);

        return $this;
    }
}

Fix for fixtures populator entity array

Fix for fixtures populator entity array


<?php
class SluggableBehavior extends ModelBehavior {

    public function setup(Model $Model, $settings = array()) {
        if (!isset($this->settings[$Model->alias])) {
            $this->settings[$Model->alias] = array(
                'titleColumn' => 'title',
                'slugColumn' => 'slug',
                'replacement' => '-'
            );
        }
        $this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], $settings);
    }

    public function beforeSave(Model $Model, $options = array()) {
        $titleColumn = $this->settings[$Model->alias]['titleColumn'];
        $slugColumn = $this->settings[$Model->alias]['slugColumn'];
        $replacement = $this->settings[$Model->alias]['replacement'];

        if (isset($Model->data[$Model->alias][$titleColumn])) {
            $Model->data[$Model->alias][$slugColumn] = Inflector::slug(strtolower($Model->data[$Model->alias][$titleColumn]), $replacement);
        }
        return true;
    }
}

<?php
class SluggableBehavior extends ModelBehavior {

    public function setup(Model $Model, $settings = array()) {
        if (!isset($this->settings[$Model->alias])) {
            $this->settings[$Model->alias] = array(
                'slugColumn' => 'slug'
            );
        }
        $this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], $settings);
    }

    public function beforeSave(Model $Model, $options = array()) {
        $displayField = $Model->displayField;
        $slugColumn = $this->settings[$Model->alias]['slugColumn'];

        if (isset($Model->data[$Model->alias][$displayField])) {
            $Model->data[$Model->alias][$slugColumn] = Inflector::slug(strtolower($Model->data[$Model->alias][$displayField]), '-');
        }
        return true;
    }
}

Make sluggable behavior use model's displayField


<?php

namespace Bundle\DoctrineUserBundle\Templating\Helper;

use Symfony\Component\Templating\Helper\Helper;
use Bundle\DoctrineUserBundle\Model\User;
use Symfony\Component\Security\SecurityContext;

/**
 * SecurityHelper.
 */
class SecurityHelper extends Helper
{
    protected $securityContext;

    /**
     * Constructor.
     *
     * @param Auth the Auth service instance
     */
    public function __construct(SecurityContext $securityContext)
    {
        $this->securityContext = $securityContext;
    }

    /**
     * Returns the authenticated user, if any
     *
     * @return Bundle\DoctrineUserBundle\Model\User
     */
    public function getUser()
    {
        return $this->securityContext->getUser();
    }

    /**
     * Tell whether or not a user is logged in
     *
     * @return bool
     **/
    public function isAuthenticated()
    {
        return $this->securityContext->isAuthenticated();
    }

    /**
     * Tell whether or not the user is anonymous
     *
     * @return bool
     **/
    public function isAnonymous()
    {
        $token = $this->securityContext->getToken();

        if(!$token) {
            return true;
        }

        return !$token->getUser() instanceof User;
    }

    /**
     * Returns the canonical name of this helper.
     *
     * @return string The canonical name
     */
    public function getName()
    {
        return 'doctrine_user_security';
    }
}

<?php

namespace Bundle\DoctrineUserBundle\Templating\Helper;

use Symfony\Component\Templating\Helper\Helper;
use Bundle\DoctrineUserBundle\Model\User;
use Symfony\Component\Security\SecurityContext;

/**
 * SecurityHelper.
 */
class SecurityHelper extends Helper
{
    protected $securityContext;

    /**
     * Constructor.
     *
     * @param Auth the Auth service instance
     */
    public function __construct(SecurityContext $securityContext)
    {
        $this->securityContext = $securityContext;
    }

    /**
     * Returns the authenticated user, if any
     *
     * @return Bundle\DoctrineUserBundle\Model\User
     */
    public function getUser()
    {
        return $this->securityContext->getUser();
    }

    /**
     * Tells whether the authenticated user is this user
     *
     * @return bool
     **/
    public function isUser(User $user)
    {
        $authenticatedUser = $this->getUser();

        return $authenticatedUser instanceof User && $authenticatedUser->is($user);
    }

    /**
     * Tell whether or not a user is logged in
     *
     * @return bool
     **/
    public function isAuthenticated()
    {
        return $this->securityContext->isAuthenticated();
    }

    /**
     * Tell whether or not the user is anonymous
     *
     * @return bool
     **/
    public function isAnonymous()
    {
        $token = $this->securityContext->getToken();

        if(!$token) {
            return true;
        }

        return !$token->getUser() instanceof User;
    }

    /**
     * Returns the canonical name of this helper.
     *
     * @return string The canonical name
     */
    public function getName()
    {
        return 'doctrine_user_security';
    }
}

Add isUser method to the security helper


<?php
namespace Neos\Flow\Mvc;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Http\Component\ComponentContext;
use Neos\Flow\Http\Component\ComponentInterface;
use Neos\Flow\Mvc\Routing\RoutingComponent;
use Neos\Flow\Security\Context;

/**
 *
 */
class PrepareMvcRequestComponent implements ComponentInterface
{
    /**
     * @Flow\Inject(lazy=false)
     * @var Context
     */
    protected $securityContext;

    /**
     * @Flow\Inject
     * @var ActionRequestFactory
     */
    protected $actionRequestFactory;

    /**
     * @inheritDoc
     */
    public function handle(ComponentContext $componentContext)
    {
        $httpRequest = $componentContext->getHttpRequest();

        $routingMatchResults = $componentContext->getParameter(RoutingComponent::class, 'matchResults');
        $actionRequest = $this->actionRequestFactory->createActionRequest($httpRequest, $routingMatchResults ?? []);
        $this->securityContext->setRequest($actionRequest);
        $componentContext->setParameter(DispatchComponent::class, 'actionRequest', $actionRequest);
    }
}

<?php
namespace Neos\Flow\Mvc;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Http\Component\ComponentContext;
use Neos\Flow\Http\Component\ComponentInterface;
use Neos\Flow\Http\ServerRequestAttributes;
use Neos\Flow\Security\Context;

/**
 *
 */
class PrepareMvcRequestComponent implements ComponentInterface
{
    /**
     * @Flow\Inject(lazy=false)
     * @var Context
     */
    protected $securityContext;

    /**
     * @Flow\Inject
     * @var ActionRequestFactory
     */
    protected $actionRequestFactory;

    /**
     * @inheritDoc
     */
    public function handle(ComponentContext $componentContext)
    {
        $httpRequest = $componentContext->getHttpRequest();

        $routingMatchResults = $httpRequest->getAttribute(ServerRequestAttributes::ROUTING_RESULTS) ?? [];
        $actionRequest = $this->actionRequestFactory->createActionRequest($httpRequest, $routingMatchResults);
        $this->securityContext->setRequest($actionRequest);
        $componentContext->setParameter(DispatchComponent::class, 'actionRequest', $actionRequest);
    }
}

TASK: Replace RouteComponent::class matchResults with ServerRequestAttributes::ROUTING_RESULTS


<?php

/**
 *    Copyright (c) ppy Pty Ltd <contact@ppy.sh>.
 *
 *    This file is part of osu!web. osu!web is distributed with the hope of
 *    attracting more community contributions to the core ecosystem of osu!.
 *
 *    osu!web is free software: you can redistribute it and/or modify
 *    it under the terms of the Affero GNU General Public License version 3
 *    as published by the Free Software Foundation.
 *
 *    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
 *    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *    See the GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with osu!web.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace App\Http\Middleware;

use Closure;

class StripCookies
{
    public function handle($request, Closure $next)
    {
        $result = $next($request);

        if (session('_strip_cookies') === true) {
            session()->forget('_strip_cookies');
            // strip all cookies from response
            foreach ($result->headers->getCookies() as $cookie) {
                $result->headers->removeCookie($cookie->getName());
            }
        }

        return $result;
    }
}

<?php

/**
 *    Copyright (c) ppy Pty Ltd <contact@ppy.sh>.
 *
 *    This file is part of osu!web. osu!web is distributed with the hope of
 *    attracting more community contributions to the core ecosystem of osu!.
 *
 *    osu!web is free software: you can redistribute it and/or modify
 *    it under the terms of the Affero GNU General Public License version 3
 *    as published by the Free Software Foundation.
 *
 *    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
 *    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *    See the GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with osu!web.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace App\Http\Middleware;

use Closure;

class StripCookies
{
    public function handle($request, Closure $next)
    {
        $result = $next($request);

        if (session('_strip_cookies') === true) {
            session()->forget('_strip_cookies');
            // strip all cookies from response
            foreach ($result->headers->getCookies() as $cookie) {
                $result->headers->removeCookie(
                    $cookie->getName(),
                    $cookie->getPath(),
                    $cookie->getDomain()
                );
            }
        }

        return $result;
    }
}

Fix cookie cleanup sometimes not working

Make sure domain and path matches while removing cookies.
Why the function doesn't accept Cookie object while setCookie accepts (requires) one is a bit beyond me.


<?php

class Crunchbutton_Cron_Job_DriverFixNotify extends Crunchbutton_Cron_Log {

	public function run(){

		$q = '
		select `order`.* from `order`
		left join restaurant using (id_restaurant)
		left join admin_notification_log using (id_order)
		where restaurant.delivery_service=1 and restaurant.active=true and admin_notification_log.id_admin_notification_log is null
		and `order`.date > date_sub(now(), interval 10 minute)
		order by `order`.id_order desc
		';
		$orders = Order::q($q);

		foreach ($orders as $order) {
			echo 'sending notifications for order '.$order->id_order."\n";
			$order->notifyDrivers();
		}

		echo 'done notifying drivers';

		// it always must call finished method at the end
		$this->finished();
	}
}

<?php

class Crunchbutton_Cron_Job_DriverFixNotify extends Crunchbutton_Cron_Log {

	public function run(){

		$q = '
		select `order`.* from `order`
		left join restaurant using (id_restaurant)
		left join admin_notification_log using (id_order)
		where restaurant.delivery_service=1 and restaurant.active=true and admin_notification_log.id_admin_notification_log is null
		and `order`.date > date_sub(now(), interval 10 minute) and `order`.date < date_sub(now(), interval 1 minute)
		order by `order`.id_order desc
		';
		$orders = Order::q($q);

		foreach ($orders as $order) {
			echo 'sending notifications for order '.$order->id_order."\n";
			$order->notifyDrivers();
		}

		echo 'done notifying drivers';

		// it always must call finished method at the end
		$this->finished();
	}
}

Add minimum of 1 minute before cleanup cron job notifies driver of order.


<?php

namespace RadDB\Providers;

use Laravel\Dusk\DuskServiceProvider;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app->environment('local', 'testing')) {
            $this->app->register(DuskServiceProvider::class);
        }
    }
}

<?php

namespace RadDB\Providers;

use Laravel\Dusk\DuskServiceProvider;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // Work around for MariaDB/MySQL key too long errors
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app->environment('local', 'testing')) {
            $this->app->register(DuskServiceProvider::class);
        }
    }
}

Set default string length to work around key too long errors


<?php

$config = \OC::$server->getConfig();
$dbConnection = \OC::$server->getDatabaseConnection();
$userManager = OC::$server->getUserManager();
$config = \OC::$server->getConfig();

/** @var Symfony\Component\Console\Application $application */
$application->add(new \OCA\Federation\Command\SyncFederationAddressBooks($userManager, $dbConnection, $config));

<?php

$dbConnection = \OC::$server->getDatabaseConnection();

/** @var Symfony\Component\Console\Application $application */
$application->add(new \OCA\Federation\Command\SyncFederationAddressBooks($dbConnection));

Fix registration of sync command

Fix registration of sync command


<?php

namespace frenna\auth\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use frenna\auth\models\LoginForm;

class AuthController extends Controller
{

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only'  => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allows'  => ['true'],
                        'roles'   => ['@'],
                    ],
                ],
            ],

            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ]
        ];
    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionLogin()
    {
        if(Yii::$app->user->isGuest) {
            $loginForm = new LoginForm();
            $post = Yii::$app->request->post();

            if($loginForm->load($post) && $loginForm->login()) {
                return $this->goBack();
            }

            return $this->render('auth/login', [
                "model" => $loginForm
            ]);
        }

        return $this->goHome();

    }

    public function actionLogout()
    {
        Yii::$app->user->logout();
        return $this->goHome();
    }
}

<?php

namespace frenna\auth\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use frenna\auth\models\LoginForm;

class AuthController extends Controller
{

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only'  => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow'   => ['true'],
                        'roles'   => ['@'],
                    ],
                ],
            ],

            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ]
        ];
    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionLogin()
    {
        if(Yii::$app->user->isGuest) {
            $loginForm = new LoginForm();
            $post = Yii::$app->request->post();

            if($loginForm->load($post) && $loginForm->login()) {
                return $this->goBack();
            }

            return $this->render('auth/login', [
                "model" => $loginForm
            ]);
        }

        return $this->goHome();

    }

    public function actionLogout()
    {
        Yii::$app->user->logout();
        return $this->goHome();
    }
}

Allow inside behaviors inside auth controller


<?php
namespace Aws\S3\Subscriber;

use GuzzleHttp\Command\Event\ProcessEvent;
use GuzzleHttp\Event\SubscriberInterface;

/**
 * Injects ObjectURL into the result model of the PutObject operation.
 *
 * @internal
 */
class PutObjectUrl implements SubscriberInterface
{
    public function getEvents()
    {
        return ['process' => ['addObjectUrl', -10]];
    }

    public function addObjectUrl(ProcessEvent $e)
    {
        if ($e->getException()) {
            return;
        }

        $name = $e->getCommand()->getName();

        if ($name === 'PutObject') {
            $e->getResult()['ObjectURL'] = $e->getRequest()->getUrl();
        } elseif ($name === 'CompleteMultipartUpload') {
            $e->getResult()['ObjectURL'] = $e->getResult()['Location'];
        }
    }
}

<?php
namespace Aws\S3\Subscriber;

use GuzzleHttp\Command\Event\ProcessEvent;
use GuzzleHttp\Event\SubscriberInterface;

/**
 * Injects ObjectURL into the result model of the PutObject operation.
 *
 * @internal
 */
class PutObjectUrl implements SubscriberInterface
{
    public function getEvents()
    {
        return ['process' => ['addObjectUrl', -10]];
    }

    public function addObjectUrl(ProcessEvent $e)
    {
        if ($e->getException()) {
            return;
        }

        $name = $e->getCommand()->getName();

        if ($name === 'PutObject' || $name === 'CopyObject') {
            $e->getResult()['ObjectURL'] = $e->getRequest()->getUrl();
        } elseif ($name === 'CompleteMultipartUpload') {
            $e->getResult()['ObjectURL'] = $e->getResult()['Location'];
        }
    }
}

Include ObjectURL in the result for CopyObject.


<?php namespace ThreadMeUp\Slack;

use Guzzle\Http\Message\Response as GuzzleResponse;

class Response
{
    protected $rawResponse;
    protected $response;
    protected $errorTypes = array(
        'invalid_auth' => 'Invalid authentication token',
        'account_inactive' => 'Authentication token is for a deleted user or team',
        'channel_not_found' => 'Value passed for channel was invalid',
        'is_archived' => 'Channel has been archived'
    );
    protected $error = null;

    public function __construct(GuzzleResponse $response)
    {
        $this->rawResponse = $response;
        $this->response = json_decode(json_encode($this->rawResponse->json()));
    }

    public function statusCode()
    {
        return $this->rawResponse->getStatusCode();
    }

    public function isOkay()
    {
        $isOkay = $this->response->ok;
        if (!$isOkay) $this->error = $this->errorTypes[$this->response->error];
    }

    public function getError()
    {
        return $this->error;
    }
}

<?php namespace ThreadMeUp\Slack;

use Guzzle\Http\Message\Response as GuzzleResponse;

class Response
{
    protected $rawResponse;
    protected $response;
    protected $errorTypes = array(
        'invalid_auth' => 'Invalid authentication token',
        'account_inactive' => 'Authentication token is for a deleted user or team',
        'channel_not_found' => 'Value passed for channel was invalid',
        'is_archived' => 'Channel has been archived'
    );
    protected $error = null;

    public function __construct(GuzzleResponse $response)
    {
        $this->rawResponse = $response;
        $this->response = json_decode(json_encode($this->rawResponse->json()));
    }

    public function statusCode()
    {
        return $this->rawResponse->getStatusCode();
    }

    public function isOkay()
    {
        $isOkay = $this->response->ok;
        if (!$isOkay) $this->error = $this->errorTypes[$this->response->error];
        return $isOkay;
    }

    public function getError()
    {
        return $this->error;
    }
}

Fix successful responses generating errors


<?php
defined('C5_EXECUTE') or die("Access Denied.");
?>

    <form method="post" action="<?= $deleteAction ?>">
        <?=Core::make("token")->output('delete_attribute')?>
        <input type="hidden" name="id" value="<?=$key->getAttributeKeyID()?>">

<?=t('Are you sure you want to delete this attribute? This cannot be undone.')?>

            <button class="btn btn-default pull-left" onclick="jQuery.fn.dialog.closeTop()"><?=t('Cancel')?></button>
            <button class="btn btn-danger pull-right" onclick="$('#ccm-dialog-delete-attribute form').submit()"><?=t('Delete Attribute')?></button>

    </form>

    <button type="button" class="btn btn-danger" data-action="delete-attribute"><?= t('Delete Attribute') ?></button>

Format translation of "Delete Attribute" for javascript


<?php
namespace Corley\MaintenanceBundle\Command;

use Corley\MaintenanceBundle\Maintenance\Runner;
use Symfony\Component\Console\Command\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class DumpApacheConfCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName("corley:maintenance:dump-apache")
            ->setDescription("How to configure your Apache web server")
            ->setHelp(<<<EOF
See how to configure your Apache2 web server in order to enable/disable maintenance mode

    <info>php app/console corley:maintenance:dump-apache</info>
EOF
        );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getContainer();

        $output->writeln(<<<EOF
Open your .htaccess file and paste those lines:

    RewriteCond %{DOCUMENT_ROOT}/{$container->getParameter("maintenance.active_link_name")} -f
    RewriteCond %{SCRIPT_FILENAME} !{$container->getParameter("maintenance.active_link_name")}
    RewriteRule ^.*$ /{$container->getParameter("maintenance.active_link_name")} [R=503,L]
    ErrorDocument 503 /{$container->getParameter("maintenance.active_link_name")}

EOF
        );
    }
}

<?php
namespace Corley\MaintenanceBundle\Command;

use Corley\MaintenanceBundle\Maintenance\Runner;
use Symfony\Component\Console\Command\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class DumpApacheConfCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName("corley:maintenance:dump-apache")
            ->setDescription("How to configure your Apache web server")
            ->setHelp(<<<EOF
See how to configure your Apache2 web server in order to enable/disable maintenance mode

    <info>php app/console corley:maintenance:dump-apache</info>
EOF
        );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getContainer();

        $output->writeln(<<<EOF
Open your .htaccess file and paste those lines:

    RewriteCond %{DOCUMENT_ROOT}/{$container->getParameter("maintenance.active_link_name")} -f
    RewriteCond %{SCRIPT_FILENAME} !{$container->getParameter("maintenance.active_link_name")}
    RewriteRule ^.*$ /{$container->getParameter("maintenance.active_link_name")} [R=503,L]

    RewriteCond %{DOCUMENT_ROOT}/{$container->getParameter("maintenance.active_link_name")} -f
    RewriteRule ^(.*)$ - [env=MAINTENANCE:1]

    <IfModule mod_headers.c>
        Header set cache-control "max-age=0,must-revalidate,post-check=0,pre-check=0" env=MAINTENANCE
        Header set Expires -1 env=MAINTENANCE
    </IfModule>

EOF
        );
    }
}

Disable cache header for Apache2 web servers

If the "headers" module is active, disable all cache information during
maintenance mode


<?php
class ComposerShell extends AppShell {
	public $pharDir;

	public function initialize(){
		if (empty($this->pharDir)){
			if (Configure::read('Composer.phar_dir') !== null) $this->pharDir = Configure::read('Composer.phar_dir');
			else $this->pharDir = dirname(dirname(dirname(__FILE__))).'Vendor'.DS.'Composer'.DS;
		}
	}

	public function main() {
		$this->out('Hello world.');;
	}

	/**
	 * Grabs the latest composer.phar from http://getcomposer.org/composer.phar
	 * Changeable at CakePHP configuration: Composer.phar_url
	 */
	public function setup(){
		$pharURL = 'http://getcomposer.org/composer.phar';
		if (Configure::read('Composer.phar_url') !== null) $pharURL = Configure::read('Composer.phar_url');

		if (!is_writable($pharDir)){
			$this->error("$pharDir is not writable.");
		}
	}
}

<?php
class ComposerShell extends AppShell {
	public $pharDir;

	public function initialize(){
		if (empty($this->pharDir)){
			if (Configure::read('Composer.phar_dir') !== null) $this->pharDir = Configure::read('Composer.phar_dir');
			else $this->pharDir = dirname(dirname(dirname(__FILE__))).DS.'Vendor'.DS.'Composer'.DS;
		}
	}

	public function main() {
		$this->out('Hello world.');;
	}

	/**
	 * Grabs the latest composer.phar from http://getcomposer.org/composer.phar
	 * Changeable at CakePHP configuration: Composer.phar_url
	 */
	public function setup(){
		$pharURL = 'http://getcomposer.org/composer.phar';
		if (Configure::read('Composer.phar_url') !== null) $pharURL = Configure::read('Composer.phar_url');

		if (!is_writable($this->pharDir)){
			$this->error("$this->pharDir is not writable.");
		}

		$this->out('<info>Setting up Composer</info>');
		$this->out("Downloading from $pharURL...");

		$content = file_get_contents($pharURL);
		if ($content === false){
			$this->error("Download failed");
		}

		$save = file_put_contents($this->pharDir.'composer.phar', $content);

		if ($save === false){
			$this->error("Unable to save to {$this->pharDir}composer.phar.");
		}

		$this->out("Composer.phar installed and saved successfully.");
	}
}

Set up composer env by downloading the latest composer.phar


<?php
// Imports
use ProjectRena\Lib\SessionHandler;
use Slim\Slim;
use Slim\Views\Twig;
use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware;

// Error display
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Load the autoloader
if(file_exists(__DIR__."/vendor/autoload.php"))
    require_once(__DIR__."/vendor/autoload.php");
else
    throw new Exception("vendor/autoload.php not found, make sure you run composer install");

// Require the config
if(file_exists(__DIR__."/config.php"))
    require_once(__DIR__."/config.php");
else
    throw new Exception("config.php not found (you might wanna start by copying config_new.php)");

// Prepare app
$app = new Slim($config["slim"]);

// Session
$session = new SessionHandler();
session_set_save_handler($session, true);
session_cache_limiter(false);
session_start();

// Launch Whoops
$app->add(new WhoopsMiddleware);

// Prepare view
$app->view(new Twig());
$app->view->parserOptions = $config["twig"];

// load the additional configs
$configFiles = glob(__DIR__ . "/config/*.php");
foreach($configFiles as $configFile)
    require_once($configFile);

// Run app
$app->run();

<?php
// Imports
use Slim\Slim;
use Slim\Views\Twig;
use ProjectRena\Lib\SessionHandler;
use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware;

// Error display
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Load the autoloader
if(file_exists(__DIR__."/vendor/autoload.php"))
    require_once(__DIR__."/vendor/autoload.php");
else
    throw new Exception("vendor/autoload.php not found, make sure you run composer install");

// Require the config
if(file_exists(__DIR__."/config.php"))
    require_once(__DIR__."/config.php");
else
    throw new Exception("config.php not found (you might wanna start by copying config_new.php)");

// Prepare app
$app = new Slim($config["slim"]);

// Session
$session = new SessionHandler();
session_set_save_handler($session, true);
session_cache_limiter(false);
session_start();

// Launch Whoops
$app->add(new WhoopsMiddleware);

// Prepare view
$app->view(new Twig());
$app->view->parserOptions = $config["twig"];

// load the additional configs
$configFiles = glob(__DIR__ . "/config/*.php");
foreach($configFiles as $configFile)
    require_once($configFile);

// Run app
$app->run();

Move stuff so it looks prettier..

Move stuff so it looks prettier..


<?php
namespace common\commands;

use Yii;
use common\models\Company;
use yii\helpers\Url;

class CompanyDropdown
{
    public function getMenuDropdown(){
        $companyDropdown = [];

        $companies = $this->findCompanies();

        foreach($companies as $company){

            $url_parts = explode("?", Url::canonical());
            $url_params = "";
            foreach($_GET as $key => $param){
                if($key=="company") continue;

                $url_params .= "$key=$param&";
            }
            $url = $url_parts[0]."?".$url_params."company={$company->id}";

            $companyDropdown[] = [
                'label'=>$company->name,
                'url'=> $url,
            ];
        }

        return $companyDropdown;
    }

    public function getDropdown(){
        $companies = $this->findCompanies();
        $companyDropdown = [];

        foreach($companies as $company){
            $companyDropdown[$company->id] = $company->name;
        }

        return $companyDropdown;
    }

    private function findCompanies(){
        $companyAccess = new CompanyAccess();

        $companies = Company::find()
        ->select(['id','name'])
        ->where( $companyAccess->getQueryConditions() )
        ->all();

        return $companies;
    }
}

<?php

namespace common\commands;

use Yii;
use common\models\Company;
use yii\helpers\Url;

class CompanyDropdown {
	public function getMenuDropdown() {
		$companyDropdown = [ ];

		$companies = $this->findCompanies ();

		foreach ( $companies as $company ) {

			$url_parts = explode ( "?", Url::canonical () );
			$url_params = "";
			foreach ( $_GET as $key => $param ) {
				if ($key == "company")
					continue;

				$url_params .= "$key=$param&";
			}
			$url = $url_parts [0] . "?" . $url_params . "company={$company->id}";

			$companyDropdown [] = [
					'label' => $company->name,
					'url' => $url
			];
		}

		return $companyDropdown;
	}
	public function getDropdown() {
		$companies = $this->findCompanies ();
		$companyDropdown = [ ];

		foreach ( $companies as $company ) {
			$companyDropdown [$company->id] = $company->name;
		}

		return $companyDropdown;
	}
	private function findCompanies() {
		$companyAccess = new CompanyAccess ();

		$companies = Company::find ()->select ( [
				'id',
				'name'
		] )
		->where ( $companyAccess->getQueryConditions () )
		->andWhere(['active'=>1])
		->all ();

		return $companies;
	}
}

Fix the findCompany to only fetch active companies


<?php
/**
 * Created by PhpStorm.
 * User: rahman
 * Date: 11/5/14
 * Time: 8:47 AM
 */

Event::listen('auth.login', function($user)
{
    Event::fire('logger', array(array('login',array('username'=>$user->username),3)));
});

Event::listen('auth.logout', function($user)
{
    $username = $user ? $user->username : '-';
    Event::fire('logger', array(array('logout',array('username'=>$user->username),3)));
});

Event::listen('logger', function($log)
{
    $log = array(
        'event_name'=> $log[0],
        'custom_parameter'=> json_encode($log[1]),
        'verbose_level' => $log[2],
        'ip_address' => Request::getClientIp(),
        'request_uri' => Request::url(),
    );

    $logger = Logger::create($log);

    $freshTimestamp = new \Carbon\Carbon();
    $log_string = $freshTimestamp.' '.$log['ip_address'].' VL'.$log['verbose_level'].' '.$logger->id.' '.$log['event_name'].' ['.$log['custom_parameter'].'] ['.$log['request_uri'].']'.PHP_EOL;

    File::append(Config::get('settings.log_file'),$log_string);

});

<?php
/**
 * Created by PhpStorm.
 * User: rahman
 * Date: 11/5/14
 * Time: 8:47 AM
 */

Event::listen('auth.login', function($user)
{
    Event::fire('logger', array(array('login',array('username'=>$user->username),3)));
});

Event::listen('auth.logout', function($user)
{
    $username = $user ? $user->username : '-';
    Event::fire('logger', array(array('logout',array('username'=>$username),3)));
});

Event::listen('logger', function($log)
{
    $log = array(
        'event_name'=> $log[0],
        'custom_parameter'=> json_encode($log[1]),
        'verbose_level' => $log[2],
        'ip_address' => Request::getClientIp(),
        'request_uri' => Request::url(),
    );

    $logger = Logger::create($log);

    $freshTimestamp = new \Carbon\Carbon();
    $log_string = $freshTimestamp.' '.$log['ip_address'].' VL'.$log['verbose_level'].' '.$logger->id.' '.$log['event_name'].' ['.$log['custom_parameter'].'] ['.$log['request_uri'].']'.PHP_EOL;

    File::append(Config::get('settings.log_file'),$log_string);

});

Fix logout logger no username

Fix logout logger no username


<?php
class screenshot extends Script
{
	public function run()
	{
		return $this->send('http://screenshotlayer.com/php_helper_scripts/scl_api.php?url=' . $this->matches[1], 'image');
	}
}

<?php
class screenshot extends Script
{
	protected $helpMessage = "'screenshot URL'\n";
	protected $description = 'Returns a screenshot of the given URL';

	public function run()
	{
		return $this->send('http://screenshotlayer.com/php_helper_scripts/scl_api.php?url=' . $this->matches[1], 'image');
	}
}

Complete the information for the help-plugin


<?php

namespace Tystr\RestOrm\Model;

use Tystr\RestOrm\Annotation\Id;
use Tystr\RestOrm\Annotation\Resource;

/**
 * @Resource("blogs")
 */
class Blog
{
    /**
     * @Id()
     */
    public $id;

    public $body;
}

<?php

namespace Tystr\RestOrm\Model;

use JMS\Serializer\Annotation\Type;
use Tystr\RestOrm\Annotation\Id;
use Tystr\RestOrm\Annotation\Resource;

/**
 * @Resource("blogs")
 */
class Blog
{
    /**
     * @Id()
     * @Type("integer")
     */
    public $id;

    /**
     * @Type("string")
     */
    public $body;
}

Add missing @Type annotations from test model


<?php

namespace BlueChip\Security\Tests\Integration;

class TestCase extends \WP_UnitTestCase
{

}

Fix error reported by PHP CS

Fix error reported by PHP CS


<?php

class SV_EmailQueue_Listener
{
    const AddonNameSpace = 'SV_EmailQueue';

    public static function install($installedAddon, array $addonData, SimpleXMLElement $xml)
    {
        $db = XenForo_Application::getDb();

        XenForo_Db::beginTransaction($db);

        $db->query("CREATE TABLE IF NOT EXISTS `xf_mail_queue_failed` (
  `mail_id` varbinary(20) NOT NULL,
  `mail_data` mediumblob NOT NULL,
  `queue_date` int unsigned NOT NULL,
  `fail_count` int unsigned NOT NULL,
  `last_fail_date` int unsigned NOT NULL,
  `dispatched` bit NOT NULL default 0,
  PRIMARY KEY (`mail_id`),
  KEY `dispatched` (`dispatched`),
  KEY `last_fail_date` (`last_fail_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;");

        XenForo_Db::commit($db);

    }

    public static function uninstall()
    {
        $db = XenForo_Application::getDb();
        XenForo_Db::beginTransaction($db);

        $db->query("insert into xf_mail_queue (`mail_data`,`queue_date`) select `mail_data`,`queue_date` from xf_mail_queue_failed");
        $db->query("drop table xf_mail_queue_failed");

        XenForo_Db::commit($db);
    }

    public static function load_class($class, &$extend)
    {
        $extend[] = self::AddonNameSpace.'_'.$class;
    }
}

<?php

class SV_EmailQueue_Listener
{
    const AddonNameSpace = 'SV_EmailQueue';

    public static function install($installedAddon, array $addonData, SimpleXMLElement $xml)
    {
        $db = XenForo_Application::getDb();

        XenForo_Db::beginTransaction($db);

        $db->query("CREATE TABLE IF NOT EXISTS `xf_mail_queue_failed` (
  `mail_id` varbinary(20) NOT NULL,
  `mail_data` mediumblob NOT NULL,
  `queue_date` int unsigned NOT NULL,
  `fail_count` int unsigned NOT NULL,
  `last_fail_date` int unsigned NOT NULL,
  `dispatched` bit NOT NULL default 0,
  PRIMARY KEY (`mail_id`),
  KEY `dispatched` (`dispatched`),
  KEY `last_fail_date` (`last_fail_date`)
) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci");

        XenForo_Db::commit($db);

    }

    public static function uninstall()
    {
        $db = XenForo_Application::getDb();
        XenForo_Db::beginTransaction($db);

        $db->query("insert into xf_mail_queue (`mail_data`,`queue_date`) select `mail_data`,`queue_date` from xf_mail_queue_failed");
        $db->query("drop table xf_mail_queue_failed");

        XenForo_Db::commit($db);
    }

    public static function load_class($class, &$extend)
    {
        $extend[] = self::AddonNameSpace.'_'.$class;
    }
}

Use utf8 unicode for collation set

Use utf8 unicode for collation set


<?php

namespace Wikidata;

use Wikidata\Property;

class Entity
{
  /**
   * @var string Entity Id
   */
  public $id;

  /**
   * @var string Entity language
   */
  public $lang;

  /**
   * @var string Entity label
   */
  public $label;

  /**
   * @var string A link to a Wikipedia article about this entity
   */
  public $wikipedia_article;

  /**
   * @var string[] List of entity aliases
   */
  public $aliases = [];

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

  /**
   * @var \Illuminate\Support\Collection Collection of entity properties
   */
  public $properties;

  /**
   * @param array $data
   * @param string $lang
   */
  public function __construct($data, $lang)
  {
    $this->parseData($data);
    $this->lang = $lang;
  }

  /**
   * Parse input data
   *
   * @param array $data
   */
  private function parseData($data)
  {
    $this->id = get_id($data[0]['item']);
    $this->label = $data[0]['itemLabel'];
    $this->wikipedia_article = $data[0]['wikipediaArticle'];
    $this->aliases = explode(', ', $data[0]['itemAltLabel']);
    $this->description = $data[0]['itemDescription'];

    $collection = collect($data)->groupBy('prop');
    $this->properties = $collection->mapWithKeys(function($item) {
      $property = new Property($item);

      return [$property->id => $property];
    });
  }
}

<?php

namespace Wikidata;

use Wikidata\Property;

class Entity
{
  /**
   * @var string Entity Id
   */
  public $id;

  /**
   * @var string Entity language
   */
  public $lang;

  /**
   * @var string Entity label
   */
  public $label;

  /**
   * @var string A link to a Wikipedia article about this entity
   */
  public $wikipedia_article;

  /**
   * @var string[] List of entity aliases
   */
  public $aliases = [];

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

  /**
   * @var \Illuminate\Support\Collection Collection of entity properties
   */
  public $properties;

  /**
   * @param array $data
   * @param string $lang
   */
  public function __construct($data, $lang)
  {
    $this->parseData($data);
    $this->lang = $lang;
  }

  /**
   * Parse input data
   *
   * @param array $data
   */
  private function parseData($data)
  {
    $this->id = get_id($data[0]['item']);
    $this->label = $data[0]['itemLabel'];
    $this->wikipedia_article = $data[0]['wikipediaArticle'];
    $this->aliases = is_string($data[0]['itemAltLabel']) ? explode(', ', $data[0]['itemAltLabel']) : [];
    $this->description = $data[0]['itemDescription'];

    $collection = collect($data)->groupBy('prop');
    $this->properties = $collection->mapWithKeys(function($item) {
      $property = new Property($item);

      return [$property->id => $property];
    });
  }
}

Check that itemAltLabel is string

Check that itemAltLabel is string


<?php

namespace duncan3dc\Proxy;

use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;

class App
{
    public function run(): void
    {
        $client = new Client([
            "http_errors"   =>  false,
        ]);

        $url = $this->generateUrl();

        $response = $client->request($_SERVER["REQUEST_METHOD"], $url, [
            "headers"       =>  [
                "User-Agent"    =>  $_SERVER["HTTP_USER_AGENT"],
            ],
            "form_params"   =>  $_POST,
        ]);

        $this->respond($response);
    }

    private function generateUrl(): string
    {
        return "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
    }

    private function respond(ResponseInterface $response): void
    {
        http_response_code($response->getStatusCode());
        header("Content-Type: " . $response->getHeader("content-type")[0]);
        echo $response->getBody();
    }
}

<?php

namespace duncan3dc\Proxy;

use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;

class App
{
    private $client;

    public function __construct()
    {
        $this->client = new Client([
            "http_errors"   =>  false,
        ]);
    }

    public function run(): void
    {
        $url = $this->generateUrl();

        $response = $this->client->request($_SERVER["REQUEST_METHOD"], $url, [
            "headers"       =>  [
                "User-Agent"    =>  $_SERVER["HTTP_USER_AGENT"],
            ],
            "form_params"   =>  $_POST,
        ]);

        $this->respond($response);
    }

    private function generateUrl(): string
    {
        return "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
    }

    private function respond(ResponseInterface $response): void
    {
        http_response_code($response->getStatusCode());
        header("Content-Type: " . $response->getHeader("content-type")[0]);
        echo $response->getBody();
    }
}

Make the guzzle client an instance variable during instantiation


<?php
/**
 * Table Definition for group_inbox
 */
require_once 'classes/Memcached_DataObject';

class Group_inbox extends Memcached_DataObject
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'group_inbox';                     // table name
    public $group_id;                        // int(4)  primary_key not_null
    public $notice_id;                       // int(4)  primary_key not_null
    public $created;                         // datetime()   not_null

    /* Static get */
    function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Group_inbox',$k,$v); }

    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE
}

<?php
/**
 * Table Definition for group_inbox
 */
require_once 'classes/Memcached_DataObject.php';

class Group_inbox extends Memcached_DataObject
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'group_inbox';                     // table name
    public $group_id;                        // int(4)  primary_key not_null
    public $notice_id;                       // int(4)  primary_key not_null
    public $created;                         // datetime()   not_null

    /* Static get */
    function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Group_inbox',$k,$v); }

    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE
}

Fix include for group inbox class

Fix include for group inbox class


<?php
namespace Solleer\User;

class SigninStatus {
    public function setSigninID($id) {
        $_SESSION['user_id'] = $id;
        return true;
    }

    public function getSigninID() {
        return $_SESSION['user_id'];
    }
}

<?php
namespace Solleer\User;

class SigninStatus {
    public function setSigninID($id, $setCookie = false) {
        if (isset($_COOKIE['user_id'])) $setCookie = true;
        $_SESSION['user_id'] = $id;
        if ($setCookie) $this->setCookie('user_id', $id);
        return true;
    }

    public function getSigninID() {
        return $_SESSION['user_id'] ?? $_COOKIE['user_id'] ?? null;
    }

    private function setCookie($name, $value) {
        if (is_array($value)) {
            foreach ($value as $key => $val) $this->setCookie($name . "[$key]", $val);
            return;
        }

        if ($value) $expire = time()+(60*60*24*365); // Expire in 1 year
        else $expire = 1;

        setCookie($name, $value ?? '', $expire, '/');
    }
}

Add ability to set cookies

Add ability to set cookies


<?php
/**
 * User: Simon Libaud
 * Date: 19/03/2017
 * Email: simonlibaud@gmail.com.
 */
namespace Sil\RouteSecurityBundle\Twig;

use Sil\RouteSecurityBundle\Security\AccessControl;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

/**
 * Class RouteSecurityExtension.
 */
class RouteSecurityExtension extends AbstractExtension
{
    private $accessControl;

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

    public function getFunctions()
    {
        return [
            new TwigFunction('hasUserAccessToRoute', [$this->accessControl, 'hasUserAccessToRoute']),
            new TwigFunction('hasUserAccessToRoutes', [$this->accessControl, 'hasUserAccessToRoutes']),
            new TwigFunction('hasUserAccessAtLeastOneRoute', [$this->accessControl, 'hasUserAccessAtLeastOneRoute']),
        ];
    }
}

<?php
/**
 * User: Simon Libaud
 * Date: 19/03/2017
 * Email: simonlibaud@gmail.com.
 */
namespace Sil\RouteSecurityBundle\Twig;

use Sil\RouteSecurityBundle\Security\AccessControl;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

/**
 * Class RouteSecurityExtension.
 */
class RouteSecurityExtension extends AbstractExtension
{
    private $accessControl;

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

    public function getFunctions(): array
    {
        return [
            new TwigFunction('hasUserAccessToRoute', [$this->accessControl, 'hasUserAccessToRoute']),
            new TwigFunction('hasUserAccessToRoutes', [$this->accessControl, 'hasUserAccessToRoutes']),
            new TwigFunction('hasUserAccessAtLeastOneRoute', [$this->accessControl, 'hasUserAccessAtLeastOneRoute']),
        ];
    }
}

Add native return type declaration (array) to Twig functions extension


<?php
define('CMIS_BROWSER_URL', 'http://my.alfresco.tld:8080/alfresco/api/-default-/public/cmis/versions/1.1/browser');
define('CMIS_BROWSER_USER', 'admin');
define('CMIS_BROWSER_PASSWORD', 'AlfrescoAdmin');
// if empty the first repository will be used
define('CMIS_REPOSITORY_ID', null);

<?php
date_default_timezone_set('Europe/Berlin');       // Set the default timezone
define('CMIS_BROWSER_URL', 'http://my.alfresco.tld:8080/alfresco/api/-default-/public/cmis/versions/1.1/browser');
define('CMIS_BROWSER_USER', 'admin');
define('CMIS_BROWSER_PASSWORD', 'AlfrescoAdmin');
// if empty the first repository will be used
define('CMIS_REPOSITORY_ID', null);

Add default timezone in examples configuration like bootstrap.php for testing


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\ORM;

/**
 * Exception thrown when a Proxy fails to retrieve an Entity result.
 *
 * @author robo
 * @since 2.0
 */
class EntityNotFoundException extends ORMException
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct('Entity was not found.');
    }
}

<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\ORM;

/**
 * Exception thrown when a Proxy fails to retrieve an Entity result.
 *
 * @author robo
 * @since 2.0
 */
class EntityNotFoundException extends ORMException
{
    /**
     * Constructor.
     */
    public function __construct($class)
    {
        parent::__construct("Entity of type '{$class}' was not found.");
    }
}

Add class name as argument.

Add class name as argument.


<?php

class UsersTableSeeder extends Seeder {

  public function run()
  {
    $faker = Faker\Factory::create();

    User::truncate();

    User::create([
      'first_name' => 'Dave',
      'email' => 'dfurnes@dosomething.org',
      'password' => 'tops3cret',
      ])->assignRole(1);

    User::create([
      'first_name' => 'Andrea',
      'email' => 'agaither@dosomething.org',
      'password' => 'tops3cret',
      ])->assignRole(1);

    foreach(range(1,25) as $index) {
      User::create([
        'first_name' => $faker->firstName,
        'email' => $faker->unique()->safeEmail,
        'birthdate' => $faker->dateTime('now'),
      ]);
    }
    foreach(range(1,25) as $index) {
      User::create([
        'first_name' => $faker->firstName,
        'phone' => $faker->unique()->phoneNumber,
        'birthdate' => $faker->dateTime('now'),
      ]);
    }
  }
}

<?php

class UsersTableSeeder extends Seeder {

  public function run()
  {
    $faker = Faker\Factory::create();

    User::truncate();

    User::create([
      'first_name' => 'Dave',
      'email' => 'dfurnes@dosomething.org',
      'password' => 'tops3cret',
      ])->assignRole(1);

    User::create([
      'first_name' => 'Andrea',
      'email' => 'agaither@dosomething.org',
      'password' => 'tops3cret',
      ])->assignRole(1);

    foreach(range(1,25) as $index) {
      User::create([
        'first_name' => $faker->firstName,
        'email' => $faker->unique()->safeEmail,
        'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
      ]);
    }
    foreach(range(1,25) as $index) {
      User::create([
        'first_name' => $faker->firstName,
        'phone' => $faker->unique()->phoneNumber,
        'birthdate' => $faker->date($format = 'm/d/Y', $max = 'now'),
      ]);
    }
  }
}

Update user table seeder to give proper MM/DD/YYYY string.


<?php

namespace App\Base\Auth;

use Illuminate\Auth\Notifications\ResetPassword as BaseResetPassword;
use Illuminate\Notifications\Messages\MailMessage;

class ResetPassword extends BaseResetPassword
{
    /**
     * Build the mail representation of the notification.
     *
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail()
    {
        $message = (new MailMessage)
            ->subject(trans('auth.password.email.action'))
            ->greeting(trans('auth.password.email.introduction'))
            ->line(trans('auth.password.email.content'))
            ->action(trans('auth.password.email.action'), route('password.reset.token', ['token' => $this->token]))
            ->line(trans('auth.password.email.conclusion'));
        return $message;
    }
}

<?php

namespace App\Base\Auth;

use Illuminate\Auth\Notifications\ResetPassword as BaseResetPassword;
use Illuminate\Notifications\Messages\MailMessage;

class ResetPassword extends BaseResetPassword
{
    /**
     * Build the mail representation of the notification.
     *
     * @param mixed $notifiable
     *
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        $message = (new MailMessage)
            ->subject(trans('auth.password.email.action'))
            ->greeting(trans('auth.password.email.introduction'))
            ->line(trans('auth.password.email.content'))
            ->action(trans('auth.password.email.action'), route('password.reset.token', ['token' => $this->token]))
            ->line(trans('auth.password.email.conclusion'));
        return $message;
    }
}

Make toMail method compatible with the base class


<?php

/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

if (file_exists($file = __DIR__.'/autoload.php')) {
    require_once $file;
} elseif (file_exists($file = __DIR__.'/autoload.php.dist')) {
    require_once $file;
}

<?php

/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

date_default_timezone_set('Europe/Paris');

if (file_exists($file = __DIR__.'/autoload.php')) {
    require_once $file;
} elseif (file_exists($file = __DIR__.'/autoload.php.dist')) {
    require_once $file;
}

Set default timezone to avoid issue with hhvm on travis


<?php
/**
 * @package api
 * @subpackage objects.factory
 */
class KalturaEntryFactory
{
	/**
	 * @param int $type
	 * @param bool $isAdmin
	 * @return KalturaBaseEntry
	 */
	static function getInstanceByType ($type, $isAdmin = false)
	{
		switch ($type)
		{
			case KalturaEntryType::MEDIA_CLIP:
				$obj = new KalturaMediaEntry();
				break;

			case KalturaEntryType::MIX:
				$obj = new KalturaMixEntry();
				break;

			case KalturaEntryType::PLAYLIST:
				$obj = new KalturaPlaylist();
				break;

			case KalturaEntryType::DATA:
				$obj = new KalturaDataEntry();
				break;

			case KalturaEntryType::LIVE_STREAM:
				if($isAdmin)
				{
					$obj = new KalturaLiveStreamAdminEntry();
				}
				else
				{
					$obj = new KalturaLiveStreamEntry();
				}
				break;

			default:
				$obj = KalturaPluginManager::loadObject('KalturaBaseEntry', $type);

				if(!$obj)
					$obj = new KalturaBaseEntry();

				break;
		}

		return $obj;
	}
}

<?php
/**
 * @package api
 * @subpackage objects.factory
 */
class KalturaEntryFactory
{
	/**
	 * @param int $type
	 * @param bool $isAdmin
	 * @return KalturaBaseEntry
	 */
	static function getInstanceByType ($type, $isAdmin = false)
	{
		switch ($type)
		{
			case KalturaEntryType::MEDIA_CLIP:
				$obj = new KalturaMediaEntry();
				break;

			case KalturaEntryType::MIX:
				$obj = new KalturaMixEntry();
				break;

			case KalturaEntryType::PLAYLIST:
				$obj = new KalturaPlaylist();
				break;

			case KalturaEntryType::DATA:
				$obj = new KalturaDataEntry();
				break;

			case KalturaEntryType::LIVE_STREAM:
				if($isAdmin)
				{
					$obj = new KalturaLiveStreamAdminEntry();
				}
				else
				{
					$obj = new KalturaLiveStreamEntry();
				}
				break;

			case KalturaEntryType::LIVE_CHANNEL:
				$obj = new KalturaLiveChannel();
				break;

			default:
				$obj = KalturaPluginManager::loadObject('KalturaBaseEntry', $type);

				if(!$obj)
					$obj = new KalturaBaseEntry();

				break;
		}

		return $obj;
	}
}

Support return of live channel

Support return of live channel


<?php

declare(strict_types=1);

/*
 * This file is part of the Nexylan packages.
 *
 * (c) Nexylan SAS <contact@nexylan.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Nexy\Gandi\Api;

/**
 * @author Jérôme Pogeant <p-jerome@hotmail.fr>
 */
final class Domain extends AbstractApi
{
    /**
     * @param array      $domain
     * @param array|null $options
     *
     * @return array
     */
    public function isAvailable(array $domain, array $options = null): array
    {
        return $this->getGandi()->getClient()->domain->available($domain, $options);
    }

    /**
     * @param string $domain
     *
     * @return array
     */
    public function info(string $domain): array
    {
        return $this->getGandi()->getClient()->domain->info($domain);
    }

    /**
     * @param array $options
     *
     * @return array
     */
    public function getList(array $options): array
    {
        return $this->getGandi()->getClient()->domain->list($options);
    }

    /**
     * @param array      $domain
     * @param array|null $options
     *
     * @return array
     */
    public function renew(array $domain, array $options = null): array
    {
        return $this->getGandi()->getClient()->domain->renew($domain, $options);
    }
}

<?php

declare(strict_types=1);

/*
 * This file is part of the Nexylan packages.
 *
 * (c) Nexylan SAS <contact@nexylan.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Nexy\Gandi\Api;

/**
 * @author Jérôme Pogeant <p-jerome@hotmail.fr>
 */
final class Domain extends AbstractApi
{
    /**
     * @param array      $domain
     * @param array|null $options
     *
     * @return array
     */
    public function isAvailable(array $domain, array $options = null): array
    {
        return $this->getGandi()->getClient()->domain->available($domain, $options);
    }

    /**
     * @param string $domain
     *
     * @return array
     */
    public function info(string $domain): array
    {
        return $this->getGandi()->getClient()->domain->info($domain);
    }

    /**
     * @param array|null $options
     *
     * @return array
     */
    public function getList(array $options = null): array
    {
        return $this->getGandi()->getClient()->domain->list($options);
    }

    /**
     * @param array      $domain
     * @param array|null $options
     *
     * @return array
     */
    public function renew(array $domain, array $options = null): array
    {
        return $this->getGandi()->getClient()->domain->renew($domain, $options);
    }
}

Add null default to getList options param


Reorder items in the config

Reorder items in the config


<?php

namespace OrgManager\ApiClient;

use GuzzleHttp\Client;

class OrgManager
{
    /** @var \GuzzleHttp\Client */
    protected $client;

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

    /**
     * @param \GuzzleHttp\Client $client
     * @param string             $apiToken
     * @param string             $rootUrl
     */
    public function __construct(Client $client, $apiToken, $rootUrl = 'https://orgmanager.miguelpiedrafita.com')
    {
        $this->client = $client;

        $this->apiToken = $apiToken;

        $this->baseUrl = $rootUrl.'/api';
    }

    /**
     *
     * @return array
     */
    public function getroot()
    {
        return $this->makeRequest('');
    }

    /**
     * @param string $resource
     * @param array  $query
     *
     * @return array
     */
    public function makeRequest($resource, array $query = [])
    {
        $results = $this->client
            ->get("{$this->baseUrl}{$resource}", compact('query'))
            ->getBody()
            ->getContents();

        return json_decode($results, true);
    }
}

<?php

namespace OrgManager\ApiClient;

use GuzzleHttp\Client;

class OrgManager
{
    /** @var \GuzzleHttp\Client */
    protected $client;

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

    /**
     * @param \GuzzleHttp\Client $client
     * @param string             $apiToken
     * @param string             $rootUrl
     */
    public function __construct(Client $client, $apiToken, $rootUrl = 'https://orgmanager.miguelpiedrafita.com')
    {
        $this->client = $client;

        $this->apiToken = $apiToken;

        $this->baseUrl = $rootUrl.'/api';
    }

    /**
     *
     * @return array
     */
    public function getRoot()
    {
        return $this->get('');
    }

    /**
     * @param string $resource
     * @param array  $query
     *
     * @return array
     */
    public function get($resource, array $query = [])
    {
        $query['api_token'] = $this->apiToken;

        $results = $this->client
            ->get("{$this->baseUrl}{$resource}", compact('query'))
            ->getBody()
            ->getContents();

        return json_decode($results, true);
    }
}

Add Api token to request

Add Api token to request


<?php

namespace Baddum\Factory418;

trait FactoryTrait
{

    /* ATTRIBUTES
     *************************************************************************/
    private static $indexList = [];

    /* PUBLIC METHODS
     *************************************************************************/
    public function registerClass($className, $indexList)
    {
        if (is_object($className)) {
            $className = get_class($className);
        }
        $factoryName = get_called_class();
        if (!isset(static::$indexList[$factoryName])) {
            self::$indexList[$factoryName] = [];
        }
        if (!is_array($indexList)) {
            $indexList = [$indexList];
        }
        foreach ($indexList as $index) {
            $id = strtolower($index);
            self::$indexList[$factoryName][$id] = $className;
        }
        return $this;
    }

    public function newInstance($index)
    {
        $factoryName = get_called_class();
        if (!isset(self::$indexList[$factoryName])) {
            return $this->onNoClassRegistered($index);
        }
        $id = strtolower($index);
        if (!isset(self::$indexList[$factoryName][$id])) {
            return $this->onNoClassRegistered($index);
        }
        $className = self::$indexList[$factoryName][$id];
        return new $className;
    }

    /* PROTECTED METHODS
     *************************************************************************/
    protected function onNoClassRegistered($index)
    {
        throw new \RuntimeException('No class registered for the index: ' . $index);
    }
}

<?php

namespace Baddum\Factory418;

trait FactoryTrait
{

    /* ATTRIBUTES
     *************************************************************************/
    private static $indexList = [];

    /* PUBLIC METHODS
     *************************************************************************/
    public function registerClass($className, $indexList)
    {
        if (is_object($className)) {
            $className = get_class($className);
        }
        $factoryName = get_called_class();
        if (!isset(self::$indexList[$factoryName])) {
            self::$indexList[$factoryName] = [];
        }
        if (!is_array($indexList)) {
            $indexList = [$indexList];
        }
        foreach ($indexList as $index) {
            $id = strtolower($index);
            self::$indexList[$factoryName][$id] = $className;
        }
        return $this;
    }

    public function newInstance($index)
    {
        $factoryName = get_called_class();
        if (!isset(self::$indexList[$factoryName])) {
            return $this->onNoClassRegistered($index);
        }
        $id = strtolower($index);
        if (!isset(self::$indexList[$factoryName][$id])) {
            return $this->onNoClassRegistered($index);
        }
        $className = self::$indexList[$factoryName][$id];
        return new $className;
    }

    /* PROTECTED METHODS
     *************************************************************************/
    protected function onNoClassRegistered($index)
    {
        throw new \RuntimeException('No class registered for the index: ' . $index);
    }
}

Fix one more issue thanks to Scrutinizer


<?php

return [
    /**
     * The current application environment
     */
    'environment' => getenv('WP_ENV'),

    /**
     * Is debug mode enabled?
     */
    'debug' => WP_DEBUG ?? false,

    /**
     * List of providers to initialise during app boot
     */
    'providers' => [
        Rareloop\Lumberjack\Providers\RouterServiceProvider::class,
        Rareloop\Lumberjack\Providers\WordPressControllersServiceProvider::class,
        Rareloop\Lumberjack\Providers\TimberServiceProvider::class,
        Rareloop\Lumberjack\Providers\ImageSizesServiceProvider::class,
        Rareloop\Lumberjack\Providers\CustomPostTypesServiceProvider::class,
        Rareloop\Lumberjack\Providers\MenusServiceProvider::class,
        Rareloop\Lumberjack\Providers\LogServiceProvider::class,
        Rareloop\Lumberjack\Providers\ThemeSupportServiceProvider::class,
    ],

    'themeSupport' => [
        'post-thumbnail',
    ],
];

<?php

return [
    /**
     * The current application environment
     */
    'environment' => getenv('WP_ENV'),

    /**
     * Is debug mode enabled?
     */
    'debug' => WP_DEBUG ?? false,

    /**
     * List of providers to initialise during app boot
     */
    'providers' => [
        Rareloop\Lumberjack\Providers\RouterServiceProvider::class,
        Rareloop\Lumberjack\Providers\WordPressControllersServiceProvider::class,
        Rareloop\Lumberjack\Providers\TimberServiceProvider::class,
        Rareloop\Lumberjack\Providers\ImageSizesServiceProvider::class,
        Rareloop\Lumberjack\Providers\CustomPostTypesServiceProvider::class,
        Rareloop\Lumberjack\Providers\MenusServiceProvider::class,
        Rareloop\Lumberjack\Providers\LogServiceProvider::class,
        Rareloop\Lumberjack\Providers\ThemeSupportServiceProvider::class,
        Rareloop\Lumberjack\Providers\LogServiceProvider::class,
    ],

    /**
    * Logs enabled, path and level
    */
    'logs' => [
        'enabled' => false,
        'path' => get_template_directory().'/app.log',
        'level' => Monolog\Logger::Error,
    ],

    'themeSupport' => [
        'post-thumbnail',
    ],
];

Add default log config settings

Add default log config settings


<?php

namespace Clue\PharComposer\Bundler;

use Clue\PharComposer\PharComposer;

use Herrera\Box\Box;

class Complete implements BundlerInterface
{
    public function build(PharComposer $pharcomposer, Box $box)
    {
        $box->buildFromDirectory($pharcomposer->getBase());
    }
}

<?php

namespace Clue\PharComposer\Bundler;

use Symfony\Component\Finder\Finder;
use Clue\PharComposer\PharComposer;
use Herrera\Box\Box;

class Complete implements BundlerInterface
{
    public function build(PharComposer $pharcomposer, Box $box)
    {
        $iterator = Finder::create()
            ->files()
            ->ignoreVCS(true)
            ->in($pharcomposer->getBase());

        $box->buildFromIterator($iterator, $pharcomposer->getBase());
    }
}

Use bundler to ignore VCS files

Use bundler to ignore VCS files


<?php

namespace App\Validator;

use Symfony\Component\Validator\Constraints\Compound;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @Annotation
 */
class Password extends Compound
{
    /**
     * @param array<string, mixed> $options
     */
    protected function getConstraints(array $options): array
    {
        return [
            new Assert\NotBlank([
                'message' => 'Please enter a password',
            ]),
            new Assert\Type('string'),
            new Assert\Length([
                'min' => 8,
                'minMessage' => 'Your password should be at least {{ limit }} characters',
                // max length allowed by Symfony for security reasons
                'max' => 4096,
            ]),
            new Assert\NotCompromisedPassword(),
        ];
    }
}

<?php

namespace App\Validator;

use Symfony\Component\Validator\Constraints\Compound;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @Annotation
 */
class Password extends Compound
{
    /**
     * @param array<string, mixed> $options
     */
    protected function getConstraints(array $options): array
    {
        return [
            new Assert\NotBlank([
                'message' => 'Please enter a password',
            ]),
            new Assert\Type('string'),
            new Assert\Length([
                'min' => 8,
                'minMessage' => 'Your password should be at least {{ limit }} characters',
                // max length allowed by Symfony for security reasons
                'max' => 4096,
            ]),
            new Assert\NotCompromisedPassword(skipOnError: true),
        ];
    }
}

Make sure pwd strength API is not required to be able to register


<?php

namespace Doctrine\Tests\Common\Cache;

use Couchbase;
use Doctrine\Common\Cache\CouchbaseCache;

class CouchbaseCacheTest extends CacheTest
{
    private $couchbase;

    public function setUp()
    {
        if (extension_loaded('couchbase')) {
            try {
                $this->couchbase = new Couchbase('127.0.0.1', 'Administrator', 'password', 'default');
            } catch(Exception $ex) {
                 $this->markTestSkipped('Could not instantiate the Couchbase cache because of: ' . $ex);
            }
        } else {
            $this->markTestSkipped('The ' . __CLASS__ .' requires the use of the couchbase extension');
        }
    }

    public function testNoExpire()
    {
        $cache = $this->_getCacheDriver();
        $cache->save('noexpire', 'value', 0);
        sleep(1);
        $this->assertTrue($cache->contains('noexpire'), 'Couchbase provider should support no-expire');
    }

    public function testLongLifetime()
    {
        $cache = $this->_getCacheDriver();
        $cache->save('key', 'value', 30 * 24 * 3600 + 1);

        $this->assertTrue($cache->contains('key'), 'Couchbase provider should support TTL > 30 days');
    }

    protected function _getCacheDriver()
    {
        $driver = new CouchbaseCache();
        $driver->setCouchbase($this->couchbase);
        return $driver;
    }
}

<?php

namespace Doctrine\Tests\Common\Cache;

use Couchbase;
use Doctrine\Common\Cache\CouchbaseCache;

class CouchbaseCacheTest extends CacheTest
{
    private $couchbase;

    public function setUp()
    {
        if (extension_loaded('couchbase')) {
            try {
                $this->couchbase = new Couchbase('127.0.0.1', 'Administrator', 'password', 'default');
            } catch(Exception $ex) {
                 $this->markTestSkipped('Could not instantiate the Couchbase cache because of: ' . $ex);
            }
        } else {
            $this->markTestSkipped('The ' . __CLASS__ .' requires the use of the couchbase extension');
        }
    }

    public function testNoExpire()
    {
        $cache = $this->_getCacheDriver();
        $cache->save('noexpire', 'value', 0);
        sleep(1);
        $this->assertTrue($cache->contains('noexpire'), 'Couchbase provider should support no-expire');
    }

    public function testLongLifetime()
    {
        $cache = $this->_getCacheDriver();
        $cache->save('key', 'value', 30 * 24 * 3600 + 1);

        $this->assertTrue($cache->contains('key'), 'Couchbase provider should support TTL > 30 days');
    }

    public function testFalseOnFailedFetch() {
        $cache = $this->_getCacheDriver();
        $result = $cache->fetch('nonexistent_key');
        $this->assertFalse($result);
        $this->assertNotNull($result);
    }

    protected function _getCacheDriver()
    {
        $driver = new CouchbaseCache();
        $driver->setCouchbase($this->couchbase);
        return $driver;
    }
}

[Cache/CouchbaseCache] Return false instead of null for compat.

This changeset fixes and verifies that instead of null, false is returned
from the fetch method. This fixes a bug which causes CouchbaseCache not
to work in combination with the ORM library. Test added.


<?php namespace ProcessWire;

class GraphQLConfig extends Moduleconfig {

  public function getDefaults()
  {
    return array(
      'baseInterfaceName' => 'page',
    );
  }

  public function getInputFields()
  {
    $inputfields = parent::getInputFields();

    $f = $this->modules->get('InputfieldText');
    $f->attr('name', 'baseInterfaceName');
    $f->label = 'Base Interface Name';
    $f->required = true;
    $inputfields->add($f);

    return $inputfields;
  }

}

<?php namespace ProcessWire;

class GraphQLConfig extends Moduleconfig {

  public function getDefaults()
  {
    return array(
      'maxLimit' => 100,
    );
  }

  public function getInputFields()
  {
    $inputfields = parent::getInputFields();

    $f = $this->modules->get('InputfieldInteger');
    $f->attr('name', 'maxLimit');
    $f->label = 'Max Limit';
    $f->description = 'Set the maximum value for `limit` selector field.';
    $f->required = true;
    $inputfields->add($f);

    return $inputfields;
  }

}

Remove the base page interface name option.


<?php

use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

class TestCase extends BaseTestCase
{
    /**
     * The base URL to use while testing the application.
     *
     * @var string
     */
    protected $baseUrl = 'http://localhost';

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__ . '/../bootstrap/app.php';

        $app->make(Kernel::class)->bootstrap();

        return $app;
    }

    protected function checkNavbarExists()
    {
        $this->see('User');
        $this->see('Market');
        $this->see('Issue');
        $this->see('Documentation');
    }

    protected function checkHeaderExists()
    {
        $this->see('YSITD Cloud');
    }

    protected function checkFooterExists()
    {
        $this->see('YSITD Cloud Portal');
    }

    protected function checkLayout()
    {
        $this->checkNavbarExists();
        $this->checkHeaderExists();
        $this->checkFooterExists();
    }
}

<?php

use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

class TestCase extends BaseTestCase
{
    /**
     * The base URL to use while testing the application.
     *
     * @var string
     */
    protected $baseUrl = 'http://localhost';

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__ . '/../bootstrap/app.php';

        $app->make(Kernel::class)->bootstrap();

        return $app;
    }

    protected function checkNavbarExists()
    {
        $this->see('User');
        $this->see('Market');
        $this->see('Issue');
        $this->see('Documentation');
    }

    protected function checkHeaderExists()
    {
        $this->see('YSITD Cloud');
    }

    protected function checkFooterExists()
    {
        $this->see('YSITD Cloud Portal');
    }

    protected function checkLayout()
    {
        $this->checkNavbarExists();
        $this->checkHeaderExists();
        $this->checkFooterExists();
    }

    protected function invokeMethod(&$object, $methodName, array $parameters = [])
    {
        $reflection = new \ReflectionClass(get_class($object));
        $method = $reflection->getMethod($methodName);
        $method->setAccessible(true);

        return $method->invokeArgs($object, $parameters);
    }
}

Add invoke method to test protected / private method


<?php
namespace Projek\Slim\Tests;

use Projek\Slim\Monolog;
use PHPUnit_Framework_TestCase;
use DateTimeZone;

abstract class TestCase extends PHPUnit_Framework_TestCase
{
    /**
     * @var Projek\Slim\Monolog
     */
    protected $logger;

    /**
     * Slim Application settings
     *
     * @var array
     */
    protected $settings = [
        'basename' => 'slim-monolog-app',
        'logger' => [
            'directory' => __DIR__.'/logs',
            'filename' => 'app',
            'level' => '',
            'handlers' => [],
        ],
    ];

    public function setUp()
    {
        $this->logger = new Monolog($this->settings['basename'], $this->settings['logger']);
    }
}

<?php
namespace Projek\Slim\Tests;

use Projek\Slim\Monolog;
use PHPUnit_Framework_TestCase;
use DateTimeZone;

abstract class TestCase extends PHPUnit_Framework_TestCase
{
    /**
     * @var Projek\Slim\Monolog
     */
    protected $logger;

    /**
     * Slim Application settings
     *
     * @var array
     */
    protected $settings = [
        'basename' => 'slim-monolog-app',
        'logger' => [
            'directory' => '',
            'filename' => 'app',
            'level' => '',
            'handlers' => [],
        ],
    ];

    public function setUp()
    {
        $this->settings['logger']['directory'] = __DIR__.'/logs';
        $this->logger = new Monolog($this->settings['basename'], $this->settings['logger']);
    }
}

Fix broken test in php 5.5

Fix broken test in php 5.5

Signed-off-by: Fery Wardiyanto <bd7846e81d12676baffd10ffe6daf3939680ab52@gmail.com>


<?php

class CodesController extends \BaseController {

	public function process($code)
	{
        $code = Code::where('code', '=', $code)->first();

        if(is_null($code) || $code->used == 1){
            return Redirect::to('/')->with('error', 'Nie znaleziono!');
        } else {

            //Snapchatty functions
            //Refresh(disappear) after 4 seconds
            header("Refresh: " . 4);

            $code->used = 1;
            $code->used_time = Carbon::now();
            $code->used_ip = Request::getClientIp();
            $mobileDetect = new Mobile_Detect();
            //Check for facebook bots (done in robots.txt)
            $code->used_useragent = $mobileDetect->getUserAgent();
            $code->save();

            $path = storage_path().'/memes/'.Meme::find($code->meme_id)->filename;
            // Get the image
            $image = Image::make($path)->widen(600, function ($constraint) {
                $constraint->upsize();
            })->encode('data-url');

            return View::make('meme')->withMeme($code->meme)->withImage($image);
        }

    }

}

<?php

class CodesController extends \BaseController {

	public function process($code)
	{
        $code = Code::where('code', '=', $code)->first();

        if(is_null($code) || $code->used == 1){
            return Redirect::to('/')->with('error', 'Nie znaleziono!');
        } else {

            //Snapchatty functions
            //Refresh(disappear) after 7 seconds
            header("Refresh: " . 7);

            $code->used = 1;
            $code->used_time = Carbon::now();
            $code->used_ip = Request::getClientIp();
            $mobileDetect = new Mobile_Detect();
            //Check for facebook bots (done in robots.txt)
            $code->used_useragent = $mobileDetect->getUserAgent();
            $code->save();

            $path = storage_path().'/memes/'.Meme::find($code->meme_id)->filename;
            // Get the image
            $image = Image::make($path)->widen(600, function ($constraint) {
                $constraint->upsize();
            })->encode('data-url');

            return View::make('meme')->withMeme($code->meme)->withImage($image);
        }

    }

}

Change interval from 4 to 7 seconds

Change interval from 4 to 7 seconds


<?php
namespace Tickets\DB;

class TicketDefaultFilter extends \Data\Filter
{
    function __construct($email, $discretionary=false)
    {
        $this->children[] = new \Data\FilterClause();
        $this->children[0]->var1 = 'email';
        $this->children[0]->var2 = "'$email'";
        $this->children[0]->op = '=';
        $this->children[] = 'and';
        $this->children[] = new \Data\FilterClause();
        $this->children[2]->var1 = 'discretionary';
        if($discretionary === false)
        {
            $this->children[2]->var2 = '0';
        }
        else
        {
            $this->children[2]->var2 = '1';
        }
        $this->children[2]->op = '=';
        $this->children[] = 'and';
        $this->children[] = new \Data\FilterClause();
        $this->children[4]->var1 = 'used';
        $this->children[4]->var2 = '0';
        $this->children[4]->op = '=';
        $this->children[] = 'and';
        $this->children[] = new \Data\FilterClause();
        $this->children[6]->var1 = 'year';
        $this->children[6]->var2 = TicketSystemSettings::getInstance()['year'];
        $this->children[6]->op = '=';
    }
}
?>

<?php
namespace Tickets\DB;

class TicketDefaultFilter extends \Data\Filter
{
    function __construct($email, $discretionary=false)
    {
        $this->children[] = new \Data\FilterClause();
        $this->children[0]->var1 = 'email';
        $this->children[0]->var2 = "'$email'";
        $this->children[0]->op = '=';
        $this->children[] = 'and';
        $clause = new \Data\FilterClause();
        if($discretionary === false)
        {
            $clause->var1 = 'sold';
            $clause->var2 = '1';
            $clause->op   = '=';
        }
        else
        {
            $clause->var1 = 'discretionary';
            $clause->var2 = '1';
            $clause->op   = '=';
            $this->children[] = $clause;
            $this->children[] = 'and';
            $clause = new \Data\FilterClause();
            $clause->var1 = 'sold';
            $clause->var2 = '0';
            $clause->op   = '=';
        }
        $this->children[] = $clause;
        $this->children[] = 'and';
        $clause = new \Data\FilterClause();
        $clause->var1 = 'used';
        $clause->var2 = '0';
        $clause->op   = '=';
        $this->children[] = $clause;
        $this->children[] = 'and';
        $clause = new \Data\FilterClause();
        $clause->var1 = 'year';
        $clause->var2 = TicketSystemSettings::getInstance()['year'];
        $clause->op   = '=';
        $this->children[] = $clause;
    }
}
?>

Make discretionary filter hide sold discretionary teams


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SettingController extends Controller
{
    /**
     * @return \Illuminate\Http\Response
     */
    public function edit()
    {
        return view('setting.edit');
    }

    /**
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $this->validate($request, [
            'start_at' => 'required|date',
            'end_at'   => 'required|date',
            'target'   => 'required|integer|min:0',
        ]);

        \Setting::set('start_at', $request->get('start_at'));
        \Setting::set('end_at', $request->get('end_at'));
        \Setting::set('target', $request->get('target'));

        \Setting::save();

        return redirect()->route('setting.edit')->with('global', '設定已更新');
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SettingController extends Controller
{
    /**
     * @return \Illuminate\Http\Response
     */
    public function edit()
    {
        return view('setting.edit');
    }

    /**
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $this->validate($request, [
            'start_at' => 'required|date|before:end_at',
            'end_at'   => 'required|date|after:start_at',
            'target'   => 'required|integer|min:0',
        ]);

        \Setting::set('start_at', $request->get('start_at'));
        \Setting::set('end_at', $request->get('end_at'));
        \Setting::set('target', $request->get('target'));

        \Setting::save();

        return redirect()->route('setting.edit')->with('global', '設定已更新');
    }
}

Add missing checking rules of activity time


<?php

/**
 * @author     Ignas Rudaitis <ignas.rudaitis@gmail.com>
 * @copyright  2010 Ignas Rudaitis
 * @license    http://www.opensource.org/licenses/mit-license.html
 * @link       http://antecedent.github.com/patchwork
 */
namespace Patchwork\Stack;

use Patchwork\Exceptions;

function push($offset)
{
    State::$offsets[] = $offset;
}

function pop()
{
    array_pop(State::$offsets);
}

function pushFor($offset, $callback)
{
    push($offset);
    try {
        $callback();
    } catch (\Exception $e) {
        $exception = $e;
    }
    pop();
    if (isset($exception)) {
        throw $exception;
    }
}

function top($property = null)
{
    $frame = reset(all());
    if ($property) {
        return isset($frame[$property]) ? $frame[$property] : null;
    }
    return $frame;
}

function topOffset()
{
    if (empty(State::$offsets)) {
        throw new Exceptions\StackEmpty;
    }
    return end(State::$offsets);
}

function all()
{
    $backtrace = debug_backtrace();
    return array_slice($backtrace, count($backtrace) - topOffset());
}

class State
{
    static $offsets = array();
}

<?php

/**
 * @author     Ignas Rudaitis <ignas.rudaitis@gmail.com>
 * @copyright  2010 Ignas Rudaitis
 * @license    http://www.opensource.org/licenses/mit-license.html
 * @link       http://antecedent.github.com/patchwork
 */
namespace Patchwork\Stack;

use Patchwork\Exceptions;

function push($offset)
{
    State::$offsets[] = $offset;
}

function pop()
{
    array_pop(State::$offsets);
}

function pushFor($offset, $callback)
{
    push($offset);
    try {
        $callback();
    } catch (\Exception $e) {
        $exception = $e;
    }
    pop();
    if (isset($exception)) {
        throw $exception;
    }
}

function top($property = null)
{
    $all = all();
    $frame = reset($all);
    if ($property) {
        return isset($frame[$property]) ? $frame[$property] : null;
    }
    return $frame;
}

function topOffset()
{
    if (empty(State::$offsets)) {
        throw new Exceptions\StackEmpty;
    }
    return end(State::$offsets);
}

function all()
{
    $backtrace = debug_backtrace();
    return array_slice($backtrace, count($backtrace) - topOffset());
}

class State
{
    static $offsets = array();
}

Fix "Only variables should be passed by reference" warning when running in strict standards mode.


<?php
if (!PHP_SAPI == 'cli') { die(); } // Only allow the CLI to run this script.

// tweeter.php
// https://github.com/plusreed/yourownbot-php

// TODO: Separate into .env
$word1 = array("Add", "your", "words", "here");
$word2 = array("Add", "your", "words", "here");
$rand_word1 = $word1[array_rand($word1, 1)];
$rand_word2 = $word2[array_rand($word2, 1)];

require_once('twitteroauth.php');

// TODO: Separate into .env
$consumerkey = "consumerkeyhere";
$consumersecret = "consumersecrethere";
$apikey = "apikeyhere";
$apisecret = "apisecrethere";

// Create a new object
$tweet = new TwitterOAuth($consumerkey, $consumersecret, $apikey, $apikeysecret);

// Randomize tweet
$tweetMessage = '$rand_word1 your own $rand_word2!';

// Make sure generated tweet is under 280 characters
if(strlen($tweetMessage) <= 280) {
	// Post the tweet
	$tweet->post('statuses/update', array('status' => $tweetMessage));
}
?>

<?php
if (!PHP_SAPI == 'cli') { die(); } // Only allow the CLI to run this script.

// tweeter.php
// https://github.com/plusreed/yourownbot-php

$word1 = array("Add", "your", "words", "here");
$word2 = array("Add", "your", "words", "here");
$rand_word1 = $word1[array_rand($word1, 1)];
$rand_word2 = $word2[array_rand($word2, 1)];

require_once('twitteroauth.php');

// TODO: Separate into .env
$consumerkey = "consumerkeyhere";
$consumersecret = "consumersecrethere";
$apikey = "apikeyhere";
$apisecret = "apisecrethere";

// Create a new object
$tweet = new TwitterOAuth($consumerkey, $consumersecret, $apikey, $apikeysecret);

// Randomize tweet
$tweetMessage = '$rand_word1 your own $rand_word2!';

// Make sure generated tweet is under 280 characters
if(strlen($tweetMessage) <= 280) {
	// Post the tweet
	$tweet->post('statuses/update', array('status' => $tweetMessage));
}
?>

Remove .env comment for word array

Remove .env comment for word array

I'm not going to separate those into a separate file for now.


<?php

/**
 * Class Dispatcher
 */
class Dispatcher extends DispatcherCore
{
    /**
     * @param null $id_shop
     *
     * @return mixed
     */
    public function getController($id_shop = null)
    {
        $isCLI = (php_sapi_name() == 'cli');
        if ($isCLI) {
            $this->controller = "Crud";
        }

        parent::getController($id_shop = null);
    }
}

<?php

/**
 * Class Dispatcher
 */
class Dispatcher extends DispatcherCore
{
    /**
     * Dispatch
     *
     * @throws PrestaShopException
     */
    public function dispatch()
    {
        $isCLI = (php_sapi_name() == 'cli');
        if ($isCLI) {
            $this->controller = "Crud";
        }

        parent::dispatch();
    }
}

Fix issue with orders page

Fix issue with orders page


<?php

class CM_Http_Response_Page_Embed extends CM_Http_Response_Page {

    /** @var string|null */
    private $_title;

    /**
     * @throws CM_Exception_Invalid
     * @return string
     */
    public function getTitle() {
        if (null === $this->_title) {
            throw new CM_Exception_Invalid('Unprocessed page has no title');
        }
        return $this->_title;
    }

    /**
     * @param CM_Page_Abstract $page
     * @return string
     */
    protected function _renderPage(CM_Page_Abstract $page) {
        $renderAdapterLayout = new CM_RenderAdapter_Layout($this->getRender(), $page);
        $this->_title = $renderAdapterLayout->fetchTitle();
        return $renderAdapterLayout->fetchPage();
    }

    protected function _process() {
        $this->_processContentOrRedirect();
    }

    /**
     * @param CM_Http_Request_Abstract $request
     * @param CM_Site_Abstract         $site
     * @param CM_Service_Manager       $serviceManager
     * @return CM_Http_Response_Page_Embed
     */
    public static function createEmbedResponseFromRequest(CM_Http_Request_Abstract $request, CM_Site_Abstract $site, CM_Service_Manager $serviceManager) {
        $request = clone $request;
        $request->popPathLanguage();

        return new self($request, $site, $serviceManager);
    }

}

<?php

class CM_Http_Response_Page_Embed extends CM_Http_Response_Page {

    /** @var string|null */
    private $_title;

    /**
     * @throws CM_Exception_Invalid
     * @return string
     */
    public function getTitle() {
        if (null === $this->_title) {
            throw new CM_Exception_Invalid('Unprocessed page has no title');
        }
        return $this->_title;
    }

    /**
     * @param CM_Page_Abstract $page
     * @return string
     */
    protected function _renderPage(CM_Page_Abstract $page) {
        $renderAdapterLayout = new CM_RenderAdapter_Layout($this->getRender(), $page);
        $this->_title = $renderAdapterLayout->fetchTitle();
        return $renderAdapterLayout->fetchPage();
    }

    protected function _process() {
        $this->_processContentOrRedirect();
    }

    public static function createFromRequest(CM_Http_Request_Abstract $request, CM_Site_Abstract $site, CM_Service_Manager $serviceManager) {
        return null;
    }

    /**
     * @param CM_Http_Request_Abstract $request
     * @param CM_Site_Abstract         $site
     * @param CM_Service_Manager       $serviceManager
     * @return CM_Http_Response_Page_Embed
     */
    public static function createEmbedResponseFromRequest(CM_Http_Request_Abstract $request, CM_Site_Abstract $site, CM_Service_Manager $serviceManager) {
        $request = clone $request;
        $request->popPathLanguage();

        return new self($request, $site, $serviceManager);
    }

}

Make sure embed response never matches a request