<?php

$config = null; // We're doing this here so it can be instantiated once but used everywhere

final class Config
{

    const MODE = 'staging'; // options are "development", "staging", "production"

    private static $instance;

    private function __construct()
    {
    }

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new Config();
        }

        return self::$instance;
    }

    public function getDbSettings()
    {
        $host = 'MySQLHostStringHere';
        $user = 'UserName';
        $pass = 'TheSecretPassword';
        $database = 'TheDatabaseToUse';
        $supportDatabase = 'PVSupport_dev';

        return array('host' => $host, 'user' => $user, 'password' => $pass, 'database' => $database, 'supportDatabase' => $supportDatabase);
    }

    public function getMaxPageSize()
    {
        return 10000;
    }

}

<?php

$config = null; // We're doing this here so it can be instantiated once but used everywhere

final class Config
{

    const MODE = 'staging'; // options are "development", "staging", "production"

    private static $instance;

    private function __construct()
    {
    }

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new Config();
        }

        return self::$instance;
    }

    public function getDbSettings()
    {
        $host = 'MySQLHostStringHere';
        $user = 'UserName';
        $pass = 'TheSecretPassword';
        $database = 'TheDatabaseToUse';
        $supportDatabase = 'PVSupport_dev';

        return array('host' => $host, 'user' => $user, 'password' => $pass, 'database' => $database, 'supportDatabase' => $supportDatabase);
    }

    public function getMaxPageSize()
    {
        return 10000;
    }

    public function getQueryResultLimit()
    {
        return 100000;
    }

}

Allow limiting of number of query results


        <?php echo formOpen('user/signup'); ?>

Sign Up

            <?php echo inputText('username', 'Username, 5-16 characters.'); ?>

            <?php echo inputPassword('password', 'Password, 6-32 characters.'); ?>

            <?php echo inputPassword('rpassword', 'Retype your password.'); ?>

            <?php echo inputSubmit('Sign In'); ?>

            Already have account? <a href="<?php echo baseUrl(); ?>user/signup">Sign In

        <?php echo formClose(); ?>

        <?php echo formOpen('user/signup'); ?>

Create Account

            <?php echo inputText('username', 'Username, 5-16 characters.'); ?>

            <?php echo inputPassword('password', 'Password, 6-32 characters.'); ?>

            <?php echo inputPassword('rpassword', 'Retype your password.'); ?>

            <?php echo inputSubmit('Create my account'); ?>

            Already have account? <a href="<?php echo baseUrl(); ?>user/signin">Sign In

        <?php echo formClose(); ?>

Change signup page to create an account and fix sign in link


<?= SYSNAME ?>: <? echo $wiredux_world_map ?>

      <iframe src="<?=SYSURL?>/app/map/index.php" frameborder="0" width="100%" height="100%">

Your browser does not support iframes.

<?= SYSNAME ?>: <? echo $wiredux_world_map ?> <a <?= "onclick=\"window.open('".SYSURL."app/map/','mywindow','width=1000,height=1000')\"" ?>>Full Screen

      <iframe src="<?=SYSURL?>/app/map/index.php" frameborder="0" width="100%" height="100%">

Your browser does not support iframes.

Add a full screen link for the world map.


<?php

namespace Symfony\Cmf\Component\Routing\NestedMatcher;

use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\UrlMatcher as SymfonyUrlMatcher;
use Symfony\Component\HttpFoundation\Request;

/**
 * Extended UrlMatcher to provide an additional interface and enhanced features.
 *
 * @author Crell
 */
class UrlMatcher extends SymfonyUrlMatcher implements FinalMatcherInterface
{
    /**
     * {@inheritdoc}
     */
    public function finalMatch(RouteCollection $collection, Request $request)
    {
        $this->routes = $collection;
        $this->match($request->getPathInfo());
    }

    /**
     * {@inheritdoc}
     */
    protected function getAttributes(Route $route)
    {
        $args = func_get_args();
        array_shift($args);
        // TODO: where does the $name come from?
        $args[] = array('_name' => $name, '_route' => $route);

        return $this->mergeDefaults(call_user_func_array('array_replace', $args), $route->getDefaults());
    }
}

<?php

namespace Symfony\Cmf\Component\Routing\NestedMatcher;

use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\UrlMatcher as SymfonyUrlMatcher;
use Symfony\Component\HttpFoundation\Request;

/**
 * Extended UrlMatcher to provide an additional interface and enhanced features.
 *
 * @author Crell
 */
class UrlMatcher extends SymfonyUrlMatcher implements FinalMatcherInterface
{
    /**
     * {@inheritdoc}
     */
    public function finalMatch(RouteCollection $collection, Request $request)
    {
        $this->routes = $collection;
        $this->match($request->getPathInfo());
    }

    /**
     * {@inheritdoc}
     */
    protected function getAttributes(Route $route, $name, $attributes)
    {
        $attributes['_name'] = $name;
        $attributes['_route'] = $route;
        return $this->mergeDefaults($attributes, $route->getDefaults());
    }
}

Update getAttributes() override to keep up with the PR for Symfony Routing.


<?php

/*
 * This file is part of the Stash package.
 *
 * (c) Robert Hafner <tedivm@tedivm.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

define('TESTING', true);// this is basically used by the StashArray driver to decide if "isEnabled()" should return
                        // true, since the Array driver is not meant for production use, just testing. We should not
                        // use this anywhere else in the project since that would defeat the point of testing.
error_reporting(-1);

$filename = __DIR__ .'/../vendor/autoload.php';

if (!file_exists($filename)) {
    echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" . PHP_EOL;
    echo " You need to execute `composer install` before running the tests. " . PHP_EOL;
    echo "         Vendors are required for complete test execution.        " . PHP_EOL;
    echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" . PHP_EOL . PHP_EOL;
    $filename = __DIR__ .'/../autoload.php';
}

$loader = require_once $filename;
$loader->add('Stash\\Test', __DIR__);

<?php

/*
 * This file is part of the Stash package.
 *
 * (c) Robert Hafner <tedivm@tedivm.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

define('TESTING', true);// this is basically used by the StashArray driver to decide if "isEnabled()" should return
                        // true, since the Array driver is not meant for production use, just testing. We should not
                        // use this anywhere else in the project since that would defeat the point of testing.
error_reporting(-1);

$filename = __DIR__ .'/../vendor/autoload.php';

if (!file_exists($filename)) {
    echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" . PHP_EOL;
    echo " You need to execute `composer install` before running the tests. " . PHP_EOL;
    echo "         Vendors are required for complete test execution.        " . PHP_EOL;
    echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" . PHP_EOL . PHP_EOL;
    $filename = __DIR__ .'/../autoload.php';
}

$loader = require $filename;
$loader->add('Stash\\Test', __DIR__);

Allow tests to be run when phpunit is installed as dependency of Stash and stash is root project


<?php

###############################################################################
# There are race conditions when using metrics cache with Nagios where
# you can have multiple check script querying gmetad and writing to the
# same file. To avoid this condition you can run this script periodically
# ie. every 10-15 seconds to populate the cache. You will find a shell
# script in this directory which runs this command on a specific schedule
###############################################################################
$conf['gweb_root'] = dirname(dirname(__FILE__));

include_once $conf['gweb_root'] . "/eval_conf.php";

$context = "cluster";
include_once $conf['gweb_root'] . "/functions.php";
include_once $conf['gweb_root'] . "/ganglia.php";
include_once $conf['gweb_root'] . "/get_ganglia.php";
# Put the serialized metrics into a file
file_put_contents($conf['nagios_cache_file'], serialize($metrics));

foreach ( $metrics as $mhost => $host_metrics ) {
    foreach ( $host_metrics as $name => $attributes ) {
        $new_metrics[$mhost][$name]['VAL'] = $metrics[$mhost][$name]['VAL'];
        if ( isset($metrics[$mhost][$name]['UNITS']) )
        $new_metrics[$mhost][$name]['UNITS'] = $metrics[$mhost][$name]['UNITS'];
    }
}

file_put_contents($conf['nagios_cache_file'], serialize($new_metrics));

?>

<?php

###############################################################################
# There are race conditions when using metrics cache with Nagios where
# you can have multiple check script querying gmetad and writing to the
# same file. To avoid this condition you can run this script periodically
# ie. every 10-15 seconds to populate the cache. You will find a shell
# script in this directory which runs this command on a specific schedule
###############################################################################
$conf['gweb_root'] = dirname(dirname(__FILE__));

include_once $conf['gweb_root'] . "/eval_conf.php";

$context = "cluster";
include_once $conf['gweb_root'] . "/functions.php";
include_once $conf['gweb_root'] . "/ganglia.php";
include_once $conf['gweb_root'] . "/get_ganglia.php";
# Put the serialized metrics into a file
file_put_contents($conf['nagios_cache_file'], serialize($metrics));

foreach ( $metrics as $mhost => $host_metrics ) {
    foreach ( $host_metrics as $name => $attributes ) {
        $new_metrics[$mhost][$name]['VAL'] = $metrics[$mhost][$name]['VAL'];
        if ( isset($metrics[$mhost][$name]['UNITS']) )
        $new_metrics[$mhost][$name]['UNITS'] = $metrics[$mhost][$name]['UNITS'];
    }
}

$temp_file = $conf['nagios_cache_file'] . ".temp";
file_put_contents($temp_file, serialize($new_metrics));
rename($temp_file, $conf['nagios_cache_file']);

?>

Write to temp file then rename

Write to temp file then rename


<?php

namespace R\Hive\Commands;

use Illuminate\Console\GeneratorCommand;

class HiveGeneratorCommand extends GeneratorCommand
{
    protected $compound = null;

    protected function getPath($name)
    {
        $name = str_replace($this->laravel->getNamespace(), '', $name);

        // Add the class type to the file name.
        return $this->laravel['path'].'/'.str_replace('\\', '/', $name).$this->type.'.php';
    }

    protected function getStub()
    {
        return;
    }

    public function fire()
    {
        if ($this->compound !== null) {
            if (parent::fire() !== false) {
                if ($this->option($this->compound)) {
                    $name = $this->argument('name');
                    $this->call("hive:{$this->compound}", ['name' => $name]);
                }
            }
        }
    }
}

<?php

namespace R\Hive\Commands;

use Illuminate\Console\GeneratorCommand;

class HiveGeneratorCommand extends GeneratorCommand
{
    protected $compound = null;

    protected function getPath($name)
    {
        $name = str_replace($this->laravel->getNamespace(), '', $name);

        // Add the class type to the file name.
        return $this->laravel['path'].'/'.str_replace('\\', '/', $name).$this->type.'.php';
    }

    protected function getStub()
    {
        return;
    }

    public function fire()
    {
        if ($this->compound !== null) {
            if (parent::fire() !== false) {
                if ($this->option($this->compound)) {
                    $name = $this->argument('name');
                    $this->call("hive:{$this->compound}", ['name' => $name]);
                }
            }
        } else {
            parent::fire();
        }
    }
}

Add missing fire command for non-compound generators.


@if(!$options['attribute'])import { Directive } from '{{ '@angular/core' }}';

{{ '@Directive' }}({
    selector: '{{ $name }}',
    template: require('html!./{{ "$name.$type.ts" }}'),
    styles: [ require('!raw!sass!./{{ "$name.$type.scss" }}') ]
})
export class {{ $upperCamelCaseName }}Directive {
    constructor() {
    }
}
@elseif($options['attribute'])import { Directive } from '{{ '@angular/core' }}';

{{ '@Directive' }}({selector: '[{{ $name }}]'})
export class {{ $upperCamelCaseName }}Directive {
    constructor() {
    }
}
@endif

@if(!$options['attribute'])import { Directive } from '{{ '@angular/core' }}';

{{ '@Directive' }}({
    selector: '{{lcfirst($upperCamelCaseName) }}',
    template: require('html!./{{ "$name.$type.ts" }}'),
    styles: [ require('!raw!sass!./{{ "$name.$type.scss" }}') ]
})
export class {{ $upperCamelCaseName }}Directive {
    constructor() {
    }
}
@elseif($options['attribute'])import { Directive } from '{{ '@angular/core' }}';

{{ '@Directive' }}({selector: '[{{ lcfirst($upperCamelCaseName) }}]'})
export class {{ $upperCamelCaseName }}Directive {
    constructor() {
    }
}
@endif

Use lower camel case to follow angular style guide


<?php
/**
 * @title          Escape Exception Trait
 * @desc           Escape the exception message.
 *
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7/ Framework / Error / CException
 * @version        1.1
 */

namespace PH7\Framework\Error\CException;

defined('PH7') or exit('Restricted access');

trait Escape
{
    protected $sAllowTags = '
';

    /**
     * Escape the exception message.
     *
     * @param string $sMsg
     */
    protected function strip($sMsg)
    {
        $this->message = strip_tags($sMsg, $this->sAllowTags);
    }
}

<?php
/**
 * @title          Escape Exception Trait
 * @desc           Escape the exception message.
 *
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7/ Framework / Error / CException
 * @version        1.1
 */

namespace PH7\Framework\Error\CException;

defined('PH7') or exit('Restricted access');

trait Escape
{
    /** @var string */
    private $sAllowTags = '
';

    /**
     * Escape the exception message.
     *
     * @param string $sMsg
     */
    protected function strip($sMsg)
    {
        $this->message = strip_tags($sMsg, $this->sAllowTags);
    }
}

Change Escape:$sAllowTags to private + add missing phpdoc comment


<?php

// Can be used by plugins/themes to check if wp-cli is running or not
define( 'WP_CLI', true );

define( 'WP_CLI_VERSION', '0.10.0-alpha' );

include WP_CLI_ROOT . 'utils.php';
include WP_CLI_ROOT . 'dispatcher.php';
include WP_CLI_ROOT . 'class-wp-cli.php';
include WP_CLI_ROOT . 'class-wp-cli-command.php';
include WP_CLI_ROOT . 'man.php';

\WP_CLI\Utils\load_dependencies();

WP_CLI::init();

WP_CLI::$runner->before_wp_load();

// Load wp-config.php code, in the global scope
eval( WP_CLI::$runner->get_wp_config_code() );

WP_CLI::$runner->after_wp_config_load();

// Load main WordPress code, in the global scope
require WP_CLI_ROOT . 'wp-settings-cli.php';

// Fix memory limit. See http://core.trac.wordpress.org/ticket/14889
@ini_set( 'memory_limit', -1 );

// Simulate a /wp-admin/ page load
$_SERVER['PHP_SELF'] = '/wp-admin/index.php';
define( 'WP_ADMIN', true );
require ABSPATH . 'wp-admin/includes/admin.php';
do_action( 'admin_init' );

WP_CLI::$runner->after_wp_load();

<?php

// Can be used by plugins/themes to check if wp-cli is running or not
define( 'WP_CLI', true );

define( 'WP_CLI_VERSION', '0.10.0-alpha' );

include WP_CLI_ROOT . 'utils.php';
include WP_CLI_ROOT . 'dispatcher.php';
include WP_CLI_ROOT . 'class-wp-cli.php';
include WP_CLI_ROOT . 'class-wp-cli-command.php';
include WP_CLI_ROOT . 'man.php';

\WP_CLI\Utils\load_dependencies();

WP_CLI::init();

WP_CLI::$runner->before_wp_load();

// Load wp-config.php code, in the global scope
eval( WP_CLI::$runner->get_wp_config_code() );

WP_CLI::$runner->after_wp_config_load();

// Simulate a /wp-admin/ page load
$_SERVER['PHP_SELF'] = '/wp-admin/index.php';
define( 'WP_ADMIN', true );
define( 'WP_NETWORK_ADMIN', false );
define( 'WP_USER_ADMIN', false );

// Load Core, mu-plugins, plugins, themes etc.
require WP_CLI_ROOT . 'wp-settings-cli.php';

// Fix memory limit. See http://core.trac.wordpress.org/ticket/14889
@ini_set( 'memory_limit', -1 );

require ABSPATH . 'wp-admin/includes/admin.php';
do_action( 'admin_init' );

WP_CLI::$runner->after_wp_load();

Define WP_ADMIN before loading WordPress

... where "loading WordPress" also includes loading plugins and themes.

Also, define WP_NETWORK_ADMIN and WP_USER_ADMIN, for completeness.

see #385


<?php
	require_once(__DIR__. '/class/DatabaseManager.php');

            $hostname = "localhost";
            $database = "aen";
            $username = "root";
            $password = "";

try{
    $connect = new PDO('mysql:host='.$hostname.';dbname='.$database, $username, $password);
 }catch (PDOException $e){
        exit('problème de connexion à la base');
      }

if( !isset($_GET['activationKey']) && !isset($_GET['mail'])){

	die("Pas de token");

}
$activationKey = $_GET['activationKey'];
$mail = $_GET['mail'];
echo $activationKey;
echo $mail;

$query = $connect->prepare("SELECT id FROM user WHERE mail='$mail'");

//Executer et récupérer l'information
$query->execute(["mail"=>$_GET['mail']]);
$results = $query->fetch();

if( !empty($results) ){
	//il existe on prépare une autre requête
	$query = $connect->prepare("UPDATE user SET active = 1 WHERE mail='$mail'");
	//On execute la nouvelle requete
	$query->execute(["mail"=>$_GET['mail']]);
	header("Location: index.php");

}else{
	die("Erreur a la fin, bdd pas mise a jour");
}
//et si il n'existe pas on die
?>

<?php
	require_once(__DIR__. '/class/DatabaseManager.php');

            $hostname = "localhost";
            $database = "aen";
            $username = "root";
            $password = "";

try{
    $connect = new PDO('mysql:host='.$hostname.';dbname='.$database, $username, $password);
 }catch (PDOException $e){
        exit('problème de connexion à la base');
      }

if( !isset($_GET['activationKey'])){

	die("Pas de token");

}
$activationKey = $_GET['activationKey'];

$query = $connect->prepare("SELECT id FROM user WHERE activation_key='$activationKey'");

//Executer et récupérer l'information
$query->execute(["activationKey"=>$_GET['activationKey']]);
$results = $query->fetch();

if( !empty($results) ){
	//il existe on prépare une autre requête
	$query = $connect->prepare("UPDATE user SET active = 1 WHERE activation_key='$activationKey'");
	//On execute la nouvelle requete
	$query->execute(["activation_key"=>$_GET['activationKey']]);
	header("Location: index.php");

}else{
	die("Erreur a la fin, bdd pas mise a jour");
}
//et si il n'existe pas on die
?>

Revert "ativation by adress mail"

Revert "ativation by adress mail"

This reverts commit 16724a7f849b1110103b05f6d964a79dc2af344d.


<?php

namespace Ekyna\Bundle\CoreBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Class GalleryImageType
 * @package Ekyna\Bundle\CoreBundle\Form\Type
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class GalleryImageType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('position', 'hidden', array(
                'attr' => array(
                    'data-role' => 'data-collection-position'
                )
            ))
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'ekyna_core_image';
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'ekyna_core_gallery_image';
    }
}

<?php

namespace Ekyna\Bundle\CoreBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Class GalleryImageType
 * @package Ekyna\Bundle\CoreBundle\Form\Type
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class GalleryImageType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('position', 'hidden', array(
                'attr' => array(
                    'data-collection-role' => 'position'
                )
            ))
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'ekyna_core_image';
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'ekyna_core_gallery_image';
    }
}

Fix gallery image position field

Fix gallery image position field


<?php

namespace Flugg\Responder\Exceptions\Http;

use Illuminate\Contracts\Validation\Validator;

/**
 * An exception thrown whan validation fails. This exception replaces Laravel's
 * [\Illuminate\Validation\ValidationException].
 *
 * @package flugger/laravel-responder
 * @author  Alexander Tømmerås <flugged@gmail.com>
 * @license The MIT License
 */
class ValidationFailedException extends HttpException
{
    /**
     * An HTTP status code.
     *
     * @var int
     */
    protected $status = 422;

    /**
     * An error code.
     *
     * @var string|null
     */
    protected $errorCode = 'validation_failed';

    /**
     * A validator for fetching validation messages.
     *
     * @var \Illuminate\Contracts\Validation\Validator
     */
    protected $validator;

    /**
     * Construct the exception class.
     *
     * @param \Illuminate\Contracts\Validation\Validator $validator
     */
    public function __construct(Validator $validator)
    {
        $this->validator = $validator;

        parent::__construct();
    }

    /**
     * Retrieve the error data.
     *
     * @return array|null
     */
    public function data()
    {
        return [$this->validator->getMessageBag()->toArray()];
    }
}

<?php

namespace Flugg\Responder\Exceptions\Http;

use Illuminate\Contracts\Validation\Validator;

/**
 * An exception thrown whan validation fails. This exception replaces Laravel's
 * [\Illuminate\Validation\ValidationException].
 *
 * @package flugger/laravel-responder
 * @author  Alexander Tømmerås <flugged@gmail.com>
 * @license The MIT License
 */
class ValidationFailedException extends HttpException
{
    /**
     * An HTTP status code.
     *
     * @var int
     */
    protected $status = 422;

    /**
     * An error code.
     *
     * @var string|null
     */
    protected $errorCode = 'validation_failed';

    /**
     * A validator for fetching validation messages.
     *
     * @var \Illuminate\Contracts\Validation\Validator
     */
    protected $validator;

    /**
     * Construct the exception class.
     *
     * @param \Illuminate\Contracts\Validation\Validator $validator
     */
    public function __construct(Validator $validator)
    {
        $this->validator = $validator;

        parent::__construct();
    }

    /**
     * Retrieve the error data.
     *
     * @return array|null
     */
    public function data()
    {
        return ['fields' => $this->validator->getMessageBag()->toArray()];
    }
}

Add missing fields key to validation exception


<?php
/* This is a list of packages and versions
 * that will be used to create the PEAR folder
 * in the windows snapshot.
 * See win32/build/mkdist.php for more details
 * $Id$
 */
$packages  = array(
// required packages for the installer
"PEAR"                  =>    "1.4.10",
"Console_Getopt"        =>    "1.2",
"Archive_Tar"           =>    "1.3.1",

// required packages for the web frontend
"PEAR_Frontend_Web"     =>    "0.5.1",
"HTML_Template_IT"      =>    "1.1.4",
"Net_UserAgent_Detect"  =>    "2.0.1",
);

?>

<?php
/* This is a list of packages and versions
 * that will be used to create the PEAR folder
 * in the windows snapshot.
 * See win32/build/mkdist.php for more details
 * $Id$
 */
$packages  = array(
// required packages for the installer
"PEAR"                  =>    "1.4.10",
"Console_Getopt"        =>    "1.2",
"Archive_Tar"           =>    "1.3.6",

// required packages for the web frontend
"PEAR_Frontend_Web"     =>    "0.5.1",
"HTML_Template_IT"      =>    "1.1.4",
"Net_UserAgent_Detect"  =>    "2.0.1",
);

?>

Upgrade dep to 1.3.7 for archive tar

Upgrade dep to 1.3.7 for archive tar


<?php
if (count($context)) {
    ?>
    <a href="<?php echo $context->getURL(); ?>"><?php echo $context->getDateTime()->format('j')?>
    <?php
} else {
    echo $context->getDateTime()->format('j');
}
?>

<?php
foreach ($context as $e) {
    //Start building an array of row classes
    $classes = array('event');

    if ($e->isAllDay()) {
        $classes[] = 'all-day';
    }

    if ($e->isInProgress()) {
        $classes[] = 'in-progress';
    }

    if ($e->isOnGoing()) {
        $classes[] = 'ongoing';
    }

    ?>
    <li class="<?php echo implode(' ', $classes); ?>">
        <?php echo $savvy->render($e, 'EventInstance/Date.tpl.php') ?> :
        <a href="<?php echo $e->getURL(); ?>"><?php echo $savvy->dbStringtoHtml($e->event->title)?>

    <?php
}
?>

<?php
if (count($context)) {
    ?>
    <a href="<?php echo $context->getURL(); ?>"><?php echo $context->getDateTime()->format('j')?>
    <?php
} else {
    echo $context->getDateTime()->format('j');
}
?>

<?php
foreach ($context as $e) {
    //Start building an array of row classes
    $classes = array('event');

    if ($e->isAllDay()) {
        $classes[] = 'all-day';
    }

    if ($e->isInProgress()) {
        $classes[] = 'in-progress';
    }

    if ($e->isOnGoing()) {
        $classes[] = 'ongoing';
    }

    ?>
    <li class="<?php echo implode(' ', $classes); ?>">
        <?php echo $savvy->render($e, 'EventInstance/TimeOnly.tpl.php') ?>
        <a href="<?php echo $e->getURL(); ?>"><?php echo $savvy->dbStringtoHtml($e->event->title)?>

    <?php
}
?>

Fix time display in Month view

Fix time display in Month view


<?php
/* ------------------------------------------------------------------------ *\
 * Image Sizes
\* ------------------------------------------------------------------------ */

add_image_size("hero", 700, 400, true);
add_image_size("hero_medium", 1200, 400, true);
add_image_size("hero_large", 2000, 400, true);

add_image_size("excerpt", 350, 200, true);
add_image_size("excerpt_medium", 525, 300, true);
add_image_size("excerpt_large", 700, 400, true);

/**
 * Display a notice explaining what size a featured image should be.
 *
 * @param string $content
 * @param integer $post_id
 * @param integer|string $thumbnail_id
 * @return string
 */
function __gulp_init_namespace___admin_post_thumbnail_html(string $content, int $post_id, $thumbnail_id): string {
    $width  = 2000;
    $height = 400;

    $notice = sprintf(__("The featured image should be at least %s by %s pixels to fill the available space.", "__gulp_init_namespace__"), $width, $height);

    if ($thumbnail_id && $meta = wp_get_attachment_metadata($thumbnail_id)) {
        if ($meta && ($meta["width"] < $width || $meta["height"] < $height)) {
            $content = "

" . sprintf(__("Display issue: %s"), $notice) . "

" . $content;
        }
    } else {
        $content = "
{$notice}
" . $content;
    }

    return $content;
}
add_filter("admin_post_thumbnail_html", "__gulp_init_namespace___admin_post_thumbnail_html", 10, 3);

Add featured image size notice

Add featured image size notice


<?php
    include_once '../../config/config-local.php';
    include_once '../../models/database.php';
    include_once '../../models/db.php';
    include_once 'countries_array.php';

    $countries = getCountries();
    $array = array();
    $count = 0;
    $keys = array_keys( $countries );

    foreach ( $keys as $key ) {
        $value = $countries[ $key ];
        $res = db_insert( 'countries', array( 'id' => NULL, 'country' => $value, 'shortname' => $key ) );
        if ( $res === false ) {
            die( "sql query died with the following error\n\"" . mysql_error() );
        }
        ++$count;
    }

    echo "You imported $count raws out of the 239 countries in the table 'countries'.";
?>

<?php
    include_once '../../config/config-local.php';
    include_once '../../models/database.php';
    include_once '../../models/db.php';
    include_once 'countries_array.php';

    $countries = getCountries();
    $array = array();
    $count = 0;

    foreach ( $countries as $key => $value ) {
        $res = db_insert( 'countries', array( 'id' => NULL, 'country' => $value, 'shortname' => $key ) );
        if ( $res === false ) {
            die( "sql query died with the following error\n\"" . mysql_error() );
        }
        ++$count;
    }

    echo "You imported $count raws out of the 239 countries in the table 'countries'.";
?>

Fix foreach to be architectical correct

Fix foreach to be architectical correct


<?php

/*
 * This file is part of the Active Collab DatabaseStructure project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\DatabaseStructure\Field\Scalar;

use LogicException;

/**
 * @package ActiveCollab\DatabaseStructure\Field\Scalar
 */
class BooleanField extends Field
{
    /**
     * @param string $name
     * @param bool   $default_value
     */
    public function __construct($name, $default_value = false)
    {
        parent::__construct($name, $default_value);
    }

    /**
     * Value of this column needs to be unique (in the given context).
     *
     * @param  string[] $context
     * @return $this
     */
    public function &unique(...$context)
    {
        throw new LogicException('Boolean columns cant be made unique');
    }

    /**
     * Return value casting code.
     *
     * @param  string $variable_name
     * @return string
     */
    public function getCastingCode($variable_name)
    {
        return '(bool) $' . $variable_name;
    }
}

<?php

/*
 * This file is part of the Active Collab DatabaseStructure project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\DatabaseStructure\Field\Scalar;

use LogicException;

/**
 * @package ActiveCollab\DatabaseStructure\Field\Scalar
 */
class BooleanField extends Field
{
    /**
     * @param string $name
     * @param bool   $default_value
     */
    public function __construct($name, $default_value = false)
    {
        parent::__construct($name, $default_value);
    }

    /**
     * {@inheritdoc}
     */
    public function &unique(...$context)
    {
        throw new LogicException('Boolean columns cant be made unique');
    }

    /**
     * {@inheritdoc}
     */
    public function getNativeType()
    {
        return 'bool';
    }

    /**
     * {@inheritdoc}
     */
    public function getCastingCode($variable_name)
    {
        return '(bool) $' . $variable_name;
    }
}

Add native type to boolean fields

Add native type to boolean fields


<?php
# Copyright (c) 2015 Jordan Turley, CSGO Win Big. All Rights Reserved.

session_start();
include 'default.php';
include 'SteamAuthentication/steamauth/userInfo.php';
$db = getDB();

if (!isset($_SESSION['steamid'])) {
	echo jsonErr('You are not logged in.');
	return;
}

$text = isset($_POST['text']) ? $_POST['text'] : null;

if (is_null($text) || strlen($text) === 0) {
	echo jsonErr('The required text for the message was not sent correctly or was left blank. Please refresh and try again.');
	return;
}

$steamUserID = $steamprofile['steamid'];

$stmt = $db->prepare('INSERT INTO `chat` (`steamUserID`, `text`, `date`, `time`) VALUES (:userid, :text, CURDATE(), CURTIME())');
$stmt->bindValue(':userid', $steamUserID);
$stmt->bindValue(':text', $text);
$stmt->execute();

echo jsonSuccess(array('message' => 'Message has been sent!'));
?>

<?php
# Copyright (c) 2015 Jordan Turley, CSGO Win Big. All Rights Reserved.

session_start();
include 'default.php';
include 'SteamAuthentication/steamauth/userInfo.php';
$db = getDB();

if (!isset($_SESSION['steamid'])) {
	echo jsonErr('You are not logged in.');
	return;
}

$text = isset($_POST['text']) ? $_POST['text'] : null;

if (is_null($text) || strlen($text) === 0) {
	echo jsonErr('The required text for the message was not sent correctly or was left blank. Please refresh and try again.');
	return;
}

$steamUserID = $steamprofile['steamid'];

# Check if they are on the blacklist for the chat
$stmt = $db->query('SELECT * FROM chatBlacklist');
$blacklist = $stmt->fetchAll();

foreach ($blacklist as $user) {
	$steamId64 = $user['steamId64'];

	if ($steamId64 === $steamUserID) {
		echo jsonSuccess(array('message' => 'You have been banned from the chat.'));
		return;
	}
}

$stmt = $db->prepare('INSERT INTO `chat` (`steamUserID`, `text`, `date`, `time`) VALUES (:userid, :text, CURDATE(), CURTIME())');
$stmt->bindValue(':userid', $steamUserID);
$stmt->bindValue(':text', $text);
$stmt->execute();

echo jsonSuccess(array('message' => 'Message has been sent!'));
?>

Add blacklist check for chat when a user sends a message


<?php

namespace ContentTranslator\Entity;

class Translate
{
    /**
     * Creates a language specific meta/options key
     * @param  string $key The meta/option key
     * @return string      Langual meta/option key
     */
    protected function createLangualKey(string $key) : string
    {
        if ($this->isLangualOption($key)) {
            return $key;
        }

        return $key . TRANSLATE_DELIMITER . $this->lang;
    }

    /**
     * Check if key is a langual option
     * @param  string  $key Option key
     * @return boolean
     */
    protected function isLangualOption($key)
    {
        return substr($key, -strlen(TRANSLATE_DELIMITER . $this->lang)) == TRANSLATE_DELIMITER . $this->lang ? true : false;
    }
}

<?php

namespace ContentTranslator\Entity;

class Translate
{
    protected $lang;
    protected $db;

    public function __construct()
    {
        global $wpdb;
        $this->db = $wpdb;
        $this->lang = \ContentTranslator\Switcher::$currentLanguage->code;
    }

    /**
     * Creates a language specific meta/options key
     * @param  string $key The meta/option key
     * @return string      Langual meta/option key
     */
    protected function createLangualKey(string $key) : string
    {
        if ($this->isLangualOption($key)) {
            return $key;
        }

        return $key . TRANSLATE_DELIMITER . $this->lang;
    }

    /**
     * Check if key is a langual option
     * @param  string  $key Option key
     * @return boolean
     */
    protected function isLangualOption($key)
    {
        return substr($key, -strlen(TRANSLATE_DELIMITER . $this->lang)) == TRANSLATE_DELIMITER . $this->lang ? true : false;
    }
}

Put $this->lang and $this->db in the entity translate


<?php

/*
 * This file is part of the Beloop package.
 *
 * Copyright (c) 2016 AHDO Studio B.V.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Feel free to edit as you please, and have fun.
 *
 * @author Arkaitz Garro <arkaitz.garro@gmail.com>
 */

namespace Beloop\Component\Course\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * Class CourseRepository.
 */
class CourseRepository extends EntityRepository
{
}

<?php

/*
 * This file is part of the Beloop package.
 *
 * Copyright (c) 2016 AHDO Studio B.V.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Feel free to edit as you please, and have fun.
 *
 * @author Arkaitz Garro <arkaitz.garro@gmail.com>
 */

namespace Beloop\Component\Course\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * Class CourseRepository.
 */
class CourseRepository extends EntityRepository
{
    public function findOneBy(array $criteria, array $orderBy = null)
    {
        $qb = $this->createQueryBuilder('c');

        $qb
            ->addSelect('l')
            ->innerJoin('c.lessons', 'l')
            ->orderBy('l.position', 'ASC');

        foreach ($criteria as $key => $value) {
            $qb
                ->andWhere(vsprintf('c.%s = :%s', [$key, $key]))
                ->setParameter($key, $value);
        }

        return $qb->getQuery()->getOneOrNullResult();
    }
}

Order lessons inside course by position

Order lessons inside course by position


<?php

declare(strict_types=1);

namespace Client\Predis\Connection;

use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Predis\Command\KeyScan;
use Predis\Connection\NodeConnectionInterface;
use Predis\Connection\Parameters;
use Psr\Log\LoggerInterface;
use Snc\RedisBundle\Client\Predis\Connection\ConnectionWrapper;
use Snc\RedisBundle\Logger\RedisLogger;

class ConnectionWrapperTest extends TestCase
{
    private MockObject $connection;
    private MockObject $logger;
    private RedisLogger $redisLogger;
    private ConnectionWrapper $wrapper;

    protected function setUp(): void
    {
        $this->connection = $this->createMock(NodeConnectionInterface::class);
        $this->connection->method('getParameters')->willReturn(new Parameters(['alias' => 'default']));
        $this->connection->method('executeCommand')->willReturn('');
        $this->redisLogger = new RedisLogger($this->logger = $this->createMock(LoggerInterface::class));
        $this->wrapper     = new ConnectionWrapper($this->connection);
        $this->wrapper->setLogger($this->redisLogger);
    }

    public function testSanitizingArguments(): void
    {
        $command = new KeyScan();
        $command->setArguments([null, 'MATCH', 'foo:bar', 'COUNT', 1000]);

        $this->logger->expects($this->once())->method('debug')->with('Executing command "SCAN NULL \'MATCH\' \'foo:bar\' \'COUNT\' 1000"');
        $this->wrapper->executeCommand($command);
    }
}

<?php

declare(strict_types=1);

namespace Snc\RedisBundle\Tests\Client\Predis\Connection;

use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Predis\Command\KeyScan;
use Predis\Connection\NodeConnectionInterface;
use Predis\Connection\Parameters;
use Psr\Log\LoggerInterface;
use Snc\RedisBundle\Client\Predis\Connection\ConnectionWrapper;
use Snc\RedisBundle\Logger\RedisLogger;

class ConnectionWrapperTest extends TestCase
{
    private MockObject $connection;
    private MockObject $logger;
    private RedisLogger $redisLogger;
    private ConnectionWrapper $wrapper;

    protected function setUp(): void
    {
        $this->connection = $this->createMock(NodeConnectionInterface::class);
        $this->connection->method('getParameters')->willReturn(new Parameters(['alias' => 'default']));
        $this->connection->method('executeCommand')->willReturn('');
        $this->redisLogger = new RedisLogger($this->logger = $this->createMock(LoggerInterface::class));
        $this->wrapper     = new ConnectionWrapper($this->connection);
        $this->wrapper->setLogger($this->redisLogger);
    }

    public function testSanitizingArguments(): void
    {
        $command = new KeyScan();
        $command->setArguments([null, 'MATCH', 'foo:bar', 'COUNT', 1000]);

        $this->logger->expects($this->once())->method('debug')->with('Executing command "SCAN NULL \'MATCH\' \'foo:bar\' \'COUNT\' 1000"');
        $this->wrapper->executeCommand($command);
    }
}

Fix wrong namespace in new test

Fix wrong namespace in new test


<?php
/**
 * @file
 * Containt Drupal\AppConsole\Generator\FormGenerator.
 */
namespace Drupal\AppConsole\Generator;

use Drupal\AppConsole\Utils\Utils;

class FormGenerator extends Generator
{
  /**
   * @param  $module
   * @param  $class_name
   * @param  $services
   * @param  $inputs
   * @param  $update_routing
   */
  public function generate($module, $class_name, $services, $inputs, $update_routing)
  {
    $path = DRUPAL_ROOT . '/' . drupal_get_path('module', $module);

    $path_form = $path . '/src/Form';

    $parameters = array(
      'class_name' => $class_name,
      'services' => $services,
      'inputs' => $inputs,
      'module_name' => $module,
      'form_id' => Utils::camelCaseToMachineName($class_name),
    );

    $this->renderFile(
      'module/module.form.php.twig',
      $path_form . '/'. $class_name .'.php',
      $parameters
    );

    if ($update_routing) {
      $this->renderFile('module/form-routing.yml.twig', $path .'/'. $module.'.routing.yml', $parameters, FILE_APPEND);
    }
  }
}

<?php
/**
 * @file
 * Containt Drupal\AppConsole\Generator\FormGenerator.
 */
namespace Drupal\AppConsole\Generator;

use Drupal\AppConsole\Utils\Utils;

class FormGenerator extends Generator
{
  /**
   * @param  $module
   * @param  $class_name
   * @param  $services
   * @param  $inputs
   * @param  $update_routing
   */
  public function generate($module, $class_name, $services, $inputs, $update_routing)
  {

    $parameters = array(
      'class_name' => $class_name,
      'services' => $services,
      'inputs' => $inputs,
      'module_name' => $module,
      'form_id' => Utils::camelCaseToMachineName($class_name),
    );

    $this->renderFile(
      'module/module.form.php.twig',
      $path_form . '/'. $class_name .'.php',
      $parameters
    );

    if ($update_routing) {
      $this->renderFile('module/form-routing.yml.twig', $path .'/'. $module.'.routing.yml', $parameters, FILE_APPEND);
    }
  }
}

Remove local vars path & path_form

Remove local vars path & path_form


<?php

namespace CultuurNet\UDB3\EventExport\FileWriter;

class TabularDataEventFormatter
{
    /**
     * @var string[]
     */
    protected $includedProperties;

    protected $columns;

    public function __construct($columns, $include)
    {
        $this->includedProperties = $include;
        $this->columns = $columns;
    }

    public function formatEvent($event)
    {
        $event = json_decode($event);
        $includedProperties = $this->includedProperties;
        $row = $this->emptyRow();

        foreach ($includedProperties as $property) {
            $column = $this->columns[$property];
            $value = $column['include']($event);

            if ($value) {
                $row[$property] = $value;
            } else {
                $row[$property] = '';
            }
        }

        return $row;
    }

    public function emptyRow()
    {
        $row = array();

        foreach ($this->includedProperties as $property) {
            $row[$property] = '';
        }

        return $row;
    }
}

<?php

namespace CultuurNet\UDB3\EventExport\FileWriter;

class TabularDataEventFormatter
{
    /**
     * A list of all included properties
     * @var string[]
     */
    protected $includedProperties;

    /**
     * A list of all columns with a callback to format them
     * @var object[]
     */
    protected $columns;

    /**
     * @param $columns A list of all columns with a callback to format them
     * @param string[] $include A list of properties to include
     */
    public function __construct($columns, $include)
    {
        $this->includedProperties = $include;
        $this->columns = $columns;
    }

    public function formatEvent($event)
    {
        $event = json_decode($event);
        $includedProperties = $this->includedProperties;
        $row = $this->emptyRow();

        foreach ($includedProperties as $property) {
            $column = $this->columns[$property];
            $value = $column['include']($event);

            if ($value) {
                $row[$property] = $value;
            } else {
                $row[$property] = '';
            }
        }

        return $row;
    }

    public function emptyRow()
    {
        $row = array();

        foreach ($this->includedProperties as $property) {
            $row[$property] = '';
        }

        return $row;
    }
}

III-168: Document the columns attribute and argument


<?php

namespace Michaeljennings\Carpenter\Nexus;

use ArrayAccess;
use ArrayIterator;
use IteratorAggregate;

class Container implements ArrayAccess, IteratorAggregate
{
    /**
     * @var array
     */
    protected $items = [];

    public function __construct(array $items, array $config, $wrapper)
    {
        foreach ($items as &$item) {
            $item = (new \ReflectionClass($wrapper))->newInstanceArgs([$item]);
        }

        $this->items = $items;
    }

    /**
     * Get an iterator for the items.
     *
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new ArrayIterator($this->items);
    }

    /**
     * Determine if an item exists at an offset.
     *
     * @param  mixed $key
     * @return bool
     */
    public function offsetExists($key)
    {
        return array_key_exists($key, $this->items);
    }

    /**
     * Get an item at a given offset.
     *
     * @param  mixed $key
     * @return mixed
     */
    public function offsetGet($key)
    {
        return $this->items[$key];
    }

    /**
     * Set the item at a given offset.
     *
     * @param  mixed $key
     * @param  mixed $value
     * @return void
     */
    public function offsetSet($key, $value)
    {
        $this->items[$key] = $value;
    }

    /**
     * Unset the item at a given offset.
     *
     * @param  string $key
     * @return void
     */
    public function offsetUnset($key)
    {
        unset($this->items[$key]);
    }
}

<?php

namespace Michaeljennings\Carpenter\Nexus;

use ArrayAccess;
use ArrayIterator;
use IteratorAggregate;

class Container implements ArrayAccess, IteratorAggregate
{
    /**
     * The items in the container.
     *
     * @var array
     */
    protected $items = [];

    public function __construct(array $items, array $config)
    {
        foreach ($items as &$item) {
            $item = new MockArray($item);
        }

        $this->items = $items;
    }

    /**
     * Get an iterator for the items.
     *
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new ArrayIterator($this->items);
    }

    /**
     * Determine if an item exists at an offset.
     *
     * @param  mixed $key
     * @return bool
     */
    public function offsetExists($key)
    {
        return array_key_exists($key, $this->items);
    }

    /**
     * Get an item at a given offset.
     *
     * @param  mixed $key
     * @return mixed
     */
    public function offsetGet($key)
    {
        return $this->items[$key];
    }

    /**
     * Set the item at a given offset.
     *
     * @param  mixed $key
     * @param  mixed $value
     * @return void
     */
    public function offsetSet($key, $value)
    {
        $this->items[$key] = $value;
    }

    /**
     * Unset the item at a given offset.
     *
     * @param  string $key
     * @return void
     */
    public function offsetUnset($key)
    {
        unset($this->items[$key]);
    }
}

Update container to use mock array rather than wrappers


<?php

namespace Kunstmaan\AdminListBundle\AdminList;

/**
 * FieldAlias
 */
class FieldAlias
{
    /**
     * FieldAlias constructor.
     *
     * @param $abbr string
     * @param $relation string
     */
    public function __construct($abbr, $relation)
    {
        $this->abbr = $abbr;
        $this->relation = $relation;
    }

    /**
     * @return string
     */
    public function getAbbr()
    {
        return $this->abbr;
    }

    /**
     * @return string
     */
    public function getRelation()
    {
        return $this->relation;
    }
}

<?php

namespace Kunstmaan\AdminListBundle\AdminList;

/**
 * FieldAlias
 */
class FieldAlias
{
    /** @var string */
    private $abbr;

    /** @var string */
    private $relation;

    /**
     * FieldAlias constructor.
     *
     * @param $abbr string
     * @param $relation string
     */
    public function __construct($abbr, $relation)
    {
        $this->abbr = $abbr;
        $this->relation = $relation;
    }

    /**
     * @return string
     */
    public function getAbbr()
    {
        return $this->abbr;
    }

    /**
     * @return string
     */
    public function getRelation()
    {
        return $this->relation;
    }
}

Fix phpstan level 1 issues

[AllBundles] Fix phpstan level 1 issues


<?php

/**
 * Met deze PHP class kunnen pagina's voor de custom error pages gemaakt worden.
 */
class ErrorCreator {

  /**
   * De titel van de test.
   */
  var $title;

  /**
   * De error code.
   */
  var $code;

  /**
   * Het bericht dat moet worden weergegeven als error message.
   */
  var $message;

  /**
   * Print de testpagina op de website. Gebruikt de variabelen uit deze
   * TestCreator instance.
   */
  function create() {
    // '../' omdat deze class altijd aangeroepen wordt vanuit de /error/ map.
    require_once '../resources/includes/PageCreator.php';

    $page = new PageCreator;

    $page->title = $this->title;
    $page->body = <<<CONTENT

Error $this->code

                  Beste bezoeker,

                  $this->message

                  Onze excuses voor het ongemak.

CONTENT;

    $page->create();
  }

}

<?php

/**
 * Met deze PHP class kunnen pagina's voor de custom error pages gemaakt worden.
 */
class ErrorCreator {

  /**
   * De titel van de test.
   */
  var $title;

  /**
   * De error code.
   */
  var $code;

  /**
   * Het bericht dat moet worden weergegeven als error message.
   */
  var $message;

  /**
   * Print de testpagina op de website. Gebruikt de variabelen uit deze
   * TestCreator instance.
   */
  function create() {
    // '../' omdat deze class altijd aangeroepen wordt vanuit de /error/ map.
    require_once '../resources/includes/PageCreator.php';

    $page = new PageCreator;
    $page->path_to_root = "../";
    $page->title = $this->title;

		$page->body = <<<CONTENT

Error $this->code

                  Beste bezoeker,

                  $this->message

                  Onze excuses voor het ongemak.

CONTENT;

    $page->create();
  }

}

Fix issue with styling on error pages

Fix issue with styling on error pages

Using the correct path_to_root now in ErrorCreator.


<?php

require_once( '../../vendor/autoload.php' );

( new \Staq\Server )
	->getCurrentApplication( )
	->addController( '/(:path)', function($path='World') {
		return 'Hello '.$path;
	})
	->run( );

<?php

require_once( '../../vendor/autoload.php' );

( new \Staq\Server )
	->getCurrentApplication( )                               // We get the current application, it will returns an empty one
	->addController( '/(:path)', function($path='World') {
		return 'Hello '.$path;
	})                                                       // We add a controller that listen every routes
	->run( );                                                // Resolve the current route, call a controller and display the result

Add comments on main file

Add comments on main file


<?php

namespace spec\SearchApi\Builders;

use SearchApi;
use SearchApi\Models;
use SearchApi\Builders\SolrQueryBuilder;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

/**
 * SolrQueryBuilderSpec - Spec test for SolrQueryBuilder
 */
class SolrQueryBuilderSpec extends ObjectBehavior {
  function it_is_initializable() {
    $this->shouldHaveType( 'SearchApi\Builders\SolrQueryBuilder' );
  }

  function it_returns_a_string() {
    $this->build( 'test' )->shouldBeString();
  }
}

<?php

namespace spec\SearchApi\Builders;

use SearchApi;
use SearchApi\Models;
use SearchApi\Builders\SolrQueryBuilder;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

/**
 * SolrQueryBuilderSpec - Spec test for SolrQueryBuilder
 */
class SolrQueryBuilderSpec extends ObjectBehavior {
  function it_is_initializable() {
    $this->shouldHaveType( 'SearchApi\Builders\SolrQueryBuilder' );
  }

  function it_returns_a_string() {
    $keyword = new Models\SearchTerm( 'test' );
    $keywords = array( $keyword );
    $this->build( $keywords )->shouldBeString();
  }
}

Rewrite spec test for SolrQueryBuilder so that a SearchTerm is passed.


<?php
/**
 * Created by PhpStorm.
 * User: Alex
 * Date: 14/04/2019
 * Time: 12:48
 */

namespace vr\api\components;

use Error;
use Exception;
use vr\core\ErrorsException;

/**
 * Class ErrorHandler
 * @package vr\api\components
 */
class ErrorHandler extends \yii\web\ErrorHandler
{
    /**
     * @param Error|Exception $exception
     *
     * @return array
     */
    protected function convertExceptionToArray($exception)
    {
        $array = parent::convertExceptionToArray($exception);

        if ($exception instanceof ErrorsException) {
            $array += [
                'data' => $exception->data,
            ];

            if (YII_DEBUG) {
                $array += [
                    'trace' => explode("\n", $exception->getTraceAsString())
                ];
            }
        }

        return $array;
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: Alex
 * Date: 14/04/2019
 * Time: 12:48
 */

namespace vr\api\components;

use Error;
use Exception;
use vr\core\ErrorsException;
use Yii;

/**
 * Class ErrorHandler
 * @package vr\api\components
 */
class ErrorHandler extends \yii\web\ErrorHandler
{
    /**
     * @var int
     */
    public $errorStatusCode = 400;

    /**
     * @param Error|Exception $exception
     *
     * @return array
     */
    protected function convertExceptionToArray($exception)
    {
        $array = parent::convertExceptionToArray($exception);

        if ($exception instanceof ErrorsException) {
            Yii::$app->response->statusCode = $this->errorStatusCode;

            $array += [
                'data' => $exception->data,
            ];

            if (YII_DEBUG) {
                $array += [
                    'trace' => explode("\n", $exception->getTraceAsString())
                ];
            }
        }

        return $array;
    }
}

Add ability to change the response status code on ErrorsException


<!DOCTYPE html>

		<meta charset="utf-8">

Password Reset

			To reset your password, complete this form: {{ URL::to('password/reset', array($token)) }}.

			This link will expire in {{ Config::get('auth.reminder.expire', 60) }} minutes.

<!DOCTYPE html>

		<meta charset="utf-8">

Password Reset

			To reset your password, complete this form: {{ URL::to('password/reset', [$token]) }}.

			This link will expire in {{ Config::get('auth.reminder.expire', 60) }} minutes.

Convert last long notation array to short notation


<?php

namespace Lensky\PerformanceBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * PostRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PostRepository extends EntityRepository
{
    /**
     * Find all posts with authors
     *
     * @return array | Post[]
     */
    public function findAllPostsAndAuthors()
    {
        $qb = $this->createQueryBuilder('p');
        $qb->addSelect('a')
            ->innerJoin('p.author', 'a');

        return $qb->getQuery()->getResult();
    }

    /**
     * Update created date for all posts
     *
     * @param \DateTime $newCreatedAt
     *
     * @return int
     */
    public function updateCreatedAtForAllPosts(\DateTime $newCreatedAt)
    {
        $qb = $this->createQueryBuilder($this->alias);
        $qb->update()
            ->set('p.createdAt', ':newCreatedAt')
            ->setParameter('newCreatedAt', $newCreatedAt);

        return $qb->getQuery()->execute();
    }
}

<?php

namespace Lensky\PerformanceBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * PostRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PostRepository extends EntityRepository
{
    /**
     * Find all posts with authors
     *
     * @return array | Post[]
     */
    public function findAllPostsAndAuthors()
    {
        $qb = $this->createQueryBuilder('p');
        $qb->addSelect('a')
            ->innerJoin('p.author', 'a');

        return $qb->getQuery()->getResult();
    }

    /**
     * Update created date for all posts
     *
     * @param \DateTime $newCreatedAt
     *
     * @return int
     */
    public function updateCreatedAtForAllPosts(\DateTime $newCreatedAt)
    {
        $qb = $this->createQueryBuilder('p');
        $qb->update()
            ->set('p.createdAt', ':newCreatedAt')
            ->setParameter('newCreatedAt', $newCreatedAt);

        return $qb->getQuery()->execute();
    }
}

Fix alias in update query

Fix alias in update query


<?php

namespace AppBundle\Services;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use CMEN\GoogleChartsBundle\GoogleCharts\Charts\Timeline;
use AppBundle\Entity\MemberRegistration;

class PersonReportService
{
    private $em;
    private $formFactory;

    public function __construct(\Doctrine\ORM\EntityManagerInterface $em, \Symfony\Component\Form\FormFactoryInterface $formFactory)
    {
        $this->em = $em;
        $this->formFactory = $formFactory;
    }

    public function buildParticipationTimeline($person)
    {
        $currentMembershipPeriod = $person->getCurrentMemberRegistration()->getMembershipTypePeriod()->getMembershipPeriod();

        $rows = [];
        foreach ($person->getParticipant() as $p) {
            if (
                $p->getManagedActivity()->getActivityStart() <= $currentMembershipPeriod->getFromDate() &&
                $p->getManagedActivity()->getActivityStart() < $currentMembershipPeriod->getToDate()
            ) {
                continue;
            }

            $rows[] = [
                'Participation',
                $p->getManagedActivity()->getName(),
                $p->getManagedActivity()->getActivityStart(),
                $p->getManagedActivity()->getActivityEnd()
            ];
        }

        $timeline = new Timeline();
        $timeline->getData()->setArrayToDataTable($rows, true);

        return $timeline;
    }

}

<?php

namespace AppBundle\Services;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use CMEN\GoogleChartsBundle\GoogleCharts\Charts\Timeline;
use AppBundle\Entity\MemberRegistration;

class PersonReportService
{
    private $em;
    private $formFactory;

    public function __construct(\Doctrine\ORM\EntityManagerInterface $em, \Symfony\Component\Form\FormFactoryInterface $formFactory)
    {
        $this->em = $em;
        $this->formFactory = $formFactory;
    }

    public function buildParticipationTimeline($person)
    {
        $currentMembershipPeriod = $person->getCurrentMemberRegistration()->getMembershipTypePeriod()->getMembershipPeriod();

        $rows = [];
        foreach ($person->getParticipant() as $p) {
            if (
                $p->getManagedActivity()->getActivityStart() <= $currentMembershipPeriod->getFromDate() &&
                $p->getManagedActivity()->getActivityStart() < $currentMembershipPeriod->getToDate()
            ) {
                continue;
            }

            $rows[] = [
                'Participation',
                $p->getManagedActivity()->getName(),
                $p->getManagedActivity()->getActivityStart(),
                $p->getManagedActivity()->getActivityEnd()
            ];
        }

        $timeline = new Timeline();
        $timeline->getData()->setArrayToDataTable($rows, true);
        $timeline->getOptions()->getTimeline()->setColorByRowLabel(true);

        return $timeline;
    }

}

Use the same colour for all activities

Use the same colour for all activities


<?php
/*
 * This file is part of the Artscore Studio Framework package.
 *
 * (c) Nicolas Claverie <info@artscore-studio.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace ASF\ContactBundle\Utils\Manager;

use ASF\CoreBundle\Entity\Manager\ASFEntityManager;

/**
 * Generic Entity Manager for this bundle
 *
 * @author Nicolas Claverie <info@artscore-studio.fr>
 *
 */
class DefaultEntityManager extends ASFEntityManager implements DefaultEntityManagerInterface {}

<?php
/*
 * This file is part of the Artscore Studio Framework package.
 *
 * (c) Nicolas Claverie <info@artscore-studio.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace ASF\ContactBundle\Utils\Manager;

use ASF\CoreBundle\Utils\Manager\ASFEntityManager;

/**
 * Generic Entity Manager for this bundle
 *
 * @author Nicolas Claverie <info@artscore-studio.fr>
 *
 */
class DefaultEntityManager extends ASFEntityManager implements DefaultEntityManagerInterface {}

Change use statement to ASFEntityManager


<?php
/**
 * sfTesterJsonResponse implements tests for the symfony response object.
 */
class sfTesterJsonResponse extends sfTester
{
  /**
   * Prepares the tester.
   */
  public function prepare()
  {
  }

  /**
   * Initializes the tester.
   */
  public function initialize()
  {
  }

  /**
   * Try to decode the response body from json format
   *
   * @return boolean
   */
  public function isJson()
  {
    $is_json = (bool) json_decode($this->browser->getResponse()->getContent());

    $is_json ? $this->tester->pass('content is valid json') : $this->tester->fail('content is not valid json');

    return $this->getObjectToReturn();
  }
}

<?php
/**
 * sfTesterJsonResponse implements tests for the symfony response object.
 */
class sfTesterJsonResponse extends sfTester
{
  /**
   * Prepares the tester.
   */
  public function prepare()
  {
  }

  /**
   * Initializes the tester.
   */
  public function initialize()
  {
  }

  /**
   * Try to decode the response body from json format
   *
   * @return boolean
   */
  public function isJson()
  {
    $is_json = json_decode($this->browser->getResponse()->getContent());
    $is_json !== false ? $this->tester->pass('content is valid json') : $this->tester->fail('content is not valid json');

    return $this->getObjectToReturn();
  }
}

Fix the Json Response tester (was returning false on empty json array)


<?php
namespace Http;

require_once('Rest/class.RestAPI.php');

class WebErrorHandler
{
    public function __invoke($request, $response, $exception)
    {
        if($exception->getCode() === \Http\Rest\ACCESS_DENIED)
        {
            $response->getBody()->write('You are not authorized to view this page. The most common cause of this is that you are not logged in to the website. Please log in then try again');
            return $response->withStatus(401);
        }
        error_log($exception->__toString());
        return $response
            ->withStatus(500)
            ->withHeader('Content-Type', 'text/html')
            ->write($exception->__toString());
   }
}

<?php
namespace Http;

require_once('Rest/class.RestAPI.php');

class WebErrorHandler
{
    public function __invoke($request, $response, $exception)
    {
        if($exception->getCode() === \Http\Rest\ACCESS_DENIED)
        {
            $response->getBody()->write('You are not authorized to view this page. The most common cause of this is that you are not logged in to the website. Please log in then try again');
            return $response->withStatus(401);
        }
        else if($exception->getCode() === \Http\Rest\INVALID_PARAM)
        {
            return $response->withJson($exception, 400);
        }
        error_log($exception->__toString());
        return $response
            ->withStatus(500)
            ->withHeader('Content-Type', 'text/html')
            ->write($exception->__toString());
   }
}

Return 400 status on bad parameters

Return 400 status on bad parameters


<?php

namespace Criterion\Test\Helper;

class NotificationsHelperTest extends \Criterion\Test\TestCase
{
    public function testEmail()
    {
        $response = \Criterion\Helper\Notifications::email('testing@localhost', 'Testing', 'Testing');
        $this->assertTrue($response);
    }

    public function testFailedEmail()
    {
        $project = new \Criterion\Model\Project(array(
            'repo' => 'git@github.com:romhut/criterion'
        ));
        $project->email = 'testing@localhost';

        $test = new \Criterion\Model\Test();

        $response = \Criterion\Helper\Notifications::failedEmail($test->id, $project);
        $this->assertTrue($response);
    }

    public function testFailedEmailNoEmail()
    {
        $project = new \Criterion\Model\Project(array(
            'repo' => 'git@github.com:romhut/criterion'
        ));

        $test = new \Criterion\Model\Test();
        $response = \Criterion\Helper\Notifications::failedEmail($test->id, $project);
        $this->assertFalse($response);
    }
}

<?php

namespace Criterion\Test\Helper;

class NotificationsHelperTest extends \Criterion\Test\TestCase
{
    public function testEmail()
    {
        $this->markTestIncomplete('We need to work out a way to mock emails');

        $response = \Criterion\Helper\Notifications::email('testing@localhost', 'Testing', 'Testing');
        $this->assertTrue($response);
    }

    public function testFailedEmail()
    {
        $this->markTestIncomplete('We need to work out a way to mock emails');

        $project = new \Criterion\Model\Project(array(
            'repo' => 'git@github.com:romhut/criterion'
        ));
        $project->email = 'testing@localhost';

        $test = new \Criterion\Model\Test();

        $response = \Criterion\Helper\Notifications::failedEmail($test->id, $project);
        $this->assertTrue($response);
    }

    public function testFailedEmailNoEmail()
    {
        $this->markTestIncomplete('We need to work out a way to mock emails');

        $project = new \Criterion\Model\Project(array(
            'repo' => 'git@github.com:romhut/criterion'
        ));

        $test = new \Criterion\Model\Test();
        $response = \Criterion\Helper\Notifications::failedEmail($test->id, $project);
        $this->assertFalse($response);
    }
}

Mark notification tests as incomplete until we can find a way to mock emails


	<?php foreach ($values as $v => $l) { ?>

			<input
				type="hidden"
				name="<?= "{$name}[{$this->escape($v)}]" ?>"
				value="0">
			<input
				type="checkbox"
				name="<?= "{$name}[{$this->escape($v)}]" ?>"
				id="<?= "{$id}[{$this->escape($v)}]" ?>"
				value="1"
				<?= isset($disabled) && $disabled ? "disabled" : null ?>
				<?= isset($readOnly) && $readOnly ? "readonly" : null ?>
				<?= in_array($v, $value) ? 'checked' : null ?>
				<?= isset($class) ? "class=\"{$class}\"" : null ?>>
			<label for="<?= "{$id}[{$this->escape($v)}]" ?>" class="checkbox">
				<?= $l ?>

	<?php } ?>

<?php if (!count($values)) { ?>
	No options available.
<?php } ?>

Add message when input-checkboxes has no values


<?php

namespace Atsys\Blog\Http\Controllers;

use App\Http\Controllers\Controller;
use Atsys\Blog\PostCategory;
use Atsys\Blog\Http\Requests\PostCategoryRequest;
use Illuminate\Http\Request;

class PostCategoriesController extends Controller
{
    public function index(Request $request)
    {
        $query = PostCategory::query();

        if ($q = $request->get('q', '')) {
            $query->where('id', 'like', "%$q%")->orWhere('title', 'like', "%$q%");
        }

        $categories = $query->get();

        return view('blog::admin.post_categories.index', compact('categories'));
    }

    public function create()
    {
        return view('blog::admin.post_categories.form');
    }

    public function store(PostCategoryRequest $request)
    {
        PostCategory::create($request->all());

        return redirect('admin/post_categories')->with('success', trans('blog::blog.category_created'));
    }

    public function edit(PostCategory $post_category)
    {
        return view('blog::admin.post_categories.edit', compact('post_category'));
    }

    public function update(PostCategoryRequest $request, PostCategory $post_category)
    {
        $post_category->update($request->all());

        return redirect('admin/post_categories')->with('success', trans('blog::blog.category_updated'));
    }

    public function destroy(PostCategory $post_category)
    {
        $post_category->delete();

        return redirect('admin/post_categories')->with('success', trans('blog::blog.category_deleted'));
    }
}

<?php

namespace Atsys\Blog\Http\Controllers;

use App\Http\Controllers\Controller;
use Atsys\Blog\PostCategory;
use Atsys\Blog\Http\Requests\PostCategoryRequest;
use Illuminate\Http\Request;

class PostCategoriesController extends Controller
{
    public function index(Request $request)
    {
        $query = PostCategory::query();

        if ($q = $request->get('q', '')) {
            $query->where('id', 'like', "%$q%")->orWhere('title', 'like', "%$q%");
        }

        $categories = $query->get();

        return view('blog::admin.post_categories.index', compact('categories'));
    }

    public function create()
    {
        return view('blog::admin.post_categories.create');
    }

    public function store(PostCategoryRequest $request)
    {
        PostCategory::create($request->all());

        return redirect('admin/post_categories')->with('success', trans('blog::blog.category_created'));
    }

    public function edit(PostCategory $post_category)
    {
        return view('blog::admin.post_categories.edit', compact('post_category'));
    }

    public function update(PostCategoryRequest $request, PostCategory $post_category)
    {
        $post_category->update($request->all());

        return redirect('admin/post_categories')->with('success', trans('blog::blog.category_updated'));
    }

    public function destroy(PostCategory $post_category)
    {
        $post_category->delete();

        return redirect('admin/post_categories')->with('success', trans('blog::blog.category_deleted'));
    }
}

Fix bug showing create post categories view


<?php

namespace Chigi\Sublime\Exception;

use Chigi\Sublime\Settings\Environment;

/**
 * Thrown when a file was not found
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class FileNotFoundException extends FileException {

    /**
     * Constructor.
     *
     * @param string $path The path to the file that was not found
     */
    public function __construct($path) {
        parent::__construct(sprintf('The file "%s" does not exist', $path));
    }

    public function setLine($line) {
        $this->line = $line;
    }

    public function setCode($code) {
        $this->code = $code;
    }

    public function setFile($file) {
        $this->file = $file;
    }

}

<?php

namespace Chigi\Sublime\Exception;

use Chigi\Sublime\Settings\Environment;

/**
 * Thrown when a file was not found
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class FileNotFoundException extends FileException {

    /**
     * Constructor.
     *
     * @param string $path The path to the file that was not found
     */
    public function __construct($path) {
        $this->path = $path;
        parent::__construct(sprintf('The file "%s" does not exist', $path));
    }

    public function setLine($line) {
        $this->line = $line;
    }

    public function setCode($code) {
        $this->code = $code;
    }

    public function setFile($file) {
        $this->file = $file;
    }

    private $path;

    public function getPath() {
        return $this->path;
    }

}

ADD path getter for the wrong file path.

Signed-off-by: Richard Lea <5e20e57f18b15612bae274c2aef7dc395ee6b2a1@zoho.com>


<?php

namespace PhpBench\Tests\Unit\Expression\Parselet;

use Generator;
use PhpBench\Expression\Ast\ParameterNode;
use PhpBench\Tests\Unit\Expression\ParseletTestCase;

class ParameterParseletTest extends ParseletTestCase
{
    /**
     * @return Generator<mixed>
     */
    public function provideParse(): Generator
    {
        yield 'property' => [
            'foo.bar',
            new ParameterNode(['foo', 'bar'])
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function provideEvaluate(): Generator
    {
        yield [
            'foo',
            ['foo' => 12],
            '12'
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function providePrint(): Generator
    {
        yield from $this->providePrintFromEvaluate();
    }
}

<?php

namespace PhpBench\Tests\Unit\Expression\Parselet;

use Generator;
use PhpBench\Expression\Ast\ParameterNode;
use PhpBench\Tests\Unit\Expression\ParseletTestCase;

class ParameterParseletTest extends ParseletTestCase
{
    /**
     * @return Generator<mixed>
     */
    public function provideParse(): Generator
    {
        yield 'property' => [
            'foo.bar',
            new ParameterNode(['foo', 'bar'])
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function provideEvaluate(): Generator
    {
        yield [
            'foo',
            ['foo' => 12],
            '12'
        ];

        yield [
            'foo.bar',
            ['foo' => ['bar' => 12]],
            '12'
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function providePrint(): Generator
    {
        yield from $this->providePrintFromEvaluate();
    }
}

Add test case to parameter parselet test


<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Core / Asset / Css
 */

namespace PH7;

use PH7\Framework\Mvc\Model\DbConfig;

defined('PH7') or exit('Restricted access');

$sBackgroundColor = DbConfig::getSetting('backgroundColor');
$sTextColor = DbConfig::getSetting('textColor');
$sLinkColor = DbConfig::getSetting('linkColor');
$sFooterLinkColor = DbConfig::getSetting('footerLinkColor');
$sLinkHoverColor = DbConfig::getSetting('linkHoverColor');

if (!empty($sBackgroundColor)) {
    printf('body {background-color: %s !important; background-image: none !important}', $sBackgroundColor);
}

if (!empty($sTextColor)) {
    printf('body {color: %s !important}', $sTextColor);
}

if (!empty($sLinkColor)) {
    printf('a {color: %s !important}', $sLinkColor);
}

if (!empty($sFooterLinkColor)) {
    printf('footer a {color: %s !important}', $sFooterLinkColor);
}

if (!empty($sLinkHoverColor)) {
    printf('a:hover, a:active {color: %s !important}', $sLinkHoverColor);
}

<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Core / Asset / Css
 */

namespace PH7;

defined('PH7') or exit('Restricted access');

use PH7\Framework\Mvc\Model\DbConfig;

$sBackgroundColor = DbConfig::getSetting('backgroundColor');
$sTextColor = DbConfig::getSetting('textColor');
$sLinkColor = DbConfig::getSetting('linkColor');
$sFooterLinkColor = DbConfig::getSetting('footerLinkColor');
$sLinkHoverColor = DbConfig::getSetting('linkHoverColor');

if (!empty($sBackgroundColor)) {
    printf('body {background-color: %s !important; background-image: none !important}', $sBackgroundColor);
}

if (!empty($sTextColor)) {
    printf('body {color: %s !important}', $sTextColor);
}

if (!empty($sLinkColor)) {
    printf('a {color: %s !important}', $sLinkColor);
}

if (!empty($sFooterLinkColor)) {
    printf('footer a {color: %s !important}', $sFooterLinkColor);
}

if (!empty($sLinkHoverColor)) {
    printf('a:hover, a:active {color: %s !important}', $sLinkHoverColor);
}

[Consistency] Move namespace import after defined or exit() code


<?php

namespace josegonzalez\Queuesadilla;

use josegonzalez\Queuesadilla\Engine\NullEngine;
use josegonzalez\Queuesadilla\Worker\TestWorker;
use josegonzalez\Queuesadilla\TestCase;
use Psr\Log\LoggerInterface;

class TestWorkerTest extends TestCase
{
    public function setUp()
    {
        $this->Engine = new NullEngine;
        $this->Worker = new TestWorker($this->Engine);
    }

    /**
     * @covers josegonzalez\Queuesadilla\Worker\Base::__construct
     * @covers josegonzalez\Queuesadilla\Worker\TestWorker::__construct
     */
    public function testConstruct()
    {
        $Worker = new TestWorker($this->Engine);
        $this->assertInstanceOf('\josegonzalez\Queuesadilla\Worker\Base', $Worker);
        $this->assertInstanceOf('\Psr\Log\LoggerInterface', $Worker->logger());
    }

    /**
     * @covers josegonzalez\Queuesadilla\Worker\Base::work
     * @covers josegonzalez\Queuesadilla\Worker\TestWorker::work
     */
    public function testWork()
    {
        $Worker = new TestWorker($this->Engine);
        $this->assertTrue($Worker->work());
        $this->assertTrue($Worker->work());
        $this->assertTrue($Worker->work());
    }
}

<?php

namespace josegonzalez\Queuesadilla;

use josegonzalez\Queuesadilla\Engine\NullEngine;
use josegonzalez\Queuesadilla\Worker\TestWorker;
use josegonzalez\Queuesadilla\TestCase;
use Psr\Log\LoggerInterface;

class TestWorkerTest extends TestCase
{
    public function setUp()
    {
        $this->Engine = new NullEngine;
        $this->Worker = new TestWorker($this->Engine);
    }

    /**
     * @covers josegonzalez\Queuesadilla\Worker\Base::__construct
     * @covers josegonzalez\Queuesadilla\Worker\TestWorker::__construct
     */
    public function testConstruct()
    {
        $Worker = new TestWorker($this->Engine);
        $this->assertInstanceOf('\josegonzalez\Queuesadilla\Worker\Base', $Worker);
        $this->assertInstanceOf('\Psr\Log\LoggerInterface', $Worker->logger());
        $this->assertInstanceOf('\Psr\Log\NullLogger', $Worker->logger());
    }

    /**
     * @covers josegonzalez\Queuesadilla\Worker\Base::work
     * @covers josegonzalez\Queuesadilla\Worker\TestWorker::work
     */
    public function testWork()
    {
        $Worker = new TestWorker($this->Engine);
        $this->assertTrue($Worker->work());
        $this->assertTrue($Worker->work());
        $this->assertTrue($Worker->work());
    }
}

Add a test to ensure the logger method is working


<?php

namespace React\Espresso;

use React\Http\Request;
use React\Http\Response;
use Silex\Application as BaseApplication;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

class Application extends BaseApplication
{
    public function __construct()
    {
        parent::__construct();

        $this['controllers'] = $this->share(function () {
            return new ControllerCollection();
        });
    }

    public function __invoke(Request $request, Response $response)
    {
        $sfRequest = $this->buildSymfonyRequest($request, $response);
        $this->handle($sfRequest);
    }

    private function buildSymfonyRequest(Request $request, Response $response)
    {
        $sfRequest = SymfonyRequest::create($request->getPath(), $request->getMethod());
        $sfRequest->attributes->set('react.espresso.request', $request);
        $sfRequest->attributes->set('react.espresso.response', $response);

        return $sfRequest;
    }
}

<?php

namespace React\Espresso;

use React\Http\Request;
use React\Http\Response;
use Silex\Application as BaseApplication;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

class Application extends BaseApplication
{
    public function __construct()
    {
        parent::__construct();

        $app = $this;

        $this['controllers_factory'] = function () use ($app) {
            return new ControllerCollection($app['route_factory']);
        };
    }

    public function __invoke(Request $request, Response $response)
    {
        $sfRequest = $this->buildSymfonyRequest($request, $response);
        $this->handle($sfRequest);
    }

    private function buildSymfonyRequest(Request $request, Response $response)
    {
        $sfRequest = SymfonyRequest::create($request->getPath(), $request->getMethod());
        $sfRequest->attributes->set('react.espresso.request', $request);
        $sfRequest->attributes->set('react.espresso.response', $response);

        return $sfRequest;
    }
}

Update deps, fix Espresso, add test

Update deps, fix Espresso, add test


<?php
class Kwc_Events_Directory_Component extends Kwc_News_Directory_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['componentName'] = trlKwfStatic('Events');
        $ret['componentCategory'] = 'admin';
        $ret['componentIcon'] = 'date';
        $ret['childModel'] = 'Kwc_Events_Directory_Model';

        $ret['generators']['detail']['class'] = 'Kwc_Events_Directory_Generator';
        $ret['generators']['detail']['component'] = 'Kwc_Events_Detail_Component';
        $ret['generators']['detail']['dbIdShortcut'] = 'events_';

        $ret['generators']['child']['component']['view'] = 'Kwc_Events_List_View_Component';

        $ret['flags']['assetsPackage'] = 'Events';

        return $ret;
    }

    public function getSelect()
    {
        $select = parent::getSelect();
        // nur aktuellen tag nehmen ohne uhrzeit, dann sieht man ein event
        // den restlichen tag, egal welche uhrzeit. - das soll so sein
        $select->where("IF(ISNULL(end_date), start_date, end_date) >= CURDATE()");
        return $select;
    }
}

<?php
class Kwc_Events_Directory_Component extends Kwc_News_Directory_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['componentName'] = trlKwfStatic('Events');
        $ret['componentCategory'] = 'admin';
        $ret['componentIcon'] = 'date';
        $ret['childModel'] = 'Kwc_Events_Directory_Model';

        $ret['generators']['detail']['class'] = 'Kwc_Events_Directory_Generator';
        $ret['generators']['detail']['component'] = 'Kwc_Events_Detail_Component';
        $ret['generators']['detail']['dbIdShortcut'] = 'events_';

        $ret['generators']['child']['component']['view'] = 'Kwc_Events_List_View_Component';

        return $ret;
    }

    public function getSelect()
    {
        $select = parent::getSelect();
        // nur aktuellen tag nehmen ohne uhrzeit, dann sieht man ein event
        // den restlichen tag, egal welche uhrzeit. - das soll so sein
        $select->where("IF(ISNULL(end_date), start_date, end_date) >= CURDATE()");
        return $select;
    }
}

Remove own Events assets package, use inherited News

Fixes problem when a web uses News and Events, where child components of detail (eg. MetaTags) would be in two packages.


@if ($slide['image_use'] !== false)

@endif

@if ($slide['mobile_image_use'] !== false)

@endif

@if (isset($slide['activate_textblock']) && $slide['activate_textblock'])
@include('partials.textblock')'
@endif

@if ($slide['image_use'] !== false)

	@if (isset($slide['activate_textblock']) && $slide['activate_textblock'])
	@include('partials.textblock')'
	@endif

@endif

@if ($slide['mobile_image_use'] !== false)

	@if (isset($slide['activate_textblock']) && $slide['activate_textblock'])
	@include('partials.textblock')'
	@endif

@endif

Move text block inside slider div

Move text block inside slider div


<?php

namespace MrJuliuss\Syntara\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Sentry;

class UpdateCommand extends Command
{

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'syntara:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Syntara update command';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $this->info('## Syntara Update ##');

        // publish sentry config
        $this->call('config:publish', array('package' => 'cartalyst/sentry' ) );

        // publish syntara config
        $this->call('config:publish', array('package' => 'mrjuliuss/syntara' ) );

        // publish syntara assets
        $this->call('asset:publish', array('package' => 'mrjuliuss/syntara' ) );

        // run migrations
        $this->call('migrate', array('--env' => $this->option('env'), '--package' => 'cartalyst/sentry' ) );
        $this->call('migrate', array('--env' => $this->option('env'), '--package' => 'mrjuliuss/syntara' ) );
    }
}

<?php

namespace MrJuliuss\Syntara\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Sentry;

class UpdateCommand extends Command
{

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'syntara:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Syntara update command';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $this->info('## Syntara Update ##');

        // publish syntara assets
        $this->call('asset:publish', array('package' => 'mrjuliuss/syntara' ) );

        // run migrations
        $this->call('migrate', array('--env' => $this->option('env'), '--package' => 'cartalyst/sentry' ) );
        $this->call('migrate', array('--env' => $this->option('env'), '--package' => 'mrjuliuss/syntara' ) );
    }
}

Revert "[Upg] update command : add publishing config"

This reverts commit 18a09131fb71ede93c47547d7e3d185abf0b16bd.


<?php

session_start();

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

$app = new Slim\App([
    'env' => 'prod',
    'root_dir' => dirname(__DIR__)
]);
$container = $app->getContainer();

$container['config'] = require __DIR__ . '/../app/config/config.php';

require __DIR__ . '/../app/bootstrap.php';

$app->run();

<?php

session_start();

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

$app = new App\Application('prod');

$app->run();

Use new Application class in prod

Use new Application class in prod


{{--Translated fields show errors in the container, not per field--}}
@if ( ! isset($translated) || ! $translated)

        @if ($errors && count($errors))
            @foreach ($errors as $error)
                {{ $error }}

            @endforeach
        @endif

@endif

{{--Translated fields show errors in the container, not per field--}}
@if ( ! isset($translated) || ! $translated)

        @if ($errors && count($errors))
            @foreach ($errors as $error)
                {{--TODO: Refactor--}}
                @if (is_array($error))
                    @foreach ($error as $_error)
                        {{ $_error }}

                    @endforeach
                @else
                    {{ $error }}

                @endif
            @endforeach
        @endif

@endif

Allow nested form error messages

Hotfix: Allow nested form error messages


<?php

namespace fennecweb\ajax\details;

use \fennecweb\WebService as WebService;

class TraitsOfOrganismsTest extends \PHPUnit_Framework_TestCase
{

    public function testExecute()
    {
        //Test if the traits to one organism is returned correctly
        list($service) = WebService::factory('details/TraitsOfOrganisms');
        $organism_ids = ['12049'];
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'organism_ids' => $organism_ids)));
        $expected = [1 => 'habitat', 5 => 'elevation', 7 => 'plant growth habitat'];
        $this->assertEquals($expected, $results);

        //Test if the traits to a collection of organisms is returned correctly
        list($service) = WebService::factory('details/TraitsOfOrganisms');
        $organism_ids = ['47757','200', '12049'];
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'organism_ids' => $organism_ids)));
        $expected = [1 => 'habitat', 5 => 'elevation', 7 => 'plant growth habitat'];
        $this->assertEquals($expected, $results);
    }
}

<?php

namespace fennecweb\ajax\details;

use \fennecweb\WebService as WebService;

class TraitsOfOrganismsTest extends \PHPUnit_Framework_TestCase
{

    public function testExecute()
    {
        //Test if the traits to one organism is returned correctly
        list($service) = WebService::factory('details/TraitsOfOrganisms');
        $organism_ids = ['12049'];
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'organism_ids' => $organism_ids)));
        $expected = [['trait_entry_id' => 753126, 'cvterm' => 'extinction status'], ['trait_entry_id' => 753127, 'cvterm' => 'geographic distribution'],
            ['trait_entry_id' => 753128, 'cvterm' => 'geographic distribution'],['trait_entry_id' => 753129, 'cvterm' => 'type specimen repository'],
            ['trait_entry_id' => 753130, 'cvterm' => 'habitat'],['trait_entry_id' => 753131, 'cvterm' => 'geographic distribution']];
        $this->assertEquals($expected, $results);

        //Test if the traits to a collection of organisms is returned correctly
        list($service) = WebService::factory('details/TraitsOfOrganisms');
        $organism_ids = ['47757','200', '12049'];
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'organism_ids' => $organism_ids)));
        $expected = [1 => 'habitat', 5 => 'elevation', 7 => 'plant growth habitat'];
        $this->assertEquals($expected, $results);
    }
}

Make one failing test pass

Make one failing test pass


<?php
// JUser/View/Helper/UserWithIp.php

namespace JUser\View\Helper;

use Zend\View\Helper\AbstractHelper;

class UserWithIp extends AbstractHelper
{
    public function __invoke($username, $ipAddress)
    {
        $geo = $this->view->geoip($ipAddress);
        $place = '';
        if ($geo&&$geo->getCity()) {
            $place .= $this->view->escapeHtml(mb_convert_encoding($geo->getCity(), "UTF-8", "auto")).", ";
        }
        if ($geo&&$geo->getCountryName()) {
            $place .= $this->view->escapeHtml(mb_convert_encoding($geo->getCountryName(), "UTF-8", "auto"));
        }

        //if they didn't pass us a user name print the place and/or ipAddress
        if (is_null($username) || 0 == strlen($username)) {
            if ('' === $place) {
                return $ipAddress;
            } else {
                $return = '%s';
                return sprintf($return, $ipAddress, $place);
            }
        }
        //otherwise return the username with a tooltip
        if ('' === $place) {
            $tooltip = $ipAddress;
        } else {
            $tooltip = $place. ' ('.$ipAddress.')';
        }
        $return = '%s';
        return sprintf($return, $tooltip, $username);
    }
}

<?php
// JUser/View/Helper/UserWithIp.php

namespace JUser\View\Helper;

use Zend\View\Helper\AbstractHelper;

class UserWithIp extends AbstractHelper
{
    public function __invoke($username, $ipAddress)
    {
        $geo = $this->view->geoip($ipAddress);
        $place = '';
        if ($geo&&$geo->getCity()) {
            $place .= $this->view->escapeHtml(mb_convert_encoding($geo->getCity(), "UTF-8", "ISO-8859-1")).", ";
        }
        if ($geo&&$geo->getCountryName()) {
            $place .= $this->view->escapeHtml(mb_convert_encoding($geo->getCountryName(), "UTF-8", "ISO-8859-1"));
        }

        //if they didn't pass us a user name print the place and/or ipAddress
        if (is_null($username) || 0 == strlen($username)) {
            if ('' === $place) {
                return $ipAddress;
            } else {
                $return = '%s';
                return sprintf($return, $ipAddress, $place);
            }
        }
        //otherwise return the username with a tooltip
        if ('' === $place) {
            $tooltip = $ipAddress;
        } else {
            $tooltip = $place. ' ('.$ipAddress.')';
        }
        $return = '%s';
        return sprintf($return, $tooltip, $username);
    }
}

Improve geo ip string decoding

Improve geo ip string decoding


<?php

namespace Neblion\BaseAppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="welcome")
     * @Template()
     */
    public function indexAction()
    {
        return array();
    }
}

<?php

namespace Neblion\BaseAppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="welcome")
     * @Template()
     */
    public function indexAction()
    {
        $user = $this->get('security.context')->getToken()->getUser();

        // Check if user has a profile
        if (!$user->getProfile()) {
            // Set flash message
            $this->get('session')->setFlash('notice', 'You have not a profile, create it!');
            return $this->redirect($this->generateUrl('profile_new'));
        }

        return array();
    }
}

Check on default controler if the user has a profile, if not redirect for creation


<?php
/* Copyright (C) NAVER <http://www.navercorp.com> */

class JSONDisplayHandler
{

	/**
	 * Produce JSON compliant content given a module object.\n
	 * @param ModuleObject $oModule the module object
	 * @return string
	 */
	function toDoc(&$oModule)
	{
		$variables = $oModule->getVariables();
		$variables['error'] = $oModule->getError();
		$variables['message'] = $oModule->getMessage();
		return json_encode($variables);
	}

}
/* End of file JSONDisplayHandler.class.php */
/* Location: ./classes/display/JSONDisplayHandler.class.php */

<?php
/* Copyright (C) NAVER <http://www.navercorp.com> */

class JSONDisplayHandler
{

	/**
	 * Produce JSON compliant content given a module object.\n
	 * @param ModuleObject $oModule the module object
	 * @return string
	 */
	public function toDoc($oModule)
	{
		$variables = $oModule->getVariables();
		$variables['error'] = $oModule->getError();
		$variables['message'] = $oModule->getMessage();

		if (Context::getRequestMethod() === 'XMLRPC')
		{
			$temp = array();
			foreach ($variables as $key => $value)
			{
				if (self::_isNumericArray($value))
				{
					$temp[$key] = array_values($value);
				}
				else
				{
					$temp[$key] = $value;
				}
			}
			$variables = $temp;
		}

		return json_encode($variables);
	}

	/**
	 * Check if an array only has numeric keys.
	 *
	 * @param array $array
	 * @return bool
	 */
	protected static function _isNumericArray($array)
	{
		if (!is_array($array) || !count($array))
		{
			return false;
		}
		foreach ($array as $key => $value)
		{
			if (intval($key) != $key)
			{
				return false;
			}
		}
		return true;
	}
}
/* End of file JSONDisplayHandler.class.php */
/* Location: ./classes/display/JSONDisplayHandler.class.php */

Fix encoding of numeric arrays in XMLRPC->JSON conversion


<?php

declare(strict_types=1);

namespace Rinvex\Tags\Console\Commands;

use Illuminate\Console\Command;

class PublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rinvex:publish:tags {--f|force : Overwrite any existing files.} {--r|resource=all}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Publish Rinvex Tags Resources.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $this->alert($this->description);

        switch ($this->option('resource')) {
            case 'config':
                $this->call('vendor:publish', ['--tag' => 'rinvex-tags-config', '--force' => $this->option('force')]);
                break;
            case 'migrations':
                $this->call('vendor:publish', ['--tag' => 'rinvex-tags-migrations', '--force' => $this->option('force')]);
                break;
            default:
                $this->call('vendor:publish', ['--tag' => 'rinvex-tags-config', '--force' => $this->option('force')]);
                $this->call('vendor:publish', ['--tag' => 'rinvex-tags-migrations', '--force' => $this->option('force')]);
                break;
        }

        $this->line('');
    }
}

<?php

declare(strict_types=1);

namespace Rinvex\Tags\Console\Commands;

use Illuminate\Console\Command;

class PublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rinvex:publish:tags {--f|force : Overwrite any existing files.} {--r|resource=all}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Publish Rinvex Tags Resources.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $this->alert($this->description);

        switch ($this->option('resource')) {
            case 'config':
                $this->call('vendor:publish', ['--tag' => 'rinvex/tags::config', '--force' => $this->option('force')]);
                break;
            case 'migrations':
                $this->call('vendor:publish', ['--tag' => 'rinvex/tags::migrations', '--force' => $this->option('force')]);
                break;
            default:
                $this->call('vendor:publish', ['--tag' => 'rinvex/tags::config', '--force' => $this->option('force')]);
                $this->call('vendor:publish', ['--tag' => 'rinvex/tags::migrations', '--force' => $this->option('force')]);
                break;
        }

        $this->line('');
    }
}

Enforce consistent artisan command tag namespacing