<?php
/**
* Alf CMS
*
* PHP 5
*
* Alf CMS
* Copyright 2013-2013, Tonight Systems, Inc. (https://github.com/tonightsystems)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @package      Alf
* @copyright    Copyright 2013-2013, Tonight Systems, Inc.
* @link         https://github.com/tonightsystems/alf-cms
* @license      MIT License (http://www.opensource.org/licenses/mit-license.php)
*/

/**
 * Define as constantes principais do sistema
 */
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(__FILE__) . DS);
define('CORE', ROOT . DS . 'core' . DS);
define('THEMES', ROOT . DS . 'themes' . DS);
define('EXT', '.php');

require CORE . 'app' . EXT;

App::load(array(
    'convenience',
    'config',
));

// Carrega as configurações do usuário
App::load('config', ROOT);

// Carrega o sistema em si
require CORE . 'init' . EXT;

<?php
/**
* Alf CMS
*
* PHP 5
*
* Alf CMS
* Copyright 2013-2013, Tonight Systems, Inc. (https://github.com/tonightsystems)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @package      Alf
* @copyright    Copyright 2013-2013, Tonight Systems, Inc.
* @link         https://github.com/tonightsystems/alf-cms
* @license      MIT License (http://www.opensource.org/licenses/mit-license.php)
*/

/**
 * Define as constantes principais do sistema
 */
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(__FILE__) . DS);
define('CORE', ROOT . DS . 'core' . DS);
define('THEMES', ROOT . DS . 'themes' . DS);
define('EXT', '.php');

require CORE . 'convenience' . EXT;
require CORE . 'config' . EXT;

// Carrega as configurações do usuário
require ROOT . 'config' . EXT;

require CORE . 'init' . EXT;

Remove chamadas desnecessárias da classe `App`


<?php

/**
 * The _include script registers a autoloader for the simpleSAMLphp libraries. It also
 * initializes the simpleSAMLphp config class with the correct path.
 */
require_once('_include.php');

/* Load simpleSAMLphp, configuration and metadata */
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();

if (empty($_REQUEST['RelayState'])) {
	SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE');
}

if (! $session->isValid('openid') ) {
	/* Authenticate with an AuthSource. */
	$hints = array();
	if (array_key_exists('openid', $_REQUEST)) $hints['openid'] = $_REQUEST['openid'];
	SimpleSAML_Auth_Default::initLogin('openid', $_REQUEST['RelayState'], NULL, $hints);
}

?>

<?php

/**
 * The _include script registers a autoloader for the simpleSAMLphp libraries. It also
 * initializes the simpleSAMLphp config class with the correct path.
 */
require_once('_include.php');

/* Load simpleSAMLphp, configuration and metadata */
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();

if (empty($_REQUEST['RelayState'])) {
	throw new SimpleSAML_Error_Error('NORELAYSTATE');
}

if (! $session->isValid('openid') ) {
	/* Authenticate with an AuthSource. */
	$hints = array();
	if (array_key_exists('openid', $_REQUEST)) $hints['openid'] = $_REQUEST['openid'];
	SimpleSAML_Auth_Default::initLogin('openid', $_REQUEST['RelayState'], NULL, $hints);
}

?>

Replace calls to SimpleSAML_Utilities::fatalError with throwing an exception.

Also remove those instances of the $session variable that became unused.

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


<?php

class CRM_Speakcivi_Tools_Helper {

  /**
   * Clean out string from unicode special chars.
   * Those unicode chars invoke bugs during insert/update on db table.
   *
   * @param string $string
   *
   * @return mixed
   */
  public static function cleanUnicodeChars($string) {
    return preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);
  }

  /**
   * Trim all strings from object.
   *
   * @param object $param
   */
  public static function trimVariables(&$param) {
    foreach ($param as $key => $value) {
      if (is_object($value)) {
        self::trimVariables($value);
      } elseif (is_array($value)) {
        foreach($value as $k => $v) {
          self::trimVariables($v);
        }
      } elseif (is_string($value)) {
        $param->$key = trim($value);
      }
    }
  }
}

<?php

class CRM_Speakcivi_Tools_Helper {

  /**
   * Clean out string from unicode special chars.
   * Those unicode chars invoke bugs during insert/update on db table.
   *
   * @param string $string
   *
   * @return mixed
   */
  public static function cleanUnicodeChars($string) {
    return preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);
  }

  /**
   * Trim all strings from object.
   *
   * @param object $param
   */
  public static function trimVariables(&$param) {
    foreach ($param as $key => $value) {
      if (is_object($value)) {
        self::trimVariables($value);
      } elseif (is_array($value)) {
        foreach($value as $k => $v) {
          self::trimVariables($v);
        }
      } elseif (is_string($value)) {
        $param->$key = self::clean($value, $key);
      }
    }
  }

  /**
   * Clean out string from redundant spaces and trim to valid length.
   *
   * @param string $value
   * @param string $type
   *
   * @return string
   */
  private static function clean($value, $type = '') {
    $value = self::cleanSpaces($value);
    switch ($type) {
      case 'phone':
        $value = mb_substr($value, 0, 32);
        break;
      case 'firstname':
      case 'lastname':
      case 'zip':
        $value = mb_substr($value, 0, 64);
        break;
      case 'email':
        $value = mb_substr($value, 0, 254);
        break;
    }
    return $value;
  }

  /**
   * Reduce redundant spaces.
   *
   * @param string $value
   *
   * @return string
   */
  private static function cleanSpaces($value) {
    return preg_replace('/\s+/', ' ', trim($value));
  }
}


<?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\HttpKernel\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Sets the session in the request.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
abstract class SessionListener implements EventSubscriberInterface
{
    public function onKernelRequest(GetResponseEvent $event)
    {
        if (!$event->isMasterRequest()) {
            return;
        }

        $request = $event->getRequest();
        $session = $this->getSession();
        if (null === $session || $request->hasSession()) {
            return;
        }

        $request->setSession($session);
    }

    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::REQUEST => array('onKernelRequest', 128),
        );
    }

    /**
     * Gets the session object.
     *
     * @return SessionInterface|null A SessionInterface instance or null if no session is available
     */
    abstract protected function getSession();
}

<?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\HttpKernel\EventListener;

use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Sets the session in the request.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
abstract class SessionListener implements EventSubscriberInterface
{
    public function onKernelRequest(GetResponseEvent $event)
    {
        if (!$event->isMasterRequest()) {
            return;
        }

        $request = $event->getRequest();
        $session = $this->getSession();
        if (null === $session || $request->hasSession()) {
            return;
        }

        $request->setSession($session);
    }

    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::REQUEST => array('onKernelRequest', 128),
        );
    }

    /**
     * Gets the session object.
     *
     * @return SessionInterface|null A SessionInterface instance or null if no session is available
     */
    abstract protected function getSession();
}

Fix issues reported by static analyse

[2.8] Fix issues reported by static analyse


<?php

namespace Travis;

class Inline {

    /**
     * Return HTML w/ inline CSS.
     *
     * @param   string  $html
     * @return  string
     */
    public static function run($html)
    {
        // build object
        $clean = new \TijsVerkoyen\CssToInlineStyles\CSSToInlineStyles();

        // set html
        $clean->setHTML($html);

        // css included w/ html
        $clean->setUseInlineStylesBlock(true);

        // convert to html
        $html = $clean->convert(false); // false for HTML mode (not XHTML, works better)

        // return
        return $html;
    }

    /**
     * Legacy alias method.
     *
     * @param   string  $html
     * @return  string
     */
    public static function convert($html)
    {
        // legacy alias
        return static::run($html);
    }

}

<?php

namespace Travis;

class Inline {

    /**
     * Return HTML w/ inline CSS.
     *
     * @param   string  $html
     * @return  string
     */
    public static function run($html)
    {
        // build object
        $clean = new \TijsVerkoyen\CssToInlineStyles\CssToInlineStyles();

        // set html
        $clean->setHTML($html);

        // css included w/ html
        $clean->setUseInlineStylesBlock(true);

        // convert to html
        $html = $clean->convert(false); // false for HTML mode (not XHTML, works better)

        // return
        return $html;
    }

    /**
     * Legacy alias method.
     *
     * @param   string  $html
     * @return  string
     */
    public static function convert($html)
    {
        // legacy alias
        return static::run($html);
    }

}

Fix case issue on class name.

Fix case issue on class name.


<?php

// Try to find the application root directory.
$appRoot = "E:\approot";
if (isset($_SERVER['ApplicationPath'])) {
    $appRoot = $_SERVER['ApplicationPath'] . '\app';
}

require_once $appRoot . '\bootstrap.php.cache';
require_once $appRoot . '\AppKernel.php';
//require_once $appRoot . '\AppCache.php';

use Symfony\Component\HttpFoundation\Request;

$kernel = new AppKernel('azure', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

<?php

// Try to find the application root directory.
$appRoot = "E:\approot\app";
if (isset($_SERVER['ApplicationPath'])) {
    $appRoot = $_SERVER['ApplicationPath'] . '\app';
}

require_once $appRoot . '\bootstrap.php.cache';
require_once $appRoot . '\AppKernel.php';
//require_once $appRoot . '\AppCache.php';

use Symfony\Component\HttpFoundation\Request;

$kernel = new AppKernel('azure', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

Fix wrong path for fallback case.

Fix wrong path for fallback case.


<?php

namespace Facilis\Users\OAuth2;

use League\OAuth2\Client\Exception\IDPException;
use League\OAuth2\Client\Provider\ProviderInterface;
use Nette\Object;

class LoginService extends Object
{

    /**
     * @var IStateStorage
     */
    private $stateStorage;

    function __construct(IStateStorage $stateStorage)
    {
        $this->stateStorage = $stateStorage;
    }

    public function login(ProviderInterface $provider, $code, $state, IOAuthAccountManager $manager)
    {
        if ($code === null) {
            // If we don't have an authorization code then get one
            $authUrl = $provider->getAuthorizationUrl();
            $this->stateStorage->storeState($provider->state);
            header('Location: ' . $authUrl);

            // Check given state against previously stored one to mitigate CSRF attack
        } elseif ($state === null || ($state !== $this->stateStorage->loadState())) {
            $this->stateStorage->storeState(null);
            throw new InvalidStateException();

        } else {

            // Try to get an access token (using the authorization code grant)
            $token = $provider->getAccessToken('authorization_code', [
                'code' => $code
            ]);

            // Optional: Now you have a token you can look up a users profile data
            try {

                // We got an access token, let's now get the user's details
                $userDetails = $provider->getUserDetails($token);

                $manager->persistOAuthAccount(get_class($provider), $token, $userDetails);

            } catch (IDPException $e) {
                throw new AuthenticationException;
            }
        }

    }
}

<?php

namespace Facilis\Users\OAuth2;

use League\OAuth2\Client\Exception\IDPException;
use League\OAuth2\Client\Provider\ProviderInterface;
use Nette\Object;

class LoginService extends Object
{

    /**
     * @var IStateStorage
     */
    private $stateStorage;

    function __construct(IStateStorage $stateStorage)
    {
        $this->stateStorage = $stateStorage;
    }

    public function login(ProviderInterface $provider, $code, $state, IOAuthAccountManager $manager)
    {
        if ($code === null) {
            // If we don't have an authorization code then get one
            $authUrl = $provider->getAuthorizationUrl();
            $this->stateStorage->storeState($provider->state);
            header('Location: ' . $authUrl);

            // Check given state against previously stored one to mitigate CSRF attack
        } elseif ($state === null || ($state !== $this->stateStorage->loadState())) {
            $this->stateStorage->storeState(null);
            throw new InvalidStateException();

        } else {

            // Try to get an access token (using the authorization code grant)
            $token = $provider->getAccessToken('authorization_code', [
                'code' => $code
            ]);

            // Optional: Now you have a token you can look up a users profile data
            try {

                // We got an access token, let's now get the user's details
                $userDetails = $provider->getUserDetails($token);

                return $manager->persistOAuthAccount(get_class($provider), $token, $userDetails);

            } catch (IDPException $e) {
                throw new AuthenticationException;
            }
        }

    }
}

Return user after oauth login

Return user after oauth login


<?php
    ?>
Game #<?php
    echo $gameid;
    ?>

Round #<?php
    echo $round->id;
    ?>

        <?php
        $colors = [ 'red', 'blue', 'green', 'yellow', 'purple', 'cyan', 'black', 'pink' ];
        foreach ( $creatures as $creature ) {
            if ( $creature->alive ) {
                ?><div style="left: <?php
                echo $creature->locationx * 25;
                ?>px; top: <?php
                echo $creature->locationy * 25;
                ?>px; position: absolute; background-color: <?php
                if ( !isset( $playerColor[ $creature->user->id ] ) ) {
                    $playerColor[ $creature->user->id ] = array_shift( $colors );
                }
                echo $playerColor[ $creature->user->id ];
                ?>; width: 25px; height: 25px;">
<?php
            }
        }
        ?>

<?php
?>

<?php
    ?>
Game #<?php
    echo $gameid;
    ?>

Round #<?php
    echo $round->id;
    ?>

        <?php
        $colors = [ 'red', 'blue', 'green', 'yellow', 'purple', 'cyan', 'black', 'pink' ];
        foreach ( $creatures as $creature ) {
            if ( $creature->alive ) {
                ?><div style="left: <?php
                echo $creature->locationx * 25;
                ?>px; top: <?php
                echo $creature->locationy * 25;
                ?>px; position: absolute; background-color: <?php
                if ( !isset( $playerColor[ $creature->user->id ] ) ) {
                    $playerColor[ $creature->user->id ] = array_shift( $colors );
                }
                echo $playerColor[ $creature->user->id ];
                ?>; width: 25px; height: 25px;">
<?php
            }
        }
        ?>

<?php
    if ( isset( $game->rounds[ $round->id + 1 ] ) ) {
        ?>
<a href="?gameid=<?php
            echo htmlspecialchars( $gameid );
        ?>&roundid=<?php
            echo htmlspecialchars( $round->id ) + 1;
        ?>">Next round
<?php
    }
    if ( $round->id > 0 ) {
        ?>
<a href="?gameid=<?php
            echo htmlspecialchars( $gameid );
        ?>&roundid=<?php
            echo htmlspecialchars( $round->id ) - 1;
        ?>">Previous round
<?php
    }
?>

Add next round, previous round option

Add next round, previous round option


<?php

namespace AppBundle\Listeners;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use AppBundle\Exceptions\NoResultException;
use AppBundle\Exceptions\InvalidParameterException;

class ExceptionListener
{
    public function __construct()
    {

    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception  = $event->getException();
        //$request = $event->getRequest();

        switch (true) {
            case $exception instanceof NoResultException:
                $codeHttp = 404;
                break;
            case $exception instanceof InvalidParameterException:
                $codeHttp = 400;
                break;
            default:
                $codeHttp = 500;
        }

        $response = new JsonResponse(array($exception->getMessage()), $codeHttp);

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

<?php

namespace AppBundle\Listeners;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use AppBundle\Exceptions\NoResultException;
use AppBundle\Exceptions\InvalidParameterException;

class ExceptionListener
{
    public function __construct()
    {

    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception  = $event->getException();

        switch (true) {
            case $exception instanceof NoResultException:
                $codeHttp = 404;
                break;
            case $exception instanceof InvalidParameterException:
                $codeHttp = 400;
                break;
            default:
                $codeHttp = 500;
        }

        $response = new JsonResponse(array($exception->getMessage()), $codeHttp);

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

Delete not need commented code

Delete not need commented code


<?php

namespace Kwetal\Workdays\Traits;

use Kwetal\DateUtils\DateTime\DateTime;

trait ReformationDay
{
    /**
     * @var string $labelReformationDay
     */
    public $labelReformationDay = 'Reformation Day';

    /**
     * Returns Reformation day
     *
     * @param int $year
     * @return DateTime
     */
    protected function getReformationDay($year)
    {
        $day = new DateTime(sprintf('%s-10-31', $year));

        return $day->addLabel($this->labelReformationDay);
    }
}

<?php

namespace Kwetal\Workdays\Traits;

use Kwetal\DateUtils\DateTime\DateTime;

trait ReformationDay
{
    /**
     * @var string $labelReformationDay
     */
    public $labelReformationDay = 'Reformation Day';

    /**
     * Returns Reformation day
     *
     * @param int $year
     * @return DateTime
     */
    protected function getReformationDay($year)
    {
        $day = new DateTime(sprintf('%s-10-31', $year));

        return [$day->addLabel($this->labelReformationDay)];
    }
}

Return Reformation day as array

Return Reformation day as array


<?php
namespace M12\Foundation;

/*                                                                        *
 * This script belongs to the "M12.Foundation" package.                   *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU General Public License, either version 3 of the   *
 * License, or (at your option) any later version.                        *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

use TYPO3\Flow\Package\Package as BasePackage;
use TYPO3\Flow\Core\Bootstrap;

/**
 * The M12.Foundation Package
 */
class Package extends BasePackage {

	/**
	 * Invokes custom PHP code directly after the package manager has been initialized.
	 *
	 * @param Bootstrap $bootstrap The current bootstrap
	 * @return void
	 */
	public function boot(Bootstrap $bootstrap) {
		$signalDispatcher = 'TYPO3\Neos\Service\NodeOperations';
		$signalName = 'afterNodeCreate';

		// We don't use `NodeOperations` during tests, so listen to original signal from TYPO3CR
		if ($bootstrap->getContext()->isTesting()) {
			$signalDispatcher = 'TYPO3\TYPO3CR\Domain\Model\Node';
		}

		$dispatcher = $bootstrap->getSignalSlotDispatcher();
		$dispatcher->connect($signalDispatcher, $signalName, 'M12\Foundation\Node\NodeConfigurator', 'afterNodeCreate');
	}
}

<?php
namespace M12\Foundation;

/*                                                                        *
 * This script belongs to the "M12.Foundation" package.                   *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU General Public License, either version 3 of the   *
 * License, or (at your option) any later version.                        *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

use TYPO3\Flow\Package\Package as BasePackage;
use TYPO3\Flow\Core\Bootstrap;

/**
 * The M12.Foundation Package
 */
class Package extends BasePackage {

	/**
	 * Invokes custom PHP code directly after the package manager has been initialized.
	 *
	 * @param Bootstrap $bootstrap The current bootstrap
	 * @return void
	 */
	public function boot(Bootstrap $bootstrap) {
		$dispatcher = $bootstrap->getSignalSlotDispatcher();
		$dispatcher->connect('TYPO3\TYPO3CR\Domain\Model\Node', 'afterNodeCreate', 'M12\Foundation\Node\NodeConfigurator', 'afterNodeCreate');
	}
}

Use existing `afterNodeCreate` signal to trigger NodeConfigurator


                 'de']) }}" title="Sprache auf Deutsch umstellen.">

                 'en']) }}" title="Switch language to English.">

Align cfg logo right on larger screens

Align cfg logo right on larger screens


<?php

namespace Ontic\NoFraud\Utils;

use Ontic\NoFraud\Interfaces\IPlugin;
use Symfony\Component\Yaml\Yaml;

class PluginUtils
{
    /**
     * @return IPlugin[]
     */
    public static function loadPlugins()
    {
        $plugins = [];
        $configurationFile = PROJECT_ROOT . '/data/config.yml';
        $configuration = Yaml::parse(file_get_contents($configurationFile));

        foreach($configuration['plugins'] as $pluginConfig)
        {
            $code = $pluginConfig['code'];
            $weight = isset($pluginConfig['weight'])
                ? $pluginConfig['weight']
                : 1;
            $authoritative = isset($pluginConfig['authoritative'])
                ? $pluginConfig['authoritative']
                : false;
            $configuration = $pluginConfig['config'];

            $pluginClass = 'Ontic\NoFraud\Plugins\\' . static::toPascalCase($code) . 'Plugin';
            $plugins[] = new $pluginClass($weight, $authoritative, $configuration);
        }

        return $plugins;
    }

    private static function toPascalCase($string)
    {
        return preg_replace_callback("/(?:^|_)([a-z])/", function($matches)
        {
            return strtoupper($matches[1]);
        }, $string);
    }
}

<?php

namespace Ontic\NoFraud\Utils;

use Ontic\NoFraud\Interfaces\IPlugin;
use Symfony\Component\Yaml\Yaml;

class PluginUtils
{
    /**
     * @return IPlugin[]
     */
    public static function loadPlugins()
    {
        $plugins = [];
        $configurationFile = PROJECT_ROOT . '/data/config.yml';
        $configuration = Yaml::parse(file_get_contents($configurationFile));

        foreach($configuration['plugins'] as $pluginConfig)
        {
            $code = $pluginConfig['code'];
            $weight = isset($pluginConfig['weight'])
                ? $pluginConfig['weight']
                : 1;
            $authoritative = isset($pluginConfig['authoritative'])
                ? $pluginConfig['authoritative']
                : false;
            $configuration = isset($pluginConfig['config'])
                ? $pluginConfig['config']
                : [];

            $pluginClass = 'Ontic\NoFraud\Plugins\\' . static::toPascalCase($code) . 'Plugin';
            $plugins[] = new $pluginClass($weight, $authoritative, $configuration);
        }

        return $plugins;
    }

    private static function toPascalCase($string)
    {
        return preg_replace_callback("/(?:^|_)([a-z])/", function($matches)
        {
            return strtoupper($matches[1]);
        }, $string);
    }
}

Remove warning when no configuration is defined


<?php

/**
 * This file contains an abstract WebController class,
 * containing methods specifically targeted for the
 * Web Usage.
 *
 * PHP Version 5.3
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */

/**
 * Web Controller class
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */
abstract class WebController extends Controller
{

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Destructor
     */
    public function __destruct()
    {
        parent::__destruct();
    }

    /**
     * Handle unimplemented calls
     *
     * @param String $name      Method name
     * @param array  $arguments Arguments passed to the method
     *
     * @return String JSON encoded error String
     */
    public function __call($name, $arguments)
    {
        return "
Not implemented
";
    }

}

?>

<?php

/**
 * This file contains an abstract WebController class,
 * containing methods specifically targeted for the
 * Web Usage.
 *
 * PHP Version 5.3
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */

/**
 * Web Controller class
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */
abstract class WebController extends Controller
{

    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Destructor.
     */
    public function __destruct()
    {
        parent::__destruct();
    }

    /**
     * Handle unimplemented calls.
     *
     * @param String $name      Method name
     * @param array  $arguments Arguments passed to the method
     *
     * @return String JSON encoded error String
     */
    public function __call($name, $arguments)
    {
        return "
Not implemented
";
    }

}

?>

system: Fix style issues for webcontroller class


<?php

namespace Project\AppBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * EvaluationRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class EvaluationRepository extends EntityRepository
{
    public function findAllBySpeaker($speakerId)
    {
        return $this->getEntityManager()
                ->createQuery(
                        'SELECT e
                        FROM ProjectAppBundle:Evaluation e
                        WHERE e.speaker = :speaker'
                )
                ->setParameter('speaker', $speakerId)
                ->getResult();
    }
}

<?php

namespace Project\AppBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * EvaluationRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class EvaluationRepository extends EntityRepository
{
    public function findAllBySpeaker($speakerId)
    {
        return $this->getEntityManager()
                ->createQuery(
                        'SELECT e
                        FROM ProjectAppBundle:Evaluation e
                        WHERE e.speaker = :speaker'
                )
                ->setParameter('speaker', $speakerId)
                ->getResult();
    }

    public function findAllUnvalidatedByPromotion($promotionId)
    {
        return $this->getEntityManager()
            ->createQuery(
                          'SELECT e
FROM ProjectAppBundle:Evaluation e
LEFT JOIN e.module m
LEFT JOIN m.promotion p
WHERE p.id = :promotion
AND e.validated = 0'
                          )
            ->setParameter('promotion', $promotionId)
            ->getResult();
    }
}

Add method to retrieve unvalidated evaluations


<?php

/** @var integer $id */
/** @var array $statistic */
?>

    <table id="<?= $id ?>" class="table no-margin">

            <?= Yii::t('hipanel:document', 'Date') ?>
            <?= Yii::t('hipanel:document', 'Count') ?>

        <?php foreach ($statistic as $date => $count) : ?>

                <?= Yii::$app->formatter->asDate($date, 'php:M Y') ?>
                <?= $count ?>

        <?php endforeach; ?>

<?php

/** @var integer $id */
/** @var array $statistic */
?>

    <table id="<?= $id ?>" class="table no-margin">

            <?= Yii::t('hipanel:document', 'Date') ?>
            <?= Yii::t('hipanel:document', 'Count') ?>

        <?php foreach ($statistic as $date => $count) : ?>

                <?= Yii::$app->formatter->asDate($date, 'php:Y-m-d') ?>
                <?= $count ?>

        <?php endforeach; ?>

Allow distinguish document generation dates (days)


<?php

/*
|--------------------------------------------------------------------------
| Ignition ignitionpowered.co.uk
|--------------------------------------------------------------------------
|
| This class extends the functionality of Ignition. You can add your
| own custom logic here.
|
*/

require_once APPPATH.'/controllers/ignition/auth.php';

class Auth extends IG_Auth {

	function appLogin(){
		$result['error'] = false;

		// read request body and decode into array
		$requestBody = json_decode(file_get_contents('php://input'),true);

		// check that username exists
		if (array_key_exists("username", $requestBody)) {
		    $result['username'] = $requestBody["username"];
		} else {
			$result['error'] = true;
		}

		// return result
        //echo json_encode($result);

        $this->output
			->set_content_type('application/json')
			->set_output(json_encode($result));
	}

}

<?php

/*
|--------------------------------------------------------------------------
| Ignition ignitionpowered.co.uk
|--------------------------------------------------------------------------
|
| This class extends the functionality of Ignition. You can add your
| own custom logic here.
|
*/

require_once APPPATH.'/controllers/ignition/auth.php';

class Auth extends IG_Auth {

	function appLogin(){
		$result['error'] = false;

		// read request body and decode into array
		$requestBody = json_decode(file_get_contents('php://input'),true);

		// check that username exists
		if (array_key_exists("username", $requestBody)) {
			$result['username'] = $requestBody["username"];
		} else {
			$result['error'] = true;
		}

		$this->output
			->set_content_type('application/json')
			->set_output(json_encode($result));
	}

}

Fix tabing and remove commented code

Fix tabing and remove commented code


  {{ Form::label('first_name', 'First Name') }}
  {{ form_error('first_name', $errors) }}
  {{ Form::text('first_name', null, ['placeholder' => 'What\'s your name?']) }}

  {{ Form::label('birthdate', 'Birthdate') }}
  {{ form_error('birthdate', $errors) }}
  {{ Form::text('birthdate',  null, ['placeholder' => 'MM/DD/YYYY']) }}

  @if(get_login_type() == 'email')
    {{ Form::label('email', 'Email') }}
    {{ form_error('email', $errors) }}
    {{ Form::text('email', null, ['placeholder' => 'you@example.com']) }}
  @else
    {{ Form::label('phone', 'Email') }}
    {{ form_error('phone', $errors) }}
    {{ Form::text('phone', null, ['placeholder' => '555-555-5555']) }}
  @endif

  {{ Form::label('first_name', 'First Name') }}
  {{ form_error('first_name', $errors) }}
  {{ Form::text('first_name', null, ['placeholder' => 'What\'s your name?']) }}

  {{ Form::label('birthdate', 'Birthdate') }}
  {{ form_error('birthdate', $errors) }}
  {{ Form::text('birthdate',  null, ['placeholder' => 'MM/DD/YYYY']) }}

  @if(get_login_type() == 'email')
    {{ Form::label('email', 'Email') }}
    {{ form_error('email', $errors) }}
    {{ Form::text('email', null, ['placeholder' => 'you@example.com']) }}
  @else
    {{ Form::label('phone', 'Cell Number') }}
    {{ form_error('phone', $errors) }}
    {{ Form::text('phone', null, ['placeholder' => '555-555-5555']) }}
  @endif

Fix cell number field label.

Fix cell number field label.


<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Aurora</title>
  <!-- include bootstrap -->
  <!-- @TODO include this with gulp, grunt, etc. -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</head>

<body>
  @include('layout.nav')

  @yield('main_content')

</body>

</html>

<!doctype html>

  <meta charset="UTF-8">
  <title>Aurora</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">

  @include('layout.nav')

  @if (Session::has('flash_message'))

      {{ Session::get('flash_message')['text'] }}

  @endif

  @yield('main_content')

Add flash messages to master layout.

Add flash messages to master layout.


<?php
OCP\JSON::checkLoggedIn();
OCP\JSON::checkAppEnabled('files_sharing');
$user = OCP\USER::getUser();
// TODO translations
$subject = $user.' shared a file with you';
$link = $_POST['link'];
$text = $user.' shared the file '.$_POST['file'].' with you. It is available for download here: '.$link;
$fromaddress = OCP\Config::getUserValue($user, 'settings', 'email', 'sharing-noreply@'.$_SERVER['HTTP_HOST']);
OC_Mail::send($_POST['toaddress'], $_POST['toaddress'], $subject, $text, $fromaddress, $user);

?>

<?php
OCP\JSON::checkLoggedIn();
OCP\JSON::checkAppEnabled('files_sharing');
$user = OCP\USER::getUser();
// TODO translations
$type = (strpos($_POST['file'], '.') === false) ? 'folder' : 'file';
$subject = $user.' shared a '.$type.' with you';
$link = $_POST['link'];
$text = $user.' shared the '.$type.' '.$_POST['file'].' with you. It is available for download here: '.$link;
$fromaddress = OCP\Config::getUserValue($user, 'settings', 'email', 'sharing-noreply@'.$_SERVER['HTTP_HOST']);
OC_Mail::send($_POST['toaddress'], $_POST['toaddress'], $subject, $text, $fromaddress, $user);

?>

Check if a private link points to a folder or file and change text accordingly


<?php

namespace LWI\DeliveryTracking\Behavior;

use LWI\DeliveryTracking\DeliveryStatus;

trait ChronopostCodesTransformer
{
    /**
     * @param string $code
     *
     * @return null | DeliveryStatus
     */
    protected function getStateFromCode($code)
    {
        switch ($code) {
            case 'D':
            case 'D1':
            case 'D2':
                $state = DeliveryStatus::stateDelivered();
                break;

            default:
                $state = DeliveryStatus::stateInProgress();
                break;
        }

        return $state;
    }
}

<?php

namespace LWI\DeliveryTracking\Behavior;

use LWI\DeliveryTracking\DeliveryStatus;

trait ChronopostCodesTransformer
{
    /**
     * @param string $code
     *
     * @return null | DeliveryStatus
     */
    protected function getStateFromCode($code)
    {
        switch ($code) {
            case 'D':
            case 'D1':
            case 'D2':
            case 'RG':
            case 'DD':
            case 'B':
            case 'U':
            case 'VC':
            case 'RI':
            case 'RR':
                $state = DeliveryStatus::stateDelivered();
                break;

            default:
                $state = DeliveryStatus::stateInProgress();
                break;
        }

        return $state;
    }
}

Add some chronopost codes to recognize

Add some chronopost codes to recognize


<?php

class HTMLPurifier_ChildDef_Picture extends HTMLPurifier_ChildDef
{
    public $type = 'picture';

    /**
     * @param array $children
     * @param HTMLPurifier_Config $config
     * @param HTMLPurifier_Context $context
     * @return array
     */
    public function validateChildren($children, $config, $context)
    {
        // if there are no tokens, delete parent node
        if (empty($children)) {
            return false;
        }

        if (!isset($config->getHTMLDefinition()->info['img'])) {
            trigger_error("Cannot allow picture without allowing img", E_USER_WARNING);
            return false;
        }

        $allowSource = isset($config->getHTMLDefinition()->info['source']);
        $hasImg = false;

        $result = array();

        // Content model:
        // Zero or more source elements, followed by one img element, optionally intermixed with script-supporting elements.
        // https://html.spec.whatwg.org/multipage/embedded-content.html#the-picture-element
        foreach ($children as $node) {
            if (($allowSource && $node->name === 'source') || $node->name === 'img') {
                $result[] = $node;
            }
            if ($node->name === 'img') {
                $hasImg = true;
                break;
            }
        }

        if (!$hasImg || empty($result)) {
            return false;
        }

        return $result;
    }
}

<?php

class HTMLPurifier_ChildDef_Picture extends HTMLPurifier_ChildDef
{
    public $type = 'picture';

    public $elements = array(
        'img'    => true,
        'source' => true,
    );

    /**
     * @param array $children
     * @param HTMLPurifier_Config $config
     * @param HTMLPurifier_Context $context
     * @return array
     */
    public function validateChildren($children, $config, $context)
    {
        // if there are no tokens, delete parent node
        if (empty($children)) {
            return false;
        }

        if (!isset($config->getHTMLDefinition()->info['img'])) {
            trigger_error("Cannot allow picture without allowing img", E_USER_WARNING);
            return false;
        }

        $allowSource = isset($config->getHTMLDefinition()->info['source']);
        $hasImg = false;

        $result = array();

        // Content model:
        // Zero or more source elements, followed by one img element, optionally intermixed with script-supporting elements.
        // https://html.spec.whatwg.org/multipage/embedded-content.html#the-picture-element
        foreach ($children as $node) {
            if (($allowSource && $node->name === 'source') || $node->name === 'img') {
                $result[] = $node;
            }
            if ($node->name === 'img') {
                $hasImg = true;
                break;
            }
        }

        if (!$hasImg || empty($result)) {
            return false;
        }

        return $result;
    }
}

Add list of allowed elements to picture child def


<?php namespace Mews\Captcha;

use Illuminate\Support\ServiceProvider;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('mews/captcha');

        require __DIR__ . '/../../routes.php';
        $this->app->validator->resolver(function ($translator, $data, $rules, $messages) {
            if (empty($messages['captcha'])) {
                $messages['captcha'] = 'It seems that you have entered an invalid :attribute code. Enter the code that you see in the image below.';
            }
            return new CaptchaValidator($translator, $data, $rules, $messages);
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['captcha'] = $this->app->share(function ($app) {
            return Captcha::instance();
        });
    }

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

<?php namespace Mews\Captcha;

use Illuminate\Support\ServiceProvider;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('mews/captcha');

        require __DIR__ . '/../../routes.php';
        $this->app->validator->resolver(function ($translator, $data, $rules, $messages) {
            return new CaptchaValidator($translator, $data, $rules, $messages);
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['captcha'] = $this->app->share(function ($app) {
            return Captcha::instance();
        });
    }

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

Fix can't translate validation message

Fix can't translate validation message


<?php

declare(strict_types=1);

require dirname(__DIR__) . '/vendor/autoload.php';
array_map('unlink', (array) glob(__DIR__ . '/tmp/*.php'));
array_map('unlink', (array) glob(__DIR__ . '/Module/tmp/{*.txt,*.php}', GLOB_BRACE));

<?php

declare(strict_types=1);

use Koriym\Attributes\AttributeReader;
use Ray\ServiceLocator\ServiceLocator;

require dirname(__DIR__) . '/vendor/autoload.php';
array_map('unlink', (array) glob(__DIR__ . '/tmp/*.php'));
array_map('unlink', (array) glob(__DIR__ . '/Module/tmp/{*.txt,*.php}', GLOB_BRACE));

// no annotation in PHP 8
if (PHP_MAJOR_VERSION >= 8) {
    ServiceLocator::setReaedr(new AttributeReader());
}

Test that all tests work without annotations


<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

    // POST example api to send mail
    $app->post('/mail/send', function (Request $request, Response $response) {
        $mail = new classes\Mailer($this->mail);
        $datapost = $request->getParsedBody();

        $mail->addAddress = $datapost['To'];
        $mail->subject = $datapost['Subject'];
        $mail->body = $datapost['Message'];
        $mail->isHtml = $datapost['Html'];
        $mail->setFrom = $datapost['From'];
        $mail->setFromName = $datapost['FromName'];
        $mail->addReplyTo = $datapost['ReplyTo'];
        $mail->addReplyToName = $datapost['ReplyToName'];

        $body = $response->getBody();
        $body->write($mail->send());
        return $response
            ->withStatus(200)
            ->withHeader('Content-Type','application/json; charset=utf-8')
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withBody($body);
    });

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

    // POST example api to send mail
    $app->post('/mail/send', function (Request $request, Response $response) {
        $mail = new classes\Mailer($this->mail);
        $datapost = $request->getParsedBody();

        $mail->addAddress = $datapost['To'];
        $mail->subject = $datapost['Subject'];
        $mail->body = $datapost['Message'];
        $mail->isHtml = $datapost['Html'];
        $mail->setFrom = $datapost['From'];
        $mail->setFromName = $datapost['FromName'];
        $mail->addReplyTo = $datapost['ReplyTo'];
        $mail->addReplyToName = $datapost['ReplyToName'];
        $mail->addCC = $datapost['CC'];
        $mail->addBCC = $datapost['BCC'];
        $mail->addAttachment = $datapost['Attachment'];

        $body = $response->getBody();
        $body->write($mail->send());
        return $response
            ->withStatus(200)
            ->withHeader('Content-Type','application/json; charset=utf-8')
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withBody($body);
    });

Add support for create cc, bcc and attachment


<?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\Cart\Context;

use Zend\Stdlib\PriorityQueue;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
final class CompositeCartContext implements CartContextInterface
{
    /**
     * @var PriorityQueue|CartContextInterface[]
     */
    private $cartContexts;

    public function __construct()
    {
        $this->cartContexts = new PriorityQueue();
    }

    /**
     * @param CartContextInterface $cartContext
     */
    public function addContext(CartContextInterface $cartContext, $priority = 0)
    {
        $this->cartContexts->insert($cartContext, $priority);
    }

    /**
     * {@inheritdoc}
     */
    public function getCart()
    {
        foreach ($this->cartContexts as $cartContext) {
            try {
                return $cartContext->getCart();
            } catch (CartNotFoundException $exception) {
                continue;
            }
        }

        throw new CartNotFoundException();
    }
}

<?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\Cart\Context;

use Zend\Stdlib\PriorityQueue;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
final class CompositeCartContext implements CartContextInterface
{
    /**
     * @var PriorityQueue|CartContextInterface[]
     */
    private $cartContexts;

    public function __construct()
    {
        $this->cartContexts = new PriorityQueue();
    }

    /**
     * @param CartContextInterface $cartContext
     * @param int $priority
     */
    public function addContext(CartContextInterface $cartContext, $priority = 0)
    {
        $this->cartContexts->insert($cartContext, $priority);
    }

    /**
     * {@inheritdoc}
     */
    public function getCart()
    {
        foreach ($this->cartContexts as $cartContext) {
            try {
                return $cartContext->getCart();
            } catch (CartNotFoundException $exception) {
                continue;
            }
        }

        throw new CartNotFoundException();
    }
}

Add typehints for ServiceRegistryInterface::all() calls


<?php
namespace Criterion\UI\Controller;

class TestController
{
    public function view(\Silex\Application $app)
    {
        $data['test'] = $app['mongo']->tests->findOne(array(
            '_id' => new \MongoId($app['request']->get('id'))
        ));

        $logs = $app['mongo']->logs->find(array(
            'test_id' => new \MongoId($app['request']->get('id'))
        ));

        $data['log'] = array();
        foreach ($logs as $log)
        {
            $data['log'][] = $log;
        }

        return $app['twig']->render('Test.twig', $data);
    }

    public function delete(\Silex\Application $app)
    {
        $test = $app['mongo']->tests->findOne(array(
            '_id' => new \MongoId($app['request']->get('id'))
        ));

        if ( ! $test)
        {
            return $app->redirect('/');
        }

        $app['mongo']->tests->remove(array(
            '_id' => new \MongoId($app['request']->get('id'))
        ));

        $app['mongo']->logs->remove(array(
            'test_id' => new \MongoId($app['request']->get('id'))
        ));

        return $app->redirect('/project/' . $test['project_id']);

    }
}

<?php
namespace Criterion\UI\Controller;

class TestController
{
    public function view(\Silex\Application $app)
    {
        $data['test'] = $app['mongo']->tests->findOne(array(
            '_id' => new \MongoId($app['request']->get('id'))
        ));

        if ( ! $data['test'])
        {
            return $app->abort(404, 'Test not found.');
        }

        $logs = $app['mongo']->logs->find(array(
            'test_id' => new \MongoId($app['request']->get('id'))
        ));

        $data['log'] = array();
        foreach ($logs as $log)
        {
            $data['log'][] = $log;
        }

        return $app['twig']->render('Test.twig', $data);
    }

    public function delete(\Silex\Application $app)
    {
        $test = $app['mongo']->tests->findOne(array(
            '_id' => new \MongoId($app['request']->get('id'))
        ));

        if ( ! $test)
        {
            return $app->abort(404, 'Test not found.');
        }

        $app['mongo']->tests->remove(array(
            '_id' => new \MongoId($app['request']->get('id'))
        ));

        $app['mongo']->logs->remove(array(
            'test_id' => new \MongoId($app['request']->get('id'))
        ));

        return $app->redirect('/project/' . $test['project_id']);

    }
}

Abort when test is not found.

Abort when test is not found.


<?php

namespace AppZap\PHPFramework\Configuration;

use AppZap\PHPFramework\Mvc\ApplicationPartMissingException;

class DefaultConfiguration {

  /**
   * @param $application
   * @throws ApplicationPartMissingException
   */
  public static function initialize($application) {
    $projectRoot = self::getProjectRoot();
    $applicationDirectoryPath = $projectRoot . $application;
    $applicationDirectory = realpath($applicationDirectoryPath);
    if (!is_dir($applicationDirectory)) {
      throw new ApplicationPartMissingException('Application folder ' . htmlspecialchars($applicationDirectoryPath) . ' not found', 1410538265);
    }
    $applicationDirectory .= '/';
    Configuration::set('phpframework', 'db.migrator.directory', $applicationDirectory . '_sql/');
    Configuration::set('phpframework', 'project_root', $projectRoot);
    Configuration::set('application', 'application', $application);
    Configuration::set('application', 'application_directory', $applicationDirectory);
    Configuration::set('application', 'routes_file', $applicationDirectory . 'routes.php');
    Configuration::set('application', 'templates_directory', $applicationDirectory . 'templates/');
    Configuration::set('phpframework', 'version', '1.4');
  }

  /**
   * @return string
   */
  protected static function getProjectRoot() {
    if (isset($_ENV['AppZap\PHPFramework\ProjectRoot'])) {
      $projectRoot = $_ENV['AppZap\PHPFramework\ProjectRoot'];
    } else {
      $projectRoot = getcwd();
    }
    $projectRoot = rtrim($projectRoot, '/') . '/';
    return $projectRoot;
  }

}

<?php

namespace AppZap\PHPFramework\Configuration;

use AppZap\PHPFramework\Mvc\ApplicationPartMissingException;

class DefaultConfiguration {

  /**
   * @param $application
   * @throws ApplicationPartMissingException
   */
  public static function initialize($application) {
    $projectRoot = self::getProjectRoot();
    $applicationDirectoryPath = $projectRoot . $application;
    $applicationDirectory = realpath($applicationDirectoryPath);
    if (!is_dir($applicationDirectory)) {
      throw new ApplicationPartMissingException('Application folder ' . htmlspecialchars($applicationDirectoryPath) . ' not found', 1410538265);
    }
    $applicationDirectory .= '/';
    Configuration::set('phpframework', 'db.migrator.directory', $applicationDirectory . '_sql/');
    Configuration::set('phpframework', 'project_root', $projectRoot);
    Configuration::set('application', 'application', $application);
    Configuration::set('application', 'application_directory', $applicationDirectory);
    Configuration::set('application', 'routes_file', $applicationDirectory . 'routes.php');
    Configuration::set('application', 'templates_directory', $applicationDirectory . 'templates/');
    Configuration::set('phpframework', 'version', '1.5-dev');
  }

  /**
   * @return string
   */
  protected static function getProjectRoot() {
    if (isset($_ENV['AppZap\PHPFramework\ProjectRoot'])) {
      $projectRoot = $_ENV['AppZap\PHPFramework\ProjectRoot'];
    } else {
      $projectRoot = getcwd();
    }
    $projectRoot = rtrim($projectRoot, '/') . '/';
    return $projectRoot;
  }

}

Set PHPFramework version to 1.5-dev

Set PHPFramework version to 1.5-dev


<?php

namespace Parabot\BDN\BotBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Parabot\BDN\BotBundle\Entity\Script;
use Parabot\BDN\BotBundle\Entity\Scripts\Git;
use Parabot\BDN\UserBundle\Entity\User;

/**
 * ScriptRepository
 */
class ScriptRepository extends EntityRepository {

    /**
     * @param int $id
     *
     * @return null|Git
     */
    public function findOneGitById($id) {
        /** @var Script $result */
        $result = $this->findOneBy([ 'id' => $id ]);
        if($result != null) {
            if(($git = $result->getGit()) != null) {
                return $result->getGit();
            }
        }

        return null;
    }

    /**
     * @param User $user
     *
     * @return Script[]
     */
    public function findByAuthor($user) {
        $query = $this->getEntityManager()->createQuery(
            'SELECT s FROM BDNBotBundle:Script s JOIN s.authors a WHERE a.id = :id'
        )->setParameter('id', $user->getId());

        return $query->getResult();
    }
}

<?php

namespace Parabot\BDN\BotBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Parabot\BDN\BotBundle\Entity\Script;
use Parabot\BDN\BotBundle\Entity\Scripts\Git;
use Parabot\BDN\UserBundle\Entity\User;

/**
 * ScriptRepository
 */
class ScriptRepository extends EntityRepository {

    /**
     * @param int $id
     *
     * @return null|Git
     */
    public function findOneGitById($id) {
        /** @var Script $result */
        $result = $this->findOneBy([ 'id' => $id ]);
        if($result != null) {
            if(($git = $result->getGit()) != null) {
                return $result->getGit();
            }
        }

        return null;
    }

    /**
     * @param User $user
     *
     * @return Script[]
     */
    public function findByAuthor($user) {
        $query = $this->getEntityManager()->createQuery(
            'SELECT s FROM BDNBotBundle:Script s JOIN s.authors a WHERE a.id = :id AND s.active = 1'
        )->setParameter('id', $user->getId());

        return $query->getResult();
    }
}

[TASK] Set active to true, because non active scripts shouldn't appear


<?php namespace Lecturize\Taxonomies\Traits;

use Lecturize\Taxonomies\Models\Taxonomy;
use Lecturize\Taxonomies\Models\Term;

/**
 * Class ModelFinder
 * @package Lecturize\Taxonomies\Traits
 */
trait ModelFinder
{
    /**
     * Find term by slug.
     *
     * @param  string  $slug
     * @return Term
     */
    public function findTerm(string $slug): Term
    {
        return Term::whereSlug($slug)->first();
    }

    /**
     * Find taxonomy by term id.
     *
     * @param  int     $term_id
     * @param  string  $taxonomy
     * @return Taxonomy
     */
    public function findTaxonomyByTerm(int $term_id, string $taxonomy): Taxonomy
    {
        return $this->findCategory($term_id, $taxonomy, 'id');
    }

    /**
     * Find category by term (category title) and taxonomy.
     *
     * @param  string|int  $term
     * @param  string      $taxonomy
     * @param  string      $term_field
     * @return Taxonomy
     */
    public function findCategory($term, string $taxonomy, string $term_field = 'title'): Taxonomy
    {
        return Taxonomy::taxonomy($taxonomy)
                       ->term($term, $term_field)
                       ->first();
    }
}

<?php namespace Lecturize\Taxonomies\Traits;

use Lecturize\Taxonomies\Models\Taxonomy;
use Lecturize\Taxonomies\Models\Term;

/**
 * Class ModelFinder
 * @package Lecturize\Taxonomies\Traits
 */
trait ModelFinder
{
    /**
     * Find term by slug.
     *
     * @param  string  $slug
     * @return Term
     */
    public function findTerm(string $slug)
    {
        return Term::whereSlug($slug)->first();
    }

    /**
     * Find taxonomy by term id.
     *
     * @param  int     $term_id
     * @param  string  $taxonomy
     * @return Taxonomy
     */
    public function findTaxonomyByTerm(int $term_id, string $taxonomy)
    {
        return $this->findCategory($term_id, $taxonomy, 'id');
    }

    /**
     * Find category by term (category title) and taxonomy.
     *
     * @param  string|int  $term
     * @param  string      $taxonomy
     * @param  string      $term_field
     * @return Taxonomy
     */
    public function findCategory($term, string $taxonomy, string $term_field = 'title')
    {
        return Taxonomy::taxonomy($taxonomy)
                       ->term($term, $term_field)
                       ->first();
    }
}

Remove return types for now

Remove return types for now


<?php

namespace Rhubarb\Website\UrlHandlers;

use Rhubarb\Crown\UrlHandlers\UrlHandler;

require_once "vendor/rhubarbphp/rhubarb/src/UrlHandlers/UrlHandler.php";
require_once "vendor/geeks-dev/php-markdown-extra-extended-stylish/markdown_extended_stylish.php";

class MarkdownUrlHandler extends UrlHandler
{
    /**
     * Return the response if appropriate or false if no response could be generated.
     *
     * @param mixed $request
     * @return bool
     */
    protected function generateResponseForRequest($request = null)
    {
        $url = $request->UrlPath;

        if ($url[strlen($url) - 1] == "/") {
            $url = $url . "index";
        }

        $rootPath = "docs";

        // If this is the manual - we could be looking at other rhubarb projects.
        if ( preg_match( "/\/manual\/([^\/]+)\//", $url, $match ) )
        {
            $url = str_replace( $match[0], "", $url );
            $rootPath = "vendor/rhubarbphp/".$match[1]."/docs/";
        }

        // Look to see if there's a markdown file at this location.
        if (file_exists($rootPath . $url . ".md")) {
            $markDownRaw = file_get_contents($rootPath . $url . ".md");

            return MarkdownExtended($markDownRaw);
        }
    }
}

<?php

namespace Rhubarb\Website\UrlHandlers;

use Rhubarb\Crown\UrlHandlers\UrlHandler;

require_once "vendor/rhubarbphp/rhubarb/src/UrlHandlers/UrlHandler.php";
require_once "vendor/geeks-dev/php-markdown-extra-extended-stylish/markdown_extended_stylish.php";

class MarkdownUrlHandler extends UrlHandler
{
    /**
     * Return the response if appropriate or false if no response could be generated.
     *
     * @param mixed $request
     * @return bool
     */
    protected function generateResponseForRequest($request = null)
    {
        $url = $request->urlPath;

        if ($url[strlen($url) - 1] == "/") {
            $url = $url . "index";
        }

        $rootPath = "docs";

        // If this is the manual - we could be looking at other rhubarb projects.
        if ( preg_match( "/\/manual\/([^\/]+)\//", $url, $match ) )
        {
            $url = str_replace( $match[0], "", $url );
            $rootPath = "vendor/rhubarbphp/".$match[1]."/docs/";
        }

        // Look to see if there's a markdown file at this location.
        if (file_exists($rootPath . $url . ".md")) {
            $markDownRaw = file_get_contents($rootPath . $url . ".md");

            return MarkdownExtended($markDownRaw);
        }
    }
}

Fix for markdown handler when using application objects branch


<?php

namespace Ojs\JournalBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;

/**
 * ArticleFileRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ArticleFileRepository extends EntityRepository
{

    /**
     * Get Article full text file.
     * @param  integer                   $articleId
     * @return ArticleFile[]
     * @throws UsernameNotFoundException
     */
    public function getArticleFullTextFiles($articleId)
    {
        try {
            $article = $this
                ->getEntityManager()
                ->getRepository('OjsJournalBundle:Article')
                ->find($articleId);

            if (!$article) {
                throw new NoResultException();
            }

            $q = $this
                ->createQueryBuilder('a')
                ->select('a')
                ->where('a.article = :article AND a.type= 0')
                ->setParameter('article', $article)
                ->getQuery();

            // The Query::getResult() method throws an exception
            // if there is no record matching the criteria.
            return $q->getResult();
        } catch (NoResultException $e) {
            $message = sprintf('There is no full text file for this article.');
            throw new UsernameNotFoundException($message, 0, $e); // TODO: UsernameNotFoundException?!
        }
    }
}

<?php

namespace Ojs\JournalBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;

/**
 * ArticleFileRepository
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ArticleFileRepository extends EntityRepository
{
    /**
     * Get Article full text file.
     * @param  integer $articleId
     * @return ArticleFile[]
     * @throws NoResultException
     */
    public function getArticleFullTextFiles($articleId)
    {
        try {
            $article = $this
                ->getEntityManager()
                ->getRepository('OjsJournalBundle:Article')
                ->find($articleId);

            if (!$article) {
                throw new NoResultException();
            }

            $q = $this
                ->createQueryBuilder('a')
                ->select('a')
                ->where('a.article = :article AND a.type= 0')
                ->setParameter('article', $article)
                ->getQuery();

            // The Query::getResult() method throws an exception
            // if there is no record matching the criteria.
            return $q->getResult();
        } catch (NoResultException $e) {
            $message = sprintf('There is no full text file for this article.');
            throw new NoResultException($message, 0, $e);
        }
    }
}

Change the exception with a more sensible one


<?php

namespace BetterReflectionTest\Fixture\InvalidInheritances
{
    interface AInterface {}
    class AClass {}
    trait ATrait {}

    interface InterfaceExtendingClass extends AClass {}
    class ClassExtendingInterface extends AInterface {}
    class ClassExtendingTrait extends ATrait {}
}

<?php

namespace BetterReflectionTest\Fixture\InvalidInheritances
{
    interface AInterface {}
    class AClass {}
    trait ATrait {}

    interface InterfaceExtendingClass extends AClass {}
    interface InterfaceExtendingTrait extends ATrait {}
    class ClassExtendingInterface extends AInterface {}
    class ClassExtendingTrait extends ATrait {}
}

Test asset: interface extending a trait (invalid)


<?php

namespace Rogue\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['event_id', 'signup_id', 'northstar_id'];

    protected $primaryKey = ['event_id'];

    // protected $with = ['content'];

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * Returns Post data
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function content()
    {
        return $this->morphTo('postable');
    }

    /**
     * Each post has events.
     */
    public function events()
    {
        return $this->morphMany(Event::class, 'eventable');
    }

    /**
     * Each post belongs to a signup.
     */
    public function signup()
    {
        return $this->belongsTo(Signup::class);
    }

    /**
     * Each post has one review.
     */
    public function review()
    {
        return $this->hasOne(Review::class);
    }

    /**
     * Get the reactions associated with this post.
     */
    public function reactions()
    {
        return $this->hasMany(Reaction::class);
    }
}

<?php

namespace Rogue\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['id', 'signup_id', 'northstar_id', 'url', 'caption', 'status', 'source', 'remote_addr'];

    /**
     * Each post has events.
     */
    public function events()
    {
        return $this->morphMany(Event::class, 'eventable');
    }

    /**
     * Each post belongs to a signup.
     */
    public function signup()
    {
        return $this->belongsTo(Signup::class);
    }

    /**
     * Each post has one review.
     */
    public function review()
    {
        return $this->hasOne(Review::class);
    }

    /**
     * Get the reactions associated with this post.
     */
    public function reactions()
    {
        return $this->hasMany(Reaction::class);
    }
}

Fix a bad merge conflict resolution

Fix a bad merge conflict resolution


<?php

namespace Guzzle\Log;

use Monolog\Logger;

/**
 * @deprecated
 * @codeCoverageIgnore
 */
class MonologLogAdapter extends AbstractLogAdapter
{
    /**
     * syslog to Monolog mappings
     */
    private static $mapping = array(
        LOG_DEBUG   => Logger::DEBUG,
        LOG_INFO    => Logger::INFO,
        LOG_WARNING => Logger::WARNING,
        LOG_ERR     => Logger::ERROR,
        LOG_CRIT    => Logger::CRITICAL,
        LOG_ALERT   => Logger::ALERT
    );

    public function __construct(Logger $logObject)
    {
        $this->log = $logObject;
    }

    public function log($message, $priority = LOG_INFO, $extras = array())
    {
        $this->log->addRecord(self::$mapping[$priority], $message);
    }
}

<?php

namespace Guzzle\Log;

use Monolog\Logger;

/**
 * @deprecated
 * @codeCoverageIgnore
 */
class MonologLogAdapter extends AbstractLogAdapter
{
    /**
     * syslog to Monolog mappings
     */
    private static $mapping = array(
        LOG_DEBUG   => Logger::DEBUG,
        LOG_INFO    => Logger::INFO,
        LOG_WARNING => Logger::WARNING,
        LOG_ERR     => Logger::ERROR,
        LOG_CRIT    => Logger::CRITICAL,
        LOG_ALERT   => Logger::ALERT
    );

    public function __construct(Logger $logObject)
    {
        $this->log = $logObject;
    }

    public function log($message, $priority = LOG_INFO, $extras = array())
    {
        $this->log->addRecord(self::$mapping[$priority], $message, $extras);
    }
}

Use the $extras argument as a $context parameter

Useful for providing dynamic data while keeping the same $message for several events.


<?php namespace GeneaLabs\Phpgmaps;

use GeneaLabs\Phpgmaps\Facades\PhpgmapsFacade;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;

class PhpgmapsServiceProvider extends ServiceProvider
{

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['phpgmaps'] = $this->app->share(function ($app) {
            return new Phpgmaps();
        });
    }

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

<?php namespace GeneaLabs\Phpgmaps;

use GeneaLabs\Phpgmaps\Facades\PhpgmapsFacade;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;

class PhpgmapsServiceProvider extends ServiceProvider
{

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['phpgmaps'] = $this->app->share(function ($app) {
            return new Phpgmaps(['http' => $app->make('request')->secure()]);
        });
    }

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

Set schema (http or https) config setting


//A file to smooth over any shortcomings of Titanium

// Ti.Codec.decodeBase64 doesn't work as expected.
// This is a workaround to write encoded binary assets to the disk
function writeBase64Asset($path, $data) {
    return file_put_contents($path, base64_decode($data));
}

function random($min, $max) {
    return rand($min, $max);
}

Add easy random via php

Add easy random via php


<?php

/**
 * CUSTOM
 *
 */

function enqueue_scripts() {

	wp_enqueue_script( 'jquery' );

	// Enqueue application bundles
 	wp_enqueue_style( 'main', get_template_directory_uri() . '/css/index-bundle.css');
	wp_enqueue_script( 'main', get_template_directory_uri() . '/js/index-bundle.js', array( 'jquery'), false, true);
}

add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );

// Init Bootstrap Hooks
if (function_exists('wp_bootstrap_hooks')) {
	wp_bootstrap_hooks(4);
}

// Include Custom Template Tags
require get_template_directory() . '/inc/remove-admin-bar-css.php';

<?php

// Include Custom Template Tags
require get_template_directory() . '/inc/remove-admin-bar-css.php';

// Init Bootstrap Hooks
if (function_exists('wp_bootstrap_hooks')) {
  wp_bootstrap_hooks(4);
}

// Enqueue Scripts
function enqueue_scripts() {
	wp_enqueue_script( 'jquery' );
 	wp_enqueue_style( 'main', get_template_directory_uri() . '/css/index-bundle.css');
	wp_enqueue_script( 'main', get_template_directory_uri() . '/js/index-bundle.js', array( 'jquery'), false, true);
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );

// Register widget area.
register_sidebar( array(
  'name'          => __( 'Widget Area', 'kicks-app' ),
  'id'            => 'sidebar-1',
  'description'   => __( 'Add widgets here to appear in your sidebar.', 'kicks-app' ),
  'before_widget' => '',
  'after_widget'  => ''
) );

function bootstrap_get_search_form_args($args) {
  return array_merge($args, array(
    'submit_label' => ''
  ));
}
add_filter( 'wp_bootstrap_get_search_form_args', 'bootstrap_get_search_form_args' );

Add Widgets and Search Form icon

Add Widgets and Search Form icon


<?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\Currency\Model;

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 CurrencyInterface extends
    TimestampableInterface,
    ToggleableInterface,
    ResourceInterface
{
    /**
     * @return string
     */
    public function getCode();

    /**
     * @param string $code
     */
    public function setCode($code);

    /**
     * Get the human-friendly name.
     *
     * @return string
     */
    public function getName();

    /**
     * @return float
     */
    public function getExchangeRate();

    /**
     * @param float $rate
     */
    public function setExchangeRate($rate);
}

<?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\Currency\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 CurrencyInterface extends
    CodeAwareInterface,
    TimestampableInterface,
    ToggleableInterface,
    ResourceInterface
{
    /**
     * Get the human-friendly name.
     *
     * @return string
     */
    public function getName();

    /**
     * @return float
     */
    public function getExchangeRate();

    /**
     * @param float $rate
     */
    public function setExchangeRate($rate);
}

Add immutable code to Currency [CurrencyBundle] Add AddCodeFormSubscriber to CurrencyType [ResourceBundle] Modify AddCodeFormSubscriber to make possible passing type of code field [Currency] Introduce code for Currency


<?php

namespace Mediator;

require_once __DIR__ . '/User.php';
require_once __DIR__ . '/Chatroom.php';

/**
 * 発生したトラブルを表すクラス、トラブル番号(number)を持つ
 *
 * @access public
 * @extends \Mediator\User
 * @author ku2ma2 <motorohi.tsumaniku@gmail.com>
 * @copyright ku2ma2
 */
class UserDefault extends User
{

    /**
     * メッセージ送信
     *
     * @access public
     * @param string $to 受信者名
     * @param string $message メッセージ
     * @return void
     */
    public function sendMessage(string $to, string $message)
    {
        $this->chatroom->sendMessage($this->name, $to, $message);
    }

    /**
     * メッセージ受信
     *
     * @access public
     * @param string $from メッセージ送信者
     * @return string フォーマット化された文字列
     */
    public function receiveMessage(string $from, string $message)
    {
        printf("%sさん => %sさん: %s\n------------------------------\n", $from, $this->getName(), $message);
    }
}

<?php

namespace Mediator;

require_once __DIR__ . '/User.php';
require_once __DIR__ . '/Chatroom.php';

/**
 * 通常ユーザー
 *
 * @access public
 * @extends \Mediator\User
 * @author ku2ma2 <motorohi.tsumaniku@gmail.com>
 * @copyright ku2ma2
 */
class UserDefault extends User
{

    /**
     * メッセージ送信
     *
     * @access public
     * @param string $to 受信者名
     * @param string $message メッセージ
     * @return void
     */
    public function sendMessage(string $to, string $message)
    {
        $this->chatroom->sendMessage($this->name, $to, $message);
    }

    /**
     * メッセージ受信
     *
     * @access public
     * @param string $from メッセージ送信者
     * @return string フォーマット化された文字列
     */
    public function receiveMessage(string $from, string $message)
    {
        printf("%sさん => %sさん: %s\n------------------------------\n", $from, $this->getName(), $message);
    }
}

Fix typo in Mediator pattern

Fix typo in Mediator pattern


<?php

namespace Northstar\Merge;

class Merger
{
    public function __construct()
    {
    }

    public function merge($field, $target, $duplicate)
    {
        switch ($field) {
            case 'last_authenticated_at':
                return $this->mergeLastAuthenticatedAt($target, $duplicate);
            case 'last_messaged_at':
                return $this->mergeLastMessagedAt($target, $duplicate);
            default:
                return false;
        }
    }

    public function mergeLastAuthenticatedAt($target, $duplicate)
    {
        $targetValue = $target->last_authenticated_at;
        $duplicateValue = $duplicate->last_authenticated_at;

        return $targetValue > $duplicateValue ? $targetValue : $duplicateValue;
    }

    public function mergeLastMessagedAt($target, $duplicate)
    {
        $targetValue = $target->last_messaged_at;
        $duplicateValue = $duplicate->last_messaged_at;

        return $targetValue > $duplicateValue ? $targetValue : $duplicateValue;
    }
}

<?php

namespace Northstar\Merge;

class Merger
{
    public function __construct()
    {
    }

    public function merge($field, $target, $duplicate)
    {
        $mergeMethod = 'merge' . studly_case($field);

        if (! method_exists($this, $mergeMethod)) {
            // throw error here
            return false;
        }

        return $this->{$mergeMethod}($target, $duplicate);
    }

    public function mergeLastAuthenticatedAt($target, $duplicate)
    {
        $targetValue = $target->last_authenticated_at;
        $duplicateValue = $duplicate->last_authenticated_at;

        return $targetValue > $duplicateValue ? $targetValue : $duplicateValue;
    }

    public function mergeLastMessagedAt($target, $duplicate)
    {
        $targetValue = $target->last_messaged_at;
        $duplicateValue = $duplicate->last_messaged_at;

        return $targetValue > $duplicateValue ? $targetValue : $duplicateValue;
    }
}

Kill switch and check if method exists instead


<?php
# Copyright (C) 2008	John Reese
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

access_ensure_global_level( plugin_config_get( 'manage_threshold' ) );

$f_repo_id = gpc_get_int( 'repo_id' );
$f_repo_name = gpc_get_string( 'repo_name' );
$f_repo_url = gpc_get_string( 'repo_url' );

$t_repo = SourceRepo::load( $f_repo_id );
$t_type = SourceType($t_repo->type);

$t_repo->name = $f_repo_name;
$t_repo->url = $f_repo_url;

$t_repo = event_signal( 'EVENT_SOURCE_UPDATE_REPO', array( $t_repo ) );

$t_repo->save();

print_successful_redirect( plugin_page( 'repo_manage_page', true ) . '&id=' . $t_repo->id );

<?php
# Copyright (C) 2008	John Reese
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

access_ensure_global_level( plugin_config_get( 'manage_threshold' ) );

$f_repo_id = gpc_get_int( 'repo_id' );
$f_repo_name = gpc_get_string( 'repo_name' );
$f_repo_url = gpc_get_string( 'repo_url' );

$t_repo = SourceRepo::load( $f_repo_id );
$t_type = SourceType($t_repo->type);

$t_repo->name = $f_repo_name;
$t_repo->url = $f_repo_url;

$t_updated_repo = event_signal( 'EVENT_SOURCE_UPDATE_REPO', array( $t_repo ) );

if ( !is_null( $t_updated_repo ) ) {
	$t_updated_repo->save();
} else {
	$t_repo->save();
}

print_successful_redirect( plugin_page( 'repo_manage_page', true ) . '&id=' . $t_repo->id );

Fix repo update when null is returned (eg, no plugin has modified the repo).


<?php

namespace App\Console;

use App\Models\Draw;
use App\Jobs\ParseBounces;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule
            ->call(function () {
                Draw::cleanup();
            })
            ->daily()
            ->environments('prod');

        $schedule
            ->job(new ParseBounces)
            ->everyMinute()
            ->withoutOverlapping()
            ->environments('prod');
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

<?php

namespace App\Console;

use App\Models\Draw;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule
            ->call(function () {
                Draw::cleanup();
            })
            ->daily()
            ->environments('prod');

        $schedule
            ->command('bounces:parse')
            ->everyMinute()
            ->withoutOverlapping()
            ->environments('prod');
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

Change parseBounce cron from a job (queued) to a command (direct)


<?php

class m131125_152138_create_paytrail_result_table extends CDbMigration
{
    public function up()
    {
        $this->execute(
            "CREATE TABLE `paytrail_result` (
                `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
                `paymentId` INT UNSIGNED NOT NULL,
                `orderNumber` VARCHAR(64) NOT NULL,
                `token` VARCHAR(64) NOT NULL,
                `url` TEXT NOT NULL,
                `status` TINYINT(4) NOT NULL DEFAULT '0',
                PRIMARY KEY (`id`)
            ) COLLATE='utf8_general_ci' ENGINE=InnoDB;"
        );
        $this->addForeignKey('paytrail_result_paymentId', 'paytrail_result', 'paymentId', 'paytrail_payment', 'id');
    }

    public function down()
    {
        $this->dropForeignKey('paytrail_result_paymentId', 'paytrail_result');
        $this->dropTable('paytrail_result');
    }
}

<?php

class m131125_152138_create_paytrail_result_table extends CDbMigration
{
    public function up()
    {
        $this->execute(
            "CREATE TABLE `paytrail_result` (
                `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
                `paymentId` INT UNSIGNED NOT NULL,
                `orderNumber` VARCHAR(64) NOT NULL,
                `token` VARCHAR(64) NOT NULL,
                `url` TEXT NOT NULL,
                `status` TINYINT(4) NOT NULL DEFAULT '0',
                PRIMARY KEY (`id`)
            ) COLLATE='utf8_general_ci' ENGINE=InnoDB;"
        );
    }

    public function down()
    {
        $this->dropTable('paytrail_result');
    }
}

Remove foreign keys from paytrail_result table creation migration

The foreign keys are added through another migration that is run after this one


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\Utils\Mapping\AnnotationDriver;

use Darvin\Utils\Mapping\Annotation\Transliteratable;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;

/**
 * Transliteratable annotation driver
 */
class TransliteratableDriver extends AbstractDriver
{
    /**
     * {@inheritdoc}
     */
    public function readMetadata(ClassMetadata $doctrineMeta, array &$meta)
    {
        $meta['transliteratable'] = array();

        foreach ($doctrineMeta->getReflectionClass()->getProperties() as $reflectionProperty) {
            $transliteratableAnnotation = $this->reader->getPropertyAnnotation(
                $reflectionProperty,
                Transliteratable::ANNOTATION
            );

            if ($transliteratableAnnotation instanceof Transliteratable) {
                $meta['transliteratable'][$reflectionProperty->getName()] = get_object_vars(
                    $transliteratableAnnotation
                );
            }
        }
    }
}

<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\Utils\Mapping\AnnotationDriver;

use Darvin\Utils\Mapping\Annotation\Transliteratable;
use Darvin\Utils\Mapping\MappingException;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;

/**
 * Transliteratable annotation driver
 */
class TransliteratableDriver extends AbstractDriver
{
    /**
     * {@inheritdoc}
     */
    public function readMetadata(ClassMetadata $doctrineMeta, array &$meta)
    {
        $meta['transliteratable'] = array();

        foreach ($doctrineMeta->getReflectionClass()->getProperties() as $reflectionProperty) {
            $transliteratableAnnotation = $this->reader->getPropertyAnnotation(
                $reflectionProperty,
                Transliteratable::ANNOTATION
            );

            if ($transliteratableAnnotation instanceof Transliteratable) {
                if (!$doctrineMeta->hasField($reflectionProperty->getName())) {
                    $message = sprintf(
                        'Property "%s::$%s" annotated with "%s" annotation must be mapped field.',
                        $doctrineMeta->getName(),
                        $reflectionProperty->getName(),
                        Transliteratable::ANNOTATION
                    );

                    throw new MappingException($message);
                }

                $meta['transliteratable'][$reflectionProperty->getName()] = get_object_vars(
                    $transliteratableAnnotation
                );
            }
        }
    }
}

Check if property is mapped field in transliteratable annotation driver.


<?php

/**
 * @file
 * This file documents all available hook functions to manipulate data.
 */

/**
 * Define custom queries to be used when batching through "children" of objects.
 *
 * @param FedoraObject $object
 *   A FedoraObject.
 *
 * @return array
 *   An array of queries to be returned to the islandora_xacml_editor module.
 *   Each entry in the array is an associate array itself with the following
 *   structure:
 *   - type: The type of query to be executed either itql or sparql.
 *   - query: The defined query string.
 *   - description: Human-readable description used in populating the options
 *   dropdown.
 */
function hook_islandora_xacml_editor_child_query($object) {
  return array(
    'sample_query' => array(
      'type' => 'itql',
      'query' => 'select $object from <#ri> where $object <fedora-rels-ext:isMemberOfCollection> <info:fedora/islandora:root>',
      'description' => t('Sweet query bro.'),
    ),
  );
}

<?php

/**
 * @file
 * This file documents all available hook functions to manipulate data.
 */

/**
 * Define custom queries to be used when batching through "children" of objects.
 *
 * @param FedoraObject $object
 *   A FedoraObject.
 *
 * @return array
 *   An array of queries to be returned to the islandora_xacml_editor module.
 *   Each entry in the array is an associate array itself with the following
 *   structure:
 *   - type: The type of query to be executed either itql or sparql.
 *   - query: The defined query string. The field we expect returned is that of
 *     "object". I.e select ?object.
 *   - description: Human-readable description used in populating the options
 *   dropdown.
 */
function hook_islandora_xacml_editor_child_query($object) {
  return array(
    'sample_query' => array(
      'type' => 'itql',
      'query' => 'select $object from <#ri> where $object <fedora-rels-ext:isMemberOfCollection> <info:fedora/islandora:root>',
      'description' => t('Sweet query bro.'),
    ),
  );
}

Clarify API doc a smidge.

Clarify API doc a smidge.


<?php

/*
 * This file is part of CSBill project.
 *
 * (c) 2013-2015 Pierre du Plessis <info@customscripts.co.za>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

$config = [
    'templating' => [
        'engines' => ['twig'],
    ],
    'assets' => [
        'version' => CSBill\CoreBundle\CSBillCoreBundle::VERSION,
    ]
];

if ($container->hasParameter('base_url')) {
    $config['assets']['base_urls'] = ['%base_url%'];
}

$container->loadFromExtension(
    'framework',
    $config
);

<?php

/*
 * This file is part of CSBill project.
 *
 * (c) 2013-2015 Pierre du Plessis <info@customscripts.co.za>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;

try {
    $baseUrl = $container->getParameter('base_url');
} catch (ParameterNotFoundException $e) {
    $baseUrl = null;
}

$config = [
    'templating' => [
        'engines' => ['twig'],
    ],
    'assets' => [
        'version' => CSBill\CoreBundle\CSBillCoreBundle::VERSION,
    ]
];

if (null !== $baseUrl) {
    $config['assets']['base_urls'] = ['%base_url%'];
}

$container->loadFromExtension(
    'framework',
    $config
);

Fix asset url error when no base url is set


<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class {{class}} extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('{{table}}', function(Blueprint $table)
		{
			$table->increments('id');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('{{table}}');
	}

}

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class {{class}} extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('{{table}}', function(Blueprint $table)
		{
			$table->increments('id');
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('{{table}}');
	}

}

Add timestamps column to migration stub.

This is consistent with the default setting for Eloquent models, having timestamps enabled.

Fixes #865.


<?php
/**
 * Returns the HTML for Fact Page list.
 *
 * Available Variables
 * - $links: Array of links, keyed by the cause name.
 */
?>

<?php print t('List of All Facts'); ?>

			<?php foreach ($links as $cause => $fact_pages): ?>

<?php print $cause; ?>

			    <?php foreach ($fact_pages as $link): ?>

<?php print $link; ?>

			    <?php endforeach ; ?>

			<?php endforeach; ?>

Use compacted lists on fact index page.

Use compacted lists on fact index page.


<?php

namespace Knp\RadBundle\Controller;

use Symfony\Component\HttpFoundation\Request;

class AssistantController extends Controller
{
    public function missingViewAction($viewName, $viewParams)
    {
        $viewPath = $this->get('knp_rad.view.path_deducer')->deducePath($viewName);
        $viewBody = $this->renderView(
            'KnpRadBundle:Assistant:_viewBody.twig.twig',
            array(
                'viewParams' => $viewParams
            )
        );

        return $this->render(
            'KnpRadBundle:Assistant:missingView.html.twig',
            array(
                'viewName'   => $viewName,
                'viewBody'   => $viewBody,
                'viewParams' => $viewParams,
                'viewPath'   => $viewPath,
            )
        );
    }

    public function createViewAction(Request $request)
    {
        $viewName = $request->request->get('viewName');
        $viewBody = $request->request->get('viewBody');
        $viewPath = $this->get('knp_rad.view.path_deducer')->deducePath($viewName);

        // in case directory does not exist
        $this->get('filesystem')->touch($viewPath);

        file_put_contents($viewPath, $viewBody);

        return new Response(null, 201);
    }
}

<?php

namespace Knp\RadBundle\Controller;

use Symfony\Component\HttpFoundation\Request;

class AssistantController extends Controller
{
    public function missingViewAction($viewName, $viewParams)
    {
        $viewPath = $this->get('knp_rad.view.path_deducer')->deducePath($viewName);
        $viewBody = $this->renderView(
            'KnpRadBundle:Assistant:_viewBody.twig.twig',
            array(
                'viewParams' => $viewParams
            )
        );

        return $this->render(
            'KnpRadBundle:Assistant:missingView.html.twig',
            array(
                'viewName'   => $viewName,
                'viewBody'   => $viewBody,
                'viewParams' => $viewParams,
                'viewPath'   => $viewPath,
            )
        );
    }

    public function createViewAction(Request $request)
    {
        $viewName = $request->request->get('viewName');
        $viewBody = $request->request->get('viewBody');
        $viewPath = $this->get('knp_rad.view.path_deducer')->deducePath($viewName);

        // in case directory does not exist
        $this->get('filesystem')->mkdir(dirname($viewPath));

        file_put_contents($viewPath, $viewBody);

        return new Response(null, 201);
    }
}

Fix directory creation by view assistant creator


<?php

require('wp_bootstrap_navwalker.php');

function wp_bootstrap_nav_menu_args($args) {

  $args = array_merge($args, array(
    //'container'         => 'div',
    //'container_class'   => 'collapse navbar-collapse',
    //'container_id'      => 'navbar-collapse',
    'menu_class'        => 'nav navbar-nav'
  ));

  if (empty($args['walker'])) {

    $args['fallback_cb'] = 'wp_bootstrap_navwalker::fallback';
    $args['walker'] = new wp_bootstrap_navwalker();
  }

  return $args;
}

?>

<?php

require('wp_bootstrap_navwalker.php');

function wp_bootstrap_nav_menu_args($args) {
  // Navbar walker does only apply to primary menu

  $menu_class = isset($args['menu_class']) ? $args['menu_class'] . ' ' : '';

  $args = array_merge($args, array(
    'menu_class'        => $menu_class . 'nav'
  ));

  if (isset($args['theme_location']) && trim($args['theme_location']) === 'primary') {
    $args['menu_class'] = $args['menu_class'] . " navbar-nav";
  }

  if (empty($args['walker'])) {
    $args['fallback_cb'] = 'wp_bootstrap_navwalker::fallback';
    $args['walker'] = new wp_bootstrap_navwalker();
  }

  return $args;
}
?>

Use navbar for primary theme location

Use navbar for primary theme location


<?php

/**
 * All containers of cell renders must implement this interface
 *
 * @package   Swat
 * @copyright 2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
interface SwatCellRendererContainer
{
	/**
	 * Adds a cell renderer to this container
	 *
	 * @param SwatCellRenderer $renderer a reference to the cell renderer to
	 *                                    add to this container.
	 */
	public function addRenderer($renderer);

	/**
	 * Gets all cell renderers in this container as a flat array
	 *
	 * @return array all the cell renderers in this container.
	 */
	public function getRenderers();

	/**
	 * Gets a cell renderer by it's unique identifier
	 *
	 * @param string $renderer_id the unique identifier of the cell renderer to
	 *                             get from this container.
	 *
	 * @return SwatCellRenderer a reference to the cell renderer.
	 */
	public function getRenderer($renderer_id);
}

?>

<?php

/**
 * All containers of cell renders must implement this interface
 *
 * @package   Swat
 * @copyright 2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
interface SwatCellRendererContainer
{
	/**
	 * Adds a cell renderer to this container
	 *
	 * @param SwatCellRenderer $renderer a reference to the cell renderer to
	 *                                    add to this container.
	 */
	public function addRenderer($renderer);

	/**
	 * Gets all cell renderers in this container as a flat array
	 *
	 * @return array all the cell renderers in this container.
	 */
	public function &getRenderers();

	/**
	 * Gets a cell renderer by it's unique identifier
	 *
	 * @param string $renderer_id the unique identifier of the cell renderer to
	 *                             get from this container.
	 *
	 * @return SwatCellRenderer a reference to the cell renderer or null if the
	 *                           renderer is not found.
	 */
	public function getRenderer($renderer_id);
}

?>

Return array of renderers by reference.

Return array of renderers by reference.

Update documentaion for getRenderer()

svn commit r975