<?php namespace GeneaLabs\MixPanel;

use Illuminate\Support\Facades\App;

class MixPanel extends \Mixpanel
{
    private $defaults = [
        'connect_timeout' => 2,
        'timeout' => 2,
    ];

    /**
     * @param array $options
     */
    public function __construct(array $options = [])
    {
        $options = array_merge($this->defaults, $options);

        parent::__construct(config('services.mixpanel.token'), $options);
    }
}

<?php namespace GeneaLabs\MixPanel;

use Illuminate\Support\Facades\App;

class MixPanel extends \Mixpanel
{
    private $defaults = [
        'consumer' => 'socket',
        'connect_timeout' => 2,
        'timeout' => 2,
    ];

    /**
     * @param array $options
     */
    public function __construct(array $options = [])
    {
        $options = array_merge($this->defaults, $options);

        parent::__construct(config('services.mixpanel.token'), $options);
    }
}

Change from default CURL consumer to SOCKET consumer

This should prevent curl requests blocking each other.


<?php namespace Morrislaptop\LaravelQueueClear;

use Illuminate\Queue\QueueManager;
use Illuminate\Contracts\Queue\Factory as FactoryContract;
use Morrislaptop\LaravelQueueClear\Contracts\Clearer as ClearerContract;

class Clearer implements ClearerContract
{
	/**
	 * @var QueueManager
	 */
	protected $manager;

	/**
	 * {@inheritDoc}
	 */
	function __construct(FactoryContract $manager)
	{
		$this->manager = $manager;
	}

	/**
	 * {@inheritDoc}
	 */
	public function clear($connection, $queue)
	{
		$count = 0;
		$connection = $this->manager->connection($connection);

		while ($job = $connection->pop($queue)) {
			$job->delete();
			$count++;
		}

		return $count;
	}

}

<?php namespace Morrislaptop\LaravelQueueClear;

use Illuminate\Queue\QueueManager;
use Illuminate\Contracts\Queue\Factory as FactoryContract;
use Morrislaptop\LaravelQueueClear\Contracts\Clearer as ClearerContract;

class Clearer implements ClearerContract
{
    /**
     * @var QueueManager
     */
    protected $manager;

    /**
     * {@inheritDoc}
     */
    function __construct(FactoryContract $manager)
    {
        $this->manager = $manager;
    }

    /**
     * {@inheritDoc}
     */
    public function clear($connection, $queue)
    {
        $count = 0;
        $connection = $this->manager->connection($connection);

        $count += $this->clearJobs($connection, $queue);
        $count += $this->clearJobs($connection, $queue . ':reserved');
        $count += $this->clearDelayedJobs($connection, $queue);

        return $count;
    }

    protected function clearJobs($connection, $queue)
    {
        $count = 0;

        while ($job = $connection->pop($queue)) {
            $job->delete();
            $count++;
        }

        return $count;
    }

    protected function clearDelayedJobs($connection, $queue)
    {
        if (method_exists($connection, 'getRedis')) {
            return $this->clearDelayedJobsOnRedis($connection, $queue);
        }

        throw new \InvalidArgumentException('Queue Connection not supported');
    }

    protected function clearDelayedJobsOnRedis($connection, $queue) {
        $key = "queues:{$queue}:delayed";
        $redis = $connection->getRedis()->connection(config('queue.connections.redis.connection'));
        $count = $redis->zcount($key, '-inf', '+inf');
        $redis->del($key);

        return $count;
    }

}

Add support for clearing reserved jobs, and delayed jobs on redis


<?php

namespace DamianTW\LaravelRoles\Services;

/**
 * Class RoleControllerService
 * @package DamianTW\LaravelRoles
 */
class RoleControllerService
{
    public function buildAuthorityStringForControllerMethod($controllerClass, $controllerMethodName)
    {
        $authorityBaseName = $this->getAuthorityBaseName($controllerClass);
        return strtoupper(snake_case($authorityBaseName) . '_' . snake_case($controllerMethodName));
    }

    public function getAuthorityFromActionName($actionName)
    {
        $parsed = explode('@', $actionName);
        return $this->buildAuthorityStringForControllerMethod($parsed[0], $parsed[1]);
    }

    private function getAuthorityBaseName($controllerClass)
    {
        return str_replace('Controller' , '' , class_basename(get_class(new $controllerClass)));
    }

}

<?php

namespace DamianTW\LaravelRoles\Services;

/**
 * Class RoleControllerService
 * @package DamianTW\LaravelRoles
 */
class RoleControllerService
{
    public function buildAuthorityStringForControllerMethod($controllerClass, $controllerMethodName)
    {
        $authorityBaseName = $this->getAuthorityBaseName($controllerClass);
        return strtoupper(snake_case($authorityBaseName) . '_' . snake_case($controllerMethodName));
    }

    public function getAuthorityFromActionName($actionName)
    {
        $parsed = explode('@', $actionName);
        return $this->buildAuthorityStringForControllerMethod($parsed[0], $parsed[1]);
    }

    private function getAuthorityBaseName($controllerClass)
    {
        return str_replace('Controller' , '' , class_basename($controllerClass));
    }

}

Fix bug with seeding roles for controllers


<?php

namespace Illuminate\Routing;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Pipeline\Pipeline as BasePipeline;
use Symfony\Component\Debug\Exception\FatalThrowableError;

/**
 * This extended pipeline catches any exceptions that occur during each slice.
 *
 * The exceptions are converted to HTTP responses for proper middleware handling.
 */
class Pipeline extends BasePipeline
{
    /**
     * Get a Closure that represents a slice of the application onion.
     *
     * @return \Closure
     */
    protected function getSlice()
    {
        return function ($stack, $pipe) {
            return function ($passable) use ($stack, $pipe) {
                try {
                    return call_user_func(parent::getSlice()($stack, $pipe), $passable);
                } catch (Exception $e) {
                    return $this->handleException($passable, $e);
                } catch (Throwable $e) {
                    return $this->handleException($passable, new FatalThrowableError($e));
                }
            };
        };
    }

    /**
     * Handle the given exception.
     *
     * @param  \Exception  $e
     * @return mixed
     */
    protected function handleException($passable, Exception $e)
    {
        if (! $this->container->bound(ExceptionHandler::class) ||
            ! $passable instanceof Request) {
            throw $e;
        }

        $handler = $this->container->make(ExceptionHandler::class);

        $handler->report($e);

        return $handler->render($passable, $e);
    }
}

<?php

namespace Illuminate\Routing;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Pipeline\Pipeline as BasePipeline;
use Symfony\Component\Debug\Exception\FatalThrowableError;

/**
 * This extended pipeline catches any exceptions that occur during each slice.
 *
 * The exceptions are converted to HTTP responses for proper middleware handling.
 */
class Pipeline extends BasePipeline
{
    /**
     * Get a Closure that represents a slice of the application onion.
     *
     * @return \Closure
     */
    protected function getSlice()
    {
        return function ($stack, $pipe) {
            return function ($passable) use ($stack, $pipe) {
                try {
                    $slice = parent::getSlice();

                    return call_user_func($slice($stack, $pipe), $passable);
                } catch (Exception $e) {
                    return $this->handleException($passable, $e);
                } catch (Throwable $e) {
                    return $this->handleException($passable, new FatalThrowableError($e));
                }
            };
        };
    }

    /**
     * Handle the given exception.
     *
     * @param  \Exception  $e
     * @return mixed
     */
    protected function handleException($passable, Exception $e)
    {
        if (! $this->container->bound(ExceptionHandler::class) ||
            ! $passable instanceof Request) {
            throw $e;
        }

        $handler = $this->container->make(ExceptionHandler::class);

        $handler->report($e);

        return $handler->render($passable, $e);
    }
}

Fix call for older PHP.

Fix call for older PHP.


<?php
/**
 *
 *
 * @author Sam Schmidt <samuel@dersam.net>
 * @since 2016-03-15
 */

namespace LinusShops\Prophet\Context;

trait Magento
{

}

<?php
/**
 *
 *
 * @author Sam Schmidt <samuel@dersam.net>
 * @since 2016-03-15
 */

namespace LinusShops\Prophet\Context;

trait Magento
{
    /**
     * @Given /^I should be able to add the product to my cart$/
     */
    public function assertCanAddProductToCart()
    {
        throw new \Behat\Behat\Tester\Exception\PendingException();
    }
}

Define tests for non-explicit fitment ux.


<?php

Route::filter('basicAuth', function()
{
    if(!Sentry::check())
    {
        return Redirect::route('getLogin');
    }

    View::share('currentUser', Sentry::getUser());
});

Route::filter('notAuth', function()
{
    if(Sentry::check())
    {
        return Redirect::route('indexDashboard');
    }
});

Route::filter('hasPermissions', function()
{
    $permissions = Config::get('syntara::permissions');

    if(!Sentry::getUser()->hasAccess($permissions[Route::currentRouteName()]))
    {
        return Redirect::route('accessDenied');
    }
});

<?php

Route::filter('basicAuth', function()
{
    if(!Sentry::check())
    {
        return Redirect::route('getLogin');
    }

    View::share('currentUser', Sentry::getUser());
});

Route::filter('notAuth', function()
{
    if(Sentry::check())
    {
        return Redirect::route('indexDashboard');
    }
});

Route::filter('hasPermissions', function()
{
    $permissions = Config::get('syntara::permissions');

    if (Route::currentRouteName() == "putUser" && Sentry::getUser()->id == Request::segment(3) ||
        Route::currentRouteName() == "showUser" && Sentry::getUser()->id == Request::segment(3)) {

    } else {
        if(!Sentry::getUser()->hasAccess($permissions[Route::currentRouteName()]))
        {
            return Redirect::route('accessDenied');
        }
    }
});

Allow users to edit their own record

Allow users to edit their own record


<?php

if (! function_exists('module_path')) {
    function module_path($name)
    {
        $module = app('modules')->find($name);

        return $module->getPath();
    }
}

if (! function_exists('config_path')) {
    /**
     * Get the configuration path.
     *
     * @param  string $path
     * @return string
     */
    function config_path($path = '')
    {
        return app()->basePath() . '/config' . ($path ? '/' . $path : $path);
    }
}

if (! function_exists('public_path')) {
    /**
     * Get the path to the public folder.
     *
     * @param  string  $path
     * @return string
     */
    function public_path($path = '')
    {
        return app()->make('path.public') . ($path ? DIRECTORY_SEPARATOR . ltrim($path, DIRECTORY_SEPARATOR) : $path);
    }
}

<?php

if (! function_exists('module_path')) {
    function module_path($name, $path = '')
    {
        $module = app('modules')->find($name);

        return $module->getPath().($path ? DIRECTORY_SEPARATOR.$path : $path);
    }
}

if (! function_exists('config_path')) {
    /**
     * Get the configuration path.
     *
     * @param  string $path
     * @return string
     */
    function config_path($path = '')
    {
        return app()->basePath() . '/config' . ($path ? '/' . $path : $path);
    }
}

if (! function_exists('public_path')) {
    /**
     * Get the path to the public folder.
     *
     * @param  string  $path
     * @return string
     */
    function public_path($path = '')
    {
        return app()->make('path.public') . ($path ? DIRECTORY_SEPARATOR . ltrim($path, DIRECTORY_SEPARATOR) : $path);
    }
}

Add optional path parameter to module_path helper


<?php

/**
 * Plugin Name: Papi
 * Description: Page Type API
 * Author: Fredrik Forsmo
 * Author URI: http://forsmo.me
 * Version: 2.3.0-dev
 * Plugin URI: https://wp-papi.github.io
 * Textdomain: papi
 */

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

// Load Composer autoload if it exists.
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
	require_once __DIR__ . '/vendor/autoload.php';
}

// Load Papi loader.
require_once __DIR__ . '/src/papi-loader.php';

<?php

/**
 * Plugin Name: Papi
 * Description: Page Type API
 * Author: Fredrik Forsmo
 * Author URI: http://forsmo.me
 * Version: 2.3.0-dev
 * Plugin URI: https://wp-papi.github.io
 * Textdomain: papi
 */

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

// Load Composer autoload if it exists and
// the Container class isn't loaded.
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) &&
	! class_exists( '\\Frozzare\\Tank\\Container' ) ) {
	require_once __DIR__ . '/vendor/autoload.php';
}

// Load Papi loader.
require_once __DIR__ . '/src/papi-loader.php';

Load composer only if container class dont exists


<?php

/*
 * This file is part of the XiideaEasyAuditBundle package.
 *
 * (c) Xiidea <http://www.xiidea.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Xiidea\EasyAuditBundle\Tests;

use PHPUnit\Framework\TestListener;

if (class_exists('Symfony\Bridge\PhpUnit\SymfonyTestsListener')) {

    class_alias('Symfony\Bridge\PhpUnit\SymfonyTestsListener', 'Xiidea\EasyAuditBundle\Tests\XiideaTestListener');

} else {
    class XiideaTestListener implements TestListener
    {
        use \PHPUnit\Framework\TestListenerDefaultImplementation;
    }
}

<?php

/*
 * This file is part of the XiideaEasyAuditBundle package.
 *
 * (c) Xiidea <http://www.xiidea.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Xiidea\EasyAuditBundle\Tests;

use PHPUnit\Framework\BaseTestListener;

if (class_exists('Symfony\Bridge\PhpUnit\SymfonyTestsListener')) {

    class_alias('Symfony\Bridge\PhpUnit\SymfonyTestsListener', 'Xiidea\EasyAuditBundle\Tests\XiideaTestListener');

} else {
    class XiideaTestListener extends BaseTestListener
    {
    }
}

:bug: Revert Back to  BaseTestListener class to support phpunit 5, php 5.6


<?php

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class RememberTestCase extends PHPUnit_Framework_TestCase
{
    const ID = '00000000-0000-0000-0000-000000000000';
    const USER_KEY = 'rememberable:37e1e4277521620256c524b5598dec2e19a04bfaf581bb9da4f83c3ad4ff7dbb7b03e7db5175eb2f3e507b4f8133fc2837eb392f7a92ce118ebff3a0e72cad9a';

    /**
     * Is SQL allowed to be issued?
     *
     * @var bool
     */
    protected static $sql = true;

    public static function setUpBeforeClass()
    {
        DB::listen(function ($query) {
            if (static::$sql === false) {
                throw new SqlIssuedException($query->sql);
            }
        });
    }

    public function setUp()
    {
        Cache::flush();
        DB::beginTransaction();
    }

    public function tearDown()
    {
        Cache::flush();
        DB::rollBack();

        static::$sql = true;
    }
}

<?php

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

abstract class RememberTestCase extends PHPUnit_Framework_TestCase
{
    const ID = '00000000-0000-0000-0000-000000000000';
    const USER_KEY = 'rememberable:37e1e4277521620256c524b5598dec2e19a04bfaf581bb9da4f83c3ad4ff7dbb7b03e7db5175eb2f3e507b4f8133fc2837eb392f7a92ce118ebff3a0e72cad9a';

    /**
     * Is SQL allowed to be issued?
     *
     * @var bool
     */
    protected static $sql = true;

    public static function setUpBeforeClass()
    {
        DB::listen(function ($query) {
            if (static::$sql === false) {
                throw new SqlIssuedException($query->sql);
            }
        });
    }

    public function setUp()
    {
        Cache::flush();
        DB::beginTransaction();
    }

    public function tearDown()
    {
        Cache::flush();
        DB::rollBack();

        static::$sql = true;
    }
}

Make the base test case abstract

Make the base test case abstract


<?php namespace duxet\Tests\Realtime;

use duxet\Realtime\ConnectionManager;
use duxet\Realtime\Connections\NullConnection;
use Mockery;

class ConnectionManagerTest extends TestCase {

    public function testConnectionName()
    {
        $config = ['driver' => 'null'];
        $manager = $this->getConfigManager($config);
        $this->assertSame([], $manager->getConnections());
        $return = $manager->connection('local');
        $this->assertInstanceOf('duxet\Realtime\Contracts\Connection', $return);
        $this->assertArrayHasKey('local', $manager->getConnections());
    }

    protected function getManager()
    {
        $config = Mockery::mock('Illuminate\Contracts\Config\Repository');
        $manager = new ConnectionManager($config);

        $manager->extend('null', function() {
           return new NullConnection;
        });

        return $manager;
    }

    protected function getConfigManager(array $config)
    {
        $manager = $this->getManager();

        $manager->getConfig()->shouldReceive('get')->once()
            ->with('realtime.connections')->andReturn(['local' => $config]);

        $config['name'] = 'local';

        return $manager;
    }

}

<?php namespace duxet\Tests\Realtime;

use duxet\Realtime\ConnectionManager;
use duxet\Realtime\Connections\NullConnection;
use Mockery;

class ConnectionManagerTest extends TestCase {

    public function testConnectionName()
    {
        $config = ['driver' => 'null'];
        $manager = $this->getConfigManager($config);
        $this->assertSame([], $manager->getConnections());
        $return = $manager->connection('local');
        $this->assertInstanceOf('duxet\Realtime\Contracts\Connection', $return);
        $this->assertArrayHasKey('local', $manager->getConnections());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testConnectionError()
    {
        $manager = $this->getManager();
        $config = ['driver' => 'error'];
        $manager->getConfig()->shouldReceive('get')->once()
            ->with('realtime.connections')->andReturn(['local' => $config]);
        $this->assertSame([], $manager->getConnections());
        $return = null;
        $manager->connection('error');
    }

    protected function getManager()
    {
        $config = Mockery::mock('Illuminate\Contracts\Config\Repository');
        $manager = new ConnectionManager($config);

        $manager->extend('null', function() {
           return new NullConnection;
        });

        return $manager;
    }

    protected function getConfigManager(array $config)
    {
        $manager = $this->getManager();

        $manager->getConfig()->shouldReceive('get')->once()
            ->with('realtime.connections')->andReturn(['local' => $config]);

        $config['name'] = 'local';

        return $manager;
    }

}

Add one more Connection Manager test

Add one more Connection Manager test


<?php

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

namespace Flarum\Tags;

use Flarum\Core\Validator\AbstractValidator;

class TagValidator extends AbstractValidator
{
    /**
     * {@inheritdoc}
     */
    protected $rules = [
        'name' => ['required'],
        'slug' => ['required', 'unique:tags'],
        'isHidden' => ['bool'],
        'description' => ['string', 'max:700'],
        'color' => ['regex:/^#([a-f0-9]{6}|[a-f0-9]{3})$/i'],
    ];
}

<?php

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

namespace Flarum\Tags;

use Flarum\Core\Validator\AbstractValidator;

class TagValidator extends AbstractValidator
{
    /**
     * {@inheritdoc}
     */
    protected $rules = [
        'name' => ['required'],
        'slug' => ['required', 'unique:tags'],
        'is_hidden' => ['bool'],
        'description' => ['string', 'max:700'],
        'color' => ['regex:/^#([a-f0-9]{6}|[a-f0-9]{3})$/i'],
    ];
}

Fix validation of "hidden" checkbox not working


<?php

declare(strict_types=1);

namespace GrumPHP\Locator;

use GrumPHP\Exception\ExecutableNotFoundException;
use GrumPHP\Util\Paths;
use Symfony\Component\Process\ExecutableFinder;

class ExternalCommand
{
    /**
     * @var list<string>
     */
    private $suffixes = ['', '.phar'];

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

    /**
     * @var ExecutableFinder
     */
    protected $executableFinder;

    public function __construct(string $binDir, ExecutableFinder $executableFinder)
    {
        $this->binDir = rtrim($binDir, '/\\');
        $this->executableFinder = $executableFinder;
    }

    public static function loadWithPaths(Paths $paths, ExecutableFinder $executableFinder): self
    {
        return new self(
            $paths->getBinDir(),
            $executableFinder
        );
    }

    public function locate(string $command): string
    {
        foreach ($this->suffixes as $suffix) {
            $cmdName = $command . $suffix;
            // Search executable:
            $executable = $this->executableFinder->find($cmdName, null, [$this->binDir]);

            if ($executable) {
                return $executable;
            }
        }

        throw ExecutableNotFoundException::forCommand(
            sprintf('The executable for "%s" could not be found.', $command)
        );
    }
}

<?php

declare(strict_types=1);

namespace GrumPHP\Locator;

use GrumPHP\Exception\ExecutableNotFoundException;
use GrumPHP\Util\Paths;
use Symfony\Component\Process\ExecutableFinder;

class ExternalCommand
{
    /**
     * @var list<string>
     */
    private $suffixes = ['', '.phar'];

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

    /**
     * @var ExecutableFinder
     */
    protected $executableFinder;

    public function __construct(string $binDir, ExecutableFinder $executableFinder)
    {
        $this->binDir = rtrim($binDir, '/\\');
        $this->executableFinder = $executableFinder;
    }

    public static function loadWithPaths(Paths $paths, ExecutableFinder $executableFinder): self
    {
        return new self(
            $paths->getBinDir(),
            $executableFinder
        );
    }

    public function locate(string $command): string
    {
        foreach ($this->suffixes as $suffix) {
            $cmdName = $command . $suffix;
            // Search executable:
            $executable = $this->executableFinder->find($cmdName, null, [$this->binDir]);

            if ($executable) {
                return $executable;
            }
        }

        throw ExecutableNotFoundException::forCommand($command);
    }
}

Fix double sprintf in exception

Fix double sprintf in exception


<?php
/**
 * Pines' information.
 *
 * @package Pines
 * @license http://www.gnu.org/licenses/agpl-3.0.html
 * @author Hunter Perrin <hunter@sciactive.com>
 * @copyright SciActive.com
 * @link http://sciactive.com/
 */
/* @var $pines pines */
defined('P_RUN') or die('Direct access prohibited');

return array(
	'name' => 'Pines',
	'author' => 'SciActive',
	'version' => '1.0.3',
	'license' => 'http://www.gnu.org/licenses/agpl-3.0.html',
	'website' => 'http://www.sciactive.com',
	'short_description' => 'Pines framework core system',
	'description' => 'The core system of the Pines PHP application framework.',
	'depend' => array(
		'php' => '>=5.2.10'
	),
	'abilities' => array(
		array('all', 'All Abilities', 'Let user do anything, regardless of whether they have the ability.')
	),
);

?>

<?php
/**
 * Pines' information.
 *
 * @package Pines
 * @license http://www.gnu.org/licenses/agpl-3.0.html
 * @author Hunter Perrin <hunter@sciactive.com>
 * @copyright SciActive.com
 * @link http://sciactive.com/
 */
/* @var $pines pines */
defined('P_RUN') or die('Direct access prohibited');

return array(
	'name' => 'Pines',
	'author' => 'SciActive',
	'version' => '1.0.2',
	'license' => 'http://www.gnu.org/licenses/agpl-3.0.html',
	'website' => 'http://www.sciactive.com',
	'short_description' => 'Pines framework core system',
	'description' => 'The core system of the Pines PHP application framework.',
	'depend' => array(
		'php' => '>=5.2.10'
	),
	'abilities' => array(
		array('all', 'All Abilities', 'Let user do anything, regardless of whether they have the ability.')
	),
);

?>

Undo version increment. 1.0.2 was never released/tagged.


<?php
require_once 'Lisphp/Runtime/BuiltinFunction.php';
require_once 'Lisphp/Runtime/PHPFunction.php';

final class Lisphp_Runtime_Object_GetAttribute implements Lisphp_Applicable {
    function apply(Lisphp_Scope $scope, Lisphp_List $arguments) {
        if (count($arguments) < 2) {
            throw new InvalidArgumentException('expected least two arguments');
        }
        $object = $first = $arguments->car()->evaluate($scope);
        $names = $arguments->cdr();
        $chain = '';
        foreach ($names as $name) {
            $name = (string) $name;
            $chain .= "->$name";
            if (isset($object->$name)) {
                $object = $object->$name;
            } else if (method_exists($object, $name)) {
                $object = new Lisphp_Runtime_PHPFunction(array($object, $name));
            } else {
                $o = (is_object($first) ? get_class($first) : gettype($first))
                   . $chain;
                throw new RuntimeException("there is no name '$name' for $o");
            }
        }
        return $object;
    }
}

<?php
require_once 'Lisphp/Runtime/BuiltinFunction.php';
require_once 'Lisphp/Runtime/PHPFunction.php';

final class Lisphp_Runtime_Object_GetAttribute implements Lisphp_Applicable {
    function apply(Lisphp_Scope $scope, Lisphp_List $arguments) {
        if (count($arguments) < 2) {
            throw new InvalidArgumentException('expected least two arguments');
        }
        $object = $first = $arguments->car()->evaluate($scope);
        $names = $arguments->cdr();
        $chain = '';
        foreach ($names as $name) {
            $name = (string) $name;
            $chain .= "->$name";
            if (isset($object->$name)) {
                $object = $object->$name;
            } else if (method_exists($object, $name) || method_exists($object, '__call')) {
                $object = new Lisphp_Runtime_PHPFunction(array($object, $name));
            } else {
                $o = (is_object($first) ? get_class($first) : gettype($first))
                   . $chain;
                throw new RuntimeException("there is no name '$name' for $o");
            }
        }
        return $object;
    }
}

Allow calling methods which use the __call magic method

Example:

    (require "vendor/autoload.php")

    (use <Predis\Client>)

    (define client (<Predis\Client>))

    (var_dump
        ((-> client set) "foo" "bar"))


<?php

//autoload
require_once dirname(__FILE__) . "/../models/API/Autoloader.php";

//load config
if (file_exists("config/config.php")) {
  include("config/config.php");
} else {
  include("../config/config.php");
}

$update = new updateController();
$update->startUpdateTransaction();

class updateController {

  private $api_key = '';
  private $api_url = '';

  function __construct() {
    $this->api_key = API_KEY;
    $this->api_url = API_URL;
  }

  function startUpdateTransaction() {
    $msp = new Client;
    $msp->setApiKey($this->api_key);
    $msp->setApiUrl($this->api_url);

    $transactionid = '1441193361';
	$endpoint = 'orders/' . $transactionid;

	try
    {
      $order = $msp->orders->patch(
            array(
                "tracktrace_code" => 'null',
                "carrier"=> 'null',
                "ship_date"=> date('Y-m-d H:i:s'),
                "reason" => 'Shipped'
            ), $endpoint);
	} catch (Exception $e)
    {
      echo "Error " . htmlspecialchars($e->getMessage());
    }
  }
}

?>

Change time to date for updating the transaction to shipped


<?php namespace Tobscure\JsonApi;

class Criteria
{
    protected $input;

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

    public function getInclude()
    {
        return explode(',', $this->getInput('include'));
    }

    public function getOffset()
    {
        return max(0, $this->getPage('offset'));
    }

    public function getLimit()
    {
        return $this->getPage('limit');
    }

    /**
     * [getSort description]
     *
     * @todo require + prefix for ascending order
     * @todo add support for multiple sorts (+foo,-bar)
     * @return [type] [description]
     */
    public function getSort()
    {
        $field = $this->getInput('sort');
        $order = null;

        if (substr($field, 0, 1) === '-') {
            $order = 'desc';
            $field = substr($field, 1);
        }

        if ($field && ! $order) {
            $order = 'asc';
        }

        return [$field => $order];
    }

    protected function getInput($key)
    {
        return isset($this->input[$key]) ? $this->input[$key] : null;
    }

    protected function getPage($key)
    {
        $page = $this->getInput('page');

        return isset($page[$key]) ? $page[$key] : '';
    }
}

<?php namespace Tobscure\JsonApi;

class Criteria
{
    protected $input;

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

    public function getInclude()
    {
        return explode(',', $this->getInput('include'));
    }

    public function getOffset()
    {
        return max(0, $this->getPage('offset'));
    }

    public function getLimit()
    {
        return $this->getPage('limit');
    }

    public function getSort()
    {
        $sort = [];

        $fields = explode(',', $this->getInput('sort'));

        foreach ($fields as $field) {
            $order = substr($field, 0, 1);

            if ($order === '+' || $order === '-') {
                $sort[substr($field, 1)] = $order === '+' ? 'asc' : 'desc';
            }
        }

        return $sort;
    }

    protected function getInput($key)
    {
        return isset($this->input[$key]) ? $this->input[$key] : null;
    }

    protected function getPage($key)
    {
        $page = $this->getInput('page');

        return isset($page[$key]) ? $page[$key] : '';
    }
}

Bring sort criteria parsing in line with the spec

- Support multiple sort criteria separated by ,
- Ignore sort criteria unless it starts with a + or -


<?php

namespace Code16\Sharp\Tests\Feature\Api;

use Carbon\Carbon;

class SetLocaleTest extends BaseApiTest
{
    protected function setUp()
    {
        parent::setUp();

        $this->login();
    }

    /** @test */
    public function we_can_ignore_locale_in_config()
    {
        $this->buildTheWorld();

        $this->assertEquals("Monday", Carbon::now()->startOfWeek()->formatLocalized("%A"));

        $this->json('get', '/sharp/api/form/person/1');

        $this->assertEquals("Monday", Carbon::now()->startOfWeek()->formatLocalized("%A"));
    }

    /** @test */
    public function we_can_set_a_locale_in_config()
    {
        $this->buildTheWorld();

        config(["sharp.locale" => "fr_FR.UTF-8"]);

        $this->assertEquals("Monday", Carbon::now()->startOfWeek()->formatLocalized("%A"));

        // Locale is set through the SetSharpLocale middleware for the request
        $this->json('get', '/sharp/api/form/person/1');

        $this->assertEquals("Lundi", Carbon::now()->startOfWeek()->formatLocalized("%A"));
    }

}

<?php

namespace Code16\Sharp\Tests\Feature\Api;

use Carbon\Carbon;

class SetLocaleTest extends BaseApiTest
{
    protected function setUp()
    {
        parent::setUp();

        $this->login();
    }

    /** @test */
    public function we_can_ignore_locale_in_config()
    {
        $this->buildTheWorld();

        $this->assertEquals("monday", strtolower(Carbon::now()->startOfWeek()->formatLocalized("%A")));

        $this->json('get', '/sharp/api/form/person/1');

        $this->assertEquals("monday", strtolower(Carbon::now()->startOfWeek()->formatLocalized("%A")));
    }

    /** @test */
    public function we_can_set_a_locale_in_config()
    {
        $this->buildTheWorld();

        config(["sharp.locale" => "fr_FR.UTF-8"]);

        $this->assertEquals("monday", strtolower(Carbon::now()->startOfWeek()->formatLocalized("%A")));

        // Locale is set through the SetSharpLocale middleware for the request
        $this->json('get', '/sharp/api/form/person/1');

        $this->assertEquals("lundi", strtolower(Carbon::now()->startOfWeek()->formatLocalized("%A")));
    }

}

Fix test for Travis env

Fix test for Travis env


<?php

namespace ChainableTest\Fixtures;

use Chainable\ChainableInterface;
use Chainable\Result\ChainResult;
use Chainable\Result\ChainResultInterface;

abstract class AbstractResponse implements ChainableInterface
{
    abstract public function getValue();

    /**
     * @param mixed $data
     *
     * @return ChainResultInterface
     */
    public function process(... $data)
    {
        return new ChainResult($this->getValue(), reset(reset($data)) === $this->getValue());
    }
}

<?php

namespace ChainableTest\Fixtures;

use Chainable\ChainableInterface;
use Chainable\Result\ChainResult;
use Chainable\Result\ChainResultInterface;

abstract class AbstractResponse implements ChainableInterface
{
    abstract public function getValue();

    /**
     * @param mixed $data
     *
     * @return ChainResultInterface
     */
    public function process(... $data)
    {
        $value = reset($data);

        return new ChainResult($this->getValue(), reset($value) === $this->getValue());
    }
}

Fix dumb error in travis php version

Fix dumb error in travis php version


<?php

use Galahad\LaravelAddressing\Entity\Country;
use Galahad\LaravelAddressing\LaravelAddressing;

/**
 * Class LaravelAddressingTest
 *
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class LaravelAddressingTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var LaravelAddressing
     */
    protected $addressing;

    /**
     * Setup the LaravelAddressing instance
     */
    protected function setUp()
    {
        $this->addressing = new LaravelAddressing();
    }

    /**
     * Testing the returning type of the country() method
     */
    public function testCountryMethodReturningType()
    {
        $country = $this->addressing->country('US');
        $this->assertTrue($country instanceof Country);
    }

    /**
     * Testing if the country has the correct name
     */
    public function testCountryMethod()
    {
        $country = $this->addressing->country('US');
        $this->assertEquals($country->getName(), 'United States');
        $this->assertEquals($country->getCountryCode(), 'US');
    }
}

<?php

use Galahad\LaravelAddressing\Entity\Country;
use Galahad\LaravelAddressing\LaravelAddressing;

/**
 * Class LaravelAddressingTest
 *
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class LaravelAddressingTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var LaravelAddressing
     */
    protected $addressing;

    /**
     * Setup the LaravelAddressing instance
     */
    protected function setUp()
    {
        $this->addressing = new LaravelAddressing();
    }

    public function testTheReturningTypeOfCountryMethod()
    {
        $country = $this->addressing->country('US');
        $this->assertTrue($country instanceof Country);
    }

    public function testIfTheCountryHasTheCorrectName()
    {
        $country = $this->addressing->country('US');
        $this->assertEquals($country->getName(), 'United States');
        $this->assertEquals($country->getCountryCode(), 'US');
    }

    public function testIfTheCountryByNameMethodIsReturningTheCorrectCountry()
    {
        $country = $this->addressing->countryByName('United States');
        $this->assertTrue($country instanceof Country);
        $this->assertEquals($country->getCountryCode(), 'US');
        $country = $this->addressing->countryByName('Brazil');
        $this->assertEquals($country->getCountryCode(), 'BR');
    }
}

Add tests for the countryByName() method


<?php

namespace Zerg\Field;

use Zerg\Stream\StringStream;

class StringTest extends \PHPUnit_Framework_TestCase
{
    public function testRead()
    {
        $string = new String(2);
        $stream = new StringStream('abc');
        $this->assertEquals('ab', $string->read($stream));
    }

    public function testUtfRead()
    {
        $string = new String(4, ['utf' => 1]);
        $stream = new StringStream("\xff\xfeabc");
        $this->assertEquals('ab', $string->read($stream));
    }
}

<?php

namespace Zerg\Field;

use Zerg\Stream\StringStream;

class StringTest extends \PHPUnit_Framework_TestCase
{
    public function testRead()
    {
        $string = new String(2);
        $stream = new StringStream('abc');
        $this->assertEquals('ab', $string->read($stream));
    }

    public function testUtfRead()
    {
        $string = new String(4, ['utf' => 1]);
        $stream = new StringStream("\xff\xfeabc");
        $this->assertEquals('ab', $string->read($stream));
    }

    public function testEmptyUtfString()
    {
        $string = new String(1, ['utf' => 1]);
        $stream = new StringStream("abc");
        $this->assertEquals('', $string->read($stream));
    }
}

Add empty utf string test

Add empty utf string test


<?php
/**
 * Phergie plugin for displaying data from tweets (https://github.com/phergie/phergie-irc-plugin-react-twitter)
 *
 * @link https://github.com/phergie/phergie-irc-plugin-react-twitter for the canonical source repository
 * @copyright Copyright (c) 2008-2014 Phergie Development Team (http://phergie.org)
 * @license http://phergie.org/license Simplified BSD License
 * @package Phergie\Irc\Plugin\React\Twitter
 */

namespace Phergie\Irc\Tests\Plugin\React\Twitter;

use Phake;
use Phergie\Irc\Bot\React\EventQueueInterface as Queue;
use Phergie\Irc\Plugin\React\Command\CommandEvent as Event;
use Phergie\Irc\Plugin\React\Twitter\Plugin;

/**
 * Tests for the Plugin class.
 *
 * @category Phergie
 * @package Phergie\Irc\Plugin\React\Twitter
 */
class PluginTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Tests that getSubscribedEvents() returns an array.
     */
    public function testGetSubscribedEvents()
    {
        $plugin = new Plugin;
        $this->assertInternalType('array', $plugin->getSubscribedEvents());
    }
}

<?php
/**
 * Phergie plugin for displaying data from tweets (https://github.com/phergie/phergie-irc-plugin-react-twitter)
 *
 * @link https://github.com/phergie/phergie-irc-plugin-react-twitter for the canonical source repository
 * @copyright Copyright (c) 2008-2014 Phergie Development Team (http://phergie.org)
 * @license http://phergie.org/license Simplified BSD License
 * @package Phergie\Irc\Plugin\React\Twitter
 */

namespace Phergie\Irc\Tests\Plugin\React\Twitter;

use Phake;
use Phergie\Irc\Bot\React\EventQueueInterface as Queue;
use Phergie\Irc\Plugin\React\Command\CommandEvent as Event;
use Phergie\Irc\Plugin\React\Twitter\Plugin;

/**
 * Tests for the Plugin class.
 *
 * @category Phergie
 * @package Phergie\Irc\Plugin\React\Twitter
 */
class PluginTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Tests that getSubscribedEvents() returns an array.
     */
    public function testGetSubscribedEvents()
    {
        $config = array(
            'consumer_key' => 'KEY',
            'consumer_secret' => 'SECRET',
            'token' => 'TOKEN',
            'token_secret' => 'TOKEN_SECRET',
        );
        $plugin = new Plugin($config);
        $this->assertInternalType('array', $plugin->getSubscribedEvents());
    }
}

Add configuration so the sole test passes


<?php

/*
Plugin Name: Opauth
Plugin URI: http://labculturadigital.org/
Description: Adds Opauth (opauth.org) support
Author: Laboratório de Cultura Digital - Flávio Zavan
Version: 0.01
Text Domain: wp-opauth
*/

define('CONF_FILE',
		dirname(__FILE__) . DIRECTORY_SEPARATOR . 'opauth.conf.php');
define('OPAUTH_PATH',
		dirname(__FILE__)
		. DIRECTORY_SEPARATOR . 'opauth'
		. DIRECTORY_SEPARATOR . 'lib'
		. DIRECTORY_SEPARATOR . 'Opauth');
define('WPOPAUTH_PATH', dirname(__FILE__));
define('WPOPAUTH_USER_TABLE_NAME', 'wpopauth_users');

if (!file_exists(CONF_FILE))
{
	trigger_error(
			__('Configuration file missing at ' . CONF_FILE
				. '. Wordpress Opauth disabled.'), E_USER_NOTICE);
	return;
}

require_once CONF_FILE;
require_once OPAUTH_PATH . DIRECTORY_SEPARATOR . 'Opauth.php';
require_once WPOPAUTH_PATH . DIRECTORY_SEPARATOR . 'wpopauth.php';

$opauth = new WPOpauth($config);

?>

<?php

/*
Plugin Name: Opauth
Plugin URI: http://labculturadigital.org/
Description: Adds Opauth (opauth.org) support
Author: Laboratório de Cultura Digital - Flávio Zavan
Version: 0.01
Text Domain: wp-opauth
*/

define('CONF_FILE',
		dirname(__FILE__) . DIRECTORY_SEPARATOR . 'opauth.conf.php');
define('OPAUTH_PATH',
		dirname(__FILE__)
		. DIRECTORY_SEPARATOR . 'opauth'
		. DIRECTORY_SEPARATOR . 'lib'
		. DIRECTORY_SEPARATOR . 'Opauth');
define('WPOPAUTH_PATH', dirname(__FILE__));
define('WPOPAUTH_USER_TABLE_NAME', 'wpopauth_users');

if (!file_exists(CONF_FILE))
{
	trigger_error(
			__('Configuration file missing at ' . CONF_FILE
				. '. Opauth disabled.'), E_USER_NOTICE);
	return;
}

require_once CONF_FILE;
require_once OPAUTH_PATH . DIRECTORY_SEPARATOR . 'Opauth.php';
require_once WPOPAUTH_PATH . DIRECTORY_SEPARATOR . 'wpopauth.php';

$opauth = new WPOpauth($config);

?>

Fix the name in an error message

Fix the name in an error message


<?php
class Af_SomethingPositive extends Plugin {

    function about() {
        return array(0.1, "Fetch image from Something Positive webcomic", "Markus Wiik");

    }
    function init($host) {
        $host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
    }

    function hook_article_filter($article) {
        $owner_uid = $article["owner_uid"];
        if (strpos($article["link"], "somethingpositive.net") !== FALSE) {
            if (strpos($article["plugin_data"], "somethingpositive,$owner_uid:") === FALSE) {
                $url = parse_url($article["link"]);
                $image_name = substr($url["path"], 0, -5) . "png";
                $article["content"] = '<img src="http://' . $url["host"] . '/' . $image_name . '"/>';
                $article["plugin_data"] = "somethingpositive,$owner_uid:" . $article["plugin_data"];
            }
            else if (isset($article["stored"]["content"])) {
                $article["content"] = $article["stored"]["content"];
            }
        }
        return $article;
    }
}
?>

<?php
class Af_SomethingPositive extends Plugin {

    function about() {
        return array(0.1, "Fetch image from Something Positive webcomic", "Markus Wiik");

    }
    function init($host) {
        $host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
    }

    function hook_article_filter($article) {
        $owner_uid = $article["owner_uid"];
        if (strpos($article["link"], "somethingpositive.net") !== FALSE) {
            if (strpos($article["plugin_data"], "somethingpositive,$owner_uid:") === FALSE) {
                $image_url = preg_replace("/shtml/", "png", $article['link']);
                $article["content"] = '<img src="' . $image_url . '"/>';
                $article["plugin_data"] = "somethingpositive,$owner_uid:" . $article["plugin_data"];
            }
            else if (isset($article["stored"]["content"])) {
                $article["content"] = $article["stored"]["content"];
            }
        }
        return $article;
    }
}
?>

Switch to preg_replace in Something Positive plugin


<?php
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

class Exception extends \RuntimeException implements \PHPUnit\Exception
{
}

<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Runner;

class Exception extends \RuntimeException implements \PHPUnit\Exception
{
}

Enable strict interpretation of scalar type declarations


<?php

namespace GuzzleHttp\Psr7;

final class Rfc7230
{
    /**
     * Header related regular expressions (copied from amphp/http package)
     * (Note: once we require PHP 7.x we could just depend on the upstream package)
     *
     * @link    https://github.com/amphp/http/blob/v1.0.1/src/Rfc7230.php#L12-L15
     * @license https://github.com/amphp/http/blob/v1.0.1/LICENSE
     */
    const HEADER_REGEX = "(^([^()<>@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m";
    const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)";
}

<?php

namespace GuzzleHttp\Psr7;

final class Rfc7230
{
    /**
     * Header related regular expressions (copied from amphp/http package)
     * (Note: once we require PHP 7.x we could just depend on the upstream package)
     *
     * Note: header delimiter (\r\n) is modified to \r?\n to accept line feed only delimiters for BC reasons.
     *
     * @link    https://github.com/amphp/http/blob/v1.0.1/src/Rfc7230.php#L12-L15
     * @license https://github.com/amphp/http/blob/v1.0.1/LICENSE
     */
    const HEADER_REGEX = "(^([^()<>@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m";
    const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)";
}

Add note about modified regex

Add note about modified regex


<?php
declare(strict_types=1);

namespace Zubr;

/**
 * \Zubr\array_key_exists()
 *
 * @link https://secure.php.net/array_key_exists
 *
 * NOTES: same as \array_key_exists()
*/
function array_key_exists($key, $search)
{
    return \array_key_exists($key, $search);
}

<?php
declare(strict_types=1);

namespace Zubr;

/**
 * \Zubr\array_key_exists()
 *
 * @link https://secure.php.net/array_key_exists
 *
 * NOTES: in Zubr, the $array parameter comes before $key
*/
function array_key_exists($array, $key)
{
    return \array_key_exists($key, $array);
}

Fix parameter order and rename params

Fix parameter order and rename params


<?php

namespace TomIrons\Tuxedo\Mailables;

use TomIrons\Tuxedo\Message;
use TomIrons\Tuxedo\TuxedoMailable;

class AlertMailable extends TuxedoMailable
{
    use Message;

    /**
     * The view to use for the message.
     *
     * @var string
     */
    public $view = 'tuxedo::templates.alert';

    /**
     * The type of alert.
     *
     * @var string|null
     */
    public $alertType = null;

    /**
     * The text of the alert.
     *
     * @var string|null
     */
    public $alertText = null;

    /**
     * Set the alert type and text for the message.
     *
     * @param string $type
     * @param string $text
     * @return $this
     */
    public function alert($type, $text)
    {
        $this->alert = true;
        $this->alertType = $type;
        $this->alertText = $text;

        return $this;
    }
}

<?php

namespace TomIrons\Tuxedo\Mailables;

use TomIrons\Tuxedo\Message;
use TomIrons\Tuxedo\TuxedoMailable;

class AlertMailable extends TuxedoMailable
{
    use Message;

    /**
     * The view to use for the message.
     *
     * @var string
     */
    public $view = 'tuxedo::templates.alert';

    /**
     * The type of alert.
     *
     * @var string|null
     */
    public $alertType = null;

    /**
     * The text of the alert.
     *
     * @var string|null
     */
    public $alertText = null;

    /**
     * Set the alert type and text for the message.
     *
     * @param string $type
     * @param string $text
     * @return $this
     */
    public function alert($type, $text)
    {
        $this->alertType = $type;
        $this->alertText = $text;

        return $this;
    }
}

Remove setting of 'alert' property

Remove setting of 'alert' property


<?php
require_once __DIR__.'/../../config.inc.php';
use TPGwidget\Data\Stops;

$file = 'https://prod.ivtr-od.tpg.ch/v1/GetStops.xml?key='.getenv('TPG_API_KEY').'&latitude='.($_GET['latitude'] ?? '').'&longitude='.($_GET['longitude'] ?? '');
$stops = @simplexml_load_file($file);

$output = [];
if ($stops) {
    foreach ($stops->stops->stop as $stop) {
        $output[] = [
            'stopNameOriginal' => $stop->stopName,
            'stopNameDisplay' => Stops::format($stop->stopName),
            'stopCode' => (string)$stop->stopCode,
        ];
    }
}

header('Content-Type: application/json');
echo json_encode($output);

<?php
require_once __DIR__.'/../../config.inc.php';
use TPGwidget\Data\Stops;

$file = 'https://prod.ivtr-od.tpg.ch/v1/GetStops.xml?key='.getenv('TPG_API_KEY').'&latitude='.($_GET['latitude'] ?? '').'&longitude='.($_GET['longitude'] ?? '');
$stops = @simplexml_load_file($file);

$output = [];
if ($stops) {
    foreach ($stops->stops->stop as $stop) {
        $output[] = [
            'stopNameOriginal' => (string)$stop->stopName,
            'stopNameDisplay' => Stops::format($stop->stopName),
            'stopCode' => (string)$stop->stopCode,
        ];
    }
}

header('Content-Type: application/json');
echo json_encode($output);

Fix nearest stops on iOS

Fix nearest stops on iOS


<?php

/**
 * @example
 * FastForward::Helpers()
 *     ->renderImage(142, 'full');
 */
class FastForward_Helpers {
    public function renderImage($id, $size = 'thumbnail') {
        echo wp_get_attachment_image($id, $size);
    }

    public function getImageAllSizes($id, $custom = array()) {
        $thumbnail = wp_get_attachment_image_src($id, 'thumbnail');
        $medium = wp_get_attachment_image_src($id, 'medium');
        $large = wp_get_attachment_image_src($id, 'large');
        $full = wp_get_attachment_image_src($id, 'full');

        if ($custom) {
            $customSize = wp_get_attachment_image_src($id, array($custom[0], $custom[1]));
        }

        $set = array(
            'thumbnail' => $thumbnail,
            'medium' => $medium,
            'large' => $large,
            'full' => $full,
            'custom' => $customSize
        );

        return $set;
    }

    public function getSinglePost($args) {
        $args = wp_parse_args($args, array(
            'posts_per_page' => 1
        ));

        $results = get_pages($args);

        return $results[0];
    }
}

<?php

/**
 * @example
 * FastForward::Helpers()
 *     ->renderImage(142, 'full');
 */
class FastForward_Helpers {
    public function renderImage($id, $size = 'thumbnail') {
        echo wp_get_attachment_image($id, $size);
    }

    public function getImageAllSizes($id, $custom = array()) {
        $thumbnail = wp_get_attachment_image_src($id, 'thumbnail');
        $medium = wp_get_attachment_image_src($id, 'medium');
        $large = wp_get_attachment_image_src($id, 'large');
        $full = wp_get_attachment_image_src($id, 'full');

        if ($custom) {
            $customSize = wp_get_attachment_image_src($id, array($custom[0], $custom[1]));
        }

        $set = array(
            'thumbnail' => $thumbnail,
            'medium' => $medium,
            'large' => $large,
            'full' => $full,
            'custom' => $customSize
        );

        return $set;
    }

    public function getSinglePost($args) {
        $args = wp_parse_args($args, array(
            'posts_per_page' => 1
        ));

        $results = get_pages($args);

        return $results[0];
    }

    /**
     * Render video from provider or raw video file.
     *
     * @param string
     * @param  boolean $echo
     */
    public function renderVideo($url, $echo = true) {
        $embedCode = wp_oembed_get($url);

        // There is no provider on whitelist or it is raw file.
        if (!$embedCode) {
            $embedCode = "<video src=\"{$url}\" autoplay controls></video>";
        }

        if ($echo) {
            echo $embedCode;
            return true;
        } else {
            return $embedCode;
        }
    }
}

Support oembed code from provider or raw file


<?php

namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_15;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\OrderedMigrationInterface;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class UpdateEmailOriginRelation implements Migration, OrderedMigrationInterface
{
    /**
     * {@inheritDoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        self::addOwnerAndOrganizationColumns($schema);
    }

    public static function addOwnerAndOrganizationColumns(Schema $schema)
    {
        $table = $schema->getTable('oro_email_origin');
        $table->addColumn('owner_id', 'integer', ['notnull' => false]);
        $table->addColumn('organization_id', 'integer', ['notnull' => false]);

        $table->addForeignKeyConstraint(
            $schema->getTable('oro_user'),
            ['owner_id'],
            ['id'],
            ['onDelete' => 'CASCADE', 'onUpdate' => null]
        );
        $table->addForeignKeyConstraint(
            $schema->getTable('oro_organization'),
            ['organization_id'],
            ['id'],
            ['onDelete' => 'SET NULL', 'onUpdate' => null]
        );
    }

    /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 0;
    }
}

<?php

namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_15;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\OrderedMigrationInterface;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class UpdateEmailOriginRelation implements Migration, OrderedMigrationInterface
{
    /**
     * {@inheritDoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        self::addOwnerAndOrganizationColumns($schema);
    }

    public static function addOwnerAndOrganizationColumns(Schema $schema)
    {
        $table = $schema->getTable('oro_email_origin');
        $table->addColumn('owner_id', 'integer', ['notnull' => false]);
        $table->addColumn('organization_id', 'integer', ['notnull' => false]);

        $table->addForeignKeyConstraint(
            $schema->getTable('oro_user'),
            ['owner_id'],
            ['id'],
            ['onDelete' => 'CASCADE', 'onUpdate' => null]
        );
        $table->addForeignKeyConstraint(
            $schema->getTable('oro_organization'),
            ['organization_id'],
            ['id'],
            ['onDelete' => 'CASCADE', 'onUpdate' => null]
        );
    }

    /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 0;
    }
}

CRM-3483: Change origin syncs (IMAP/EWS) to use origin
- Fix migration for oro_email_origin


<?php

namespace Kanboard\Notification;

use Kanboard\Core\Base;
use Kanboard\Core\Notification\NotificationInterface;

/**
 * Webhook Notification
 *
 * @package  Kanboard\Notification
 * @author   Frederic Guillot
 */
class WebhookNotification extends Base implements NotificationInterface
{
    /**
     * Send notification to a user
     *
     * @access public
     * @param  array     $user
     * @param  string    $event_name
     * @param  array     $event_data
     */
    public function notifyUser(array $user, $event_name, array $event_data)
    {
    }

    /**
     * Send notification to a project
     *
     * @access public
     * @param  array     $project
     * @param  string    $event_name
     * @param  array     $event_data
     */
    public function notifyProject(array $project, $event_name, array $event_data)
    {
        $url = $this->configModel->get('webhook_url');
        $token = $this->configModel->get('webhook_token');

        if (! empty($url)) {
            if (strpos($url, '?') !== false) {
                $url .= '&token='.$token;
            } else {
                $url .= '?token='.$token;
            }

            $payload = array(
                'event_name' => $event_name,
                'event_data' => $event_data,
            );

            $this->httpClient->postJson($url, $payload);
        }
    }
}

<?php

namespace Kanboard\Notification;

use Kanboard\Core\Base;
use Kanboard\Core\Notification\NotificationInterface;

/**
 * Webhook Notification
 *
 * @package  Kanboard\Notification
 * @author   Frederic Guillot
 */
class WebhookNotification extends Base implements NotificationInterface
{
    /**
     * Send notification to a user
     *
     * @access public
     * @param  array     $user
     * @param  string    $event_name
     * @param  array     $event_data
     */
    public function notifyUser(array $user, $event_name, array $event_data)
    {
    }

    /**
     * Send notification to a project
     *
     * @access public
     * @param  array     $project
     * @param  string    $event_name
     * @param  array     $event_data
     */
    public function notifyProject(array $project, $event_name, array $event_data)
    {
        $url = $this->configModel->get('webhook_url');
        $token = $this->configModel->get('webhook_token');

        if (! empty($url)) {
            if (strpos($url, '?') !== false) {
                $url .= '&token='.$token;
            } else {
                $url .= '?token='.$token;
            }

            $payload = array(
                'event_name' => $event_name,
                'event_data' => $event_data,
                'event_author' => ($this->userSession->isLogged() ? $this->userSession->getUsername() : NULL),
            );

            $this->httpClient->postJson($url, $payload);
        }
    }
}

Send event author in webhook notification


<?php

namespace Bundle\DoctrinePaginatorBundle\Document;

/**
 * @Document(collection="doctrine_paginator_test")
 */
class Test
{
    /**
     * @Id
     */
    public $id;

    /**
     * @Field(type="string")
     */
    public $title;
}

<?php

namespace Bundle\DoctrinePaginatorBundle\Document;

/**
 * @mongodb:Document(collection="doctrine_paginator_test")
 */
class Test
{
    /**
     * @mongodb:Id
     */
    public $id;

    /**
     * @mongodb:Field(type="string")
     */
    public $title;
}

Update test document mapping annotations


<?php

/*
 * Copyright 2012 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

final class PhabricatorRedirectController extends PhabricatorController {

  private $uri;

  public function willProcessRequest(array $data) {
    $this->uri = $data['uri'];
  }

  public function processRequest() {
    return id(new AphrontRedirectResponse())->setURI($this->uri);
  }

}

<?php

/*
 * Copyright 2012 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

final class PhabricatorRedirectController extends PhabricatorController {

  private $uri;

  public function shouldRequireLogin() {
    return false;
  }

  public function shouldRequireEnabledUser() {
    return false;
  }

  public function willProcessRequest(array $data) {
    $this->uri = $data['uri'];
  }

  public function processRequest() {
    return id(new AphrontRedirectResponse())->setURI($this->uri);
  }

}

Allow redirecting when not logged in

Allow redirecting when not logged in

Summary:
Without this, the https redirect doesn't work if you're not logged in, because
the login check in willBeginExecution happens before the redirect controller
can redirect. This also has the unpleasant effect of the login page on http
(when it should have redirected to https) not having any css or js.

Test Plan:
With the https redirect enabled, loaded phabricator without being logged in,
and saw that I got redirected to the https login page instead of seeing a
http login page.

Reviewers: epriestley, vrana

Reviewed By: epriestley

CC: aran, Korvin

Differential Revision: https://secure.phabricator.com/D3438


<?php

namespace ConnectHolland\Sulu\BlockBundle;

use Nijens\ProtocolStream\Stream\Stream;
use Nijens\ProtocolStream\StreamManager;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class ConnectHollandSuluBlockBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function boot()
    {
        $streamManager = new StreamManager();
        if (is_null($streamManager->getStream('sulu-block-bundle'))) {
            $rootDirectory = $this->container->get('kernel')->getRootDir();
            $stream = new Stream('sulu-block-bundle', [
                'blocks' => __DIR__.'/Resources/templates/blocks/',
                'properties' => __DIR__.'/Resources/templates/properties/',
                'app-properties' => $rootDirectory.'/Resources/ConnectHollandSuluBlockBundle/templates/properties/',
            ]);

            StreamManager::create()->registerStream($stream);
        }

        $this->container->get('twig.loader')->addPath($this->getPath().'/Resources/views', 'sulu-block-bundle');

        parent::boot();
    }
}

<?php

namespace ConnectHolland\Sulu\BlockBundle;

use Nijens\ProtocolStream\StreamManager;
use Nijens\ProtocolStream\Stream\Stream;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class ConnectHollandSuluBlockBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        $rootDirectory = $container->getParameter('kernel.root_dir');
        $this->registerStream($rootDirectory);

        parent::build($container);
    }

    /**
     * {@inheritdoc}
     */
    public function boot()
    {
        $rootDirectory = $this->container->get('kernel')->getRootDir();
        $this->registerStream($rootDirectory);
        $this->container->get('twig.loader')->addPath($this->getPath().'/Resources/views', 'sulu-block-bundle');

        parent::boot();
    }

    /**
     * Register the stream for the given $rootDirectory.
     *
     * @param string $rootDirectory
     */
    public function registerStream($rootDirectory)
    {
        $streamManager = new StreamManager();
        if (is_null($streamManager->getStream('sulu-block-bundle'))) {
            $stream = new Stream('sulu-block-bundle', [
                'blocks' => __DIR__.'/Resources/templates/blocks/',
                'properties' => __DIR__.'/Resources/templates/properties/',
                'app-properties' => $rootDirectory.'/Resources/ConnectHollandSuluBlockBundle/templates/properties/',
            ]);

            StreamManager::create()->registerStream($stream);
        }
    }
}

Load the stream wrapper at build

Load the stream wrapper at build

The stream wrapper should also be available when building the container.


<?php defined('C5_EXECUTE') or die("Access Denied.");
$form = Loader::helper('form');
print $form->textarea($editor->getConversationEditorInputName(), $editor->getConversationEditorMessageBody(), array('class'=>'unbound conversation-editor redactor_conversation_editor_'.$editor->getConversationObject()->getConversationID()));
?>
<script>
$(function() {
    var textarea = $('textarea.unbound.redactor_conversation_editor_<?=$editor->getConversationObject()->getConversationID()?>').removeClass('unbound');
    $(textarea).redactor({
        autoresize: false,
        buttons: [ 'bold','italic','deleted','|','fontcolor','|','link' ],
        callback: function(obj) {
            ConcreteEvent.publish('ConversationRedactorEditorLoaded',obj);
            ConcreteEvent.bind('ConversationSubmitForm',function(){
                obj.setCode("");
    			$('.preview.processing').each(function(){
    				$('input[rel="'+ $(this).attr('rel') +'"]').remove();
    				$(this).remove();
    			});
    			if($('.ccm-conversation-attachment-container').is(':visible')) {
    				$('.ccm-conversation-attachment-container').toggle();
    			}
            });
        }
    });
});
</script>

<?php defined('C5_EXECUTE') or die("Access Denied.");
$form = Loader::helper('form');
print $form->textarea($editor->getConversationEditorInputName(), $editor->getConversationEditorMessageBody(), array('class'=>'unbound conversation-editor redactor_conversation_editor_'.$editor->getConversationObject()->getConversationID()));
?>
<script>
$(function() {
    var textarea = $('textarea.unbound.redactor_conversation_editor_<?=$editor->getConversationObject()->getConversationID()?>').removeClass('unbound');
    $(textarea).redactor({
        'concrete5': {
            filemanager: <?=$fp->canAccessFileManager()?>,
            sitemap: <?=$tp->canAccessSitemap()?>,
            lightbox: true
        },
        autoresize: false,
        buttons: [ 'bold','italic','deleted','|','fontcolor','|','link' ],
        callback: function(obj) {
            ConcreteEvent.publish('ConversationRedactorEditorLoaded',obj);
            ConcreteEvent.bind('ConversationSubmitForm',function(){
                obj.setCode("");
    			$('.preview.processing').each(function(){
    				$('input[rel="'+ $(this).attr('rel') +'"]').remove();
    				$(this).remove();
    			});
    			if($('.ccm-conversation-attachment-container').is(':visible')) {
    				$('.ccm-conversation-attachment-container').toggle();
    			}
            });
        }
    });
});
</script>

Update conversation editor's redactor config to include c5 specific settings

Former-commit-id: 138509255a479ed280d18bbb43272d6cb3248777


<?php

/**
 * Part of the Tracker package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.  It is also available at
 * the following URL: http://www.opensource.org/licenses/BSD-3-Clause
 *
 * @package    Tracker
 * @version    1.0.0
 * @author     Antonio Carlos Ribeiro @ PragmaRX
 * @license    BSD License (3-clause)
 * @copyright  (c) 2013, PragmaRX
 * @link       http://pragmarx.com
 */

namespace PragmaRX\Tracker\Data\Repositories;

use PragmaRX\Tracker\Support\Config;

class Route extends Repository {

	public function __construct($model, Config $config)
	{
		parent::__construct($model);

		$this->config = $config;
	}

	public function isTrackable($route)
	{
		$forbidden = $this->config->get('do_not_track_routes');

		return
			$route->currentRouteName() &&
			! in_array_wildcard($route->currentRouteName(), $forbidden);
	}

}

<?php

/**
 * Part of the Tracker package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.  It is also available at
 * the following URL: http://www.opensource.org/licenses/BSD-3-Clause
 *
 * @package    Tracker
 * @version    1.0.0
 * @author     Antonio Carlos Ribeiro @ PragmaRX
 * @license    BSD License (3-clause)
 * @copyright  (c) 2013, PragmaRX
 * @link       http://pragmarx.com
 */

namespace PragmaRX\Tracker\Data\Repositories;

use PragmaRX\Tracker\Support\Config;

class Route extends Repository {

	public function __construct($model, Config $config)
	{
		parent::__construct($model);

		$this->config = $config;
	}

	public function isTrackable($route)
	{
		$forbidden = $this->config->get('do_not_track_routes');

		return
			! $forbidden ||
			! $route->currentRouteName() ||
			! in_array_wildcard($route->currentRouteName(), $forbidden);
	}

}

Fix not loggin on empty routes

Fix not loggin on empty routes


<?php

namespace Rasulian\ZarinPal;

use Illuminate\Support\ServiceProvider;

class ZarinPalServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../config/zarinpal.php' => $this->app->configPath().'/zarinpal.php',
        ], 'config');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        require __DIR__.'../config/zarinpal.php';
    }
}

<?php

namespace Rasulian\ZarinPal;

use Illuminate\Support\ServiceProvider;

class ZarinPalServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../config/zarinpal.php' => $this->app->configPath().'/zarinpal.php',
        ], 'config');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Update zarin pal service provider

Update zarin pal service provider


<?php

class Octopus_Logger_File {

    function __construct($file) {
        $this->file = $file;
        $this->_handle = null;
    }

    function _open() {

        if (!$this->_handle = @fopen($this->file, 'a')) {
            print "Can't open log file: $this->file.";
        }

    }

    function log($line) {

        if (!$this->_handle) {
            $this->_open();
        }

        if ($this->_handle) {
            $line = date('r') . ': ' . $line;
            @fwrite($this->_handle, $line . "\n");
        }

    }

}

?>

<?php

class Octopus_Logger_File {

    function __construct($file) {
        $this->file = $file;
        $this->_handle = null;
    }

    function _open() {

        if (!$this->_handle = @fopen($this->file, 'a')) {
            print "Can't open log file: $this->file.";
            exit();
        }

        @chmod($this->file, 0666);

    }

    function log($line) {

        if (!$this->_handle) {
            $this->_open();
        }

        if ($this->_handle) {
            $line = date('r') . ': ' . $line;
            @fwrite($this->_handle, $line . "\n");
        }

    }

}

Mark log files mode 666 when creating them


<?php

require_once ('/includes/functions/init.php'); // Initial theme setup and constants
require_once ('/includes/functions/menus.php'); // Register Menus
require_once ('/includes/functions/sidebar.php'); // Sidebar
require_once ('/includes/functions/scripts.php'); // Scripts and stylesheets
require_once ('/includes/functions/custom.php'); // Custom functions

?>

<?php

require_once ('includes/functions/init.php'); // Initial theme setup and constants
require_once ('includes/functions/menus.php'); // Register Menus
require_once ('includes/functions/sidebar.php'); // Sidebar
require_once ('includes/functions/scripts.php'); // Scripts and stylesheets
require_once ('includes/functions/custom.php'); // Custom functions

?>

Remove "/" that caused errors on remote host


<?php

final class DiffusionHovercardEngineExtension
  extends PhabricatorHovercardEngineExtension {

  const EXTENSIONKEY = 'diffusion';

  public function isExtensionEnabled() {
    return PhabricatorApplication::isClassInstalled(
      'PhabricatorDiffusionApplication');
  }

  public function getExtensionName() {
    return pht('Diffusion Commits');
  }

  public function canRenderObjectHovercard($object) {
    return ($object instanceof PhabricatorRepositoryCommit);
  }

  public function renderHovercard(
    PhabricatorHovercardView $hovercard,
    PhabricatorObjectHandle $handle,
    $commit,
    $data) {

    $viewer = $this->getViewer();

    $author_phid = $commit->getAuthorPHID();
    if ($author_phid) {
      $author = $viewer->loadHandle($author)->renderLink();
    } else {
      $commit_data = $commit->loadCommitData();
      $author = phutil_tag('em', array(), $commit_data->getAuthorName());
    }

    $hovercard->setTitle($handle->getName());
    $hovercard->setDetail($commit->getSummary());

    $hovercard->addField(pht('Author'), $author);
    $hovercard->addField(pht('Date'),
      phabricator_date($commit->getEpoch(), $viewer));

    if ($commit->getAuditStatus() !=
      PhabricatorAuditCommitStatusConstants::NONE) {

      $hovercard->addField(pht('Audit Status'),
        PhabricatorAuditCommitStatusConstants::getStatusName(
          $commit->getAuditStatus()));
    }
  }

}

<?php

final class DiffusionHovercardEngineExtension
  extends PhabricatorHovercardEngineExtension {

  const EXTENSIONKEY = 'diffusion';

  public function isExtensionEnabled() {
    return PhabricatorApplication::isClassInstalled(
      'PhabricatorDiffusionApplication');
  }

  public function getExtensionName() {
    return pht('Diffusion Commits');
  }

  public function canRenderObjectHovercard($object) {
    return ($object instanceof PhabricatorRepositoryCommit);
  }

  public function renderHovercard(
    PhabricatorHovercardView $hovercard,
    PhabricatorObjectHandle $handle,
    $commit,
    $data) {

    $viewer = $this->getViewer();

    $author_phid = $commit->getAuthorPHID();
    if ($author_phid) {
      $author = $viewer->renderHandle($author_phid);
    } else {
      $commit_data = $commit->loadCommitData();
      $author = phutil_tag('em', array(), $commit_data->getAuthorName());
    }

    $hovercard->setTitle($handle->getName());
    $hovercard->setDetail($commit->getSummary());

    $hovercard->addField(pht('Author'), $author);
    $hovercard->addField(pht('Date'),
      phabricator_date($commit->getEpoch(), $viewer));

    if ($commit->getAuditStatus() !=
      PhabricatorAuditCommitStatusConstants::NONE) {

      $hovercard->addField(pht('Audit Status'),
        PhabricatorAuditCommitStatusConstants::getStatusName(
          $commit->getAuditStatus()));
    }
  }

}

Fix an issue with rendering some commit hovercards

Summary: This logic wasn't quite right.

Test Plan: Hovered over a recognized commit, got a valid hovercard

Reviewers: chad

Reviewed By: chad

Differential Revision: https://secure.phabricator.com/D14925


<?php

namespace HTML5test\Automate;

use GuzzleHttp\Client;

class HTML5test {

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

        $this->client = new Client([
            'base_uri'  => $this->config['endpoint'],
            'timeout'   => 5.0
        ]);
    }

    public function getIdentifiers($source) {
        $response = $this->client->get('getIdentifiers', [
            'query' => [ 'source' => $source ]
        ]);

        return json_decode((string) $response->getBody());
    }

    public function getTask($source, $identifier) {
        $response = $this->client->get('getTask', [
            'query' => [ 'source' => $source, 'identifier' => $identifier ]
        ]);

        return json_decode((string) $response->getBody());
    }

    public function hasTask($task) {
        $response = $this->client->get('hasTask', [
            'query' => [ 'task' => $task ]
        ]);

        return json_decode((string) $response->getBody());
    }
}

<?php

namespace HTML5test\Automate;

use GuzzleHttp\Client;

class HTML5test {

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

        $this->client = new Client([
            'base_uri'  => $this->config['endpoint'],
            'timeout'   => 20.0
        ]);
    }

    public function getIdentifiers($source) {
        $response = $this->client->get('getIdentifiers', [
            'query' => [ 'source' => $source ]
        ]);

        return json_decode((string) $response->getBody());
    }

    public function getTask($source, $identifier) {
        $response = $this->client->get('getTask', [
            'query' => [ 'source' => $source, 'identifier' => $identifier ]
        ]);

        return json_decode((string) $response->getBody());
    }

    public function hasTask($task) {
        $response = $this->client->get('hasTask', [
            'query' => [ 'task' => $task ]
        ]);

        return json_decode((string) $response->getBody());
    }
}

Increase the timeout for connecting to html5test.com


<?php declare(strict_types=1);

namespace Symplify\BetterPhpDocParser\Attributes\Ast\PhpDoc;

use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocChildNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
use Symplify\BetterPhpDocParser\Attributes\Attribute\AttributeTrait;
use Symplify\BetterPhpDocParser\Attributes\Contract\Ast\AttributeAwareNodeInterface;

final class AttributeAwarePhpDocNode extends PhpDocNode implements AttributeAwareNodeInterface
{
    use AttributeTrait;

    /**
     * @var PhpDocChildNode[]|AttributeAwareNodeInterface[]
     */
    public $children = [];
}

<?php declare(strict_types=1);

namespace Symplify\BetterPhpDocParser\Attributes\Ast\PhpDoc;

use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocChildNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
use Symplify\BetterPhpDocParser\Attributes\Attribute\AttributeTrait;
use Symplify\BetterPhpDocParser\Attributes\Contract\Ast\AttributeAwareNodeInterface;

final class AttributeAwarePhpDocNode extends PhpDocNode implements AttributeAwareNodeInterface
{
    use AttributeTrait;

    /**
     * @var PhpDocChildNode[]|AttributeAwareNodeInterface[]
     */
    public $children = [];

    public function __toString(): string
    {
        return "/**\n * " . implode("\n * ", $this->children) . "\n */";
    }
}

[BetterPhpDocParser] Fix doc block printer for last node space


<?php

/*
 * This file is part of JoliTypo - a project by JoliCode.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

namespace JoliTypo\Bridge\Symfony\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('joli_typo');

        $rootNode
            ->fixXmlConfig('preset')
            ->children()
                ->arrayNode('presets')
                    ->useAttributeAsKey('name')
                    ->isRequired()
                    ->prototype('array')
                        ->children()
                            ->scalarNode('locale')->end()
                            ->arrayNode('fixers')
                                ->prototype('scalar')
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

<?php

/*
 * This file is part of JoliTypo - a project by JoliCode.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

namespace JoliTypo\Bridge\Symfony\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('joli_typo');
        $rootNode = $this->getRootNode($treeBuilder, 'joli_typo');

        $rootNode
            ->fixXmlConfig('preset')
            ->children()
                ->arrayNode('presets')
                    ->useAttributeAsKey('name')
                    ->isRequired()
                    ->prototype('array')
                        ->children()
                            ->scalarNode('locale')->end()
                            ->arrayNode('fixers')
                                ->prototype('scalar')
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }

    private function getRootNode(TreeBuilder $treeBuilder, $name)
    {
        // BC layer for symfony/config 4.1 and older
        if (! \method_exists($treeBuilder, 'getRootNode')) {
            return $treeBuilder->root($name);
        }
        return $treeBuilder->getRootNode();
    }
}

Remove deprecated usage of tree builder where possible


<?php

namespace App\Providers;

use Collection;
use Facades\App\Services\SmsTools as SmsTools;
use Illuminate\Support\ServiceProvider;
use Validator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('smsCount', function ($attribute, $value, $parameters, $validator) {
            return SmsTools::count($value) <= intval($parameters[0]);
        });

        Validator::replacer('smsCount', function ($message, $attribute, $rule, $parameters) {
            return str_replace(':size', $parameters[0], $message);
        });

        Validator::extend('in_keys', function ($attribute, $value, $parameters, $validator) {
            return Collection($parameters)->contains(function ($parameter) use ($value, $validator) {
                return array_key_exists($value, array_get($validator->getData(), $parameter));
            });
        });
    }

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

<?php

namespace App\Providers;

use Facades\App\Services\SmsTools as SmsTools;
use Illuminate\Support\ServiceProvider;
use Validator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('smsCount', function ($attribute, $value, $parameters, $validator) {
            return SmsTools::count($value) <= intval($parameters[0]);
        });

        Validator::replacer('smsCount', function ($message, $attribute, $rule, $parameters) {
            return str_replace(':size', $parameters[0], $message);
        });

        Validator::extend('in_keys', function ($attribute, $value, $parameters, $validator) {
            return collect($parameters)->contains(function ($parameter) use ($value, $validator) {
                return array_key_exists($value, array_get($validator->getData(), $parameter));
            });
        });
    }

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

Use function collect instead of class Collection


<?php
// mySQL configuration
// used for accessing database
include ('../../config.php');

global  $config_table, $server, $user, $password, $base;
$server = $databaseServer;   // replace by you mySQL server, could be something like 'localhost:3306' or 'localhost', or 'mysql.myhost.com'
$user = $databaseUser;     // replace by your login to mySQL server
$password = $databasePasswd; // replace by your password
$base = $databaseName;     // replace by the database where you want to create tables
// Table with phpTrafficA configuration, you can change it if you wish
$config_table = "phpTrafficA_conf";
?>

<?php
// mySQL configuration
// used for accessing database
include ($_SERVER["DOCUMENT_ROOT"] . '/config.php');

global  $config_table, $server, $user, $password, $base;
$server = $databaseServer;   // replace by you mySQL server, could be something like 'localhost:3306' or 'localhost', or 'mysql.myhost.com'
$user = $databaseUser;     // replace by your login to mySQL server
$password = $databasePasswd; // replace by your password
$base = $databaseName;     // replace by the database where you want to create tables
// Table with phpTrafficA configuration, you can change it if you wish
$config_table = "phpTrafficA_conf";
?>

Undo relative paths as it is causing include errors in traffic


<?php

namespace SilverLeague\Console\Command\Object;

use SilverLeague\Console\Command\SilverStripeCommand;
use SilverLeague\Console\Framework\Utility\ObjectUtilities;
use SilverStripe\Core\Injector\Injector;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Shows which Object is returned from the Injector
 *
 * @package silverstripe-console
 * @author  Robbie Averill <robbie@averill.co.nz>
 */
class LookupCommand extends SilverStripeCommand
{
    use ObjectUtilities;

    /**
     * {@inheritDoc}
     */
    protected function configure()
    {
        $this
            ->setName('object:lookup')
            ->setDescription('Shows which Object is returned from the Injector')
            ->addArgument('object', InputArgument::REQUIRED, 'The Object to look up');
    }

    /**
     * {@inheritDoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $object = $input->getArgument('object');
        $resolvedTo = get_class(Injector::inst()->get($object));

        $output->writeln('<comment>' . $object . '</comment> resolves to <info>' . $resolvedTo . '</info>');
        if ($module = $this->getModuleName($object)) {
            $output->writeln('<info>Module:</info> <comment>' . $module . '</comment>');
        }
    }
}

<?php

namespace SilverLeague\Console\Command\Object;

use SilverLeague\Console\Command\SilverStripeCommand;
use SilverLeague\Console\Framework\Utility\ObjectUtilities;
use SilverStripe\Core\Injector\Injector;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Shows which Object is returned from the Injector
 *
 * @package silverstripe-console
 * @author  Robbie Averill <robbie@averill.co.nz>
 */
class LookupCommand extends SilverStripeCommand
{
    use ObjectUtilities;

    /**
     * {@inheritDoc}
     */
    protected function configure()
    {
        $this
            ->setName('object:lookup')
            ->setDescription('Shows which Object is returned from the Injector')
            ->addArgument('object', InputArgument::REQUIRED, 'The Object to look up');
    }

    /**
     * {@inheritDoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $object = $input->getArgument('object');
        $resolvedTo = get_class(Injector::inst()->get($object));

        $output->writeln('<comment>' . $object . '</comment> resolves to <info>' . $resolvedTo . '</info>');
        if ($module = $this->getModuleName($resolvedTo)) {
            $output->writeln('<info>Module:</info> <comment>' . $module . '</comment>');
        }
    }
}

FIX Return resolved module name rather than original class module name


<?php

final class PhabricatorVeryWowEnglishTranslation
  extends PhutilTranslation {

  public function getLocaleCode() {
    return 'en_W*';
  }

  protected function getTranslations() {
    return array(
      'Search' => 'Search! Wow!',
      'Review Code' => 'Wow! Code Review! Wow!',
      'Tasks and Bugs' => 'Much Bug! Very Bad!',
      'Cancel' => 'Nope!',
      'Advanced Search' => 'Much Search!',
      'No search results.' => 'No results! Wow!',
      'Send' => 'Bark Bark!',
    );
  }

}

<?php

final class PhabricatorVeryWowEnglishTranslation
  extends PhutilTranslation {

  public function getLocaleCode() {
    return 'en_W*';
  }

  protected function getTranslations() {
    return array(
      'Search' => 'Search! Wow!',
      'Review Code' => 'Wow! Code Review! Wow!',
      'Tasks and Bugs' => 'Much Bug! Very Bad!',
      'Cancel' => 'Nope!',
      'Advanced Search' => 'Much Search!',
      'No search results.' => 'No results! Wow!',
      'Send' => 'Bark Bark!',
      'Partial' => 'Pawtial',
      'Partial Upload' => 'Pawtial Upload',
    );
  }

}

Improve translation of some file strings

Summary: Ref T7149. hue hue hue hue

Test Plan: hue hue

Reviewers: chad

Reviewed By: chad

Subscribers: epriestley

Maniphest Tasks: T7149

Differential Revision: https://secure.phabricator.com/D12080


<?php
/**
 * Routes - all standard routes are defined here.
 *
 * @author David Carr - dave@daveismyname.com
 * @version 3.0
 */

use Core\Router;
use Helpers\Hooks;

/** Define static routes. */

// Default Routing
Router::any('', 'App\Controllers\Welcome@index');
Router::any('subpage', 'App\Controllers\Welcome@subPage');

Router::any('admin/(:any)(/(:any)(/(:any)(/(:all))))', array(
    'filters' => 'test',
    'uses'    => 'App\Controllers\Demo@test'
));

// The default Auth Routes.
Router::any('login',  array('filters' => 'guest|csrf', 'uses' => 'App\Controllers\Users@login'));
Router::get('logout', array('filters' => 'auth',       'uses' => 'App\Controllers\Users@logout'));

// The User's Dashboard.
Router::get('dashboard', array('filters' => 'auth', 'uses' => 'App\Controllers\Users@dashboard'));

// The User's Profile.
Router::any('profile', array('filters' => 'auth', 'uses' => 'App\Controllers\Users@profile'));

// The Framework's Language Changer.
Router::any('language/(:any)', 'App\Controllers\Language@change');
/** End default Routes */

/** Module Routes. */
$hooks = Hooks::get();

$hooks->run('routes');
/** End Module Routes. */

<?php
/**
 * Routes - all standard routes are defined here.
 *
 * @author David Carr - dave@daveismyname.com
 * @version 3.0
 */

use Core\Router;
use Helpers\Hooks;

/** Define static routes. */

// Default Routing
Router::any('', 'App\Controllers\Welcome@index');
Router::any('subpage', 'App\Controllers\Welcome@subPage');

Router::any('admin/(:any)(/(:any)(/(:any)(/(:all))))', array(
    'filters' => 'test',
    'uses'    => 'App\Controllers\Demo@test'
));

// The default Auth Routes.
Router::any('login',  array('filters' => 'guest|csrf', 'uses' => 'App\Controllers\Users@login'));
Router::get('logout', array('filters' => 'auth',       'uses' => 'App\Controllers\Users@logout'));

// The User's Dashboard.
Router::get('dashboard', array('filters' => 'auth', 'uses' => 'App\Controllers\Users@dashboard'));

// The User's Profile.
Router::any('profile', array('filters' => 'auth|csrf', 'uses' => 'App\Controllers\Users@profile'));

// The Framework's Language Changer.
Router::any('language/(:any)', 'App\Controllers\Language@change');
/** End default Routes */

/** Module Routes. */
$hooks = Hooks::get();

$hooks->run('routes');
/** End Module Routes. */

Add CSRF filter to '/profile' Route.

Add CSRF filter to '/profile' Route.


<?PHP  // $Id$
       // Authentication by looking up an IMAP server

// This code is completely untested so far  -  IT NEEDS TESTERS!
// Looks like it should work though ...

$CFG->auth_imaphost   = "127.0.0.1";  // Should be IP number
$CFG->auth_imaptype   = "imap";       // imap, imapssl, imapcert
$CFG->auth_imapport   = "143";        // 143, 993

function auth_user_login ($username, $password) {
// Returns true if the username and password work
// and false if they are wrong or don't exist.

    global $CFG;

    switch ($CFG->auth_imaptype) {
        case "imap":
            $host = "{$CFG->auth_imaphost:$CFG->auth_imapport}INBOX";
        break;
        case "imapssl":
            $host = "{$CFG->auth_imaphost:$CFG->auth_imapport/imap/ssl}INBOX";
        break;
        case "imapcert":
            $host = "{$CFG->auth_imaphost:$CFG->auth_imapport/imap/ssl/novalidate-cert}INBOX";
        break;
    }

    if ($connection = imap_open($host, $username, $password, OP_HALFOPEN)) {
        imap_close($connection);
        return true;

    } else {
        return false;
    }
}

?>

<?PHP  // $Id$
       // Authentication by looking up an IMAP server

// This code is completely untested so far  -  IT NEEDS TESTERS!
// Looks like it should work though ...

$CFG->auth_imaphost   = "127.0.0.1";  // Should be IP number
$CFG->auth_imaptype   = "imap";   // imap, imapssl, imapcert
$CFG->auth_imapport   = "143";        // 143, 993
$CFG->auth_imapinfo   = "Just use the same username and password as your school email account";

function auth_user_login ($username, $password) {
// Returns true if the username and password work
// and false if they are wrong or don't exist.

    global $CFG;

    switch ($CFG->auth_imaptype) {
        case "imapssl":
            $host = "\{$CFG->auth_imaphost:$CFG->auth_imapport/imap/ssl}INBOX";
        break;

        case "imapcert":
            $host = "\{$CFG->auth_imaphost:$CFG->auth_imapport/imap/ssl/novalidate-cert}INBOX";
        break;

        default:
            $host = "\{$CFG->auth_imaphost:$CFG->auth_imapport}INBOX";
    }

    if ($connection = imap_open($host, $username, $password, OP_HALFOPEN)) {
        imap_close($connection);
        return true;

    } else {
        return false;
    }
}

?>

Remove { error, and move things around

Remove { error, and move things around


<?php
use PHPUnit\Framework\TestCase;

class DelegatedAuthorizationsTest extends TestCase
{
    public function testDelegatedAuthorizations()
    {
        $profileId = "profileId";

        $args = array(
            "profile_id" => $profileId,
        );

        $http = $this->createMock('HttpRequest');
        $http->expects($this->once())
            ->method('http_post')
            ->with(
                $this->equalTo('https://api.cronofy.com/v1/delegated_authorizations'),
                $this->equalTo($args),
                $this->equalTo(array(
                    'Authorization: Bearer accessToken',
                    'Host: api.cronofy.com',
                    'Content-Type: application/json; charset=utf-8',
                ))
            )
            ->will($this->returnValue(array("", 202)));

        $cronofy = new Cronofy(array(
            "client_id" => "clientId",
            "client_secret" => "clientSecret",
            "access_token" => "accessToken",
            "refresh_token" => "refreshToken",
            "http_client" => $http,
        ));

        $cronofy->request_delegated_authorization($args);
    }
}

<?php
use PHPUnit\Framework\TestCase;

class DelegatedAuthorizationsTest extends TestCase
{
    public function testDelegatedAuthorizations()
    {
        $profileId = "profileId";
        $email = "emailOfAccountToAccess";
        $callback_url = "http://www.example.com/callback";
        $scopes = ["read_events"];
        $state = "user-state";

        $args = array(
            "profile_id" => $profileId,
            "email" => $email,
            "callback_url" => $callback_url,
            "scope" => $scopes,
            "state" => $state
        );

        $http = $this->createMock('HttpRequest');
        $http->expects($this->once())
            ->method('http_post')
            ->with(
                $this->equalTo('https://api.cronofy.com/v1/delegated_authorizations'),
                $this->equalTo($args),
                $this->equalTo(array(
                    'Authorization: Bearer accessToken',
                    'Host: api.cronofy.com',
                    'Content-Type: application/json; charset=utf-8',
                ))
            )
            ->will($this->returnValue(array("", 202)));

        $cronofy = new Cronofy(array(
            "client_id" => "clientId",
            "client_secret" => "clientSecret",
            "access_token" => "accessToken",
            "refresh_token" => "refreshToken",
            "http_client" => $http,
        ));

        $cronofy->request_delegated_authorization($args);
    }
}

Send rest of request params

Send rest of request params


<?php

// Make sure we are called from index.php
if (!defined('SECURITY')) die('Hacking attempt');

if ($setting->getValue('maintenance') && !$user->isAdmin($user->getUserId($_POST['username']))) {
  $_SESSION['POPUP'][] = array('CONTENT' => 'You are not allowed to login during maintenace.', 'TYPE' => 'info');
} else if ($user->checkLogin(@$_POST['username'], @$_POST['password']) ) {
  empty($_POST['to']) ? $to = $_SERVER['PHP_SELF'] : $to = $_POST['to'];
  $port = ($_SERVER["SERVER_PORT"] == "80" or $_SERVER["SERVER_PORT"] == "443") ? "" : (":".$_SERVER["SERVER_PORT"]);
  $location = @$_SERVER['HTTPS'] === true ? 'https://' . $_SERVER['SERVER_NAME'] . $port . $to : 'http://' . $_SERVER['SERVER_NAME'] . $port . $to;
  if (!headers_sent()) header('Location: ' . $location);
  exit('<meta http-equiv="refresh" content="0; url=' . $location . '"/>');
} else if (@$_POST['username'] && @$_POST['password']) {
  $_SESSION['POPUP'][] = array('CONTENT' => 'Unable to login: '. $user->getError(), 'TYPE' => 'errormsg');
}

// Load login template
$smarty->assign('CONTENT', 'default.tpl');
?>

<?php

// Make sure we are called from index.php
if (!defined('SECURITY')) die('Hacking attempt');

if ($setting->getValue('maintenance') && !$user->isAdmin($user->getUserId($_POST['username']))) {
  $_SESSION['POPUP'][] = array('CONTENT' => 'You are not allowed to login during maintenace.', 'TYPE' => 'info');
} else if ($user->checkLogin(@$_POST['username'], @$_POST['password']) ) {
  empty($_POST['to']) ? $to = $_SERVER['PHP_SELF'] : $to = $_POST['to'];
  $port = ($_SERVER["SERVER_PORT"] == "80" or $_SERVER["SERVER_PORT"] == "443") ? "" : (":".$_SERVER["SERVER_PORT"]);
  $location = @$_SERVER['HTTPS'] === true ? 'https://' . $_SERVER['SERVER_NAME'] . $port . $to : 'http://' . $_SERVER['SERVER_NAME'] . $port . $to;
  if (!headers_sent()) header('Location: ' . $location);
  exit('<meta http-equiv="refresh" content="0; url=' . htmlspecialchars($location) . '"/>');
} else if (@$_POST['username'] && @$_POST['password']) {
  $_SESSION['POPUP'][] = array('CONTENT' => 'Unable to login: '. $user->getError(), 'TYPE' => 'errormsg');
}

// Load login template
$smarty->assign('CONTENT', 'default.tpl');
?>

Fix for reflected XSS security issue.

Fix for reflected XSS security issue.