<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace ImboClientCli;

/**
 * Version class
 *
 * @package Application
 * @author Christer Edvartsen <cogo@starzinger.net>
 */
class Version {
    /**
     * The current version
     *
     * This string will be replaced by the actual version when installed via pear
     *
     * @var string
     */
    static private $id = '@package_version@';

    /**
     * Get the version number only
     *
     * @return string
     */
    static public function getVersionNumber() {
        if (strpos(self::$id, '@package_version') === 0) {
            return 'dev';
        }

        return self::$id;
    }

    /**
     * Get the version string
     *
     * @return string
     */
    static public function getVersionString() {
        return 'ImboClientCli-' . self::getVersionNumber() . ' by Christer Edvartsen';
    }
}

<?php
/**
 * This file is part of the ImboClientCli package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace ImboClientCli;

/**
 * Version class
 *
 * @package Application
 * @author Christer Edvartsen <cogo@starzinger.net>
 */
class Version {
    /**
     * The current version
     *
     * @var string
     */
    const VERSION = 'dev';
}

Remove PEAR-related stuff and fixed some comments


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use CodeIgniter\CLI\CLI;

CLI::error('ERROR: '.$heading);
CLI::write($message);
CLI::newLine();

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use CodeIgniter\CLI\CLI;

CLI::error('ERROR: ' . $code);
CLI::write($message);
CLI::newLine();

Fix undefined variable "heading" in cli 404


<?php

//This should be run on cron.

include_once('config.php');

$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$timeNow = date("Y-m-d H:i:s");
$saved = 0;
foreach( ['yes','limited','no','unknown'] as $wheelchair_filter ){
    $json = json_decode(file_get_contents("https://wheelmap.org/api/nodes?api_key=$wheelmap_api_key&bbox=-2.413769,51.363902,-2.310473,51.415048&wheelchair=$wheelchair_filter"), true);
    $item_count = $json['meta']['item_count_total'];

    $success = $mysqli->query("INSERT INTO venue_counts (`category`,`wheelchair`,`time`,`count`) VALUES ('0','$wheelchair_filter','$timeNow','$item_count')");
    if( !$success ){
        die( $mysqli->error );
    }
    else{
        $saved++;
    }
}

echo "Saved $saved rows to DB.";

<?php

//This should be run on cron.

include_once('config.php');

$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$timeNow = gmdate("Y-m-d H:i:s");
$saved = 0;
foreach( ['yes','limited','no','unknown'] as $wheelchair_filter ){
    $json = json_decode(file_get_contents("https://wheelmap.org/api/nodes?api_key=$wheelmap_api_key&bbox=-2.413769,51.363902,-2.310473,51.415048&wheelchair=$wheelchair_filter"), true);
    $item_count = $json['meta']['item_count_total'];

    $success = $mysqli->query("INSERT INTO venue_counts (`category`,`wheelchair`,`time`,`count`) VALUES ('0','$wheelchair_filter','$timeNow','$item_count')");
    if( !$success ){
        die( $mysqli->error );
    }
    else{
        $saved++;
    }
}

echo "Saved $saved rows to DB.";

Switch to store GMT dates.

Switch to store GMT dates.


<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Update of the doc for equals to Model

Update of the doc for equals to Model


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

namespace Darvin\ImageBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Add Imagine filter sets compiler pass
 */
class AddImagineFilterSetsPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $filterSets = [];

        $config = $container->getParameter('darvin_image.imagine');

        foreach ($config['filter_sets'] as $name => $filterSet) {
            $filterSets[$name] = array_merge_recursive($config['filter_defaults'], [
                'cache' => 'darvin_image',
            ], $filterSet);
        }

        $container->setParameter(
            'liip_imagine.filter_sets',
            array_merge($container->getParameter('liip_imagine.filter_sets'), $filterSets)
        );
    }
}

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

namespace Darvin\ImageBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Add Imagine filter sets compiler pass
 */
class AddImagineFilterSetsPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $filterSets = [];

        $config = $container->getParameter('darvin_image.imagine');

        foreach ($config['filter_sets'] as $name => $filterSet) {
            $filterSets[$name] = array_merge_recursive($config['filter_defaults'], [
                'cache' => 'darvin_image',
            ], $filterSet);
        }

        $container->setParameter(
            'liip_imagine.filter_sets',
            array_merge($filterSets, $container->getParameter('liip_imagine.filter_sets'))
        );
    }
}

Change filter sets merge priority in add Imagine filter sets compiler pass.


<?php
/**
* Packages everything into a nice PHAR archive
*/

if(file_exists('emulator.phar')) {
  unlink('emulator.phar');
}

$phar = new Phar('emulator.phar', 0, 'emulator.phar');

$phar->buildFromDirectory(dirname(__DIR__));
$phar->delete('composer.phar');
$phar->setDefaultStub('emulator/emulator.php');

<?php
/**
* Packages everything into a nice PHAR archive
*/

if(file_exists('emulator.phar')) {
  unlink('emulator.phar');
}

$phar = new Phar('emulator.phar', 0, 'emulator.phar');

$phar->buildFromDirectory(dirname(__DIR__));

if(file_exists('phar://emulator.phar/composer.phar')) {
  $phar->delete('composer.phar');
}

$phar->setDefaultStub('emulator/emulator.php');

Check before attempting to remove composer from phar archive


<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();

require_once __DIR__.'/../app/AppKernel.php';

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1', '89.158.15.146')) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();

require_once __DIR__.'/../app/AppKernel.php';

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Add ip on ip dev

Add ip on ip dev


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use \App\Manga;
use \App\MangaInformation;

class MangaEditController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index($id)
    {
        if (\Auth::user()->isAdmin() == false && \Auth::user()->isMaintainer() == false) {
            return view('error.403');
        }

        $manga = Manga::find($id);
        if ($manga == null) {
            return view('error.404');
        }

        $name = $manga->getName();
        $info = MangaInformation::find($id);
        if ($info != null) {
            $mu_id = $info->getMangaUpdatesId();
        }

        $archives = $manga->getArchives('ascending');

        return view('manga.edit')->with('id', $id)
                                 ->with('mu_id', $mu_id)
                                 ->with('name', $name)
                                 ->with('archives', $archives);
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use \App\Manga;
use \App\MangaInformation;

class MangaEditController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index($id)
    {
        if (\Auth::user()->isAdmin() == false && \Auth::user()->isMaintainer() == false) {
            return view('error.403');
        }

        $manga = Manga::find($id);
        if ($manga == null) {
            return view('error.404');
        }

        $name = $manga->getName();
        $info = MangaInformation::find($id);
        $mu_id = null;
        if ($info != null) {
            $mu_id = $info->getMangaUpdatesId();
        }

        $archives = $manga->getArchives('ascending');

        return view('manga.edit')->with('id', $id)
                                 ->with('mu_id', $mu_id)
                                 ->with('name', $name)
                                 ->with('archives', $archives);
    }
}

Fix undefined variable error. (woops)

Fix undefined variable error. (woops)


<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\Test\DependencyResolver;

use Composer\DependencyResolver\Literal;
use Composer\Package\MemoryPackage;

class LiteralTest extends \PHPUnit_Framework_TestCase
{
    public function testLiteral()
    {
        $literal = new Literal(new MemoryPackage('foo', '1'), true);
        $this->markTestIncomplete('Eh?');
    }
}

<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\Test\DependencyResolver;

use Composer\DependencyResolver\Literal;
use Composer\Package\MemoryPackage;

class LiteralTest extends \PHPUnit_Framework_TestCase
{
    protected $package;

    public function setUp()
    {
        $this->package = new MemoryPackage('foo', '1');
        $this->package->setId(12);
    }

    public function testLiteralWanted()
    {
        $literal = new Literal($this->package, true);

        $this->assertEquals(12, $literal->getId());
        $this->assertEquals('+'.(string) $this->package, (string) $literal);
    }

    public function testLiteralUnwanted()
    {
        $literal = new Literal($this->package, false);

        $this->assertEquals(-12, $literal->getId());
        $this->assertEquals('-'.(string) $this->package, (string) $literal);
    }

    public function testLiteralInverted()
    {
        $literal = new Literal($this->package, false);

        $inverted = $literal->inverted();

        $this->assertInstanceOf('\Composer\DependencyResolver\Literal', $inverted);
        $this->assertTrue($inverted->isWanted());
        $this->assertSame($this->package, $inverted->getPackage());
        $this->assertFalse($literal->equals($inverted));

        $doubleInverted = $inverted->inverted();

        $this->assertInstanceOf('\Composer\DependencyResolver\Literal', $doubleInverted);
        $this->assertFalse($doubleInverted->isWanted());
        $this->assertSame($this->package, $doubleInverted->getPackage());

        $this->assertTrue($literal->equals($doubleInverted));
    }
}

Add a few proper tests for literals, all tests passing now


<?php

function rewriteHeader($headline, $oldTag, $newTag) {
	if (strpos($headline, $oldTag) === 0) {
		$data = substr($headline, strlen($oldTag));
		$data = str_replace('"', '', $data);
		return $newTag . $data . "\n";
	}
	else {
		return NULL;
	}
}

if (count($argv) < 2) {
  echo "Too few params. Need a file name to apply changes.";
  exit -1;
}

$filenames = array_slice($argv, 1);

foreach ($filenames as $target) {
	$filename = realpath($target);
	$content = file_get_contents($filename);

	$parts = explode('---', $content);

	$tokens = count($parts);

	$header = explode("\n", $parts[$tokens - 2]);
	$body = $parts[$tokens - 1];

	$newHeader = "";

	foreach ($header as $headline) {
		$newHeader .= rewriteHeader($headline, 'Title:', 'Title:');
		$newHeader .= rewriteHeader($headline, 'date:', 'Date:');
		$newHeader .= rewriteHeader($headline, 'categories:', 'Tags:');
	}

	$newHeader .= "Category: Blog\n";
	$newHeader .= "Author: Antonio Jesus Sanchez Padial\n";

	file_put_contents($filename, $newHeader . $body);
}

<?php

function rewriteHeader($headline, $oldTag, $newTag) {
	if (strpos($headline, $oldTag) === 0) {
		$data = substr($headline, strlen($oldTag));
		$data = str_replace('"', '', $data);
		return $newTag . $data . "\n";
	}
	else {
		return NULL;
	}
}

if (count($argv) < 2) {
  echo "Too few params. Need a file name to apply changes.";
  exit -1;
}

$filenames = array_slice($argv, 1);

foreach ($filenames as $target) {
	$filename = realpath($target);
	$content = file_get_contents($filename);

	$parts = explode('---', $content);

	$tokens = count($parts);

	$header = explode("\n", $parts[$tokens - 2]);
	$body = $parts[$tokens - 1];

	$newHeader = "";

	foreach ($header as $headline) {
		$newHeader .= rewriteHeader($headline, 'title:', 'Title:');
		$newHeader .= rewriteHeader($headline, 'date:', 'Date:');
		$newHeader .= rewriteHeader($headline, 'categories:', 'Tags:');
	}

	$newHeader .= "Category: Blog\n";
	$newHeader .= "Author: Antonio Jesus Sanchez Padial\n";

	file_put_contents($filename, $newHeader . $body);
}

Undo title to lowercase in octopress header.


<?php
include('db.php');
$releasequery = $sql->query('SELECT releaseid, releasename, releasedate, releasecover FROM ' . $sql->get_table_prefix() . 'releases ORDER BY releasedate DESC');
while($releaserow = $sql->fetch_assoc($releasequery)) {
 //MOD: check hidden release
 if($sql->num_rows($sql->query('SELECT releaseid FROM ' . $sql->get_table_prefix() . 'hiddenrels WHERE releaseid = "' . $sql->real_escape_string($releaserow['releaseid']) . '"')) > 0) continue;

 echo '
' . $releaserow['releasename'] . '
';
}
?>

<?php
include('db.php');
$releasequery = $sql->query('SELECT releaseid, releasename, releasedate, releasecover FROM ' . $sql->get_table_prefix() . 'releases ORDER BY releasedate DESC');
while($releaserow = $sql->fetch_assoc($releasequery)) {
 //Check hidden release
 if($sql->num_rows($sql->query('SELECT releaseid FROM ' . $sql->get_table_prefix() . 'hiddenrels WHERE releaseid = "' . $sql->real_escape_string($releaserow['releaseid']) . '"')) > 0) continue;
 echo '
' . $releaserow['releasename'] . '
';
}
?>

Remove "MOD" comment in hidden release feature

This will be a built-in feature.


<?php

namespace Knplabs\MarkupValidatorBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

/**
 * Dependency injection container compiler pass to register markup validation
 * processors. It finds all services having the "markup_validator.processor"
 * tag and adds them to the validator
 *
 * @author Antoine Hérault <antoine.herault@gmail.com>
 */
class RegisterValidatorsPass implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
        foreach ($container->findTaggedServiceIds('markup_validator.processor') as $id => $attributes) {
            if (isset($attributes[0]['alias'])) {
                $container->setAlias(sprintf('markup_validator.%s_processor', $attributes[0]['alias']), $id);
            }
        }
    }
}

<?php

namespace Knplabs\MarkupValidatorBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

/**
 * Dependency injection container compiler pass to register markup validation
 * processors. It finds all services having the "markup_validator.processor"
 * tag and adds them to the validator
 *
 * @author Antoine Hérault <antoine.herault@gmail.com>
 */
class RegisterProcessorsPass implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
        foreach ($container->findTaggedServiceIds('markup_validator.processor') as $id => $attributes) {
            if (isset($attributes[0]['alias'])) {
                $container->setAlias(sprintf('markup_validator.%s_processor', $attributes[0]['alias']), $id);
            }
        }
    }
}

Fix typo in compiler pass

Fix typo in compiler pass


<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

function prefs_header_list()
{
	return array(
		'header_shadow_start' => array(
			'name' => tra('Header shadow start'),
			'type' => 'textarea',
			'size' => '2',
			'default' => '',
		),
		'header_shadow_end' => array(
			'name' => tra('Header shadow end'),
			'type' => 'textarea',
			'size' => '2',
			'default' => '',
		),
		'header_custom_css' => array(
			'name' => tra('Custom CSS'),
			'description' => tra('Includes a custom block of CSS inline in all pages.'),
			'type' => 'textarea',
			'size' => 5,
			'default' => '',
		),
		'header_custom_js' => array(
			'name' => tra('Custom JavaScript'),
			'description' => tra('Includes a custom block of inline JavaScript in all pages.'),
			'type' => 'textarea',
			'size' => 5,
			'default' => '',
			'hint' => tra('Do not include the <script> and </script> tags.'),
		),
	);
}

<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

function prefs_header_list()
{
	return array(
		'header_shadow_start' => array(
			'name' => tra('Header shadow start'),
			'type' => 'textarea',
			'size' => '2',
			'default' => '',
		),
		'header_shadow_end' => array(
			'name' => tra('Header shadow end'),
			'type' => 'textarea',
			'size' => '2',
			'default' => '',
		),
		'header_custom_css' => array(
			'name' => tra('Custom CSS'),
			'description' => tra('Includes a custom block of CSS inline in all pages.'),
			'type' => 'textarea',
			'size' => 5,
			'default' => '',
			'filter' => 'none',
		),
		'header_custom_js' => array(
			'name' => tra('Custom JavaScript'),
			'description' => tra('Includes a custom block of inline JavaScript in all pages.'),
			'type' => 'textarea',
			'size' => 5,
			'default' => '',
			'hint' => tra('Do not include the <script> and </script> tags.'),
			'filter' => 'none',
		),
	);
}

[FIX] css: Allow url etc in custom css and js prefs (thanks luci)

git-svn-id: 84b83dd0f57d36a02bb8202710824ee41d1b7ca0@41591 b456876b-0849-0410-b77d-98878d47e9d5


<?php

  /**
   * Sloth-PHP
   * Tiny php framework, not actually as slow as it sounds.
   *
   * Written and copyrighted 2014+
   * by Sven Marc 'cybrox' Gehring
   */

  /* Allow user to switch app dir */
  define("APPDIR", "app");
  define("SUBDIR", "/git/giftfox/");

  /* Require needed fiels */
  require_once('./core/base.class.php');
  require_once('./core/router.class.php');
  require_once('./core/uri.class.php');
  require_once('./core/autoloader.class.php');

  try {

    /* Invoke base boot to get data we need */
    Base::boot();

    /* Register the autloader and load our files */
    Autoloader::register();
    Autoloader::load_app();
    Autoloader::load_dbs();

    /* Create function alias for simple templating */
    function __($name){ echo Registry::get($name); }

    /* Actually render page or catch errors */
    Router::route_process($_SERVER);

  } catch(Exception $e) {
    if(get_class($e) == "LazySloth") Error::shutdown($e);
    else Error::shutdown(new LazySloth($e));
  }
?>

<?php

  /**
   * Sloth-PHP
   * Tiny php framework, not actually as slow as it sounds.
   *
   * Written and copyrighted 2014+
   * by Sven Marc 'cybrox' Gehring
   */

  /* Allow user to switch app dir */
  define("APPDIR", "app");
  define("SUBDIR", "giftfox/");

  /* Require needed fiels */
  require_once('./core/base.class.php');
  require_once('./core/router.class.php');
  require_once('./core/uri.class.php');
  require_once('./core/autoloader.class.php');

  try {

    /* Invoke base boot to get data we need */
    Base::boot();

    /* Register the autloader and load our files */
    Autoloader::register();
    Autoloader::load_app();
    Autoloader::load_dbs();

    /* Create function alias for simple templating */
    function __($name){ echo Registry::get($name); }

    /* Actually render page or catch errors */
    Router::route_process($_SERVER);

  } catch(Exception $e) {
    if(get_class($e) == "LazySloth") Error::shutdown($e);
    else Error::shutdown(new LazySloth($e));
  }
?>

Adjust path for location on production drive


Exclude "_modified" property from "getAll" method

The "getAll" method of the Entity class should return an array with real
attributes of the Entity object but not internally used properties.


<?php

namespace Lauft\Behat\BashExtension\Context;

/**
 * BashContext context for Behat BDD tool.
 * Provides bash base step definitions.
 */
class BashContext extends RawBashContext
{
    /**
     * @When /^I run "([^"]*)"(?: with "([^"]*)")?$/
     *
     * @param string $command
     * @param string $arguments
     */
    public function iRunCommand($command, $arguments = '')
    {
        $arguments = strtr($arguments, array('\'' => '"'));

        $this->process->setWorkingDirectory($this->workingDir);
        $this->process->setCommandLine($command.' '.$arguments);
        $this->process->start();
        $this->process->wait();
    }
}

<?php

namespace Lauft\Behat\BashExtension\Context;

/**
 * BashContext context for Behat BDD tool.
 * Provides bash base step definitions.
 */
class BashContext extends RawBashContext
{
    /** @var string */
    protected $rootDirectory;

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

    /** @var Process */
    protected $process;

    public function __construct($rootDirectory = DIRECTORY_SEPARATOR)
    {
        $this->rootDirectory = $rootDirectory;
        $this->process = new Process(null);
    }

    /**
    /**
     * @When /^I run "([^"]*)"(?: with "([^"]*)")?$/
     *
     * @param string $command
     * @param string $arguments
     */
    public function iRunCommand($command, $arguments = '')
    {
        $arguments = strtr($arguments, array('\'' => '"'));

        $this->process->setWorkingDirectory($this->workingDir);
        $this->process->setCommandLine($command.' '.$arguments);
        $this->process->start();
        $this->process->wait();
    }
}

Add necessary member variables for iRunCommand


<!DOCTYPE html>

	<link rel="stylesheet" href="bootstrap.min.css" type="text/css" >
	<link rel="stylesheet" href="base.css" type="text/css" >
	<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
	<link href='dist/css/bootstrap-material-design.min.css' rel='stylesheet' type='text/css'>
	<link href='dist/css/ripples.min.css' rel='stylesheet' type='text/css'>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Coupley</title>

Change script order to load Jquery first


<?php namespace Orchestra\Avatar\Handlers;

use Illuminate\Support\Arr;
use Orchestra\Avatar\Handler;
use Orchestra\Avatar\HandlerInterface;

class Gravatar extends Handler implements HandlerInterface
{
    /**
     * Service URL.
     */
    const URL = 'http://www.gravatar.com/avatar';

    /**
     * {@inheritdoc}
     */
    protected $name = 'gravatar';

    /**
     * {@inheritdoc}
     */
    public function render()
    {
        $url = sprintf(
            '%s/%s?s=%d',
            static::URL,
            $this->getGravatarIdentifier(),
            $this->getGravatarSize()
        );

        if (! is_null($default = Arr::get($this->config, 'gravatar.default'))) {
            $url .= "&d=".urlencode($default);
        }

        return $url;
    }

    /**
     * Get Gravatar identifier.
     *
     * @return string
     */
    protected function getGravatarIdentifier()
    {
        return md5(strtolower(trim($this->getIdentifier())));
    }

    /**
     * Get Gravatar size.
     *
     * @return mixed
     */
    protected function getGravatarSize()
    {
        $size = $this->getSize();

        return Arr::get($this->config, "sizes.{$size}", 'small');
    }
}

<?php namespace Orchestra\Avatar\Handlers;

use Illuminate\Support\Arr;
use Orchestra\Avatar\Handler;
use Orchestra\Avatar\HandlerInterface;

class Gravatar extends Handler implements HandlerInterface
{
    /**
     * Service URL.
     */
    const URL = 'http://www.gravatar.com/avatar';

    /**
     * {@inheritdoc}
     */
    protected $name = 'gravatar';

    /**
     * {@inheritdoc}
     */
    public function render()
    {
        $url = sprintf(
            '%s/%s?s=%d',
            static::URL,
            $this->getGravatarIdentifier(),
            $this->getGravatarSize()
        );

        if (! is_null($default = Arr::get($this->config, 'gravatar.default'))) {
            $url .= "&d=".urlencode($default);
        }

        return $url;
    }

    /**
     * Get Gravatar identifier.
     *
     * @return string
     */
    protected function getGravatarIdentifier()
    {
        return md5(strtolower(trim($this->getIdentifier())));
    }

    /**
     * Get Gravatar size.
     *
     * @return mixed
     */
    protected function getGravatarSize()
    {
        $size = $this->getSize();

        return Arr::get($this->config, "sizes.{$size}", (is_int($size) ? $size : 'small'));
    }
}

Allow to manually set size.

Allow to manually set size.

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

namespace Ise\WebSecurityBundle\Controller;

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;

class ReportController extends AbstractController
{
    private $logger;
    private static $storageTest = [];

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
    /**
     * Report middleware for handling CSP requests.
     *
     * @param Request $req
     * @return void
     */
    public function report(Request $req)
    {
        $this->logger->info($req->getContent());
        array_push(ReportController::$storageTest, $req->getContent());
        $res = new JsonResponse($req->getContent());
        return $res;
    }
    public function index(Request $req)
    {
        return new JsonResponse(ReportController::$storageTest);
    }
}

<?php

namespace Ise\WebSecurityBundle\Controller;

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;

class ReportController extends AbstractController
{
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
    /**
     * Report middleware for handling CSP requests.
     *
     * @param Request $req
     * @return void
     */
    public function report(Request $req)
    {
        $this->logger->debug($req->getContent());
        $res = new JsonResponse($req->getContent());
        return $res;
    }
}

Cut back on unused code in Report Controller


<?php
namespace GraphiteAlert;
use Guzzle\Http\Client;

class GraphiteData
{
    protected $config;
    protected $client;

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

        $this->client = new Client($config['url']);
    }

    public function fetch($target, $lookback)
    {
        $args = [
            'target' => $target,
            'format' => 'json',
            'from' => "-{$lookback}min"
            ];

        $request = $this->client->get('/render?'.http_build_query($args))
            ->setAuth($this->config['user'], $this->config['pass'], 'Digest');

        $r = $request->send();
        $data = $r->json();

        return $this->reformat($data);
    }

    protected function reformat($data)
    {
        $out = array();

        if (!isset($data[0]['datapoints']))
        {
            var_dump($data);
            throw new \Exception("Bad data from graphite");
        }
        foreach($data[0]['datapoints'] as $point)
        {
            if (is_null($point[0]))
                continue;
            $out[$point[1]] = $point[0];
        }

        return $out;
    }
}

<?php
namespace GraphiteAlert;
use Guzzle\Http\Client;

class GraphiteData
{
    protected $config;
    protected $client;

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

        $this->client = new Client($config['url']);
    }

    public function fetch($target, $lookback)
    {
        $args = [
            'target' => $target,
            'format' => 'json',
            'from' => "-{$lookback}min"
            ];

        $request = $this->client->get('/render?'.http_build_query($args))
            ->setAuth($this->config['user'], $this->config['pass'], 'Digest');

        $r = $request->send();
        $data = $r->json();

        try {
            return $this->reformat($data);
        }
        catch(\Exception $e)
        {
            throw new \Exception("Unable to reformat $target", 0, $e);
        }
    }

    protected function reformat($data)
    {
        $out = array();

        if (!isset($data[0]['datapoints']))
        {
            var_dump($data);
            throw new \Exception("Bad data from graphite");
        }
        foreach($data[0]['datapoints'] as $point)
        {
            if (is_null($point[0]))
                continue;
            $out[$point[1]] = $point[0];
        }

        return $out;
    }
}

Throw better exceptions on invalid data

Throw better exceptions on invalid data


<?php

defined( 'NODEMON_RUNNING') || die( 'Access denied.' );

// See https://github.com/xblau/node-interface/wiki/Configuration
// for more info about these options.

$nodeconfig = array(
    'pagetitle' => 'Litecoin Node Interface',
    'pagedesc' => '',
    'autorefresh' => 30,
    'serverurl' => 'http://127.0.0.1:9332/',
    'username' => 'username',
    'password' => 'password',
    'broadcast' => false,
);

?>

<?php

defined( 'NODEMON_RUNNING') || die( 'Access denied.' );

// See https://github.com/xblau/node-interface/wiki/Configuration
// for more info about these options.

$nodeconfig = array(
    'pagetitle' => 'Litecoin Node Interface',
    'pagedesc' => '',
    'autorefresh' => 120,
    'serverurl' => 'http://127.0.0.1:9332/',
    'username' => 'username',
    'password' => 'password',
    'broadcast' => false,
);

?>

Set default autorefresh time to 120s (from 30)


<?php

$this->startSetup();

$this->run("
CREATE TABLE `{$this->getTable('magefm_cdn/cache')}` (
    id integer UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    store_id smallint UNSIGNED NOT NULL,
    path text NOT NULL,
    created_at timestamp NULL DEFAULT NULL
) ENGINE=InnoDB ;
");

$this->endSetup();

<?php

$this->startSetup();

$this->run("

CREATE TABLE `{$this->getTable('magefm_cdn/cache')}` (
    id integer UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    store_id smallint UNSIGNED NOT NULL,
    path text NOT NULL,
    created_at timestamp NULL DEFAULT NULL
) ENGINE=InnoDB ;

CREATE TABLE `magefm_cdn_cache_idx1`
    ON `{$this->getTable('magefm_cdn/cache')}` (store_id, path(512));

");

$this->endSetup();

Index on magefm_cdn_cache table (path limited to 512)


<?php
namespace phorkie;

class Forker
{
    public function forkLocal($repo)
    {
        $new = $this->fork($repo->gitDir);
        \copy($repo->gitDir . '/description', $new->gitDir . '/description');
        return $new;
    }

    public function forkRemote($cloneUrl, $originalUrl)
    {
        $new = $this->fork($cloneUrl);
        file_put_contents(
            $new->gitDir . '/description',
            'Fork of ' . $originalUrl
        );
        return $new;
    }

    protected function fork($pathOrUrl)
    {
        $rs = new Repositories();
        $new = $rs->createNew();
        $vc = $new->getVc();
        \rmdir($new->gitDir);//VersionControl_Git wants an existing dir, git clone not
        $vc->getCommand('clone')
            //this should be setOption, but it fails with a = between name and value
            ->addArgument('--separate-git-dir')
            ->addArgument($GLOBALS['phorkie']['cfg']['gitdir'] . '/' . $new->id . '.git')
            ->addArgument($pathOrUrl)
            ->addArgument($new->workDir)
            ->execute();
        foreach (\glob($new->gitDir . '/hooks/*') as $hookfile) {
            \unlink($hookfile);
        }

        $db = new Database();
        $db->getIndexer()->addRepo($new);

        return $new;
    }
}

?>

<?php
namespace phorkie;

class Forker
{
    public function forkLocal($repo)
    {
        $new = $this->fork($repo->gitDir);
        \copy($repo->gitDir . '/description', $new->gitDir . '/description');
        $this->index($new);
        return $new;
    }

    public function forkRemote($cloneUrl, $originalUrl)
    {
        $new = $this->fork($cloneUrl);
        file_put_contents(
            $new->gitDir . '/description',
            'Fork of ' . $originalUrl
        );
        $this->index($new);
        return $new;
    }

    protected function fork($pathOrUrl)
    {
        $rs = new Repositories();
        $new = $rs->createNew();
        $vc = $new->getVc();
        \rmdir($new->gitDir);//VersionControl_Git wants an existing dir, git clone not
        $vc->getCommand('clone')
            //this should be setOption, but it fails with a = between name and value
            ->addArgument('--separate-git-dir')
            ->addArgument($GLOBALS['phorkie']['cfg']['gitdir'] . '/' . $new->id . '.git')
            ->addArgument($pathOrUrl)
            ->addArgument($new->workDir)
            ->execute();
        foreach (\glob($new->gitDir . '/hooks/*') as $hookfile) {
            \unlink($hookfile);
        }

        return $new;
    }

    protected function index($repo)
    {
        $db = new Database();
        $db->getIndexer()->addRepo($repo);
    }
}

?>

Index forks only after their description has been set


<?php

require_once('tests/php/base.php');
require_once('framework/php/classes/plants/PeoplePlant.php');

class PeoplePlantTests extends UnitTestCase {
	function testPeoplePlant(){
		$r = array();
		$p = new PeoplePlant('people', $r);
		$this->assertIsa($p, 'PeoplePlant');

		$p->doListSync(1);
		$this->assertTrue(1, 'Called doListSync');
	}
}

?>

<?php
require_once('tests/php/base.php');
require_once('framework/php/classes/plants/PeoplePlant.php');

class PeoplePlantTests extends UnitTestCase {
	function testPeoplePlant(){
		$r = array();
		$p = new PeoplePlant('people', $r);
		$this->assertIsa($p, 'PeoplePlant');

		$p->doListSync(1);
		$this->assertTrue(1, 'Called doListSync');

		$api_key = getenv("MAILCHIMP_API_KEY");
		// an already-created list for testing
		$test_id = "b607c6d911";
		if($api_key) {
			// add syncing from a local list to $test_id mailchimp list
			// editList, then verify it worked
			// deleteList, then verify local list is removed and remote list is unchanged
		}
	}
}

?>

Add a stub for more mailchimp sync tests in PeoplePlant


<?php

namespace Websight\GcsProvider;

use ErrorException;
use Google_Auth_AssertionCredentials;
use Google_Client;
use Google_Service_Storage;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem;
use Storage;
use Superbalist\Flysystem\GoogleStorage\GoogleStorageAdapter;

/**
 * Class CloudStorageServiceProvider
 * Configures Google Cloud Storage Access for flysystem
 *
 * @package Websight\GcsProvider
 */
class CloudStorageServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        Storage::extend('gcs', function ($app, $config) {
            try {
                $credentials = new Google_Auth_AssertionCredentials(
                    $config['service_account'],
                    [
                        Google_Service_Storage::DEVSTORAGE_READ_WRITE
                    ],
                    file_get_contents($config['service_account_certificate']),
                    $config['service_account_certificate_password']
                );

                $client = new Google_Client();
                $client->setAssertionCredentials($credentials);

                $service = new Google_Service_Storage($client);
                $adapter = new GoogleStorageAdapter($service, $config['bucket']);

                return new Filesystem($adapter);
            } catch (ErrorException $e) {
                throw new ErrorException("GCS Flysystem adapter is not configured correctly.");
            }
        });
    }

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

<?php

namespace Websight\GcsProvider;

use ErrorException;
use Google_Auth_AssertionCredentials;
use Google_Client;
use Google_Service_Storage;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem;
use Storage;
use Superbalist\Flysystem\GoogleStorage\GoogleStorageAdapter;

/**
 * Class CloudStorageServiceProvider
 * Configures Google Cloud Storage Access for flysystem
 *
 * @package Websight\GcsProvider
 */
class CloudStorageServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        Storage::extend('gcs', function ($app, $config) {
            try {
                $credentials = new Google_Auth_AssertionCredentials(
                    $config['service_account'],
                    [
                        Google_Service_Storage::DEVSTORAGE_FULL_CONTROL
                    ],
                    file_get_contents($config['service_account_certificate']),
                    $config['service_account_certificate_password']
                );

                $client = new Google_Client();
                $client->setAssertionCredentials($credentials);

                $service = new Google_Service_Storage($client);
                $adapter = new GoogleStorageAdapter($service, $config['bucket']);

                return new Filesystem($adapter);
            } catch (ErrorException $e) {
                throw new ErrorException("GCS Flysystem adapter is not configured correctly.");
            }
        });
    }

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

Revert "CloudStorage Adapter only needs Read-Write access scopes"

This reverts commit ea0516b5415c0ea994e127f8da74efa97f7a0beb.


<?php

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

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Symfony\Component\HttpKernel\EventListener\DebugHandlersListener;

return static function (ContainerConfigurator $container) {
    $container->parameters()->set('debug.error_handler.throw_at', -1);

    $container->services()
        ->set('debug.debug_handlers_listener', DebugHandlersListener::class)
            ->args([
                null, // Exception handler
                service('monolog.logger.php')->nullOnInvalid(),
                null, // Log levels map for enabled error levels
                param('debug.error_handler.throw_at'),
                param('kernel.debug'),
                service('debug.file_link_formatter'),
                param('kernel.debug'),
                service('monolog.logger.deprecation')->nullOnInvalid(),
            ])
            ->tag('kernel.event_subscriber')
            ->tag('monolog.logger', ['channel' => 'php'])

        ->set('debug.file_link_formatter', FileLinkFormatter::class)
            ->args([param('debug.file_link_format')])

        ->alias(FileLinkFormatter::class, 'debug.file_link_formatter')
    ;
};

<?php

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

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Symfony\Component\HttpKernel\EventListener\DebugHandlersListener;

return static function (ContainerConfigurator $container) {
    $container->parameters()->set('debug.error_handler.throw_at', -1);

    $container->services()
        ->set('debug.debug_handlers_listener', DebugHandlersListener::class)
            ->args([
                null, // Exception handler
                service('monolog.logger.php')->nullOnInvalid(),
                null, // Log levels map for enabled error levels
                param('debug.error_handler.throw_at'),
                param('kernel.debug'),
                param('kernel.debug'),
                service('monolog.logger.deprecation')->nullOnInvalid(),
            ])
            ->tag('kernel.event_subscriber')
            ->tag('monolog.logger', ['channel' => 'php'])

        ->set('debug.file_link_formatter', FileLinkFormatter::class)
            ->args([param('debug.file_link_format')])

        ->alias(FileLinkFormatter::class, 'debug.file_link_formatter')
    ;
};

[FrameworkBundle][5.4] Remove fileLinkFormat property from DebugHandlersListener


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

namespace Darvin\Utils\HttpFoundation;

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * AJAX response
 */
class AjaxResponse extends JsonResponse
{
    /**
     * @param string $html       HTML
     * @param bool   $success    Is success
     * @param string $message    Message
     * @param array  $data       Additional data
     * @param bool   $reloadPage Whether to reload page
     * @param int    $status     Response status code
     * @param array  $headers    Response headers
     */
    public function __construct(
        $html = '',
        $success = true,
        $message = null,
        array $data = array(),
        $reloadPage = false,
        $status = 200,
        array $headers = array()
    ) {
        parent::__construct(array_merge($data, array(
            'html'       => $html,
            'message'    => $message,
            'reloadPage' => $reloadPage,
            'success'    => $success,
        )), $status, $headers);
    }
}

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

namespace Darvin\Utils\HttpFoundation;

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * AJAX response
 */
class AjaxResponse extends JsonResponse
{
    /**
     * @param string $html        HTML
     * @param bool   $success     Is success
     * @param string $message     Message
     * @param array  $data        Additional data
     * @param string $redirectUrl Redirect URL
     * @param int    $status      Response status code
     * @param array  $headers     Response headers
     */
    public function __construct(
        $html = '',
        $success = true,
        $message = null,
        array $data = array(),
        $redirectUrl = null,
        $status = 200,
        array $headers = array()
    ) {
        parent::__construct(array_merge($data, array(
            'html'        => $html,
            'message'     => $message,
            'redirectUrl' => $redirectUrl,
            'success'     => $success,
        )), $status, $headers);
    }
}

Replace "reloadPage" AJAX response class constructor argument with "redirectUrl".


<?php

namespace App\Transformers\Inbound\Web;

use App\Transformers\Datum;
use App\Transformers\Inbound\WebTransformer;

class Article extends WebTransformer
{
    use HasBlocks;

    protected function getExtraFields(Datum $datum)
    {
        return array_merge($this->getBlockFields($datum), [
            'date' => $datum->date('date'),
        ]);
    }
}

<?php

namespace App\Transformers\Inbound\Web;

use App\Transformers\Datum;
use App\Transformers\Inbound\WebTransformer;

class Article extends WebTransformer
{
    use HasBlocks {
        getExtraFields as getBlockFields;
    }

    protected function getExtraFields(Datum $datum)
    {
        return array_merge($this->getBlockFields($datum), [
            'date' => $datum->date('date'),
        ]);
    }
}

Fix `getBlockFields` in article inbound transformer [API-332]


<?php
declare(strict_types = 1);

namespace Pages\Components\Forms;

use Pages\IViewable;

final class IconButtonFormComponent implements IViewable{
  private string $url;
  private string $icon;
  private ?string $color = null;

  public function __construct(string $url, string $icon){
    $this->url = $url;
    $this->icon = $icon;
  }

  public function color(string $color): self{
    $this->color = $color;
    return $this;
  }

  public function echoBody(): void{
    $color_class = $this->color === null ? '' : ' icon-color-'.$this->color;

    echo <<<HTML
<form action="$this->url">
  <button type="submit" class="icon">
    icon$color_class">
  </button>
</form>
HTML;
  }
}

?>

<?php
declare(strict_types = 1);

namespace Pages\Components\Forms;

use Pages\IViewable;

final class IconButtonFormComponent implements IViewable{
  private string $url;
  private string $icon;
  private ?string $color = null;

  public function __construct(string $url, string $icon){
    $this->url = $url;
    $this->icon = $icon;
  }

  public function color(string $color): self{
    $this->color = $color;
    return $this;
  }

  /** @noinspection JSUnresolvedVariable */
  public function echoBody(): void{
    $color_class = $this->color === null ? '' : ' icon-color-'.$this->color;

    echo <<<HTML
<form action="$this->url" method="get" onsubmit="window.location=this.action;return false">
  <button type="submit" class="icon">
    icon$color_class">
  </button>
</form>
HTML;
  }
}

?>

Tweak icon button forms to avoid trailing question mark in URLs


<?php

namespace RadDB\Http\Requests;

use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(Request $request)
    {
        // Build the validation rules
        $rules = [
            'surveyId'       => 'required|exists:testdates,id|integer',
            'recommendation' => 'required|string|max:500',
            'resolved'       => 'integer',
            'WONum'          => 'string|nullable|max:20',
            'ServiceReport'  => 'file|mimes:pdf',
        ];

        // If 'resolved' was checked, then add validation rules for
        // 'RecResolveDate' and 'ResolvedBy'.
        if ($request->has('resolved')) {
            $rules['RecResolveDate'] = 'required|date_format:Y-m-d';
            $rules['ResolvedBy'] = 'required|string|max:10';
        }

        return $rules;
    }
}

<?php

namespace RadDB\Http\Requests;

use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(Request $request)
    {
        // Build the validation rules
        $rules = [
            'surveyId'       => 'required|exists:testdates,id|integer',
            'recommendation' => 'required|string|max:500',
            'resolved'       => 'integer',
            'WONum'          => 'string|nullable|max:20',
            'ServiceReport'  => 'file|mimes:pdf',
        ];

        // If 'resolved' was checked, then add validation rules for
        // 'RecResolveDate' and 'ResolvedBy'.
        if ($request->filled('resolved')) {
            $rules['RecResolveDate'] = 'required|date_format:Y-m-d';
            $rules['ResolvedBy'] = 'required|string|max:10';
        }

        return $rules;
    }
}

Switch to Request filled() method

Switch to Request filled() method

Behaviour of Request has() method changed in Laravel 5.5. filled() now
has the old behaviour.

https://laravel.com/docs/5.5/requests#retrieving-input


<?php
$ini = parse_ini_file("params.ini", true);
date_default_timezone_set($ini['common']['timezone']);
$date = date('Y-m-d H:i:s', time());
$connection = mysqli_connect($ini['mysql']['mysql_hostname'],$ini['mysql']['mysql_username'],$ini['mysql']['mysql_password'],$ini['mysql']['mysql_database'])
    or die("Connection Error " . mysqli_error($connection));

$sql = "SELECT SUM(nest_heat_state) AS IS_HEATING, SUM(if(auto_away = '1', 1, 0)) AS AT_HOME, SUM(if(auto_away = '0', 1, 0)) AS AUTO_AWAY,
        (SELECT COUNT(*) AS leaf FROM (SELECT leaf FROM status WHERE leaf = 1 AND (DATE(date) BETWEEN (date('".$_GET['start']."')) AND (date('".$_GET['end']."')))
        GROUP BY date(date) ORDER BY date ASC) status) AS LEAF FROM status WHERE (DATE(date) BETWEEN (date('".$_GET['start']."')) AND (date('".$_GET['end']."')));";

$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
}
mysqli_close($connection);
echo json_encode($rows);
?>

<?php
$ini = parse_ini_file("params.ini", true);
date_default_timezone_set($ini['common']['timezone']);
$date = date('Y-m-d H:i:s', time());
$connection = mysqli_connect($ini['mysql']['mysql_hostname'],$ini['mysql']['mysql_username'],$ini['mysql']['mysql_password'],$ini['mysql']['mysql_database'])
    or die("Connection Error " . mysqli_error($connection));

$sql = "SELECT SUM(nest_heat_state) AS IS_HEATING, SUM(if(auto_away = '1', 1, 0)) AS AT_HOME, SUM(if(auto_away = '0', 1, 0)) AS AUTO_AWAY,
        (SELECT COUNT(*) AS leaf FROM (SELECT leaf FROM status WHERE leaf = 1 AND (DATE(date) BETWEEN (date('".$_GET['start']."')) AND (date('".$_GET['end']."')))
        ) status) AS LEAF FROM status WHERE (DATE(date) BETWEEN (date('".$_GET['start']."')) AND (date('".$_GET['end']."')));";

$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
}
mysqli_close($connection);
echo json_encode($rows);
?>

Fix Nest Leafs on Energy page

Fix Nest Leafs on Energy page

Remove GROUP BY date(date) ORDER BY date ASC
Old sql included a group by date that resulted in there always being one leaf per day (if any)


<?php
declare(strict_types = 1);

namespace Vinnia\Util\Tests;

use PHPUnit\Framework\TestCase;
use Vinnia\Util\Set;

class SetTest extends TestCase
{
    public function testHashesObjects()
    {
        $set = new Set();
        $a = [1];
        $b = [1];

        $set->add($a);

        $this->assertEquals(true, $set->contains($b));
    }

    public function testAddingTheSameValueTwiceDoesNotIncreaseCount()
    {
        $set = new Set(1);

        $this->assertCount(1, $set);

        $set->add(1);

        $this->assertCount(1, $set);
    }

    public function testNullIsUnique()
    {
        $set = new Set(null);

        $this->assertCount(1, $set);
        $set->add(null);

        $this->assertCount(1, $set);
    }
}

<?php
declare(strict_types = 1);

namespace Vinnia\Util\Tests;

use PHPUnit\Framework\TestCase;
use Vinnia\Util\Set;

class SetTest extends TestCase
{
    public function testHashesObjects()
    {
        $set = new Set();
        $a = [1];
        $b = [1];

        $set->add($a);

        $this->assertEquals(true, $set->contains($b));
    }

    public function testAddingTheSameValueTwiceDoesNotIncreaseCount()
    {
        $set = new Set(1);

        $this->assertCount(1, $set);

        $set->add(1);

        $this->assertCount(1, $set);
    }

    public function testNullIsUnique()
    {
        $set = new Set(null);

        $this->assertCount(1, $set);
        $set->add(null);

        $this->assertCount(1, $set);
    }

    public function testConstructorUsesHashFunction()
    {
        $set = new Set(1, 2, 3);
        $set->add(1);

        $this->assertCount(3, $set);
    }
}

Add test for Set constructor

Add test for Set constructor


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

//Database settings
$config['db_type'] = "mysql";
$config['db_host'] = "localhost";
$config['db_user'] = "root";
$config['db_password'] = "";
$config['db_port'] = 3306;
$config['db_name'] = "pdnsmanager";

// Authentication source
$config['auth_type'] = 'db';

//Remote update
$config['nonce_lifetime'] = 15;

//Number of rows in domain overview
$config['domain_rows'] = 15;

// If config-user.php does not exist, redirect to the setup page
if(!(include 'config-user.php')) {
  Header("Location: install.php");
}

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

//Database settings
$config['db_type'] = "mysql";
$config['db_host'] = "localhost";
$config['db_user'] = "root";
$config['db_password'] = "";
$config['db_port'] = 3306;
$config['db_name'] = "pdnsmanager";

// Authentication source
$config['auth_type'] = 'db';

// LDAP settings
$config['ldap_uri'] = 'ldapi:///';
$config['ldap_bind_dn'] = '';
$config['ldap_bind_pw'] = '';
$config['ldap_base_dn'] = '';
$config['ldap_search'] = 'uid=%user%';

//Remote update
$config['nonce_lifetime'] = 15;

//Number of rows in domain overview
$config['domain_rows'] = 15;

// If config-user.php does not exist, redirect to the setup page
if(!(include 'config-user.php')) {
  Header("Location: install.php");
}

Add LDAP settings to default config.

Add LDAP settings to default config.


<?php

namespace AppBundle\Controller;

use AppBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use AppBundle\Form\Type\RegisterType;

class RegistrationController extends Controller
{
    /**
     * @Route("/inscription", name="registration")
     * @Method({"GET","POST"})
     */
    public function registrationAction(Request $request)
    {
        // Only for user not logged
        if($this->getUser()){
            return $this->redirectToRoute('homepage');
        }

        $user = new User();
        $form = $this->createForm(RegisterType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()){
            $wantNewsletter =  isset($request->get('register')['newsletter']) ? true : false;
            $this->container->get('app.user')->create($user, $wantNewsletter);
            //return $this->redirectToRoute('registration');
        }

        return $this->render('registration.html.twig', array(
            'form'      => $form->createView()
        ));
    }

    /**
     * @Route("/inscription/activation/{code}", name="registration.activation", requirements={"code": "[a-z0-9]+"})
     * @Method({"GET","POST"})
     */
    public function AccountActivationAction(Request $request)
    {

    }
}

<?php

namespace AppBundle\Controller;

use AppBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use AppBundle\Form\Type\RegisterType;

class RegistrationController extends Controller
{
    /**
     * @Route("/inscription", name="registration")
     * @Method({"GET","POST"})
     */
    public function registrationAction(Request $request)
    {
        // Only for user not logged
        if($this->getUser()){
            return $this->redirectToRoute('homepage');
        }

        $user = new User();
        $form = $this->createForm(RegisterType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()){
            $wantNewsletter =  isset($request->get('register')['newsletter']) ? true : false;
            $this->container->get('app.user')->create($user, $wantNewsletter);
            return $this->redirectToRoute('registration');
        }

        return $this->render('registration.html.twig', array(
            'form'      => $form->createView()
        ));
    }

    /**
     * @Route("/inscription/activation/{code}", name="registration.activation", requirements={"code": "[a-z0-9]+"})
     * @Method({"GET")
     */
    public function accountActivationAction(Request $request)
    {

    }
}

Fix (Register controller): PHP code should follow PSR-1 basic coding standard


<?php

namespace MethodPhpDocsNamespace;

use SomeNamespace\Amet as Dolor;

interface FooInterface
{

	/**
	 * @return void
	 */
	public function phpDocVoidMethodFromInterface();

}

class FooParentParent
{

	/**
	 * @return void
	 */
	public function phpDocVoidParentMethod()
	{

	}

}

abstract class FooParent extends FooParentParent implements FooInterface
{

	/**
	 * @return Static
	 */
	public function doLorem()
	{

	}

	/**
	 * @return static
	 */
	public function doIpsum(): self
	{

	}

	/**
	 * @return $this
	 */
	public function doThis()
	{
		return $this;
	}

	/**
	 * @return $this|null
	 */
	public function doThisNullable()
	{
		return $this;
	}

	/**
	 * @return $this|Bar|null
	 */
	public function doThisUnion()
	{

	}

	/**
	 * @return void
	 */
	public function phpDocVoidMethod()
	{

	}

}

<?php

namespace MethodPhpDocsNamespace;

use SomeNamespace\Amet as Dolor;

interface FooInterface
{

	/**
	 * @return void
	 */
	public function phpDocVoidMethodFromInterface();

}

class FooParentParent
{

	/**
	 * @return void
	 */
	public function phpDocVoidParentMethod()
	{

	}

}

abstract class FooParent extends FooParentParent implements FooInterface
{

	/**
	 * @return Static
	 */
	public function doLorem()
	{

	}

	/**
	 * @return static
	 */
	public function doIpsum(): self
	{

	}

	/**
	 * @return $this
	 */
	public function doThis()
	{
		return $this;
	}

	/**
	 * @return $this|null
	 */
	public function doThisNullable()
	{
		return $this;
	}

	/**
	 * @return $this|Bar|null
	 */
	public function doThisUnion()
	{

	}

	/**
	 * @return void
	 */
	public function phpDocVoidMethod()
	{

	}

	/**
	 * {@inheritDoc}
	 */
	public function phpDocVoidParentMethod()
	{

	}

}

Test - one more reproduction for implicit phpDoc issues


<?php
/**
 * Creates an editable field that displays members in a given group
 *
 * @package userforms
 */

class EditableMemberListField extends EditableFormField
{

    private static $singular_name = 'Member List Field';

    private static $plural_name = 'Member List Fields';

    private static $has_one = array(
        'Group' => 'Group'
    );

    /**
     * @return FieldList
     */
    public function getCMSFields()
    {
        $fields = parent::getCMSFields();

        $fields->removeByName('Default');
        $fields->removeByName('Validation');

        $fields->addFieldToTab(
            'Root.Main',
            DropdownField::create(
                "GroupID",
                _t('EditableFormField.GROUP', 'Group'),
                Group::get()->map()
            )->setEmptyString(' ')
        );

        return $fields;
    }

    public function getFormField()
    {
        if (empty($this->GroupID)) {
            return false;
        }

        $members = Member::map_in_groups($this->GroupID);
        $field = new DropdownField($this->Name, $this->EscapedTitle, $members);
        $this->doUpdateFormField($field);
        return $field;
    }

    public function getValueFromData($data)
    {
        if (isset($data[$this->Name])) {
            $memberID = $data[$this->Name];
            $member = Member::get()->byID($memberID);
            return $member ? $member->getName() : "";
        }

        return false;
    }
}

<?php
/**
 * Creates an editable field that displays members in a given group
 *
 * @package userforms
 */

class EditableMemberListField extends EditableFormField
{

    private static $singular_name = 'Member List Field';

    private static $plural_name = 'Member List Fields';

    private static $has_one = array(
        'Group' => 'Group'
    );

    /**
     * @return FieldList
     */
    public function getCMSFields()
    {
        $fields = parent::getCMSFields();

        $fields->removeByName('Default');
        $fields->removeByName('Validation');

        $fields->addFieldToTab(
            'Root.Main',
            DropdownField::create(
                "GroupID",
                _t('EditableFormField.GROUP', 'Group'),
                Group::get()->map()
            )->setEmptyString(' ')
        );

        return $fields;
    }

    public function getFormField()
    {
        if (empty($this->GroupID)) {
            return false;
        }

        $members = Member::map_in_groups($this->GroupID);

        $field = DropdownField::create($this->Name, $this->EscapedTitle, $members)
            ->setTemplate('UserFormsDropdownField')
            ->setFieldHolderTemplate('UserFormsField_holder');

        $this->doUpdateFormField($field);

        return $field;
    }

    public function getValueFromData($data)
    {
        if (isset($data[$this->Name])) {
            $memberID = $data[$this->Name];
            $member = Member::get()->byID($memberID);
            return $member ? $member->getName() : "";
        }

        return false;
    }
}

FIX Use userforms template for member list field, fixes display rule issue


<?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\BlogBundle\Entity\Manager;

use ASF\CoreBundle\Entity\Manager\ASFEntityManager;

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

<?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\BlogBundle\Entity\Manager;

use ASF\CoreBundle\Entity\Manager\ASFEntityManager;

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

Fix typo in interface name

Fix typo in interface name


<?php
/**
 * Template file for notifications
 *
 * @package Dragooon:WeNotif
 * @author Shitiz "Dragooon" Garg <Email mail@dragooon.net> <Url http://smf-media.com>
 * @copyright 2012, Shitiz "Dragooon" Garg <mail@dragooon.net>
 * @license
 *		Licensed under "New BSD License (3-clause version)"
 *		http://www.opensource.org/licenses/BSD-3-Clause
 * @version 1.0
 */

function template_notifications_block()
{
	global $txt, $context, $settings, $scripturl;

	echo '

		', $context['unread_notifications'], '
		', $txt['notification_unread_title'], '';
	foreach ($context['quick_notifications'] as $notification)
	{
		echo '

getID(), '\'">
				', $notification->getText(), '

				', timeformat($notification->getTime()), '

';
	}
	echo '

';
}
?>

Make the cursor as pointer for quick notifications


<?php

final class PhabricatorHarbormasterConfigOptions
  extends PhabricatorApplicationConfigOptions {

  public function getName() {
    return pht('Harbormaster');
  }

  public function getDescription() {
    return pht('Configure Harbormaster build engine.');
  }

  public function getFontIcon() {
    return 'fa-ship';
  }

  public function getGroup() {
    return 'apps';
  }

  public function getOptions() {
    return array(
      $this->newOption('jenkins.host', 'string', null)
        ->setDescription(pht('Jenkins installation hostname.')),
      $this->newOption('jenkins.user-id', 'string', null)
        ->setDescription(pht('Username for accessing Jenkins.')),
      $this->newOption('jenkins.api-token', 'string', null)
        ->setMasked(true)
        ->setDescription(pht('API token for accessing Jenkins.')),
    );
  }

}

<?php

final class PhabricatorHarbormasterConfigOptions
  extends PhabricatorApplicationConfigOptions {

  public function getName() {
    return pht('Harbormaster');
  }

  public function getDescription() {
    return pht('Configure Harbormaster build engine.');
  }

  public function getFontIcon() {
    return 'fa-ship';
  }

  public function getGroup() {
    return 'apps';
  }

  public function getOptions() {
    return array(
      $this->newOption('jenkins.host', 'string', null)
        ->setDescription(pht('Jenkins installation hostname.')),
      $this->newOption('jenkins.user-id', 'string', null)
        ->setDescription(pht('Username for accessing Jenkins.')),
      $this->newOption('jenkins.api-token', 'string', null)
        ->setHidden(true)
        ->setDescription(pht('API token for accessing Jenkins.')),
    );
  }

}

Migrate "Jenkins API Token" config setting from masked to hidden

Related to "T6518-harbormaster-notify-jenkins-step" branch, but can't put it in there because "setHidden" method was added only to master recently (see ebebeb8f7cb7f1691fd65d3a5579efd26376afe4).


<?php

/**
 * Dump the passed variable(s) and end the script.
 *
 * @param  dynamic  mixed
 * @return void
 */
if (! function_exists('dd')) {
    function dd()
    {
        echo '<pre>'."\n";
        array_map(function($x) { print_r($x); }, func_get_args());
        echo '</pre>';
        die;
    }
}

<?php

/**
 * Dump the passed variable(s) and end the script.
 *
 * @param  dynamic  mixed
 * @return void
 */
if (! function_exists('dd')) {
    function dd()
    {
        array_map(function($x) { print_r($x); echo"\n"; }, func_get_args());
        die;
    }
}

Clean up dd() helper method

Clean up dd() helper method


<?php

if (!function_exists('set_message')) {
    function set_message($text, $type = 'success') {
        $CI =& get_instance();
        $CI->messages->add($text, $type);
    }
}

if (!function_exists('set_message_error')) {
    function set_message_error($text) {
        set_message($text, 'error');
    }
}

if (!function_exists('set_message_success')) {
    function set_message_success($text) {
        set_message($text, 'success');
    }
}

if (!function_exists('set_message_warning')) {
    function set_message_warning($text) {
        set_message($text, 'warning');
    }
}

if (!function_exists('keepValidationErrors')) {
    function keepValidationErrors() {
        $CI =& get_instance();

        $CI->messages->keepValidationErrors();
    }
}

if (!function_exists('show_message')) {
    function show_message($type = null) {
        $CI =& get_instance();

        return $CI->messages->show($type);
    }
}

<?php

if (!function_exists('flash_messages')) {
    function flash_messages() {
        return new \Plasticbrain\FlashMessages\FlashMessages;
    }
}

if (!function_exists('set_message')) {
    function set_message($text, $type = 'success') {
        flash_messages()->add($text, $type);
    }
}

if (!function_exists('set_message_error')) {
    function set_message_error($text) {
        set_message($text, 'error');
    }
}

if (!function_exists('set_message_success')) {
    function set_message_success($text) {
        set_message($text, 'success');
    }
}

if (!function_exists('set_message_warning')) {
    function set_message_warning($text) {
        set_message($text, 'warning');
    }
}

if (!function_exists('keepValidationErrors')) {
    function keepValidationErrors() {
        if (FALSE === ($OBJ =& _get_validation_object())) {
            // No action
        } else {
            $errors = $OBJ->error_array();

            foreach ($errors as $error) {
                set_message_error($error);
            }
        }
    }
}

if (!function_exists('show_message')) {
    function show_message($type = null) {
        return flash_messages()->display($type);
    }
}

Modify helper message with Plasticbrain\FlashMessages


<?php

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

namespace Surfnet\StepupMiddleware\CommandHandlingBundle\Command;

use Symfony\Component\Validator\Constraints as Assert;

abstract class AbstractCommand implements Command
{
    /**
     * @Assert\NotBlank()
     * @Assert\Type(type="string")
     *
     * @var string
     */
    public $UUID;

    public function __toString()
    {
        return get_class($this) . '[' . $this->UUID . ']';
    }
}

<?php

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

namespace Surfnet\StepupMiddleware\CommandHandlingBundle\Command;

use Symfony\Component\Validator\Constraints as Assert;

abstract class AbstractCommand implements Command
{
    /**
     * @Assert\NotBlank()
     * @Assert\Type(type="string")
     * @Assert\Regex(pattern="~^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$~")
     *
     * @var string
     */
    public $UUID;

    public function __toString()
    {
        return get_class($this) . '[' . $this->UUID . ']';
    }
}

Validate the Command UUID to be UUIDv4

Validate the Command UUID to be UUIDv4


<?php

require_once 'DemoPage.php';

/**
 * The front page of the demo application
 *
 * This page displays a quick introduction to the Swat Demo Application
 *
 * @package   SwatDemo
 * @copyright 2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class FrontPage extends DemoPage
{
	public function init()
	{
		$this->start_time = microtime(true);

		$this->demo = 'FrontPage';

		$this->ui = new SwatUI();
		$this->ui->loadFromXML('../include/pages/'.strtolower($this->demo).'.xml');

		$this->initUI();

		$this->ui->init();

		$this->navbar->createEntry($this->app->title);
	}

	public function initUI()
	{
		$content = $this->ui->getWidget('content');
		$content->content = "Welcome to the Swat Widget Gallery. ".
			"Here you will find a number of examples of the different widgets ".
			"Swat provides.";
	}

	public function process()
	{
	}

	public function build()
	{
		parent::build();

		$this->layout->title = $this->app->title;
	}

	protected function createLayout()
	{
		return new SwatLayout('../layouts/no_source.php');
	}
}

?>

<?php

require_once 'DemoPage.php';

/**
 * The front page of the demo application
 *
 * This page displays a quick introduction to the Swat Demo Application
 *
 * @package   SwatDemo
 * @copyright 2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class FrontPage extends DemoPage
{
	public function init()
	{
		$this->start_time = microtime(true);

		$this->demo = 'FrontPage';

		$this->ui = new SwatUI();
		$this->ui->loadFromXML('../include/pages/'.strtolower($this->demo).'.xml');

		$this->initUI();

		$this->ui->init();

		$this->navbar->createEntry($this->app->title);

		$this->documentation_menu = $this->getDocumentationMenu();
	}

	public function initUI()
	{
		$content = $this->ui->getWidget('content');
		$content->content = "Welcome to the Swat Widget Gallery. ".
			"Here you will find a number of examples of the different widgets ".
			"Swat provides.";
	}

	public function process()
	{
	}

	public function build()
	{
		parent::build();

		$this->layout->title = $this->app->title;
	}

	protected function createLayout()
	{
		return new SwatLayout('../layouts/no_source.php');
	}
}

?>

Add documentation menu to the front page.

svn commit r1956


@section('content')
	<iframe src="https://kiwiirc.com/client/irc.rizon.net/#r/a/dio"
		style="border:0; width:100%; height:700px; margin: 60px 5px 0 5px;"
	></iframe>
@stop

Add further style changes to the IRC display


<?php
namespace HtSettingsModulerTest\Service;

use HtSettingsModule\Service\SettingsService;
use HtSettingsModule\Options\ModuleOptions;

class SettingsServiceTest extends \PHPUnit_Framework_TestCase
{
    public function testSave()
    {
        $settingsService= new SettingsService(
            new ModuleOptions,
            $this->getMock('HtSettingsModule\Mapper\SettingsMapperInterface')
        );
    }
}

<?php
namespace HtSettingsModulerTest\Service;

use HtSettingsModule\Service\SettingsService;
use HtSettingsModule\Options\ModuleOptions;
use HtSettingsModule\Entity\Parameter;

class SettingsServiceTest extends \PHPUnit_Framework_TestCase
{
    public function testInsertParameter()
    {
        $options = new ModuleOptions;
        $settingsMapper = $this->getMock('HtSettingsModule\Mapper\SettingsMapperInterface');
        $settingsService= new SettingsService(
            $options,
            $settingsMapper
        );

        $namespace  = 'network_settings';
        $name       = 'ip_address';
        $value      = '192.168.1.1';

        $parameter = new Parameter;
        $parameter->setNamespace($namespace);
        $parameter->setName($name);
        $parameter->setValue($value);

        $options->getCacheOptions()->setEnabled(true);
        $cacheManager = $this->getMock('HtSettingsModule\Service\CacheManagerInterface');
        $cacheManager->expects($this->once())
            ->method('delete')
            ->with($namespace);
        $settingsService->setCacheManager($cacheManager);

        $settingsMapper->expects($this->once())
            ->method('insertParameter')
            ->with($parameter);

        $settingsService->saveParameter($namespace, $name, $value);
    }

    public function testUpdateParameter()
    {
        $options = new ModuleOptions;
        $settingsMapper = $this->getMock('HtSettingsModule\Mapper\SettingsMapperInterface');
        $settingsService= new SettingsService(
            $options,
            $settingsMapper
        );

        $namespace  = 'network_settings';
        $name       = 'ip_address';
        $value      = '192.168.1.1';
        $newValue   = '192.168.10.1';

        $orginalParameter = new Parameter;
        $orginalParameter->setNamespace($namespace);
        $orginalParameter->setName($name);
        $orginalParameter->setValue($value);

        $newParameter = clone $orginalParameter;
        $newParameter->setValue($newValue);

        $options->getCacheOptions()->setEnabled(false);

        $settingsMapper->expects($this->once())
            ->method('findParameter')
            ->with($namespace, $name)
            ->will($this->returnValue($orginalParameter));

        $settingsMapper->expects($this->once())
            ->method('updateParameter')
            ->with($newParameter);

        $settingsService->saveParameter($namespace, $name, $newValue);
    }
}

Update tests for settigs service

Update tests for settigs service


<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Http\Controllers;

use App\Models\Chat\Channel;
use App\Models\Chat\UserChannel;
use App\Models\User;
use Auth;
use Request;

class ChatController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');

        return parent::__construct();
    }

    public function index()
    {
        $json = [];

        $targetUser = User::lookup(Request::input('sendto'), 'id');
        if ($targetUser) {
            $json['target'] = json_item($targetUser, 'UserCompact');
            $json['can_message'] = priv_check('ChatStart', $targetUser)->can();

            $channel = Channel::where('name', Channel::getPMChannelName($targetUser, Auth::user()))->first();

            if ($channel !== null && !$channel->hasUser(Auth::user())) {
                $channel->addUser(Auth::user());
            }
        }

        $presence = UserChannel::presenceForUser(Auth::user());

        return ext_view('chat.index', compact('presence', 'messages', 'json'));
    }
}

<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Http\Controllers;

use App\Models\Chat\Channel;
use App\Models\Chat\UserChannel;
use App\Models\User;
use Auth;
use Request;

class ChatController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');

        return parent::__construct();
    }

    public function index()
    {
        $json = [];

        $targetUser = User::lookup(Request::input('sendto'), 'id');
        if ($targetUser) {
            $json['target'] = json_item($targetUser, 'UserCompact');
            $json['can_message'] = priv_check('ChatStart', $targetUser)->can();

            $channel = Channel::where('name', Channel::getPMChannelName($targetUser, Auth::user()))->first();

            if ($channel !== null && !$channel->hasUser(Auth::user())) {
                $channel->addUser(Auth::user());
            }
        }

        $presence = UserChannel::presenceForUser(Auth::user());

        return ext_view('chat.index', compact('presence', 'json'));
    }
}

Remove nonexistent and unused variable

Remove nonexistent and unused variable


<?php

class UsersTableSeeder extends Seeder {

    public function run()
    {
        DB::table('users')->delete();

        $users = array(
            array(
                'username'      => 'admin',
                'email'      => 'admin@test.com',
                'password'   => Hash::make('admin'),
                'confirmed'   => 0,
                'confirmation_code' => md5(microtime().Config::get('app.key')),
                'created_at' => new DateTime,
                'updated_at' => new DateTime,
            ),
            array(
                'username'      => 'user',
                'email'      => 'user@test.com',
                'password'   => Hash::make('user'),
                'confirmed'   => 0,
                'confirmation_code' => md5(microtime().Config::get('app.key')),
                'created_at' => new DateTime,
                'updated_at' => new DateTime,
            )
        );

        DB::table('users')->insert( $users );
    }

}

<?php

class UsersTableSeeder extends Seeder {

    public function run()
    {
        DB::table('users')->delete();

        $users = array(
            array(
                'username'      => 'admin',
                'email'      => 'admin@test.com',
                'password'   => Hash::make('admin'),
                'confirmed'   => 0,
                'created_at' => new DateTime,
                'updated_at' => new DateTime,
            ),
            array(
                'username'      => 'user',
                'email'      => 'user@test.com',
                'password'   => Hash::make('user'),
                'confirmed'   => 0,
                'created_at' => new DateTime,
                'updated_at' => new DateTime,
            )
        );

        DB::table('users')->insert( $users );
    }

}

Update default value of confirmation code


<?php
namespace phpSmug;

use phpSmug\Api\ApiInterface;
use phpSmug\Exception\InvalidArgumentException;
use phpSmug\Exception\BadMethodCallException;
use phpSmug\HttpClient\HttpClient;
use phpSmug\HttpClient\HttpClientInterface;

/**
 * Simple yet very cool PHP SmugMug client
 *
 * @method Api\User user()
 *
 */

class Client
{
    /**
     * @var array
     */
    private $options = array(
        'endpoint_url'  => 'https://api.smugmug.com/api/v2/',
        'user_agent'    => 'phpSmug (http://phpsmug.com)',
        'timeout'       => 10,
        'cache_dir'     => null,
        'api_key'       => null,
    );

    /**
     * The instance used to communicate with SmugMug
     *
     * @var HttpClient
     */
    private $httpClient;

    /**
     * Instantiate a new SmugMug client
     *
     * @param null|HttpClientInterface $httpClient SmugMug http client
     */
    public function __construct(HttpClientInterface $httpClient = null)
    {
        $this->httpClient = $httpClient;
    }

    /**
     * @param string $name
     *
     * @return ApiInterface
     *
     * @throws InvalidArgumentException
     */
    public function api($name)
    {
        switch ($name) {
            case 'user':
                $api = new Api\User($this);
                break;

            default:
                throw new InvalidArgumentException(sprintf('Undefined api instance called: "%s"', $name));
        }

        return $api;
    }
}

?>

<?php
namespace phpSmug;

//use phpSmug\Api\ApiInterface;
use phpSmug\Exception\InvalidArgumentException;
use phpSmug\Exception\BadMethodCallException;
use phpSmug\HttpClient\HttpClient;
use phpSmug\HttpClient\HttpClientInterface;

/**
 * Simple yet very cool PHP SmugMug client
 *
 * @method Api\User user()
 *
 */

class Client
{
    /**
     * @var array
     */
    private $options = array(
        'endpoint_url'  => 'https://api.smugmug.com/api/v2/',
        'user_agent'    => 'phpSmug (http://phpsmug.com)',
        'timeout'       => 10,
        'cache_dir'     => null,
        'api_key'       => null,
    );

    /**
     * The instance used to communicate with SmugMug
     *
     * @var HttpClient
     */
    private $httpClient;

    /**
     * Instantiate a new SmugMug client
     *
     * @param null|HttpClientInterface $httpClient SmugMug http client
     */
    public function __construct(HttpClientInterface $httpClient = null)
    {
        $this->httpClient = $httpClient;
    }

    /**
     * @param string $name
     *
     * @return ApiInterface
     *
     * @throws InvalidArgumentException
     */
    public function api($name)
    {
        switch ($name) {
            case 'user':
                $api = new Api\User($this);
                break;

            default:
                throw new InvalidArgumentException(sprintf('Undefined api instance called: "%s"', $name));
        }

        return $api;
    }
}

?>

Comment out file we dont need

Comment out file we dont need


<?php

class Sign2pay_Payment_Block_Info_Sign2pay extends Mage_Payment_Block_Info
{
    protected function _prepareSpecificInformation($transport = null)
    {
        if (null !== $this->_paymentSpecificInformation) {
            return $this->_paymentSpecificInformation;
        }
        $info = $this->getInfo();
        $transport = new Varien_Object();
        if (!empty($info['last_trans_id'])) {
            $transport->setData('Transaction URL', 'https://merchant.sign2pay.com/en/purchases/'.$info['last_trans_id']);
        }
        $transport = parent::_prepareSpecificInformation($transport);
        return $transport;
    }
}

<?php

class Sign2pay_Payment_Block_Info_Sign2pay extends Mage_Payment_Block_Info
{
    protected function _prepareSpecificInformation($transport = null)
    {
        if (null !== $this->_paymentSpecificInformation) {
            return $this->_paymentSpecificInformation;
        }
        $info = $this->getInfo();
        $transport = new Varien_Object();
        if (!empty($info['last_trans_id']) && Mage::app()->getStore()->isAdmin()) {
            $transport->setData('Transaction URL', 'https://merchant.sign2pay.com/en/purchases/'.$info['last_trans_id']);
        }
        $transport = parent::_prepareSpecificInformation($transport);
        return $transport;
    }
}

Fix transaction url showing in customer order view


<?php

if ( ! function_exists('cache') )
{
    function cache($key, Closure $closure)
    {
        $content = Cache::get($key);
        if ( ! $content ) {
            ob_start();

            $closure();
            $content = ob_get_contents();
            ob_end_clean();
            Cache::forever($key, $content);
            Log::debug('writing cache', [$key]);
        } else {
            Log::debug('reading cache', [$key]);
        }

        return $content;
    }
}

<?php

if ( ! function_exists('cache') )
{
    function cache($key, $condition = true, Closure $closure)
    {
        $content = $condition ? Cache::get($key) : false;
        if ( ! $content ) {
            ob_start();

            $closure();
            $content = ob_get_contents();
            ob_end_clean();
	    if ($condition) {
		    Cache::forever($key, $content);
		    Log::debug('writing cache', [$key]);
	    }
        } else {
            Log::debug('reading cache', [$key]);
        }

        return $content;
    }
}

Add an optional second parameter to cache, used to conditionaly enable/disable caching


<?php

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

namespace Blackfire\Player\Tests\ExpressionLanguage;

use Faker\Provider\Image;

/**
 * Workaround for http://lorempixel.com/ unavailability.
 * This is the service used by the native Image Provider.
 */
class SafeFakerImageProvider extends Image
{
    public static function imageUrl($width = 640, $height = 480, $category = null, $randomize = true, $word = null, $gray = false)
    {
        // Should be an image, but whatever...
        return 'https://blackfire.io/api/v1/';
    }
}

<?php

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

namespace Blackfire\Player\Tests\ExpressionLanguage;

use Faker\Provider\Image;

/**
 * Workaround for http://lorempixel.com/ unavailability.
 * This is the service used by the native Image Provider.
 */
class SafeFakerImageProvider extends Image
{
    public static function imageUrl($width = 640, $height = 480, $category = null, $randomize = true, $word = null, $gray = false, $format = 'png')
    {
        // Should be an image, but whatever...
        return 'https://blackfire.io/api/v1/';
    }
}

Fix BC break in Faker

Fix BC break in Faker


<?php
    include_once 'models/dependencies.php';
    include_once 'header.php';

    if ( isset( $_GET[ 'resource' ] ) ) {
        $resource = $_GET[ 'resource' ];
    }
    else {
        $resource = '';
    }
    $resource = basename( $resource );
    $filename = 'controllers/' . $resource . '.php';
    if ( !file_exists( $filename ) ) {
        $resource = 'dashboard';
        $filename = 'controllers/' . $resource . '.php';
    }
    include_once $filename;
    $controllername = ucfirst( $resource ) . 'Controller';
    $controller = new $controllername();
    try {
        $controller->dispatch( $_GET, $_POST, $_FILES, $_SERVER[ 'REQUEST_METHOD' ] );
    }
    catch ( NotImplemented $e ) {
        die( 'An attempt was made to call a not implemented function: ' . $e->getFunctionName() );
    }
    catch ( RedirectException $e ) {
        $url = $e->getURL();
        header( 'Location: ' . $url );
    }
    catch ( HTTPErrorException $e ) {
        header( $e->header );
    }
?>

<?php
    include_once 'models/dependencies.php';
    include_once 'header.php';

    if ( isset( $_GET[ 'resource' ] ) ) {
        $resource = $_GET[ 'resource' ];
    }
    else {
        $resource = '';
    }
    $resource = basename( $resource );
    $filename = 'controllers/' . $resource . '.php';
    if ( !file_exists( $filename ) ) {
        $resource = 'dashboard';
        $filename = 'controllers/' . $resource . '.php';
    }
    include_once $filename;
    $controllername = ucfirst( $resource ) . 'Controller';
    $controller = new $controllername();
    try {
        $controller->dispatch( $_GET, $_POST, $_FILES, $_SERVER[ 'REQUEST_METHOD' ] );
    }
    catch ( NotImplemented $e ) {
        die( 'An attempt was made to call a not implemented function: ' . $e->getFunctionName() );
    }
    catch ( RedirectException $e ) {
        global $config;

        $url = $e->getURL();

        header( 'Location: ' . $config[ 'base' ] . $url );
    }
    catch ( HTTPErrorException $e ) {
        header( $e->header );
    }
?>

Fix HTTP redirects to be absolute

Fix HTTP redirects to be absolute


<?php
require 'vendor/autoload.php';
require 'lib/readConfig.php';

// Read config file
$config = readConfig('config');

if ($config === FALSE) {
    die('Config file not found');
}

// Start Slim
$app = new \Slim\Slim();

$app->post('/comments', function () use ($app) {
    $data = $app->request()->post();

    // We're looking for the honey pot field and testing mandatory fields
    if ((isset($data['company'])) ||
        (!isset($data['name'])) ||
        (!isset($data['email'])) ||
        (!isset($data['message'])) ||
        (!isset($data['post'])))
    {
        echo('Aborting...');
        return;
    }

    $emailHash = md5(trim(strtolower($data['email'])));

    $shellCommand = './new-comment.sh';
    $shellCommand .= ' --name ' . escapeshellarg($data['name']);
    $shellCommand .= ' --hash \'' . $emailHash . '\'';
    $shellCommand .= ' --post ' . escapeshellarg($data['post']);
    $shellCommand .= ' --message ' . escapeshellarg($data['message']);

    if (isset($data['url'])) {
        $shellCommand .= ' --url ' . escapeshellarg($data['url']);
    }

    exec($shellCommand, $output);
});

$app->run();

?>

<?php
require 'vendor/autoload.php';
require 'lib/readConfig.php';

// Read config file
$config = readConfig('config');

if ($config === FALSE) {
    die('Config file not found');
}

// Start Slim
$app = new \Slim\Slim();

$app->post('/comments', function () use ($app) {
    $data = $app->request()->post();

    // Checking for the honey pot
    if ((isset($data['company'])) && (!empty($data['company']))) {
        return;
    }

    // Checking for mandatory fields
    if ((!isset($data['name'])) ||
        (!isset($data['email'])) ||
        (!isset($data['message'])) ||
        (!isset($data['post'])))
    {
        echo('Mandatory fields are missing.');
        return;
    }

    $emailHash = md5(trim(strtolower($data['email'])));

    $shellCommand = './new-comment.sh';
    $shellCommand .= ' --name ' . escapeshellarg($data['name']);
    $shellCommand .= ' --hash \'' . $emailHash . '\'';
    $shellCommand .= ' --post ' . escapeshellarg($data['post']);
    $shellCommand .= ' --message ' . escapeshellarg($data['message']);

    if (isset($data['url'])) {
        $shellCommand .= ' --url ' . escapeshellarg($data['url']);
    }

    exec($shellCommand, $output);
});

$app->run();

?>

Change check for honey pot

Change check for honey pot