<?php

class Controller_Post extends Controller_Abstract
{
    public function get($postId, $slug = null)
    {
        $post = $this->_getContainer()->Post()->load($postId);

        // While we only need post ID, ensure that we use post slug for SEO
        if ($slug != $post->getSlug()) {
            header("Location: " . $post->getUrl());
        }

        echo $this->_getTwig()->render('post.html.twig', array(
            'session'       => $this->_getSession(),
            'post'          => $post,
            'local_config'  => $this->_getContainer()->LocalConfig(),
        ));
    }
}

<?php

class Controller_Post extends Controller_Abstract
{
    public function get($postId, $slug = null)
    {
        $post = $this->_getContainer()->Post()->load($postId);

        // While we only need post ID, ensure that we use post slug for SEO
        if ($slug != $post->getSlug()) {
            header("Location: " . $post->getUrl(), true, 301);
        }

        echo $this->_getTwig()->render('post.html.twig', array(
            'session'       => $this->_getSession(),
            'post'          => $post,
            'local_config'  => $this->_getContainer()->LocalConfig(),
        ));
    }
}

Make sure we 301 redirect to the slug URL.


<?php
namespace Behapi\Extension\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

use Behat\Behat\EventDispatcher\Event\OutlineTested;
use Behat\Behat\EventDispatcher\Event\ScenarioTested;

use Behapi\Extension\Tools\LastHistory;

/**
 * Listener that cleans everything once a Scenario was finished
 *
 * @author Baptiste Clavié <clavie.b@gmail.com>
 */
class Cleaner implements EventSubscriberInterface
{
    /** @var LastHistory */
    private $history;

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

    /** {@inheritDoc} */
    public static function getSubscribedEvents()
    {
        return [
            OutlineTested::AFTER => 'clear',
            ScenarioTested::AFTER => 'clear'
        ];
    }

    /** Resets the current history of the current client */
    public function clear(): void
    {
        $this->history->reset();
    }
}

<?php
namespace Behapi\Extension\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

use Behat\Behat\EventDispatcher\Event\OutlineTested;
use Behat\Behat\EventDispatcher\Event\ScenarioTested;

use Behapi\Extension\Tools\LastHistory;

/**
 * Listener that cleans everything once a Scenario was finished
 *
 * @author Baptiste Clavié <clavie.b@gmail.com>
 */
class Cleaner implements EventSubscriberInterface
{
    /** @var LastHistory */
    private $history;

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

    /** {@inheritDoc} */
    public static function getSubscribedEvents()
    {
        return [
            OutlineTested::AFTER => ['clear', -99],
            ScenarioTested::AFTER => ['clear', -99]
        ];
    }

    /** Resets the current history of the current client */
    public function clear(): void
    {
        $this->history->reset();
    }
}

Add some priorities on listeners

Add some priorities on listeners


#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

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

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

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

echo "Code coverage was 100%\n";

#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

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

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

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

echo "Code coverage was 100%\n";

Remove --dev from composer install.

Remove --dev from composer install.

--dev is the default.


<?php
namespace Devture\Bundle\UserBundle\Twig;

use Devture\Bundle\UserBundle\AccessControl\AccessControl;

class UserExtension extends \Twig_Extension {

	private $control;

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

	public function getName() {
		return 'devture_user_user_extension';
	}

	public function getFunctions() {
		return array(
			'get_user' => new \Twig_Function_Method($this, 'getUser'),
			'is_logged_in' => new \Twig_Function_Method($this, 'isLoggedIn'),
			'is_granted' => new \Twig_Function_Method($this, 'isGranted'),
		);
	}

	/**
	 * @return \Devture\Bundle\UserBundle\Model\User|NULL
	 */
	public function getUser() {
		return $this->control->getUser();
	}

	/**
	 * @return boolean
	 */
	public function isLoggedIn() {
		return $this->control->isLoggedIn();
	}

	/**
	 * @param string $role
	 * @return boolean
	 */
	public function isGranted($role) {
		return $this->control->isGranted($role);
	}

}

<?php
namespace Devture\Bundle\UserBundle\Twig;

use Devture\Bundle\UserBundle\AccessControl\AccessControl;

class UserExtension extends \Twig_Extension {

	private $control;

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

	public function getName() {
		return 'devture_user_user_extension';
	}

	public function getFunctions() {
		return array(
			new \Twig_SimpleFunction('get_user', array($this, 'getUser')),
			new \Twig_SimpleFunction('is_logged_in', array($this, 'isLoggedIn')),
			new \Twig_SimpleFunction('is_granted', array($this, 'isGranted')),
		);
	}

	/**
	 * @return \Devture\Bundle\UserBundle\Model\User|NULL
	 */
	public function getUser() {
		return $this->control->getUser();
	}

	/**
	 * @return boolean
	 */
	public function isLoggedIn() {
		return $this->control->isLoggedIn();
	}

	/**
	 * @param string $role
	 * @return boolean
	 */
	public function isGranted($role) {
		return $this->control->isGranted($role);
	}

}

Fix deprecated Twig class usage

Fix deprecated Twig class usage


<?php

require_once(dirname(__FILE__)."/../pfccommand.class.php");

class pfcCommand_connect extends pfcCommand
{
  function run(&$xml_reponse, $clientid, $param, $sender, $recipient, $recipientid)
  {
    $c =& $this->c;
    $u =& $this->u;

    // disconnect last connected users from the server if necessary
    $container =& $c->getContainerInstance();
    $disconnected_users = $container->removeObsoleteNick(NULL, $c->timeout);

    // setup some user meta
    $nickid = $container->getNickId($u->nick);
    // store the user ip
    $container->setMeta($_SERVER["REMOTE_ADDR"], "ip", "nickname", $nickid);
    // store the admin flag
    $container->setMeta($c->isadmin, "isadmin", "nickname", $nickid);
    // connect to the server
    $xml_reponse->addScript("pfc.handleResponse('connect', 'ok', '');");

    return $clientid;
  }
}

?>

<?php

require_once(dirname(__FILE__)."/../pfccommand.class.php");

class pfcCommand_connect extends pfcCommand
{
  function run(&$xml_reponse, $clientid, $param, $sender, $recipient, $recipientid)
  {
    $c =& $this->c;
    $u =& $this->u;

    // disconnect last connected users from the server if necessary
    $container =& $c->getContainerInstance();
    $disconnected_users = $container->removeObsoleteNick(NULL, $c->timeout);

    // setup some user meta
    $nickid = $u->nickid;
    // store the user ip
    $container->setMeta($_SERVER["REMOTE_ADDR"], "ip", "nickname", $nickid);
    // store the admin flag
    $container->setMeta($c->isadmin, "isadmin", "nickname", $nickid);
    // connect to the server
    $xml_reponse->addScript("pfc.handleResponse('connect', 'ok', '');");

    return $clientid;
  }
}

?>

Simplify and optimize the code

Simplify and optimize the code

git-svn-id: 14496471c1e7f47aed4ccd4e743787d9efef7a8c@586 2772adf2-ac07-0410-9d30-e29d8120292e


<?php

namespace Alcohol\PasteBundle\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

class ExceptionListener
{
    /**
     * @param GetResponseForExceptionEvent $event
     */
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        $response = new Response($exception->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);

        if ($exception instanceof HttpExceptionInterface) {
            $response->setStatusCode($exception->getStatusCode());
            $response->headers->replace($exception->getHeaders());
        }

        $event->setResponse($response);
    }
}

<?php

namespace Alcohol\PasteBundle\EventListener;

use Predis\Connection\ConnectionException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;

class ExceptionListener
{
    /**
     * @param GetResponseForExceptionEvent $event
     */
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        $response = new Response($exception->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);

        if ($exception instanceof ConnectionException) {
            $exception = new ServiceUnavailableHttpException(300, $exception->getMessage(), $exception);
            $event->setException($exception);
        }

        if ($exception instanceof HttpExceptionInterface) {
            $response->setStatusCode($exception->getStatusCode());
            $response->headers->replace($exception->getHeaders());
        }

        $event->setResponse($response);
    }
}

Return proper response if redis is not available


<?php

namespace Chrisgeary92\Pagespeed;

class Response
{
    /**
     * PageSpeed API response data
     *
     * @var array
     */
    protected $attributes;

    /**
     * Create a new PageSpeed response
     *
     * @param array $attributes
     */
    public function __construct(array $attributes)
    {
        $this->attributes = $attributes;
    }

    /**
     * Return API response from PageSpeed Service
     *
     * @return array
     */
    public function getAttributes()
    {
        return $this->attributes;
    }

    /**
     * Allow public access of $attribute properties
     *
     * @param string $attribute
     * @return mixed
     */
    public function __get($attribute)
    {
        if (array_key_exists($attribute, $this->attributes)) {
            return $this->attributes[$attribute];
        }
    }

    /**
     * Convert $attributes to JSON if cast to a string
     *
     * @return string
     */
    public function __toString()
    {
        return json_encode($this->data);
    }

    /**
     * Return only the $attributes for var_dump()
     *
     * @return array
     */
    public function __debugInfo()
    {
        return $this->getAttributes();
    }
}

<?php

namespace Chrisgeary92\Pagespeed;

class Response
{
    /**
     * PageSpeed API response data
     *
     * @var array
     */
    protected $attributes;

    /**
     * Create a new PageSpeed response
     *
     * @param array $attributes
     */
    public function __construct(array $attributes)
    {
        $this->attributes = $attributes;
    }

    /**
     * Return API response from PageSpeed Service
     *
     * @return array
     */
    public function getAttributes()
    {
        return $this->attributes;
    }

    /**
     * Allow public access of $attribute properties
     *
     * @param string $attribute
     * @return mixed
     */
    public function __get($attribute)
    {
        if (array_key_exists($attribute, $this->attributes)) {
            return $this->attributes[$attribute];
        }
    }

    /**
     * Convert $attributes to JSON if cast to a string
     *
     * @return string
     */
    public function __toString()
    {
        return json_encode($this->attributes);
    }

    /**
     * Return only the $attributes for var_dump()
     *
     * @return array
     */
    public function __debugInfo()
    {
        return $this->getAttributes();
    }
}

Fix incorrectly named property "data" to be "attributes"


<?php
class JSiteConfig extends JConfig
{
	var $sitename = 'Nooku Server - Default';
}
?>

<?php
class JSiteConfig extends JConfig
{
	var $sitename = 'Open Police';
	var $site = "9999";
}
?>

Use 9999 as default site

Use 9999 as default site


<?php

function smarty_compiler_translateStatic($params, Smarty $smarty) {
	/** @var CM_Render $render */
	$render = $smarty->getTemplateVars('render');
	$key = eval('return ' . $params['key'] . ';');

	return $render->getTranslation($key, array());
}

<?php

function smarty_compiler_translateStatic($params, Smarty $smarty) {
	/** @var CM_Render $render */
	$render = $smarty->getTemplateVars('render');
	$key = eval('return ' . $params['key'] . ';');

	return $render->getTranslation($key);
}

t257: Remove unneeded params-argument for Render::getTranslation()


<?php

/**
 * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
 * @package yii2-widgets
 * @subpackage yii2-widget-select2
 * @version 2.0.2
 */

namespace kartik\select2;

use Yii;

/**
 * Asset bundle for Select2 Widget
 *
 * @author Kartik Visweswaran <kartikv2@gmail.com>
 * @since 1.0
 */
class Select2Asset extends \kartik\base\AssetBundle
{
    /**
     * @inheritdoc
     */
    public function init()
    {
        $this->setSourcePath(__DIR__ . '/assets');
        $this->setupAssets('css', ['css/select2']);
        $this->setupAssets('js', ['js/select2.full', 'js/select2-krajee']);
        parent::init();
    }
}

<?php

/**
 * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
 * @package yii2-widgets
 * @subpackage yii2-widget-select2
 * @version 2.0.2
 */

namespace kartik\select2;

use Yii;

/**
 * Asset bundle for Select2 Widget
 *
 * @author Kartik Visweswaran <kartikv2@gmail.com>
 * @since 1.0
 */
class Select2Asset extends \kartik\base\AssetBundle
{
    /**
     * @inheritdoc
     */
    public function init()
    {
        $this->setSourcePath(__DIR__ . '/assets');
        $this->setupAssets('css', ['css/select2']);
        $this->setupAssets('js', ['js/all-krajee', 'js/select2.full', 'js/select2-krajee']);
        parent::init();
    }
}

Add all-krajee.js to Select2 Assets

Add all-krajee.js to Select2 Assets


<?php
namespace LazyRecord\Schema;

// a class alias of SchemaDeclare
// SchemaDeclare should be deprecated now.
class DeclareSchema extends SchemaDeclare { }

<?php
namespace LazyRecord\Schema;

// a class alias of SchemaDeclare
// SchemaDeclare should be deprecated now.
abstract class DeclareSchema extends SchemaDeclare { }

Declare schema class should be abstract

Declare schema class should be abstract


<?php

class EngineBlock_Corto_Filter_Command_PolicyDecisionPoint extends EngineBlock_Corto_Filter_Command_Abstract
{
    /**
     * This command may modify the response attributes
     *
     * @return array
     */
    public function getResponseAttributes()
    {
        return $this->_responseAttributes;
    }

    public function execute()
    {
        if (!$this->_serviceProvider->policyEnforcementDecisionRequired) {
            return;
        }

        EngineBlock_ApplicationSingleton::getLog()->debug(
            "Policy Enforcement Point consult"
        );

        $validator = $this->_getValidator();
        $hasAccess = $validator->hasAccess(
            $this->_collabPersonId,
            $this->_identityProvider->entityId,
            $this->_serviceProvider->entityId,
            $this->_responseAttributes
        );

        if ($hasAccess) {
            return;
        }

        $message = "Policy Decision Point: access denied.";
        if ($validator->getMessage()) {
            $message = $validator->getMessage();
        }

        EngineBlock_ApplicationSingleton::getLog()->debug(
            "Policy Enforcement Point access denied: " . $message
        );
        throw new EngineBlock_Corto_Exception_PEPNoAccess($message);
    }

    /**
     * @return EngineBlock_PolicyDecisionPoint_PepValidator
     */
    protected function _getValidator()
    {
        return new EngineBlock_PolicyDecisionPoint_PepValidator();
    }
}

<?php

class EngineBlock_Corto_Filter_Command_PolicyDecisionPoint extends EngineBlock_Corto_Filter_Command_Abstract
{
    /**
     * This command may modify the response attributes
     *
     * @return array
     */
    public function getResponseAttributes()
    {
        return $this->_responseAttributes;
    }

    public function execute()
    {
        $serviceProvider = EngineBlock_SamlHelper::findRequesterServiceProvider(
            $this->_serviceProvider,
            $this->_request,
            $this->_server->getRepository()
        );

        if (!$serviceProvider) {
            $serviceProvider = $this->_serviceProvider;
        }

        if (!$serviceProvider->policyEnforcementDecisionRequired) {
            return;
        }

        EngineBlock_ApplicationSingleton::getLog()->debug(
            "Policy Enforcement Point consult"
        );

        $validator = $this->_getValidator();
        $hasAccess = $validator->hasAccess(
            $this->_collabPersonId,
            $this->_identityProvider->entityId,
            $serviceProvider->entityId,
            $this->_responseAttributes
        );

        if ($hasAccess) {
            return;
        }

        $message = "Policy Decision Point: access denied.";
        if ($validator->getMessage()) {
            $message = $validator->getMessage();
        }

        EngineBlock_ApplicationSingleton::getLog()->debug(
            "Policy Enforcement Point access denied: " . $message
        );
        throw new EngineBlock_Corto_Exception_PEPNoAccess($message);
    }

    /**
     * @return EngineBlock_PolicyDecisionPoint_PepValidator
     */
    protected function _getValidator()
    {
        return new EngineBlock_PolicyDecisionPoint_PepValidator();
    }
}

Make the PEP pass the actual SP to the PDP in case of a trusted proxy.


<?php
/**
 * Configuration file for the OpenID provider.
 */

$config = array(

	/* The authentication source that should be used. */
	'auth' => 'default-sp',

	/* The name of the attribute which contains the username of the user. */
	'username_attribute' => 'uid',

	/* The directory where OpenID data is stored. */
	'filestore' => '/tmp/ssp-openid-provider',

);

<?php
/**
 * Configuration file for the OpenID provider.
 */

$config = array(

	/* The authentication source that should be used. */
	'auth' => 'default-sp',

	/* The name of the attribute which contains the username of the user. */
	'username_attribute' => 'uid',

	/* The directory where OpenID data is stored. */
	'filestore' => '/var/lib/simplesamlphp-openid-provider',

);

openidProvider: Change the default directory for the data store.

The default configuration uses a directory in /tmp, which may allow
an user to create this directory before simpleSAMLphp attempts to
create it. This can allow the user to overwrite files the webserver has
access to.

This patch changes the default directory.

git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@2084 44740490-163a-0410-bde0-09ae8108e29a


<?php

// skip if people table not generated yet
if (!DB::oneRecord('SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA = SCHEMA() AND TABLE_NAME = "people"')) {
    print("Skipping migration because table doesn't exist yet\n");
    return static::STATUS_SKIPPED;
}

// skip if people table already has AssignedPassword column
if (DB::oneRecord('SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = SCHEMA() AND TABLE_NAME = "people" AND COLUMN_NAME = "AssignedPassword"')) {
    print("Skipping migration because table already has AssignedPassword column\n");
    return static::STATUS_SKIPPED;
}

print("Upgrading people table\n");
DB::nonQuery('ALTER TABLE `people` CHANGE `PasswordClear` `AssignedPassword` VARCHAR(255) NULL DEFAULT NULL');

print("Upgrading history_people table\n");
DB::nonQuery('ALTER TABLE `history_people` CHANGE `PasswordClear` `AssignedPassword` VARCHAR(255) NULL DEFAULT NULL');

return static::STATUS_EXECUTED;

<?php

$skipped = false;

// skip if people table not generated yet
if (!static::tableExists('people')) {
    print("Skipping migration because table `people` doesn't exist yet\n");
    return static::STATUS_SKIPPED;
}

// skip if people table already has AssignedPassword column
if (static::columnExists('people', 'AssignedPassword')) {
    print("Skipping migration because table `people` already has column `AssignedPassword`\n");
    return static::STATUS_SKIPPED;
}

// skip if people table does not have a legacy PasswordClear column to rename
if (!static::columnExists('people', 'PasswordClear')) {
    print("Skipping migration because table `people` does not have legacy column `PasswordClear`\n");
    return static::STATUS_SKIPPED;
}

print("Upgrading people table\n");
DB::nonQuery('ALTER TABLE `people` CHANGE `PasswordClear` `AssignedPassword` VARCHAR(255) NULL DEFAULT NULL');

print("Upgrading history_people table\n");
DB::nonQuery('ALTER TABLE `history_people` CHANGE `PasswordClear` `AssignedPassword` VARCHAR(255) NULL DEFAULT NULL');

return static::STATUS_EXECUTED;

Make assigned-password migration script more robust


<?php

namespace spec\Omniphx\Forrest\Providers\Laravel;

use Illuminate\Config\Repository as Config;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class LaravelSessionSpec extends ObjectBehavior
{
    public function let(Config $config, SessionInterface $session)
    {
        $this->beConstructedWith($config, $session);
    }

    public function it_is_initializable(Config $config)
    {
        $config->get(Argument::any())->shouldBeCalled();
        $this->shouldHaveType('Omniphx\Forrest\Providers\Laravel\LaravelSession');
    }

    public function it_should_allow_a_get(SessionInterface $session)
    {
        $session->has(Argument::any())->shouldBeCalled()->willReturn(true);
        $session->get(Argument::any())->shouldBeCalled();
        $this->get('test');
    }

    public function it_should_allow_a_put(SessionInterface $session)
    {
        $session->set(Argument::any(), Argument::any())->shouldBeCalled();
        $this->put('test', 'value');
    }

    public function it_should_allow_a_has(SessionInterface $session)
    {
        $session->has(Argument::any())->shouldBeCalled();
        $this->has('test');
    }

    public function it_should_throw_an_exception_if_token_does_not_exist(SessionInterface $session)
    {
        $session->has(Argument::any())->shouldBeCalled()->willReturn(false);
        $this->shouldThrow('\Omniphx\Forrest\Exceptions\MissingKeyException')->duringGet('test');
    }
}

<?php

namespace spec\Omniphx\Forrest\Providers\Laravel;

use Illuminate\Config\Repository as Config;
use Illuminate\Contracts\Session\Session as Session;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class LaravelSessionSpec extends ObjectBehavior
{
    public function let(Config $config, Session $session)
    {
        $this->beConstructedWith($config, $session);
    }

    public function it_is_initializable(Config $config)
    {
        $config->get(Argument::any())->shouldBeCalled();
        $this->shouldHaveType('Omniphx\Forrest\Providers\Laravel\LaravelSession');
    }

    public function it_should_allow_a_get(Session $session)
    {
        $session->has(Argument::any())->shouldBeCalled()->willReturn(true);
        $session->get(Argument::any())->shouldBeCalled();
        $this->get('test');
    }

    public function it_should_allow_a_put(Session $session)
    {
        $session->put(Argument::any(), Argument::any())->shouldBeCalled();
        $this->put('test', 'value');
    }

    public function it_should_allow_a_has(Session $session)
    {
        $session->has(Argument::any())->shouldBeCalled();
        $this->has('test');
    }

    public function it_should_throw_an_exception_if_token_does_not_exist(Session $session)
    {
        $session->has(Argument::any())->shouldBeCalled()->willReturn(false);
        $this->shouldThrow('\Omniphx\Forrest\Exceptions\MissingKeyException')->duringGet('test');
    }
}

Fix broken spec tests in Laravel Session implementation


<?php
namespace app\controllers;

use fproject\rest\ActiveController;
use yii\db\ActiveQuery;

class UserController extends ActiveController{
    public $modelClass = 'app\models\User';

    /**
     * Condition to find all resources with relations.
     * Use '@findAllCondition' as the key for client-side condition
     * @param array $params
     * @return ActiveQuery
     */
    public function findAllCondition($params)
    {
        /** @var ActiveQuery $query */
        $query = \Yii::createObject(ActiveQuery::className(), [$this->modelClass]);

        $query->joinWith([
            'profile'=> function ($q) {
                /** @var ActiveQuery $q */
                $q->select('id,phone');
            },
            'department',
        ]);

        return $query;
    }
}

<?php
namespace app\controllers;

use fproject\rest\ActiveController;
use yii\db\ActiveQuery;

class UserController extends ActiveController{
    public $modelClass = 'app\models\User';

    public $useSecureSearch = false;

    /**
     * Condition to find all resources with relations.
     * Use '@findAllCondition' as the key for client-side condition
     * @param array $params
     * @return ActiveQuery
     */
    public function findAllCondition($params)
    {
        /** @var ActiveQuery $query */
        $query = \Yii::createObject(ActiveQuery::className(), [$this->modelClass]);

        $query->joinWith([
            'profile'=> function ($q) {
                /** @var ActiveQuery $q */
                $q->select('id,phone');
            },
            'department',
        ]);

        return $query;
    }
}

Set $useSecureSearch to false to allow full-functional client testing


<?php

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

namespace Sylius\Component\Channel\Model;

use Sylius\Component\Resource\Model\CodeAwareInterface;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;
use Sylius\Component\Resource\Model\ToggleableInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface ChannelInterface extends CodeAwareInterface, TimestampableInterface, ToggleableInterface, ResourceInterface
{
    /**
     * @return string
     */
    public function getName();

    /**
     * @param string $name
     */
    public function setName($name);

    /**
     * @return string
     */
    public function getDescription();

    /**
     * @param string $description
     */
    public function setDescription($description);

    /**
     * @return string
     */
    public function getHostname();

    /**
     * @param string $url
     */
    public function setHostname($hostname);

    /**
     * @return string
     */
    public function getColor();

    /**
     * @param string $color
     */
    public function setColor($color);
}

<?php

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

namespace Sylius\Component\Channel\Model;

use Sylius\Component\Resource\Model\CodeAwareInterface;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;
use Sylius\Component\Resource\Model\ToggleableInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface ChannelInterface extends CodeAwareInterface, TimestampableInterface, ToggleableInterface, ResourceInterface
{
    /**
     * @return string
     */
    public function getName();

    /**
     * @param string $name
     */
    public function setName($name);

    /**
     * @return string
     */
    public function getDescription();

    /**
     * @param string $description
     */
    public function setDescription($description);

    /**
     * @return string
     */
    public function getHostname();

    /**
     * @param string $hostname
     */
    public function setHostname($hostname);

    /**
     * @return string
     */
    public function getColor();

    /**
     * @param string $color
     */
    public function setColor($color);
}

Fix missing parameter in docs of setChannel function


<?php namespace Flarum\Extend;

use Illuminate\Foundation\Application;
use Flarum\Core\Models\Notification;
use Flarum\Core\Models\User;

class NotificationType implements ExtenderInterface
{
    protected $class;

    protected $enabled = [];

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

    public function enableByDefault($method)
    {
        $this->enabled[] = $method;

        return $this;
    }

    public function extend(Application $app)
    {
        $notifier = $app['flarum.notifier'];
        $class = $this->class;

        $notifier->registerType($class);

        Notification::registerType($class);

        foreach ($notifier->getMethods() as $method => $sender) {
            if ($sender::compatibleWith($class)) {
                User::registerPreference(User::notificationPreferenceKey($class::getType(), $method), 'boolval', isset($this->enabled[$method]));
            }
        }
    }
}

<?php namespace Flarum\Extend;

use Illuminate\Foundation\Application;
use Flarum\Core\Models\Notification;
use Flarum\Core\Models\User;

class NotificationType implements ExtenderInterface
{
    protected $class;

    protected $enabled = [];

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

    public function enableByDefault($method)
    {
        $this->enabled[] = $method;

        return $this;
    }

    public function extend(Application $app)
    {
        $notifier = $app['flarum.notifier'];
        $class = $this->class;

        $notifier->registerType($class);

        Notification::registerType($class);

        foreach ($notifier->getMethods() as $method => $sender) {
            if ($sender::compatibleWith($class)) {
                User::registerPreference(User::notificationPreferenceKey($class::getType(), $method), 'boolval', in_array($method, $this->enabled));
            }
        }
    }
}

Fix notification preferences not being enabled by default


<?php

class CRM_Logviewer_Page_LogViewer extends CRM_Core_Page {

  public function run() {
    $this->assign('currentTime', date('Y-m-d H:i:s'));
    $config = CRM_Core_Config::singleton();
    $file_log = CRM_Core_Error::createDebugLogger();
    $logFileName = $file_log->_filename;
    $logFileFormat = $file_log->_lineFormat;
    $file_log->close();
    $this->assign('fileName', $logFileName);
    $entries = array();

    if ($handle = @fopen($logFileName,'r')) {
      $line = 0;
      while (!feof($handle)) {
        $line++;
        $dd = fgets($handle);
        if (strlen($dd) >= 15 && (' ' != $dd[0])) {
          $date = substr($dd,0,15);
          if (preg_match("/^[A-Z][a-z]{2} [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/",$date)) {
            $entry_url = CRM_Utils_System::url('civicrm/admin/logviewer/logentry', $query = 'lineNumber='.$line);
            $entries[$line] = array('lineNumber' => ''.$line.'', 'dateTime' => $date, 'message' => substr($dd,16));
          }
        }
      }
      fclose($handle);
      krsort($entries);
      $this->assign('logEntries', $entries);
    }
    parent::run();
  }

}

<?php

class CRM_Logviewer_Page_LogViewer extends CRM_Core_Page {

  public function run() {
    $this->assign('currentTime', date('Y-m-d H:i:s'));
    $file_log = CRM_Core_Error::createDebugLogger();
    $logFileName = $file_log->_filename;
    $file_log->close();
    $this->assign('fileName', $logFileName);
    $entries = array();

    if ($handle = @fopen($logFileName,'r')) {
      $line = 0;
      while (!feof($handle)) {
        $line++;
        $dd = fgets($handle);
        if (strlen($dd) >= 15 && (' ' != $dd[0])) {
          $date = substr($dd,0,15);
          if (preg_match("/^[A-Z][a-z]{2} [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/",$date)) {
            $entry_url = CRM_Utils_System::url('civicrm/admin/logviewer/logentry', $query = 'lineNumber='.$line);
            $entries[$line] = array('lineNumber' => ''.$line.'', 'dateTime' => $date, 'message' => substr($dd,16));
          }
        }
      }
      fclose($handle);
      krsort($entries);
      $this->assign('logEntries', $entries);
    }
    parent::run();
  }

}

Remove a couple unused variables.

Remove a couple unused variables.


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Core\Repository;

use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Core\Model\TaxonInterface;
use Sylius\Component\Product\Repository\ProductRepositoryInterface as BaseProductRepositoryInterface;

interface ProductRepositoryInterface extends BaseProductRepositoryInterface
{
    /**
     * @param mixed|null $taxonId
     */
    public function createListQueryBuilder(string $locale, $taxonId = null): QueryBuilder;

    public function createShopListQueryBuilder(
        ChannelInterface $channel,
        TaxonInterface $taxon,
        string $locale,
        array $sorting = [],
        bool $includeAllDescendants = false
    ): QueryBuilder;

    public function createListQueryBuilderByChannelAndLocaleCode(ChannelInterface $channel, string $localeCode): QueryBuilder;

    /**
     * @return array|ProductInterface[]
     */
    public function findLatestByChannel(ChannelInterface $channel, string $locale, int $count): array;

    public function findOneByChannelAndSlug(ChannelInterface $channel, string $locale, string $slug): ?ProductInterface;

    public function findOneByCode(string $code): ?ProductInterface;
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Core\Repository;

use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Core\Model\TaxonInterface;
use Sylius\Component\Product\Repository\ProductRepositoryInterface as BaseProductRepositoryInterface;

interface ProductRepositoryInterface extends BaseProductRepositoryInterface
{
    /**
     * @param mixed|null $taxonId
     */
    public function createListQueryBuilder(string $locale, $taxonId = null): QueryBuilder;

    public function createShopListQueryBuilder(
        ChannelInterface $channel,
        TaxonInterface $taxon,
        string $locale,
        array $sorting = [],
        bool $includeAllDescendants = false
    ): QueryBuilder;

    /**
     * @return array|ProductInterface[]
     */
    public function findLatestByChannel(ChannelInterface $channel, string $locale, int $count): array;

    public function findOneByChannelAndSlug(ChannelInterface $channel, string $locale, string $slug): ?ProductInterface;

    public function findOneByCode(string $code): ?ProductInterface;
}

[API][Product] Remove custom product collection data provider in favour of custom product extension


@extends('core::layouts.master')

@section('content-header')

    Dashboard

 {{ trans('core::core.breadcrumb.home') }}

@stop

@section('content')

{{ trans('dashboard::dashboard.welcome-message') }}

@stop

@extends('layouts.master')

@section('content-header')

    Dashboard

 {{ trans('core::core.breadcrumb.home') }}

@stop

@section('content')

{{ trans('dashboard::dashboard.welcome-message') }}

@stop

Extend the admin theme layout

Extend the admin theme layout


<?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
     */
    protected $view = 'tuxedo::templates.alert';

    /**
     * The plain text view to use for the message.
     *
     * @var string
     */
    protected $textView = 'tuxedo::templates.alert-plain';

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

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

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

        return $this;
    }

    /**
     * Set the alert "message" for the message.
     *
     * @param string $text
     * @return $this
     */
    public function text($text)
    {
        $this->text = $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
     */
    protected $view = 'tuxedo::templates.alert';

    /**
     * The plain text view to use for the message.
     *
     * @var string
     */
    protected $textView = 'tuxedo::templates.alert-plain';

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

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

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

        return $this;
    }

    /**
     * Set the alert text for the message.
     *
     * @param $message
     * @return $this
     */
    public function message($message)
    {
        $this->text = $message;

        return $this;
    }
}

Change function name to not interfere with another


<?php

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

namespace Symfony\Component\DomCrawler\Test\Constraint;

use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\DomCrawler\Crawler;

final class CrawlerSelectorAttributeValueSame extends Constraint
{
    private $selector;
    private $attribute;
    private $expectedText;

    public function __construct(string $selector, string $attribute, string $expectedText)
    {
        $this->selector = $selector;
        $this->attribute = $attribute;
        $this->expectedText = $expectedText;
    }

    /**
     * {@inheritdoc}
     */
    public function toString(): string
    {
        return sprintf('has a node matching selector "%s" with attribute "%s" of value "%s"', $this->selector, $this->attribute, $this->expectedText);
    }

    /**
     * @param Crawler $crawler
     *
     * {@inheritdoc}
     */
    protected function matches($crawler): bool
    {
        $crawler = $crawler->filter($this->selector);
        if (!\count($crawler)) {
            return false;
        }

        return $this->expectedText === trim($crawler->getNode(0)->getAttribute($this->attribute));
    }

    /**
     * @param Crawler $crawler
     *
     * {@inheritdoc}
     */
    protected function failureDescription($crawler): string
    {
        return 'the Crawler '.$this->toString();
    }
}

<?php

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

namespace Symfony\Component\DomCrawler\Test\Constraint;

use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\DomCrawler\Crawler;

final class CrawlerSelectorAttributeValueSame extends Constraint
{
    private $selector;
    private $attribute;
    private $expectedText;

    public function __construct(string $selector, string $attribute, string $expectedText)
    {
        $this->selector = $selector;
        $this->attribute = $attribute;
        $this->expectedText = $expectedText;
    }

    /**
     * {@inheritdoc}
     */
    public function toString(): string
    {
        return sprintf('has a node matching selector "%s" with attribute "%s" of value "%s"', $this->selector, $this->attribute, $this->expectedText);
    }

    /**
     * @param Crawler $crawler
     *
     * {@inheritdoc}
     */
    protected function matches($crawler): bool
    {
        $crawler = $crawler->filter($this->selector);
        if (!\count($crawler)) {
            return false;
        }

        return $this->expectedText === trim($crawler->attr($this->attribute));
    }

    /**
     * @param Crawler $crawler
     *
     * {@inheritdoc}
     */
    protected function failureDescription($crawler): string
    {
        return 'the Crawler '.$this->toString();
    }
}

[FrameworkBundle] Allow to use the BrowserKit assertions with Panther and API Platform's test client


<?php

namespace DreamFactory\Core\Events;

use DreamFactory\Core\Contracts\ServiceRequestInterface;
use DreamFactory\Core\Contracts\ServiceResponseInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ApiEvent extends ServiceEvent
{
    public $request;

    public $response;

    /**
     * Create a new event instance.
     *
     * @param string                        $path
     * @param ServiceRequestInterface       $request
     * @param ServiceResponseInterface|null $response
     * @param mixed                         $resource
     */
    public function __construct($path, $request, $response = null, $resource = null)
    {
        $this->request = $request;
        $this->response = $response;
        $name = strtolower($path . '.' . $request->getMethod());
        parent::__construct($name, $resource);
    }

    public function makeData()
    {
        $response = (empty($this->response) || $this->response instanceof RedirectResponse ||
            $this->response instanceof StreamedResponse)
            ? [] : $this->response->toArray();

        return array_merge(parent::makeData(),
            [
                'request'  => $this->request->toArray(),
                'response' => $response
            ]
        );
    }
}

<?php

namespace DreamFactory\Core\Events;

use DreamFactory\Core\Contracts\ServiceRequestInterface;
use DreamFactory\Core\Contracts\ServiceResponseInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ApiEvent extends ServiceEvent
{
    public $request;

    public $response;

    /**
     * Create a new event instance.
     *
     * @param string                        $path
     * @param ServiceRequestInterface       $request
     * @param ServiceResponseInterface|null $response
     * @param mixed                         $resource
     */
    public function __construct($path, $request, $response = null, $resource = null)
    {
        $this->request = $request;
        $this->response = $response;

        if (empty($resource)) {
            $name = strtolower($path . '.' . $request->getMethod());
        } else {
            $name = strtolower($path . '.' . $resource . '.' . $request->getMethod());
        }
        parent::__construct($name, $resource);
    }

    public function makeData()
    {
        $response = (empty($this->response) || $this->response instanceof RedirectResponse ||
            $this->response instanceof StreamedResponse)
            ? [] : $this->response->toArray();

        return array_merge(parent::makeData(),
            [
                'request'  => $this->request->toArray(),
                'response' => $response
            ]
        );
    }
}

Fix scripting for remote web services.

Fix scripting for remote web services.


<?php
/*
 * This file is part of phpnsc.
 *
 * (c) ResearchGate GmbH <bastian.hofmann@researchgate.net>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace rg\tools\phpnsc;

class NamespaceString
{
    private $namespaceVendor;
    private $root;
    private $fullFilePath;

    public function __construct($namespaceVendor, $root, $fullFilePath)
    {
        $this->namespaceVendor = $namespaceVendor;
        $this->root = $root;
        $this->fullFilePath = $fullFilePath;
    }

    public function getNamespace()
    {
        $namespace = '';
        $relativePath = str_replace($this->root, '', $this->fullFilePath);
        $relativePathParts = explode('/', $relativePath);
        for ($i = 1; $i < count($relativePathParts) - 1; ++$i) {
            $namespace .= '\\'.$relativePathParts[$i];
        }

        if ($this->namespaceVendor) {
            return $this->namespaceVendor.$namespace;
        }

        return trim($namespace, '\\');
    }

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

<?php
/*
 * This file is part of phpnsc.
 *
 * (c) ResearchGate GmbH <bastian.hofmann@researchgate.net>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace rg\tools\phpnsc;

class NamespaceString
{
    private $namespaceVendor;
    private $root;
    private $fullFilePath;

    public function __construct($namespaceVendor, $root, $fullFilePath)
    {
        $this->namespaceVendor = $namespaceVendor;
        $this->root = $root;
        $this->fullFilePath = $fullFilePath;
    }

    public function getNamespace()
    {
        $namespace = '';
        $relativePath = str_replace($this->root, '', $this->fullFilePath);
        $relativePathParts = explode(DIRECTORY_SEPARATOR, $relativePath);
        for ($i = 1; $i < count($relativePathParts) - 1; ++$i) {
            $namespace .= '\\'.$relativePathParts[$i];
        }

        if ($this->namespaceVendor) {
            return $this->namespaceVendor.$namespace;
        }

        return trim($namespace, '\\');
    }

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

Fix issue with Windows file paths

Fix issue with Windows file paths


<?php

/**
 * Output library
 * @author M2Mobi, Heinz Wiesinger
 */
class Output
{

    /**
     * Constructor
     */
    public function __construct()
    {

    }

    /**
     * Destructor
     */
    public function __destruct()
    {

    }

    /**
     * Print given message immediatly
     * @param String $msg Message to print
     * @return void
     */
    public static function cli_print($msg)
    {
        require_once("class.m2datetime.inc.php");
        echo M2DateTime::get_datetime() . ": " . $msg;
    }

    /**
     * Print status information ([ok] or [failed])
     * @param String $msg Message to print
     * @return void
     */
    public static function cli_print_status($bool)
    {
        require_once("class.m2datetime.inc.php");
        if ($bool === TRUE)
        {
            echo "[ok]\n";
        }
        else
        {
            echo "[failed]\n";
        }
    }

    /**
     * Print given message immediatly
     * @param String $msg Message to print
     * @return void
     */
    public static function cli_println($msg)
    {
        require_once("class.m2datetime.inc.php");
        echo M2DateTime::get_datetime() . ": " . $msg . "\n";
    }

}

?>

<?php

/**
 * Output library
 * @author M2Mobi, Heinz Wiesinger
 */
class Output
{

    /**
     * Constructor
     */
    public function __construct()
    {

    }

    /**
     * Destructor
     */
    public function __destruct()
    {

    }

    /**
     * Print given message immediatly
     * @param String $msg Message to print
     * @return void
     */
    public static function cli_print($msg)
    {
        require_once("class.m2datetime.inc.php");
        echo M2DateTime::get_datetime() . ": " . $msg;
    }

    /**
     * Print status information ([ok] or [failed])
     * @param String $msg Message to print
     * @return void
     */
    public static function cli_print_status($bool)
    {
        require_once("class.m2datetime.inc.php");
        if ($bool === TRUE)
        {
            echo "[ok]\n";
        }
        else
        {
            echo "[failed]\n";
        }
    }

    /**
     * Print given message immediatly
     * @param String $msg Message to print
     * @return void
     */
    public static function cli_println($msg)
    {
        require_once("class.m2datetime.inc.php");
        echo M2DateTime::get_datetime() . ": " . $msg . "\n";
    }

    /**
     * Trigger a PHP error
     * @param String $info The error string that should be printed
     * @return void
     */
    public static function error($info)
    {
        if (isset($_GET['controller']) && isset($_GET['method']))
        {
            trigger_error($_GET['controller'] . "/" . $_GET['method'] . ": " . $info);
        }
        else
        {
            trigger_error($info);
        }
    }

}

?>

Add error() function to Output class

application: Add error() function to Output class


<?php
/*
  $Id$

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2002 osCommerce

  Released under the GNU General Public License
*/

define('HEADING_TITLE', 'Server Information');

define('TITLE_SERVER_HOST', 'Server Host:');
define('TITLE_SERVER_OS', 'Server OS:');
define('TITLE_SERVER_DATE', 'Server Date:');
define('TITLE_SERVER_UP_TIME', 'Server Up Time:');
define('TITLE_HTTP_SERVER', 'HTTP Server:');
define('TITLE_PHP_VERSION', 'PHP Version:');
define('TITLE_ZEND_VERSION', 'Zend:');
define('TITLE_DATABASE_HOST', 'Database Host:');
define('TITLE_DATABASE', 'Database:');
define('TITLE_DATABASE_DATE', 'Datebase Date:');

define('TEXT_EXPORT_INTRO', 'The following information can be submitted to osCommerce by clicking on the Send button. You can also save the information to a file by clicking Save. This information is totally anonymous and cannot be used to identify an individual system. It will be used for support and development purposes only.');
define('TEXT_EXPORT_INFO', 'Export Server Information');

define('SUCCESS_INFO_SUBMIT', 'Your information has been submitted sucessfully.');
define('ERROR_INFO_SUBMIT', 'Could not connect to the osCommerce website to submit your configuration. Please try again later');

?>

<?php
/*
  $Id$

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2002 osCommerce

  Released under the GNU General Public License
*/

define('HEADING_TITLE', 'Server Information');

define('TITLE_SERVER_HOST', 'Server Host:');
define('TITLE_SERVER_OS', 'Server OS:');
define('TITLE_SERVER_DATE', 'Server Date:');
define('TITLE_SERVER_UP_TIME', 'Server Up Time:');
define('TITLE_HTTP_SERVER', 'HTTP Server:');
define('TITLE_PHP_VERSION', 'PHP Version:');
define('TITLE_ZEND_VERSION', 'Zend:');
define('TITLE_DATABASE_HOST', 'Database Host:');
define('TITLE_DATABASE', 'Database:');
define('TITLE_DATABASE_DATE', 'Database Date:');

define('TEXT_EXPORT_INTRO', 'The following information can be submitted to osCommerce by clicking on the Send button. You can also save the information to a file by clicking Save. This information is totally anonymous and cannot be used to identify an individual system. It will be used for support and development purposes only.');
define('TEXT_EXPORT_INFO', 'Export Server Information');

define('SUCCESS_INFO_SUBMIT', 'Your information has been submitted sucessfully.');
define('ERROR_INFO_SUBMIT', 'Could not connect to the osCommerce website to submit your configuration. Please try again later');

?>

Fix bug OSC-1094 - Incorrect spelling of database


<?php

use Phinx\Migration\AbstractMigration;

class AddUidToDocuments extends AbstractMigration
{
		public function change()
		{
			$strategy = defined('ORM_UID_STRATEGY') && ORM_UID_STRATEGY == 'mysql' ? 'mysql' : 'php';
			$table = $this->table('documents');
			$table->addColumn("uid", "string")
					->update();

			$docs = Document::all();
			if(!empty($docs)){
				foreach($docs as $d){
					$path_elems = explode('/', $d->path);
					if(!empty($path_elems)){
						$file = array_pop($path_elems);
						$uid = substr($file, 0, strlen($file) - (strlen($d->extension) + 1) );
						$d->uid = $uid;
						$d->save();
					}
					else{
						continue;
					}
				}
			}
		}
}

<?php

use Phinx\Migration\AbstractMigration;
use Pragma\Docs\Models\Document;

class AddUidToDocuments extends AbstractMigration
{
		public function change()
		{
			$strategy = defined('ORM_UID_STRATEGY') && ORM_UID_STRATEGY == 'mysql' ? 'mysql' : 'php';
			$table = $this->table('documents');
			$table->addColumn("uid", "string")
					->update();

			$docs = Document::all();
			if(!empty($docs)){
				foreach($docs as $d){
					$path_elems = explode('/', $d->path);
					if(!empty($path_elems)){
						$file = array_pop($path_elems);
						$uid = substr($file, 0, strlen($file) - (strlen($d->extension) + 1) );
						$d->uid = $uid;
						$d->save();
					}
					else{
						continue;
					}
				}
			}
		}
}

Fix Document class unknown in migration

Fix Document class unknown in migration


<?php

/**
 * @package         Billing
 * @copyright       Copyright (C) 2012-2016 BillRun Technologies Ltd. All rights reserved.
 * @license         GNU Affero General Public License Version 3; see LICENSE.txt
 */

/**
 * Charge action controller class
 *
 * @package     Controllers
 * @subpackage  Action
 */
class ChargeAction extends Action_Base {

	/**
	 * method to execute the pay process for payment gateways.
	 * it's called automatically by the cli main controller
	 */
	public function execute() {
		$possibleOptions = array(
			'stamp' => true,
		);

		if (($options = $this->_controller->getInstanceOptions($possibleOptions)) === FALSE) {
			return;
		}

		$extraParams = $this->_controller->getParameters();
		if (!empty($extraParams)) {
			$options = array_merge($extraParams, $options);
		}
		Billrun_Bill_Payment::checkPendingStatus($options);
		if (!isset($options['pending'])) {
			$this->getController()->addOutput("Starting to charge unpaid payments");
			Billrun_Bill_Payment::makePayment($options);
			$this->getController()->addOutput("Charging Done");
		}
	}

}

<?php

/**
 * @package         Billing
 * @copyright       Copyright (C) 2012-2016 BillRun Technologies Ltd. All rights reserved.
 * @license         GNU Affero General Public License Version 3; see LICENSE.txt
 */

/**
 * Charge action controller class
 *
 * @package     Controllers
 * @subpackage  Action
 */
class ChargeAction extends Action_Base {

	/**
	 * method to execute the pay process for payment gateways.
	 * it's called automatically by the cli main controller
	 */
	public function execute() {
		$possibleOptions = array(
			'stamp' => true,
		);

		if (($options = $this->_controller->getInstanceOptions($possibleOptions)) === FALSE) {
			return;
		}

		$extraParams = $this->_controller->getParameters();
		if (!empty($extraParams)) {
			$options = array_merge($extraParams, $options);
		}
		$this->getController()->addOutput("Checking pending payments...");
		Billrun_Bill_Payment::checkPendingStatus($options);
		if (!isset($options['pending'])) {
			$this->getController()->addOutput("Starting to charge unpaid payments...");
			Billrun_Bill_Payment::makePayment($options);
		}
		$this->getController()->addOutput("Charging Done");
	}

}

Modify some charge action messages

Modify some charge action messages


<?php

namespace TomPHP\HalClient;

use TomPHP\HalClient\Exception\UnknownContentTypeException;
use Assert\Assertion;

final class Client implements ResourceFetcher
{
    /** @var HttpClient */
    private $httpClient;

    /** @var Processor[] */
    private $processors;

    /** @param Processor[] $processors */
    public function __construct(HttpClient $httpClient, array $processors)
    {
        Assertion::allIsInstanceOf($processors, Processor::class);

        $this->httpClient = $httpClient;

        foreach ($processors as $processor) {
            $this->processors[$processor->getContentType()] = $processor;
        }
    }

    public function get($url)
    {
        $response = $this->httpClient->get($url);

        $contentType = $response->getHeader('content-type');

        if (!array_key_exists($contentType, $this->processors)) {
            throw new UnknownContentTypeException($contentType);
        }

        $processor = $this->processors[$contentType];

        return $processor->process($response, $this);
    }
}

<?php

namespace TomPHP\HalClient;

use TomPHP\HalClient\Exception\UnknownContentTypeException;
use Assert\Assertion;

final class Client implements ResourceFetcher
{
    /** @var HttpClient */
    private $httpClient;

    /** @var Processor[] */
    private $processors;

    /** @return self */
    public static function create()
    {
        return new self(new GuzzleHttpClient(), [new HalJsonProcessor()]);
    }

    /** @param Processor[] $processors */
    public function __construct(HttpClient $httpClient, array $processors)
    {
        Assertion::allIsInstanceOf($processors, Processor::class);

        $this->httpClient = $httpClient;

        foreach ($processors as $processor) {
            $this->processors[$processor->getContentType()] = $processor;
        }
    }

    public function get($url)
    {
        $response = $this->httpClient->get($url);

        $contentType = $response->getHeader('content-type');

        if (!array_key_exists($contentType, $this->processors)) {
            throw new UnknownContentTypeException($contentType);
        }

        $processor = $this->processors[$contentType];

        return $processor->process($response, $this);
    }
}

Add create() method to give recommended config


<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Advent of Code</title>

Advent of Code Solutions

<?php for($i = 1; $i <= 25; $i++) : ?>

<a href="day<?php printf('%02d', $i); ?>/part1.php">Part 1 <a href="day<?php printf('%02d', $i); ?>/part2.php">Part 2

<?php endfor; ?>

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Advent of Code</title>

Advent of Code Solutions

<?php for($i = 1; $i <= 24; $i++) : ?>

<a href="day<?php printf('%02d', $i); ?>/part1.php">Part 1 <a href="day<?php printf('%02d', $i); ?>/part2.php">Part 2

<?php endfor; ?>

Part 1

Remove day 25 part 2 link

Remove day 25 part 2 link


<?php
namespace Concrete\Core\File\ImportProcessor;

use Concrete\Core\Entity\File\Version;

interface ProcessorInterface
{
    public function shouldProcess(Version $version);
    public function process(Version $version);
}

<?php

namespace Concrete\Core\File\ImportProcessor;

use Concrete\Core\Entity\File\Version;

/**
 * The interface that file processors should implement.
 */
interface ProcessorInterface
{
    /**
     * Should this processor process a specific file version?
     *
     * @param \Concrete\Core\Entity\File\Version $version
     *
     * @return bool
     */
    public function shouldProcess(Version $version);

    /**
     * Process a specific file version.
     *
     * @param \Concrete\Core\Entity\File\Version $version
     *
     * @throws \Exception in case of errors
     */
    public function process(Version $version);
}

Add PHPDoc to file import processor interface


<?php

class Denkmal_Elasticsearch_Type_Song extends CM_Elastica_Type_Abstract {

    const INDEX_NAME = 'song';

    protected $_mapping = array(
        'label' => array('type' => 'string'),
    );

    protected $_indexParams = array(
        'index' => array(
            'number_of_shards'   => 1,
            'number_of_replicas' => 0
        ),
    );

    protected function _getQuery($ids = null, $limit = null) {
        $query = '
            SELECT song.id, song.label
			FROM `denkmal_model_song` song
	    ';

        if (is_array($ids)) {
            $query .= ' WHERE song.id IN (' . implode(',', $ids) . ')';
        }
        if (($limit = (int) $limit) > 0) {
            $query .= ' LIMIT ' . $limit;
        }
        return $query;
    }

    protected function _getDocument(array $data) {
        $doc = new Elastica_Document($data['id'],
            array(
                'label' => $data['label'],
            )
        );
        return $doc;
    }

    /**
     * @param Denkmal_Model_Song $item
     * @return int
     */
    protected static function _getIdForItem($item) {
        return $item->getId();
    }
}

<?php

class Denkmal_Elasticsearch_Type_Song extends CM_Elastica_Type_Abstract {

    const INDEX_NAME = 'song';

    protected $_mapping = array(
        'label' => array('type' => 'string'),
    );

    protected $_indexParams = array(
        'index' => array(
            'number_of_shards'   => 1,
            'number_of_replicas' => 0
        ),
    );

    protected function _getQuery($ids = null, $limit = null) {
        $query = '
            SELECT `song`.*
			      FROM `denkmal_model_song` `song`
        ';

        if (is_array($ids)) {
            $query .= ' WHERE song.id IN (' . implode(',', $ids) . ')';
        }
        if (($limit = (int) $limit) > 0) {
            $query .= ' LIMIT ' . $limit;
        }
        return $query;
    }

    protected function _getDocument(array $data) {
        $doc = new Elastica_Document($data['id'],
            array(
                'label' => $data['label'],
            )
        );
        return $doc;
    }

    /**
     * @param Denkmal_Model_Song $item
     * @return int
     */
    protected static function _getIdForItem($item) {
        return $item->getId();
    }
}

Select all fields from from table in song type


<?php

namespace Daruwanov\Provider;

use Silex\Application;
use Silex\ServiceProviderInterface;
use Mandrill;
use Mandrill_Messages;

/*
 * MandrillServiceProvider
 */
class MandrillMessagesServiceProvider implements ServiceProviderInterface
{
    /*
     * register
     */
    public function register(Application $app)
    {
        $app['mandrill.messages'] = $app->share(function() use ($app) {
            if(isset($app['mandrill']) && is_array($app['mandrill'])) {
                $mandrill = new Mandrill($app['mandrill']['password']);
                $mandrillMessages = new  Mandrill_Messages($mandrill);
            }
            else {
              throw new \Exception("Bas");
            }
            return $mandrillMessages;
        });
    }

    public function boot(Application $app)
    {

    }
}

<?php

namespace Daruwanov\Provider;

use Silex\Application;
use Silex\ServiceProviderInterface;
use Mandrill;
use Mandrill_Messages;

/*
 * MandrillServiceProvider
 */
class MandrillMessagesServiceProvider implements ServiceProviderInterface
{
    /*
     * register
     */
    public function register(Application $app)
    {
        $app['mandrill.messages'] = $app->share(function() use ($app) {
            if(isset($app['mandrill']) && is_array($app['mandrill'])) {
                $mandrill = new Mandrill($app['mandrill']['password']);
                $mandrillMessages = new  Mandrill_Messages($mandrill);
            }
            else {
              throw new \Exception("Error: Array key 'mandrill' does not exist or input data not Array");
            }
            return $mandrillMessages;
        });
    }

    public function boot(Application $app)
    {

    }
}

Add Error title if Service does not register success.


<?php

namespace Radebatz\ACache\Tests\Decorators\Psr;

use Cache\IntegrationTests\CachePoolTest;
use Radebatz\ACache\ApcCache;
use Radebatz\ACache\ArrayCache;
use Radebatz\ACache\Decorators\Psr\CacheItemPool;

if (version_compare(phpversion(), '5.4.0', 'ge') && class_exists('\Cache\IntegrationTests\CachePoolTest')) {

/**
 * Additional Psr integration tests.
 */
class IntegrationTest extends CachePoolTest
{
    /*
     * {@inheritdoc}
     */
    public function createCachePool()
    {
        return new CacheItemPool(new ApcCache());
        return new CacheItemPool(new ArrayCache());
    }
}

} else {

/**
 * Dummy Psr integration tests.
 */
class IntegrationTest extends \PHPUnit_Framework_TestCase
{
    public function testDummy()
    {
        $this->assertTrue(true);
    }
}

}

<?php

namespace Radebatz\ACache\Tests\Decorators\Psr;

use Cache\IntegrationTests\CachePoolTest;
use Radebatz\ACache\ArrayCache;
use Radebatz\ACache\Decorators\Psr\CacheItemPool;

if (version_compare(phpversion(), '5.4.0', 'ge') && class_exists('\Cache\IntegrationTests\CachePoolTest')) {

/**
 * Additional Psr integration tests.
 */
class IntegrationTest extends CachePoolTest
{
    /*
     * {@inheritdoc}
     */
    public function createCachePool()
    {
        return new CacheItemPool(new ArrayCache(array(), true));
    }
}

} else {

/**
 * Dummy Psr integration tests.
 */
class IntegrationTest extends \PHPUnit_Framework_TestCase
{
    public function testDummy()
    {
        $this->assertTrue(true);
    }
}

}

Use ArrayCache for integration tests

Use ArrayCache for integration tests


<?php

/*
 * This file is part of the Limenius\Liform package.
 *
 * (c) Limenius <https://github.com/Limenius/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Limenius\Liform\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\FormType;

/**
 * Adds a 'liform' configuration option to instances of FormType
 *
 * @author Nacho Martín <nacho@limenius.com>
 */
class AddLiformExtension extends AbstractTypeExtension
{
    /**
     * Returns the name of the type being extended.
     *
     * @return string
     */
    public function getExtendedType()
    {
        return FormType::class;
    }

    /**
     * Add the liform option
     *
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefined(['liform']);
    }
}

<?php

/*
 * This file is part of the Limenius\Liform package.
 *
 * (c) Limenius <https://github.com/Limenius/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Limenius\Liform\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\FormType;

/**
 * Adds a 'liform' configuration option to instances of FormType
 *
 * @author Nacho Martín <nacho@limenius.com>
 */
class AddLiformExtension extends AbstractTypeExtension
{
    /**
     * Returns the name of the type being extended.
     *
     * @return string
     */
    public function getExtendedType()
    {
        return FormType::class;
    }

    /**
     * {@inheritdoc}
     */
    public static function getExtendedTypes(): iterable
    {
        return [FormType::class];
    }

    /**
     * Add the liform option
     *
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefined(['liform']);
    }
}

Fix deprecation warning in Symfony 4.2

Fix deprecation warning in Symfony 4.2

This addresses `Not implementing the static getExtendedTypes() method in Limenius\Liform\Form\Extension\AddLiformExtension when implementing the Symfony\Component\Form\FormTypeExtensionInterface is deprecated since Symfony 4.2. The method will be added to the interface in 5.0.`


<?php

namespace App\Http\Requests;

class ContactFormRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = ['firstname'  => 'required|min:3',
                    'lastname' => 'required|min:3',
                    'gender'   => 'required|max:1',
                    #'mobile' => 'phone',
                    #'mobile_country' => 'required_with:mobile|size:2' /* FIXME: LENGHT MUST BE EXACT 2 */
                ];

        switch ($this->method()) {
            case 'PATCH':
            case 'PUT':
            case 'POST':
                return $rules;
                break;
            default:
                return [];
                break;
        }
    }
}

<?php

namespace App\Http\Requests;

class ContactFormRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = ['firstname' => 'required|min:3',
                    'lastname' => 'required|min:3',
                    'gender' => 'required|max:1',
                    'birthdate' => 'date_format:'.trans('app.dateformat.carbon'),
                    #'mobile' => 'phone',
                    #'mobile_country' => 'required_with:mobile|size:2' /* FIXME: LENGHT MUST BE EXACT 2 */
                ];

        switch ($this->method()) {
            case 'PATCH':
            case 'PUT':
            case 'POST':
                return $rules;
                break;
            default:
                return [];
                break;
        }
    }
}

Add birthdate localized format input validation


<?php

namespace App\Libraries\Parser;

interface ParserInterface
{
    public function __construct(array $request);

    public function parse();

    public function getEvent();

    public function getAttachment();

    public function getRawRequest();

    public function buildSlackAttachment();

    public function getSuscribers();
}

<?php

namespace App\Libraries\Parser;

use App\Libraries\Slack\SlackAttachment;

interface ParserInterface
{
    public function __construct(array $request);

    public function parse();

    public function getEvent(): string;

    public function getAttachment(): SlackAttachment;

    public function getRawRequest(): array;

    public function buildSlackAttachment();

    public function getSuscribers(): array;
}

Add return type to functions

Add return type to functions


<?php

namespace Oro\Bundle\SecurityBundle\Acl\Cache;

use Doctrine\Common\Cache\FilesystemCache as BaseFilesystemCache;

/**
 * The aim of this class is just modify an algorithm is used to generate file names
 * to avoid very long file names. We can do not use additional sha256 encoding used
 * in the original FilesystemCache class because $id passed to getFilename is quite unique itself.
 */
class FilesystemCache extends BaseFilesystemCache
{
    /**
     * {@inheritdoc}
     */
    protected function getFilename($id)
    {
        $id = preg_replace('@[\\\/:"*?<>|]+@', '', $id);

        return $this->directory . DIRECTORY_SEPARATOR . $id . $this->extension;
    }
}

<?php

namespace Oro\Bundle\SecurityBundle\Acl\Cache;

use Doctrine\Common\Cache\FilesystemCache as BaseFilesystemCache;

/**
 * The aim of this class is just modify an algorithm is used to generate file names
 * to avoid very long file names. We can do not use additional sha256 encoding used
 * in the original FilesystemCache class because $id passed to getFilename is quite unique itself.
 */
class FilesystemCache extends BaseFilesystemCache
{
    /**
     * {@inheritdoc}
     */
    protected function getFilename($id)
    {
        $id = preg_replace('@[\\\/:"*?<>|]+@', '', $id);

        return $this->directory . DIRECTORY_SEPARATOR . $id . self::EXTENSION;
    }
}

PIM-4035: Fix deprecated use of extension property (doctrine 2.5)


@if (Session::has('flashNotification.message'))
@if (Session::has('flashNotification.modal'))
@include('partials.modal', ['modalClass' => 'flashModal', 'title' => 'Notice', 'body' => Session::get('flashNotification.message')])
@else

		<button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>

{{ Session::get('flashNotification.message') }}

@endif

@if (Session::get('flashNotification.autoHide'))

@endif

<?php
	Session::forget('flashNotification.message');
    Session::forget('flashNotification.modal');
    Session::forget('flashNotification.autoHide');
?>
@endif

@if (Session::has('flashNotification.message'))
@if (Session::has('flashNotification.modal'))
@include('partials.modal', ['modalClass' => 'flashModal', 'title' => 'Notice', 'body' => Session::get('flashNotification.message')])
@else

		<button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>

{!! session('flashNotification.message') !!}

@endif

@if (Session::get('flashNotification.autoHide'))

@endif

<?php
	Session::forget('flashNotification.message');
    Session::forget('flashNotification.modal');
    Session::forget('flashNotification.autoHide');
?>
@endif

Update output to render HTML

Update output to render HTML

Fixes #2


<!DOCTYPE html>
<html lang="<?php echo $sf_user->getCulture() ?>"<?php if ('rtl' == sfCultureInfo::getInstance($sf_user->getCulture())->direction): ?> dir="rtl"<?php endif; ?>>

    <?php include_http_metas() ?>
    <?php include_metas() ?>
    <?php include_title() ?>
    <link rel="shortcut icon" href="<?php echo public_path('favicon.ico') ?>"/>
    <?php include_stylesheets() ?>
    <?php if ($sf_context->getConfiguration()->isDebug()): ?>

    <?php endif; ?>
    <?php include_javascripts() ?>

  <body class="<?php echo $sf_context->getModuleName() ?> <?php echo $sf_context->getActionName() ?>">

    <?php echo get_partial('header') ?>

      <?php echo $sf_content ?>

    <?php echo get_partial('footer') ?>

      <?php echo get_component('default', 'updateCheck') ?>

      <?php echo __('Printed: %d%', array('%d%' => date('Y-m-d'))) ?>

<!DOCTYPE html>
<html lang="<?php echo $sf_user->getCulture() ?>"<?php if ('rtl' == sfCultureInfo::getInstance($sf_user->getCulture())->direction): ?> dir="rtl"<?php endif; ?>>

    <?php include_http_metas() ?>
    <?php include_metas() ?>
    <?php include_title() ?>
    <link rel="shortcut icon" href="<?php echo public_path('favicon.ico') ?>"/>
    <?php include_stylesheets() ?>
    <?php if ($sf_context->getConfiguration()->isDebug()): ?>

    <?php endif; ?>
    <?php include_javascripts() ?>

  <body class="<?php echo $sf_context->getModuleName() ?> <?php echo $sf_context->getActionName() ?> user-<?php echo $sf_user->isAuthenticated() ? 'logged' : 'anonymous' ?>">

    <?php echo get_partial('header') ?>

      <?php echo $sf_content ?>

    <?php echo get_partial('footer') ?>

      <?php echo get_component('default', 'updateCheck') ?>

      <?php echo __('Printed: %d%', array('%d%' => date('Y-m-d'))) ?>

Add class to body tag to mark user status


<?php
/**
 * PHP version 5.6
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace Ewallet\Bridges\Tests;

use Money\Money;

trait ProvidesMoneyMatcher
{
    public function getMatchers()
    {
        return [
            'amount' => function(Money $subject, $value) {
                return $subject->getAmount() === $value;
            }
        ];
    }
}

<?php
/**
 * PHP version 5.6
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace Ewallet\Bridges\Tests;

use Money\Money;
use PhpSpec\Exception\Example\FailureException;

/**
 * Adds `shouldAmount` inline matcher to verify that an amount expressed in
 * cents is equal to the amount of the subject `Money` object
 */
trait ProvidesMoneyMatcher
{
    public function getMatchers()
    {
        return [
            'amount' => function(Money $subject, $expectedAmount) {
                if ($subject->getAmount() !== $expectedAmount) {
                    throw new FailureException(sprintf(
                        'Current money amount should be "%s" not "%s".',
                        $expectedAmount, $subject->getAmount()
                    ));
                }
                return true;
            }
        ];
    }
}

Improve error message in phpspec inline matcher.


<?php

namespace Michaeljennings\Carpenter\View;

use Michaeljennings\Carpenter\Contracts\View;
use Michaeljennings\Carpenter\Exceptions\ViewNotFoundException;

class Native implements View
{
    /**
     * Return the required view
     *
     * @param       $view
     * @param array $data
     * @return string
     * @throws ViewNotFoundException
     */
    public function make($view, $data = [])
    {
        if ( ! file_exists($view)) {
            throw new ViewNotFoundException("The table template could not be found. No file found at '{$view}'");
        }

        extract($data);
        include($view);

        // Get the content
        $content = ob_get_contents();
        // Clear the output buffer
        ob_end_clean();

        // Return the content
        return $content;
    }
}

<?php

namespace Michaeljennings\Carpenter\View;

use Michaeljennings\Carpenter\Contracts\View;
use Michaeljennings\Carpenter\Exceptions\ViewNotFoundException;

class Native implements View
{
    /**
     * Return the required view
     *
     * @param       $view
     * @param array $data
     * @return string
     * @throws ViewNotFoundException
     */
    public function make($view, $data = [])
    {
        if ( ! file_exists($view)) {
            throw new ViewNotFoundException("The table template could not be found. No file found at '{$view}'");
        }

        ob_start();

        if ( ! empty($data)) {
            extract($data);
        }

        include($view);

        return ob_get_clean();
    }
}

Update native renderer to be less risky

Update native renderer to be less risky


    <button class="dms-view-more-button btn btn-info">
        View More
    </button>

Fix HTML escaping issue on html display fields


<?php

final class HeraldAnotherRuleField extends HeraldField {

  const FIELDCONST = 'rule';

  public function getHeraldFieldName() {
    return pht('Another Herald rule');
  }

  public function getFieldGroupKey() {
    return HeraldBasicFieldGroup::FIELDGROUPKEY;
  }

  public function supportsObject($object) {
    return true;
  }

  public function getHeraldFieldValue($object) {
    return null;
  }

  public function getHeraldFieldConditions() {
    return array(
      HeraldAdapter::CONDITION_RULE,
      HeraldAdapter::CONDITION_NOT_RULE,
    );
  }

  public function getHeraldFieldValueType($condition) {
    // NOTE: This is a bit magical because we don't currently have a reasonable
    // way to populate it from here.
    return id(new HeraldSelectFieldValue())
      ->setKey(self::FIELDCONST)
      ->setOptions(array());
  }

}

<?php

final class HeraldAnotherRuleField extends HeraldField {

  const FIELDCONST = 'rule';

  public function getHeraldFieldName() {
    return pht('Another Herald rule');
  }

  public function getFieldGroupKey() {
    return HeraldBasicFieldGroup::FIELDGROUPKEY;
  }

  public function supportsObject($object) {
    return true;
  }

  public function getHeraldFieldValue($object) {
    return null;
  }

  public function getHeraldFieldConditions() {
    return array(
      HeraldAdapter::CONDITION_RULE,
      HeraldAdapter::CONDITION_NOT_RULE,
    );
  }

  public function getHeraldFieldValueType($condition) {
    // NOTE: This is a bit magical because we don't currently have a reasonable
    // way to populate it from here.
    return id(new HeraldSelectFieldValue())
      ->setKey(self::FIELDCONST)
      ->setOptions(array());
  }

  public function renderConditionValue(
    PhabricatorUser $viewer,
    $condition,
    $value) {

    $value = (array)$value;

    return $viewer->renderHandleList($value);
  }

}

Correct rendering of "Another Herald Rule" conditions in Herald

Summary: Fixes T8920. These are semi-magical and need to be slightly special cased, now.

Test Plan: {F654502}

Reviewers: chad, btrahan

Reviewed By: btrahan

Subscribers: epriestley

Maniphest Tasks: T8920

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


<?php

namespace Honeybee\Ui\Renderer\Html\Honeybee\Ui\Activity;

use Honeybee\Ui\Renderer\ActivityRenderer;

class HtmlActivityRenderer extends ActivityRenderer
{
    protected function getTemplateParameters()
    {
        $activity = $this->getPayload('subject');

        $default_css = [
            'button',
            'button-' . strtolower($activity->getName())
        ];
        if ($this->getOption('plain_activity')) {
            $default_css = [
                'activity',
                'activity-' . strtolower($activity->getName())
            ];
        }

        $params = [];
        $params['css'] = $this->getOption('css', $default_css);
        $params['form_id'] = $this->getOption('form_id', $activity->getSettings()->get('form_id', 'formid'));
        $params['form_parameters'] = $this->getOption('form_parameters', $activity->getUrl()->getParameters());
        $params['form_method'] = $this->getOption('form_method', ($activity->getVerb() === 'read') ? 'GET' : 'POST');
        $params['form_css'] = $this->getOption('form_css');

        return array_replace_recursive(parent::getTemplateParameters(), $params);
    }
}

<?php

namespace Honeybee\Ui\Renderer\Html\Honeybee\Ui\Activity;

use Honeybee\Ui\Renderer\ActivityRenderer;

class HtmlActivityRenderer extends ActivityRenderer
{
    protected function getTemplateParameters()
    {
        $activity = $this->getPayload('subject');

        $default_css = [
            'activity',
            'activity-' . strtolower($activity->getName())
        ];

        $params = [];
        $params['css'] = $this->getOption('css', $default_css);
        $params['form_id'] = $this->getOption('form_id', $activity->getSettings()->get('form_id', 'formid'));
        $params['form_parameters'] = $this->getOption('form_parameters', $activity->getUrl()->getParameters());
        $params['form_method'] = $this->getOption('form_method', ($activity->getVerb() === 'read') ? 'GET' : 'POST');
        $params['form_css'] = $this->getOption('form_css');
        $params['emphasized'] = (bool)$this->getOption('emphasized', false);

        return array_replace_recursive(parent::getTemplateParameters(), $params);
    }
}

Change default CSS classes for rendered activities


<?php

namespace Naterweb\Routing\Urls;

use Naterweb\Engine\Configuration;

class UrlBuilder {

	private $urlParams;

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

	public function build()
	{
		$friendlyUrl = Configuration::get_option('friendly_urls');
		$domain = Configuration::get_option('site_domain');

		$params = array();
		$params[] = $domain;

		$formatString = "%s/";
		$formatString .= $friendlyUrl ? '' : '?url=';

		foreach ($this->urlParams as $key => $value) {
			$formatString .= '%s/%s/';
			$params[] = urlencode($key);
			$params[] = urlencode($value);
		}

		return vsprintf($formatString, $params);
	}

}

<?php

namespace Naterweb\Routing\Urls;

use Naterweb\Engine\Configuration;

class UrlBuilder {

	private $urlParams;

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

	public function build()
	{
		$friendlyUrl = Configuration::get_option('friendly_urls');
		$domain = Configuration::get_option('site_domain');

		$params = array();
		$params[] = $domain;

		$formatString = "%s";
		$formatString .= $friendlyUrl ? '' : '?url=';
		$firstPass = True;
		foreach ($this->urlParams as $key => $value) {
			$formatString .= $firstPass ? '%s/%s' : '/%s/%s';
			$params[] = urlencode($key);
			$params[] = urlencode($value);
			$firstPass = False;
		}

		return vsprintf($formatString, $params);
	}

}

Fix issue with separating variables

Fix issue with separating variables


<?php

declare(strict_types=1);

namespace AlgoWeb\PODataLaravel\Controllers;

class MetadataControllerContainer
{
    private $metadata;

    /**
     * @param array $meta
     */
    public function setMetadata(array $meta)
    {
        $this->metadata = $meta;
    }

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

    /**
     * @param  string $modelName
     * @param  string $verb
     * @return array
     */
    public function getMapping($modelName, $verb)
    {
        return $this->metadata[$modelName][$verb];
    }
}

<?php

declare(strict_types=1);

namespace AlgoWeb\PODataLaravel\Controllers;

class MetadataControllerContainer
{
    /** @var array[] */
    private $metadata;

    /**
     * @param array[] $meta
     */
    public function setMetadata(array $meta): void
    {
        $this->metadata = $meta;
    }

    /**
     * @return array[]
     */
    public function getMetadata()
    {
        return $this->metadata;
    }

    /**
     * @param  string $modelName
     * @param  string $verb
     * @return mixed
     */
    public function getMapping($modelName, $verb)
    {
        return $this->metadata[$modelName][$verb];
    }
}

Add type-hints to Controller-related classes


<?php
namespace MindOfMicah\LaravelDatatables;

use Illuminate\Http\JsonResponse;

class Datatable
{
    protected $model;
    protected $columns;

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

    public function asJsonResponse()
    {
        $data = [];
        $total = $amount_displayed = 0;
        if ($this->model) {
            $model_name = $this->model;
            if ($this->columns) {

            }
            $models = $model_name::select($this->columns?:'*')->get();
            $data = $models->toArray();
            $total = count($models);
            $amount_displayed = count($models);
        }

        $data = ([
            'aaData'=>$data,
            'iTotalRecords'=>$total,
            'iTotalDisplayRecords'=>$amount_displayed
        ]);
        return new JsonResponse($data, 200);
    }

    public function forEloquentModel($model)
    {
        $this->model = $model;
        return $this;
    }

    public function pluckColumns($argument1)
    {
        $this->columns[] = $argument1;
        return $this;
    }
}

<?php
namespace MindOfMicah\LaravelDatatables;

use Illuminate\Http\JsonResponse;

class Datatable
{
    protected $model;
    protected $columns;

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

    public function asJsonResponse()
    {
        $data = [];
        $total = $amount_displayed = 0;
        if ($this->model) {
            $model_name = $this->model;
            if ($this->columns) {

            }
            $sql = $model_name::query()->select($this->columns ?: '*');

            $total = ($sql->count());
            $models = $sql->take($this->a->input('length'))->get();
            $data = $models->toArray();

            $total = $total;
            $amount_displayed = count($models);
        }

        $data = ([
            'aaData'=>$data,
            'iTotalRecords'=>$total,
            'iTotalDisplayRecords'=>$amount_displayed
        ]);
        return new JsonResponse($data, 200);
    }

    public function forEloquentModel($model)
    {
        $this->model = $model;
        return $this;
    }

    public function pluckColumns($argument1)
    {
        $this->columns[] = $argument1;
        return $this;
    }
}

Allow us to limit the amount of returned results


<?php

function smarty_function_user_activity(array $params, Smarty_Internal_Template $template) {
	$force_display = isset($params['force_display']);
	/** @var CM_Model_User $user  */
	$user = $params['user'];

	if ($user->getVisible()) {
		/** @var CM_Model_User $viewer  */
		return 'Online';
	}

	$activity_stamp = $user->getLatestactivity();
	$activity_delta = time() - $activity_stamp;
	if (!$force_display && $activity_delta > 7 * 86400) {
		return '';
	}

	if (($activity_delta / 86400) >= 1) {
		$count = floor($activity_delta / 86400);
		$unit = 'd';
	} elseif (($activity_delta / 3600) >= 1) {
		$count = floor($activity_delta / 3600);
		$unit = 'h';
	} elseif (($activity_delta / 60) >= 1) {
		$count = floor($activity_delta / 60);
		$unit = 'm';
	} else {
		$count = 1;
		$unit = 'm';
	}
	return 'Online: ' . $count . ' ' . CM_Language::section('profile.labels')->text('activity_' . $unit);

}

<?php

function smarty_function_user_activity(array $params, Smarty_Internal_Template $template) {
	$force_display = isset($params['force_display']);
	/** @var CM_Model_User $user  */
	$user = $params['user'];

	if ($user->getVisible()) {
		/** @var CM_Model_User $viewer  */
		return 'Online';
	}

	$activity_stamp = $user->getLatestactivity();
	$activity_delta = time() - $activity_stamp;
	if (!$force_display && $activity_delta > 10 * 86400) {
		return '';
	}

	if (($activity_delta / 86400) >= 1) {
		$count = floor($activity_delta / 86400);
		$unit = 'd';
	} elseif (($activity_delta / 3600) >= 1) {
		$count = floor($activity_delta / 3600);
		$unit = 'h';
	} elseif (($activity_delta / 60) >= 1) {
		$count = floor($activity_delta / 60);
		$unit = 'm';
	} else {
		$count = 1;
		$unit = 'm';
	}
	return 'Online: ' . $count . ' ' . CM_Language::section('profile.labels')->text('activity_' . $unit);

}

Hide user-activity after 10 (instead of 7) days


<?php
    require_once('simpletest/unit_tester.php');
    require_once('simpletest/reporter.php');

    require_once(dirname(__FILE__).'/acceptance_test.php');
    require_once(dirname(__FILE__).'/annotation_test.php');
    require_once(dirname(__FILE__).'/constrained_annotation_test.php');
    require_once(dirname(__FILE__).'/annotation_parser_test.php');
    require_once(dirname(__FILE__).'/doc_comment_test.php');

    class AllTests extends GroupTest {
          function __construct($title = false) {
              parent::__construct($title);
              $this->addTestClass('TestOfAnnotations');
              $this->addTestClass('TestOfPerformanceFeatures');
              $this->addTestClass('TestOfSupportingFeatures');
              $this->addTestClass('TestOfAnnotation');
              $this->addTestClass('TestOfConstrainedAnnotation');
              $this->addTestClass('TestOfMatchers');
              $this->addTestClass('TestOfAnnotationMatchers');
              $this->addTestClass('TestOfDocComment');

          }
      }

    Addendum::setRawMode(false);
    $test = new AllTests('All tests in reflection mode');
    $test->run(new HtmlReporter());

    Addendum::setRawMode(true);
    $test = new AllTests('All tests in raw mode');
    $test->run(new HtmlReporter());
?>

<?php
    require_once('simpletest/unit_tester.php');
    require_once('simpletest/reporter.php');

    require_once(dirname(__FILE__).'/acceptance_test.php');
    require_once(dirname(__FILE__).'/annotation_test.php');
    require_once(dirname(__FILE__).'/constrained_annotation_test.php');
    require_once(dirname(__FILE__).'/annotation_parser_test.php');
    require_once(dirname(__FILE__).'/doc_comment_test.php');

    class AllTests extends GroupTest {
          function __construct($title = false) {
              parent::__construct($title);
              $this->addTestClass('TestOfAnnotations');
              $this->addTestClass('TestOfPerformanceFeatures');
              $this->addTestClass('TestOfSupportingFeatures');
              $this->addTestClass('TestOfAnnotation');
              $this->addTestClass('TestOfConstrainedAnnotation');
              $this->addTestClass('TestOfMatchers');
              $this->addTestClass('TestOfAnnotationMatchers');
              $this->addTestClass('TestOfDocComment');

          }
      }
    $reporter = TextReporter::inCli() ? new TextReporter() : new HtmlReporter();

    Addendum::setRawMode(false);
    $test = new AllTests('All tests in reflection mode');
    $test->run($reporter);

    Addendum::setRawMode(true);
    $test = new AllTests('All tests in raw mode');
    $test->run($reporter);
?>

Use TextReporter when in cli mode.

Use TextReporter when in cli mode.


<?php
/*
 * Copyright (c) Ouzo contributors, http://ouzoframework.org
 * This file is made available under the MIT License (view the LICENSE file for more information).
 */

namespace Ouzo\Tests;

use Ouzo\Db;
use Ouzo\Utilities\Cache;
use PHPUnit\Framework\TestCase;

class DbTransactionalTestCase extends TestCase
{
    public function setUp(): void
    {
        Cache::clear();
        if (Db::getInstance()->isConnected()) {
            Db::getInstance()->beginTransaction();
            Db::getInstance()->disableTransactions();
        }
    }

    public function tearDown(): void
    {
        Cache::clear();
        if (Db::getInstance()->isConnected()) {
            Db::getInstance()->enableTransactions();
            Db::getInstance()->rollbackTransaction();
        }
    }
}

<?php
/*
 * Copyright (c) Ouzo contributors, http://ouzoframework.org
 * This file is made available under the MIT License (view the LICENSE file for more information).
 */

namespace Ouzo\Tests;

use Ouzo\Db;
use Ouzo\Utilities\Cache;
use PHPUnit\Framework\TestCase;

abstract class DbTransactionalTestCase extends TestCase
{
    public function setUp(): void
    {
        Cache::clear();
        if (Db::getInstance()->isConnected()) {
            Db::getInstance()->beginTransaction();
            Db::getInstance()->disableTransactions();
        }
    }

    public function tearDown(): void
    {
        Cache::clear();
        if (Db::getInstance()->isConnected()) {
            Db::getInstance()->enableTransactions();
            Db::getInstance()->rollbackTransaction();
        }
    }
}

Fix running single PHPUnit test

Fix running single PHPUnit test


<?php
namespace Joindin;

require_once '../src/Joindin/Service/Autoload.php';

spl_autoload_register('Joindin\Service\autoload::autoload');

session_cache_limiter(false);
session_start();
ini_set('display_errors', 'on');

// include dependencies
require '../vendor/Slim/Slim.php';
require '../vendor/TwigView.php';

// include view controller
require '../src/Joindin/View/Filters.php';

$config = array();
$configFile = realpath(__DIR__ . '/../config/config.php');
if (is_readable($configFile)) {
    include $configFile;
}

// initialize Slim
$app = new \Slim(
    array(
        'mode' => 'development',
        'view' => new \TwigView(),
        'custom' => $config,
    )
);

// set Twig base folder, view folder and initialize Joindin filters
\TwigView::$twigDirectory = realpath(__DIR__ . '/../vendor/Twig/lib/Twig');
$app->view()->setTemplatesDirectory('../views');
\Joindin\View\Filter\initialize($app->view()->getEnvironment());

// register routes
new Controller\Application($app);
new Controller\Event($app);

// execute application
$app->run();

<?php
namespace Joindin;

require_once '../src/Joindin/Service/Autoload.php';

spl_autoload_register('Joindin\Service\Autoload::autoload');

session_cache_limiter(false);
session_start();
ini_set('display_errors', 'on');

// include dependencies
require '../vendor/Slim/Slim.php';
require '../vendor/TwigView.php';

// include view controller
require '../src/Joindin/View/Filters.php';

$config = array();
$configFile = realpath(__DIR__ . '/../config/config.php');
if (is_readable($configFile)) {
    include $configFile;
}

// initialize Slim
$app = new \Slim(
    array(
        'mode' => 'development',
        'view' => new \TwigView(),
        'custom' => $config,
    )
);

// set Twig base folder, view folder and initialize Joindin filters
\TwigView::$twigDirectory = realpath(__DIR__ . '/../vendor/Twig/lib/Twig');
$app->view()->setTemplatesDirectory('../views');
\Joindin\View\Filter\initialize($app->view()->getEnvironment());

// register routes
new Controller\Application($app);
new Controller\Event($app);

// execute application
$app->run();

Update case of autoload class

Update case of autoload class


<?php namespace GeneaLabs\Bones\Marshal;

use GeneaLabs\Bones\Marshal\Events\EventGenerator;
use Watson\Validating\ValidatingTrait;

class BonesMarshalBaseModel extends \BaseModel
{
    use ValidatingTrait;
    use EventGenerator;

    /**
     * @var bool
     */
    protected $throwValidationExceptions = true;
}

<?php namespace GeneaLabs\Bones\Marshal;

use GeneaLabs\Bones\Marshal\Events\EventGenerator;
use Watson\Validating\ValidatingTrait;

class BonesMarshalBaseModel extends \Model
{
    use ValidatingTrait;
    use EventGenerator;

    /**
     * @var bool
     */
    protected $throwValidationExceptions = true;
}

Update to extend Model instead of BaseModel