<?php

/**
 * A bootstrap for the Dropbox SDK usage examples
 * @link https://github.com/BenTheDesigner/Dropbox/tree/master/examples
 */

// Don't allow direct access to the boostrap
if(basename($_SERVER['REQUEST_URI']) == 'bootstrap.php'){
	exit('bootstrap.php does nothing on its own. Please see the examples provided');
}

// Set error reporting
error_reporting(-1);
ini_set('display_errors', 'On');
ini_set('html_errors', 'On');

// Register a simple autoload function
spl_autoload_register(function($class){
	$class = str_replace('\\', '/', $class);
	require_once('../' . $class . '.php');
});

// Set your consumer key, secret and callback URL
$key      = 'XXXXXXXXXXXXXXX';
$secret   = 'XXXXXXXXXXXXXXX';
$callback = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

// Instantiate the required Dropbox objects
$encrypter = new \Dropbox\OAuth\Storage\Encrypter('12345678901234567890123456789012');
$storage = new \Dropbox\OAuth\Storage\Session($encrypter);
$OAuth = new \Dropbox\OAuth\Consumer\Curl($key, $secret, $storage, $callback);
$dropbox = new \Dropbox\API($OAuth);

<?php

/**
 * A bootstrap for the Dropbox SDK usage examples
 * @link https://github.com/BenTheDesigner/Dropbox/tree/master/examples
 */

// Don't allow direct access to the boostrap
if (!isset($_SERVER['REQUEST_URI']))
{
	exit('This script cannot be run from command line');
}

if(basename($_SERVER['REQUEST_URI']) == 'bootstrap.php')
{
	exit('bootstrap.php does nothing on its own. Please see the examples provided');
}

// Set error reporting
error_reporting(-1);
ini_set('display_errors', 'On');
ini_set('html_errors', 'On');

// Register a simple autoload function
spl_autoload_register(function($class){
	$class = str_replace('\\', '/', $class);
	require_once('../' . $class . '.php');
});

// Set your consumer key, secret and callback URL
$key      = 'XXXXXXXXXXXXXXX';
$secret   = 'XXXXXXXXXXXXXXX';

$protocol = (!empty($_SERVER['HTTPS'])) ? 'https' : 'http';
$callback = $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

// Instantiate the required Dropbox objects
$encrypter = new \Dropbox\OAuth\Storage\Encrypter('12345678901234567890123456789012');
$storage = new \Dropbox\OAuth\Storage\Session($encrypter);
$OAuth = new \Dropbox\OAuth\Consumer\Curl($key, $secret, $storage, $callback);
$dropbox = new \Dropbox\API($OAuth);

Stop example script execution if running from command line. Added support for HTTPS hosts for example scripts.


<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class UserControllerTest extends TestCase
{
    use DatabaseMigrations;

    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function test_login()
    {
        $user = factory(App\User::class)->create();

        $response = $this->call('POST', '/login', [
            'username' => $user['username'],
            'password' => 'secret',
        ]);

        $this->assertRedirectedTo('/');
        $this->assertSessionHas('user_logged_in', true);
    }
}

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class UserControllerTest extends TestCase
{
    use DatabaseMigrations;

    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function test_login()
    {
        $user = factory(App\User::class)->create();

        $response = $this->call('POST', '/login', [
            'username' => $user['username'],
            'password' => 'secret',
        ]);

        $this->assertRedirectedTo('/');
    }
}

Remove test condition about session since it's currently not working


<?php

CroogoNav::add('sidebar', 'menus', array(
	'icon' => array('sitemap', 'large'),
	'title' => __d('croogo', 'Menus'),
	'url' => array(
		'plugin' => 'menus',
		'admin' => true,
		'controller' => 'menus',
		'action' => 'index',
	),
	'weight' => 20,
	'children' => array(
		'menus' => array(
			'title' => __d('croogo', 'Menus'),
			'url' => array(
				'plugin' => 'menus',
				'admin' => true,
				'controller' => 'menus',
				'action' => 'index',
			),
			'weight' => 10,
		),
		'add_new' => array(
			'title' => __d('croogo', 'Add new'),
			'url' => array(
				'plugin' => 'menus',
				'admin' => true,
				'controller' => 'menus',
				'action' => 'add',
			),
			'weight' => 20,
			'htmlAttributes' => array('class' => 'separator'),
		),
	),
));

<?php

CroogoNav::add('sidebar', 'menus', array(
	'icon' => array('sitemap', 'large'),
	'title' => __d('croogo', 'Menus'),
	'url' => array(
		'plugin' => 'menus',
		'admin' => true,
		'controller' => 'menus',
		'action' => 'index',
	),
	'weight' => 20,
	'children' => array(
		'menus' => array(
			'title' => __d('croogo', 'Menus'),
			'url' => array(
				'plugin' => 'menus',
				'admin' => true,
				'controller' => 'menus',
				'action' => 'index',
			),
			'weight' => 10,
		),
	),
));

Remove "Add new" from Menu sidebar

Remove "Add new" from Menu sidebar

Closes #376


<?php

class CMService_AwsS3Versioning_Response_Version {

    /**
     * @param array $data
     */
    public function __construct(array $data) {
        $key = $data['Key'];
        $id = $data['VersionId'];
        $lastModified = $data['LastModified'];
    }
}

<?php

class CMService_AwsS3Versioning_Response_Version {

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

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

    /** @var DateTime */
    private $_lastModified;

    /**
     * @param array $data
     */
    public function __construct(array $data) {
        $this->_key = (string) $data['Key'];
        $this->_id = (string) $data['VersionId'];
        $this->_lastModified = new DateTime($data['LastModified']);
    }

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

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

    /**
     * @return DateTime
     */
    public function getLastModified() {
        return $this->_lastModified;
    }
}

Implement getters for version response

Implement getters for version response


<?php

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

class CreateInstallationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('installations', function (Blueprint $table) {
            $table->increments('id');
            $table->string('token')->unique();
            $table->integer('active')->default(0);
            $table->timestamps();
        });
    }

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

<?php

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

class CreateInstallationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('installations', function (Blueprint $table) {
            $table->increments('id');
            $table->string('token')->unique();
            $table->boolean('active')->default(false);
            $table->timestamps();
        });
    }

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

Change active to a boolean

Change active to a boolean


<?php
class FrontEndGridField extends GridField {
    /**
     * Returns the whole gridfield rendered with all the attached components
     * @return string
     */
    public function FieldHolder($properties=array()) {
        Requirements::block(FRAMEWORK_DIR.'/css/GridField.css');
        Requirements::css(FRONTEND_GRIDFIELD_BASE.'/css/FrontEndGridField.css');

        Requirements::add_i18n_javascript(FRAMEWORK_DIR.'/javascript/lang');
        Requirements::javascript(THIRDPARTY_DIR.'/jquery-ui/jquery-ui.js');
        Requirements::javascript(FRAMEWORK_ADMIN_DIR.'/javascript/ssui.core.js');
		Requirements::javascript(THIRDPARTY_DIR.'/jquery-entwine/dist/jquery.entwine-dist.js');
        Requirements::javascript(FRONTEND_GRIDFIELD_BASE.'/javascript/FrontEndGridField.js');

        return parent::FieldHolder();
    }
}
?>

<?php
class FrontEndGridField extends GridField {
    /**
     * Returns the whole gridfield rendered with all the attached components
     * @return string
     */
    public function FieldHolder($properties=array()) {
        Requirements::block(FRAMEWORK_DIR.'/css/GridField.css');
        Requirements::css(FRONTEND_GRIDFIELD_BASE.'/css/FrontEndGridField.css');

        Requirements::add_i18n_javascript(FRAMEWORK_DIR.'/javascript/lang');
        Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
        Requirements::javascript(THIRDPARTY_DIR.'/jquery-ui/jquery-ui.js');
        Requirements::javascript(FRAMEWORK_ADMIN_DIR.'/javascript/ssui.core.js');
		Requirements::javascript(THIRDPARTY_DIR.'/jquery-entwine/dist/jquery.entwine-dist.js');
        Requirements::javascript(FRONTEND_GRIDFIELD_BASE.'/javascript/FrontEndGridField.js');

        return parent::FieldHolder();
    }
}
?>

Make sure jQuery is always included

Make sure jQuery is always included


<?php
	#
	# $Id: news.php,v 1.1.2.18 2004-11-26 14:57:20 dan Exp $
	#
	# Copyright (c) 1998-2003 DVL Software Limited
	#

	DEFINE('MAX_PORTS', 20);

	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/common.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/databaselogin.php');

	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/getvalues.php');

	DEFINE('NEWSCACHE', $_SERVER['DOCUMENT_ROOT'] . '/../caching/cache/news.rss');

	if (file_exists(NEWSCACHE) && is_readable(NEWSCACHE)) {
		readfile(NEWSCACHE);
	}

	$Statistics->Save();
?>

<?php
	#
	# $Id: news.php,v 1.1.2.19 2005-05-17 22:47:34 dan Exp $
	#
	# Copyright (c) 1998-2003 DVL Software Limited
	#

	DEFINE('MAX_PORTS', 20);

	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/common.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/databaselogin.php');

	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/getvalues.php');

	DEFINE('NEWSCACHE', $_SERVER['DOCUMENT_ROOT'] . '/../caching/cache/news.rss');

	header('Content-type: application/rss+xml');

	if (file_exists(NEWSCACHE) && is_readable(NEWSCACHE)) {
		readfile(NEWSCACHE);
	}

	$Statistics->Save();
?>

Put the content type here.

Put the content type here.

git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@3330 46e82423-29d8-e211-989e-002590a4cdd4


<div class="update" data-productname="<?php p($_['productName']) ?>" data-version="<?php p($_['version']) ?>">

<?php p($l->t('Update needed')) ?>

			<?php if ($_['tooBig']) {
				p($l->t('Please use the command line updater because you have a big instance.'));
			} else {
				p($l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
			} ?>

			<?php
			print_unescaped($l->t('For help, see the  documentation.', [link_to_docs('admin-cli-upgrade')])); ?>

<div class="update" data-productname="<?php p($_['productName']) ?>" data-version="<?php p($_['version']) ?>">

<?php p($l->t('Update needed')) ?>

			<?php if ($_['tooBig']) {
				p($l->t('Your instance possibly hosts many users and files. To ensure a smooth upgrade process, please use the command line updater (occ upgrade).'));
			} else {
				p($l->t('Automatic updating was disabled in config.php. To upgrade your instance, please use the command line updater (occ upgrade).'));
			} ?>

			<?php
			print_unescaped($l->t('For help, see the  documentation.', [link_to_docs('admin-cli-upgrade')])); ?>

Make admin feedback easier understandable


<?php

//namespace Mockery\Adapter\Phpunit;
namespace Wecamp\FlyingLiqourice;

class NyanListener implements \PHPUnit_Framework_TestListener
{

    public function endTest(\PHPUnit_Framework_Test $test, $time)
    {
        usleep(rand(20000, 300000));
    }

    /**
     * Add Mockery files to PHPUnit's blacklist so they don't showup on coverage reports
     */
    public function startTestSuite(\PHPUnit_Framework_TestSuite $suite)
    {
    }
    /**
     *  The Listening methods below are not required for Mockery
     */
    public function addError(\PHPUnit_Framework_Test $test, \Exception $e, $time)
    {
    }

    public function addFailure(\PHPUnit_Framework_Test $test, \PHPUnit_Framework_AssertionFailedError $e, $time)
    {
    }

    public function addIncompleteTest(\PHPUnit_Framework_Test $test, \Exception $e, $time)
    {
    }

    public function addSkippedTest(\PHPUnit_Framework_Test $test, \Exception $e, $time)
    {
    }

    public function addRiskyTest(\PHPUnit_Framework_Test $test, \Exception $e, $time)
    {
    }

    public function endTestSuite(\PHPUnit_Framework_TestSuite $suite)
    {
    }

    public function startTest(\PHPUnit_Framework_Test $test)
    {
    }
}

<?php

//namespace Mockery\Adapter\Phpunit;
namespace Wecamp\FlyingLiqourice;

class NyanListener implements \PHPUnit_Framework_TestListener
{

    public function endTest(\PHPUnit_Framework_Test $test, $time)
    {
        usleep(rand(20000, 100000));
    }

    /**
     * Add Mockery files to PHPUnit's blacklist so they don't showup on coverage reports
     */
    public function startTestSuite(\PHPUnit_Framework_TestSuite $suite)
    {
    }
    /**
     *  The Listening methods below are not required for Mockery
     */
    public function addError(\PHPUnit_Framework_Test $test, \Exception $e, $time)
    {
    }

    public function addFailure(\PHPUnit_Framework_Test $test, \PHPUnit_Framework_AssertionFailedError $e, $time)
    {
    }

    public function addIncompleteTest(\PHPUnit_Framework_Test $test, \Exception $e, $time)
    {
    }

    public function addSkippedTest(\PHPUnit_Framework_Test $test, \Exception $e, $time)
    {
    }

    public function addRiskyTest(\PHPUnit_Framework_Test $test, \Exception $e, $time)
    {
    }

    public function endTestSuite(\PHPUnit_Framework_TestSuite $suite)
    {
    }

    public function startTest(\PHPUnit_Framework_Test $test)
    {
    }
}

unittests: Use laserpointer to play with nyancat to reduce sleep


<?php
namespace Omise\Payment\Gateway\Validator\Offsite;

use Magento\Payment\Gateway\Command\CommandException;
use Magento\Payment\Gateway\Validator\AbstractValidator;

class InternetbankingChargeCommandResponseValidator extends AbstractValidator
{
    /**
     * @var string
     */
    protected $message;

    /**
     * Performs domain-related validation for business object
     *
     * @param  array $validationSubject
     *
     * @return ResultInterface
     */
    public function validate(array $validationSubject)
    {
        return $this->createResult(true, []);
    }
}

<?php
namespace Omise\Payment\Gateway\Validator\Offsite;

use Magento\Payment\Gateway\Validator\AbstractValidator;

class InternetbankingChargeCommandResponseValidator extends AbstractValidator
{
    /**
     * @var string
     */
    protected $message;

    /**
     * Performs domain-related validation for business object
     *
     * @param  array $validationSubject
     *
     * @return ResultInterface
     */
    public function validate(array $validationSubject)
    {
        if (! isset($validationSubject['response']) || $validationSubject['response']['object'] !== 'omise') {
            return $this->failed(__('Transaction has been declined, please contact our support if you have any questions'));
        }

        if ($validationSubject['response']['status'] === 'failed') {
            return $this->failed(__($validationSubject['response']['message']));
        }

        $charge = $validationSubject['response']['data'];

        if (! isset($charge['object']) || $charge['object'] !== 'charge') {
            return $this->failed(__('Couldn\'t retrieve charge transaction, please contact our support if you have any questions.'));
        }

        if ($charge['status'] === 'failed') {
            return $this->failed(__('Payment failed. ' . ucfirst($charge['failure_message']) . ', please contact our support if you have any questions.'));
        }

        $captured = $charge['captured'] ? $charge['captured'] : $charge['paid'];

        if ($charge['status'] === 'pending'
            && $charge['authorized'] == false
            && $captured == false
            && $charge['authorize_uri']
        ) {
            return $this->createResult(true, []);
        }

        return $this->failed(__('Payment failed, invalid payment status, please contact our support if you have any questions'));
    }

    /**
     * @param  \Magento\Framework\Phrase|string $message
     *
     * @return \Magento\Payment\Gateway\Validator\ResultInterface
     */
    protected function failed($message)
    {
        return $this->createResult(false, [ $message ]);
    }
}

Add validation rules to the internetbanking command response validator.


<?php

namespace RachidLaasri\LaravelInstaller\Helpers;

use Exception;
use Illuminate\Support\Facades\Artisan;

class DatabaseManager
{

    /**
     * Migrate and seed the database.
     *
     * @return array
     */
    public function migrateAndSeed()
    {
        return $this->migrate();
    }

    /**
     * Run the migration and call the seeder.
     *
     * @return array
     */
    private function migrate()
    {
        try{
            Artisan::call('migrate', ["--force"=> true ]);
        }
        catch(Exception $e){
            return $this->response($e->getMessage());
        }

        return $this->seed();
    }

    /**
     * Seed the database.
     *
     * @return array
     */
    private function seed()
    {
        try{
            Artisan::call('db:seed');
        }
        catch(Exception $e){
            return $this->response($e->getMessage());
        }

        return $this->response(trans('messages.final.finished'), 'success');
    }

    /**
     * Return a formatted error messages.
     *
     * @param $message
     * @param string $status
     * @return array
     */
    private function response($message, $status = 'danger')
    {
        return array(
            'status' => $status,
            'message' => $message
        );
    }
}

<?php

namespace RachidLaasri\LaravelInstaller\Helpers;

use Exception;
use Illuminate\Support\Facades\Artisan;

class DatabaseManager
{

    /**
     * Migrate and seed the database.
     *
     * @return array
     */
    public function migrateAndSeed()
    {
        $this->sqlite();
        return $this->migrate();
    }

    /**
     * Run the migration and call the seeder.
     *
     * @return array
     */
    private function migrate()
    {
        try{
            Artisan::call('migrate', ["--force"=> true ]);
        }
        catch(Exception $e){
            return $this->response($e->getMessage());
        }

        return $this->seed();
    }

    /**
     * Seed the database.
     *
     * @return array
     */
    private function seed()
    {
        try{
            Artisan::call('db:seed');
        }
        catch(Exception $e){
            return $this->response($e->getMessage());
        }

        return $this->response(trans('messages.final.finished'), 'success');
    }

    /**
     * Return a formatted error messages.
     *
     * @param $message
     * @param string $status
     * @return array
     */
    private function response($message, $status = 'danger')
    {
        return array(
            'status' => $status,
            'message' => $message
        );
    }

        /**
     * check database type. If SQLite, then create the database file.
     */
    private function sqlite()
    {
        if(DB::connection() instanceof SQLiteConnection) {
            $database = DB::connection()->getDatabaseName();
            if(!file_exists($database)) {
                touch($database);
                DB::reconnect(Config::get('database.default'));
            }
        }
    }
}

Create sqlite database if use select that.

If a user decides to utilize sqlite, let's go ahead and make the database for them.


<?php

/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

namespace Sonata\DoctrinePHPCRAdminBundle\Route;

use Sonata\AdminBundle\Builder\RouteBuilderInterface;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Route\RouteCollection;

class PathInfoBuilderSlashes implements RouteBuilderInterface
{
    /**
     * RouteBuilder that allows slashes in the ids.
     *
     * {@inheritDoc}
     */
    function build(AdminInterface $admin, RouteCollection $collection)
    {

        $collection->add('list');
        $collection->add('create');
        $collection->add('batch', null, array(), array('_method' => 'POST'));
        $collection->add('edit', $admin->getRouterIdParameter().'/edit', array(), array('id' => '.+'));
        $collection->add('delete', $admin->getRouterIdParameter().'/delete', array(), array('id' => '.+'));
        $collection->add('export');
        $collection->add('show', $admin->getRouterIdParameter().'/show', array(), array('id' => '.+', '_method' => 'GET'));

        // add children urls
        foreach ($admin->getChildren() as $children) {
            $collection->addCollection($children->getRoutes());
        }
    }
}

<?php

/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

namespace Sonata\DoctrinePHPCRAdminBundle\Route;

use Sonata\AdminBundle\Builder\RouteBuilderInterface;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Route\RouteCollection;

class PathInfoBuilderSlashes implements RouteBuilderInterface
{
    /**
     * RouteBuilder that allows slashes in the ids.
     *
     * {@inheritDoc}
     */
    function build(AdminInterface $admin, RouteCollection $collection)
    {

        $collection->add('list');
        $collection->add('create');
        $collection->add('batch', null, array(), array('_method' => 'POST'));
        $collection->add('edit', $admin->getRouterIdParameter().'/edit', array(), array('id' => '.+'));
        $collection->add('delete', $admin->getRouterIdParameter().'/delete', array(), array('id' => '.+'));
        $collection->add('export');
        $collection->add('show', $admin->getRouterIdParameter().'/show', array(), array('id' => '.+', '_method' => 'GET'));

        if ($admin->isAclEnabled()) {
            $collection->add('acl', $admin->getRouterIdParameter().'/acl', array(), array('id' => '.+'));
        }

        // add children urls
        foreach ($admin->getChildren() as $children) {
            $collection->addCollection($children->getRoutes());
        }
    }
}

Add route for ACL Editor

Add route for ACL Editor

This is needed to access the ACL editor added in sonata-project/SonataAdminBundle#1475


<?php

// default settings

define('XMLSERVICELIB', 'ZENDSVR6');   //library with IBM XMLTOOLKIT objects
define('DFTLIB', 'QGPL');              //library for creation of temporary objects
define('ZSTOOLKITLIB', 'ZENDSVR6');    //library with service program
define('ZSTOOLKITPGM', 'ZSXMLSRV');    //service program name
define('DBPROTOCOL', 'ibm_db2');
define('XMLINTERNALKEY', '/tmp/Toolkit'); // default IPC (InternalKey)

<?php

// default settings

define('XMLSERVICELIB', 'ZENDPHP7');   //library with IBM XMLTOOLKIT objects
define('DFTLIB', 'QGPL');              //library for creation of temporary objects
define('ZSTOOLKITLIB', 'ZENDPHP7');    //library with service program
define('ZSTOOLKITPGM', 'ZSXMLSRV');    //service program name
define('DBPROTOCOL', 'ibm_db2');
define('XMLINTERNALKEY', '/tmp/Toolkit'); // default IPC (InternalKey)

Use ZS9 library in default settings

Use ZS9 library in default settings


<?php

	class ErrorHandler
	{
		static public function install()
		{
			set_error_handler("ErrorHandler::handle");
		}

		static public function handle($errno, $errstr, $errfile, $errline)
		{
			if(!(error_reporting() & $errno))
			{
				return;
			}

			throw new Exception($errstr . " [" . $errfile . " @ line " . $errline . "]");
			return true;
		}

		static public function mailException($e)
		{
			Helpers::sendMail(
				Config::get("exceptions.mail_to"),
				"[" . Config::get("app.internal_name") . "] " . $e->getMessage(),
				"An unhandled " . get_class($e) . " occured on " . date("l, j F Y H:i:s A") . ":\r\n\r\n" .
					$e->getMessage() . "\r\n" .
					"Request URI: " . $_SERVER["REQUEST_URI"] . "\r\n\r\n" .
					print_r(@$_POST, true)
			);
		}
	}

<?php

	class ErrorHandler
	{
		static public function install()
		{
			set_error_handler("ErrorHandler::handle");
		}

		static public function handle($errno, $errstr, $errfile, $errline)
		{
			if(!(error_reporting() & $errno))
			{
				return;
			}

			throw new Exception($errstr . " [" . $errfile . " @ line " . $errline . "]");
			return true;
		}

		static public function mailException($e)
		{
			Helpers::sendMail(
				Config::get("exceptions.mail_to"),
				"[" . Config::get("app.internal_name") . "] " . $e->getMessage(),
				"An unhandled " . get_class($e) . " occured on " . date("l, j F Y H:i:s A") . ":\r\n\r\n" .
					$e->getMessage() . "\r\n" .
					"Request URI: " . $_SERVER["REQUEST_URI"] . "\r\n\r\n" .
					print_r(@$_REQUEST, true)
			);
		}
	}

Use $_REQUEST instead of $_POST in exception notification emails.


<?php

namespace JWX\JWT\Parameter;

/**
 * PBES2 Salt Input parameter
 *
 * @link https://tools.ietf.org/html/rfc7518#section-4.8.1.1
 */
class PBES2SaltInputParameter extends RegisteredJWTParameter
{
	/**
	 * Constructor
	 *
	 * @param string $salt Base64url encoded salt input value
	 */
	public function __construct($salt) {
		parent::__construct(self::PARAM_PBES2_SALT_INPUT, (string) $salt);
	}
}

<?php

namespace JWX\JWT\Parameter;

use JWX\Util\Base64;

/**
 * PBES2 Salt Input parameter
 *
 * @link https://tools.ietf.org/html/rfc7518#section-4.8.1.1
 */
class PBES2SaltInputParameter extends RegisteredJWTParameter
{
	/**
	 * Constructor
	 *
	 * @param string $salt Base64url encoded salt input value
	 */
	public function __construct($salt) {
		parent::__construct(self::PARAM_PBES2_SALT_INPUT, (string) $salt);
	}

	/**
	 * Get computed salt value
	 *
	 * @param AlgorithmParameter $algo
	 * @return string
	 */
	public function salt(AlgorithmParameter $algo) {
		return $algo->value() . "\0" . Base64::urlDecode($this->value());
	}
}

Add salt method to salt input parameter

Add salt method to salt input parameter


<?php

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

class CreateTableResources extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('resources', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('slug');
            $table->string('review')->nullable();
            $table->string('content')->nullable();
            $table->string('attachment')->nullable();

            $table->integer('former_id')->unsigned()->nullable();

            $table->integer('category_id')->unsigned()->index();
            $table->foreign('category_id')->references('id')->on('categories');

            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');

            $table->softDeletes();
            $table->timestamps();
        });
    }

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

<?php

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

class CreateTableResources extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('resources', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('slug');
            $table->string('review')->nullable();
            $table->string('content')->nullable();
            $table->string('attachment')->nullable();

            $table->integer('former_id')->unsigned()->nullable();

            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');

            $table->softDeletes();
            $table->timestamps();
        });
    }

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

Revert the duplication of the reference in resources table


<?php
/*
 * This file bootstraps the test environment.
 */
namespace Doctrine\Tests;

error_reporting(E_ALL | E_STRICT);

if (file_exists(__DIR__ . '/../../../vendor/autoload.php')) {
    // dependencies were installed via composer - this is the main project
    $classLoader = require __DIR__ . '/../../../vendor/autoload.php';
} elseif (file_exists(__DIR__ . '/../../../../../autoload.php')) {
    // installed as a dependency in `vendor`
    $classLoader = require __DIR__ . '/../../../../../autoload.php';
} else {
    throw new \Exception('Can\'t find autoload.php. Did you install dependencies via composer?');
}

/* @var $classLoader \Composer\Autoload\ClassLoader */
$classLoader->add('Doctrine\\Tests\\', __DIR__ . '/../../');
unset($classLoader);

<?php
/*
 * This file bootstraps the test environment.
 */

error_reporting(E_ALL | E_STRICT);

if (file_exists(__DIR__ . '/../../../vendor/autoload.php')) {
    // dependencies were installed via composer - this is the main project
    $classLoader = require __DIR__ . '/../../../vendor/autoload.php';
} elseif (file_exists(__DIR__ . '/../../../../../autoload.php')) {
    // installed as a dependency in `vendor`
    $classLoader = require __DIR__ . '/../../../../../autoload.php';
} else {
    throw new Exception('Can\'t find autoload.php. Did you install dependencies via Composer?');
}

/* @var $classLoader \Composer\Autoload\ClassLoader */
$classLoader->add('Doctrine\\Tests\\', __DIR__ . '/../../');
unset($classLoader);

Remove not needed stuff from the PHPUnit boostrap file


<?php
namespace Neos\Flow\Security\Authentication\Token;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Mvc\ActionRequest;

/**
 * Marker interface for authentication tokens which don't need a session.
 */
interface UsernamePasswordInterface
{
    public function getUsername(): string;

    public function getPassword(): string;
}

<?php
namespace Neos\Flow\Security\Authentication\Token;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

/**
 * Marker interface for authentication tokens which hold a username and password
 */
interface UsernamePasswordInterface
{
    public function getUsername(): string;

    public function getPassword(): string;
}

Correct style and interface description

Correct style and interface description


<?php

namespace App\Handler\Email;

class SendAdminNotificationEmailHandler extends AbstractEmailHandler
{
    protected function configureMessage(\Swift_Message $email): void
    {
        $email
            ->setSubject('Your account has been created')
            ->setBody(
              $this->renderView(
                  // app/Resources/views/Emails/admin_notification.html.twig
                  'Emails/admin_notification.html.twig',
                  array(
                    'username' => $username,
                    'organization' => $organization
                  ) // pass values to the template
              ),
              'text/html'
            )
        ;
    }
}

<?php

namespace App\Handler\Email;

class SendAdminNotificationEmailHandler extends AbstractEmailHandler
{
    protected function configureMessage(\Swift_Message $email): void
    {
      $userName = 'staticUser';
      $organization = 'staticOrg';
        $email
            ->setSubject('An account was created that needs to be approved')
            ->setBody(
              $this->templating->render(
                  // app/Resources/views/Emails/admin_notification.html.twig
                  'Emails/admin_notification.html.twig',
                  array(
                    'username' => $userName,
                    'organization' => $organization
                  ) // pass values to the template
              ),
              'text/html'
            )
        ;
    }
}

Update template code for admin email, use hardcoded values for template.


<?php namespace Manavo\BootstrapForms;

use Illuminate\Html\HtmlServiceProvider as IlluminateHtmlServiceProvider;

class BootstrapFormsServiceProvider extends IlluminateHtmlServiceProvider
{

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('manavo/bootstrap-forms');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function registerFormBuilder()
    {
        $this->app->bindShared('form', function ($app) {
            $form = new FormBuilder($app['html'], $app['url'],
                $app['session.store']->getToken());

            return $form->setSessionStore($app['session.store']);
        });
    }

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

}

<?php namespace Manavo\BootstrapForms;

use Illuminate\Html\HtmlServiceProvider as IlluminateHtmlServiceProvider;

class BootstrapFormsServiceProvider extends IlluminateHtmlServiceProvider
{

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        if (version_compare($app::VERSION, '5.0') < 0) {
            $this->package('manavo/bootstrap-forms');
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function registerFormBuilder()
    {
        $this->app->bindShared('form', function ($app) {
            $form = new FormBuilder($app['html'], $app['url'],
                $app['session.store']->getToken());

            return $form->setSessionStore($app['session.store']);
        });
    }

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

}

Check for Laravel 4 before calling $this->package()


<?php

namespace Aurora\Auth;

use GuzzleHttp\Exception\ClientException;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Auth\EloquentUserProvider;

class NorthstarUserProvider extends EloquentUserProvider implements UserProvider
{
    /**
     * Retrieve a user by the given credentials.
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        // Get the Northstar user
        $northstar = new \Aurora\Services\Northstar;
        $response = $northstar->getUser('email', $credentials['email']);

        // If a matching user is found, find or create local Aurora user.
        return $this->createModel()->firstOrCreate([
            '_id' => $response['_id'],
        ]);
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $credentials
     * @return bool
     */
    public function validateCredentials(Authenticatable $user, array $credentials)
    {
        $northstar = new \Aurora\Services\Northstar;
        try {
            $northstar->login($credentials);

            return true;
        } catch (ClientException $e) {
            // If an exception is returned, we couldn't log in...
        }

        return false;
    }
}

<?php

namespace Aurora\Auth;

use GuzzleHttp\Exception\ClientException;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Auth\EloquentUserProvider;

class NorthstarUserProvider extends EloquentUserProvider implements UserProvider
{
    /**
     * Retrieve a user by the given credentials.
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        // Get the Northstar user
        $northstar = new \Aurora\Services\Northstar;
        $response = $northstar->getUser('email', $credentials['email']);

        // If a matching user is found, find or create local Aurora user.
        return $this->createModel()->firstOrCreate([
            '_id' => $response->id,
        ]);
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $credentials
     * @return bool
     */
    public function validateCredentials(Authenticatable $user, array $credentials)
    {
        $northstar = new \Aurora\Services\Northstar;
        try {
            $northstar->login($credentials);

            return true;
        } catch (ClientException $e) {
            // If an exception is returned, we couldn't log in...
        }

        return false;
    }
}

Update user provider to expect model.

Update user provider to expect model.


<?php

namespace SimplyTestable\ApiBundle\Resque\Job;

use Resque\Job\AbstractInstance as BaseJob;

abstract class AbstractJob extends BaseJob {
}

<?php

namespace SimplyTestable\ApiBundle\Resque\Job;

use Glit\ResqueBundle\Job\BaseJob;

abstract class AbstractJob extends BaseJob {
}

Extend ResqueBundle BaseJob to get access to container


<?php

namespace Tooly;

use Composer\IO\IOInterface;
use Composer\Script\Event;
use Tooly\Factory\ToolFactory;
use Tooly\Script\Helper;
use Tooly\Script\Helper\Filesystem;
use Tooly\Script\Helper\Downloader;
use Tooly\Script\Helper\Verifier;
use Tooly\Script\Processor;
use TM\GPG\Verification\Verifier as GPGVerifier;

/**
 * @package Tooly
 */
class ScriptHandler
{
    /**
     * @param Event $event
     */
    public static function installPharTools(Event $event)
    {
        $data = [];

        $composer = $event->getComposer();
        $extras = $composer->getPackage()->getExtra();

        if (true === array_key_exists('tools', $extras)) {
            $data = array_merge($data, $extras['tools']);
        }

        $tools = ToolFactory::createTools(
            $event->getComposer()->getConfig()->get('bin-dir'),
            $data
        );

        $gpgVerifier = null;

        if (true === class_exists(GPGVerifier::class)) {
            $gpgVerifier = new GPGVerifier;
        }

        $helper = new Helper(new Filesystem, new Downloader, new Verifier($gpgVerifier));
        $processor = new Processor($event->getIO(), $helper, $event->isDevMode());

        foreach ($tools as $tool) {
            $processor->process($tool);
        }
    }
}

<?php

namespace Tooly;

use Composer\IO\IOInterface;
use Composer\Script\Event;
use Tooly\Factory\ToolFactory;
use Tooly\Script\Configuration;
use Tooly\Script\Helper;
use Tooly\Script\Helper\Filesystem;
use Tooly\Script\Helper\Downloader;
use Tooly\Script\Helper\Verifier;
use Tooly\Script\Processor;
use TM\GPG\Verification\Verifier as GPGVerifier;

/**
 * @package Tooly
 */
class ScriptHandler
{
    /**
     * @param Event $event
     */
    public static function installPharTools(Event $event)
    {
        $gpgVerifier = null;
        $configuration = new Configuration($event->getComposer(), $event->isDevMode(), $event->getIO()->isInteractive());

        if (true === class_exists(GPGVerifier::class)) {
            $gpgVerifier = new GPGVerifier;
        }

        $helper = new Helper(new Filesystem, new Downloader, new Verifier($gpgVerifier));
        $processor = new Processor($event->getIO(), $helper, $configuration);

        foreach ($configuration->getTools() as $tool) {
            $processor->process($tool);
        }
    }
}

Create configuration in script handler

Create configuration in script handler


<?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/setup.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

/** @var \Composer\Autoload\ClassLoader $loader */
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

$kernel = new AppKernel('dev', false);
$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/setup.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

/** @var \Composer\Autoload\ClassLoader $loader */
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

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

Put dev environments back in debug mode

Put dev environments back in debug mode


<?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'))
) {
    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', '31.32.220.167', 'fe80::1', '::1'))
) {
    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 for dev mode

Add IP for dev mode


<?php

abstract class CRM_Securefiles_Backend {

  abstract protected function uploadFile($file, $user = null);
  abstract protected function downloadFile($file, $user = null);
  abstract protected function listFiles($user = null);
  abstract protected function fileMetadata($file, $user = null);

  function cleanup() {}
  function buildSettingsForm($form) {}
  function defaultSettings($defaults) { return $defaults; }
  function saveSettings($values) {}
}

<?php

abstract class CRM_Securefiles_Backend {

  abstract protected function uploadFile($file, $user = null);
  abstract protected function downloadFile($file, $user = null);
  abstract protected function listFiles($user = null);
  abstract protected function fileMetadata($file, $user = null);

  function cleanup() {}
  function buildSettingsForm(&$form) {}
  function defaultSettings(&$defaults) {}
  function saveSettings($values) {}
  function validateSettings(&$form) { return true;}
}

Set vars to pass by reference

Set vars to pass by reference


<?php include('theme/header.php'); ?>

<?php

include('dbconnect.php');

$sql = "INSERT INTO small_victories (date, latest_amount) VALUES ('2017-01-25', '31945.78');";

if (mysqli_query($connection, $sql)) {
  echo "The new amount was added.";
} else {
  echo "Oops! " . $sql . "<br>" . mysqli_error($connection);
}

mysqli_close($connection);

?>

<?php include('theme/footer.php'); ?>

<?php include('theme/header.php'); ?>

<?php

include('dbconnect.php');

//$sql = "INSERT INTO small_victories (date, latest_amount) VALUES ('2017-01-25', '31945.78');";
$sql = '';

if (mysqli_query($connection, $sql)) {
  echo "The new amount was added.";
} else {
  echo "Oops! " . $sql . "<br>" . mysqli_error($connection);
}

mysqli_close($connection);

?>

<?php include('theme/footer.php'); ?>

Comment out the test entry until this section can be built correctly


<?php

require_once('apps/files_sharing/lib_share.php');
require_once('apps/files_sharing/sharedstorage.php');

OC_Filesystem::registerStorageType("shared", "OC_Filestorage_Shared", array("datadir"=>"string"));
OC_Util::addScript("files_sharing", "share");
OC_Util::addScript("3rdparty", "chosen/chosen.jquery.min");
OC_Util::addStyle( 'files_sharing', 'sharing' );
OC_Util::addStyle("3rdparty", "chosen/chosen");
OC_App::addNavigationEntry(array(
  "id" => "files_sharing_list",
  "order" => 2,
  "href" => OC_Helper::linkTo( "files_sharing", "list.php" ),
  "name" => "Shared"));

?>

<?php

require_once('apps/files_sharing/lib_share.php');
require_once('apps/files_sharing/sharedstorage.php');

OC_Filesystem::registerStorageType("shared", "OC_Filestorage_Shared", array("datadir"=>"string"));
OC_Util::addScript("files_sharing", "share");
OC_Util::addScript("3rdparty", "chosen/chosen.jquery.min");
OC_Util::addStyle( 'files_sharing', 'sharing' );
OC_Util::addStyle("3rdparty", "chosen/chosen");

?>

Remove navigation entry for shared files


<?php

class Denkmal_MessagePushNotification_SendJob extends CM_Jobdistribution_Job_Abstract {

    protected function _execute(CM_Params $params) {
        /** @var Denkmal_Params $params */
        $message = $params->getMessage('message');

        $serviceManager = CM_Service_Manager::getInstance();
        /** @var Denkmal_Push_Notification_Sender $sender */
        $sender = $serviceManager->get('push-notification-sender', 'Denkmal_Push_Notification_Sender');
        $render = new CM_Frontend_Render(null, null, $serviceManager);
        $formatter = new Denkmal_MessagePushNotification_Formatter($render);

        $pushNotificationMessage = new Denkmal_Push_Notification_Message();
        $pushNotificationMessage->setExpires((new DateTime())->add(new DateInterval('PT6H')));
        $pushNotificationMessage->setData($formatter->getPushData($message));

        $subscriptionList = new Denkmal_Push_SubscriptionList_All();
        $sender->sendNotifications($subscriptionList->getItems(), $pushNotificationMessage);
    }
}

<?php

class Denkmal_MessagePushNotification_SendJob extends CM_Jobdistribution_Job_Abstract {

    protected function _execute(CM_Params $params) {
        /** @var Denkmal_Params $params */
        $message = $params->getMessage('message');
        $region = $message->getVenue()->getRegion();
        $site = Denkmal_Site_Region_Abstract::getSiteByRegion($region);

        $serviceManager = CM_Service_Manager::getInstance();
        /** @var Denkmal_Push_Notification_Sender $sender */
        $sender = $serviceManager->get('push-notification-sender', 'Denkmal_Push_Notification_Sender');

        $environment = new CM_Frontend_Environment($site);
        $render = new CM_Frontend_Render($environment, null, $serviceManager);
        $formatter = new Denkmal_MessagePushNotification_Formatter($render);

        $pushNotificationMessage = new Denkmal_Push_Notification_Message();
        $pushNotificationMessage->setExpires((new DateTime())->add(new DateInterval('PT6H')));
        $pushNotificationMessage->setData($formatter->getPushData($message));

        $subscriptionList = new Denkmal_Push_SubscriptionList_Site($site);
        $sender->sendNotifications($subscriptionList->getItems(), $pushNotificationMessage);
    }
}

Send message notifications only to subscribers of region's site


<?php

namespace Rogue\Http\Middleware;

use Closure;

class AuthenticateApi
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->method() === 'POST' || $request->method() === 'PUT') {
            if ($request->header('X-DS-Rogue-API-Key') !== env('ROGUE_API_KEY')) {
                throw new UnauthorizedAccessException;
            }
        }

        return $next($request);
    }
}

<?php

namespace Rogue\Http\Middleware;

use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Middleware\Authenticate;

class AuthenticateApi extends Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function handle($request, Closure $next, ...$guards)
    {
        // Only protected POST, PUT, and DELETE routes
        if (! in_array($request->method(), ['POST', 'PUT', 'DELETE'])) {
            return $next($request);
        }

        // Allow using the `X-DS-Rogue-API-Key` header to override auth.
        if ($request->hasHeader('X-DS-Rogue-API-Key')) {
            if ($request->header('X-DS-Rogue-API-Key') !== config('app.api_key')) {
                throw new AuthenticationException;
            }

            return $next($request);
        }

        // Otherwise, we can't do anything!
        // @TODO: Instead, pass on to default auth middleware with Gateway guard.
        throw new AuthenticationException;
    }
}

Fix imported exception & protect DELETE routes too.


<?php
/**
 * @file
 * Template for the subscribed message.
 */
?>

<?php print $message; ?>

<?php print $update_link; ?>

<?php print $unsubscribe_link; ?>

<?php
/**
 * @file
 * Template for the subscribed message.
 */
?>

<?php print $message; ?>

<?php print $unsubscribe_link; ?>

<?php print $update_link; ?>

Change link order for consistency

Change link order for consistency


<?php require_once 'config.php';

if ($env == 'production') {
  error_reporting(E_ERROR | E_PARSE);
}

function print_files($url, $dir)
{
  $hide = ".";

  $myDirectory = opendir($dir);

  if ($myDirectory) {
    while ($entryName = readdir($myDirectory))
    {
      $dirArray[] = $entryName;
    }

    closedir($myDirectory);

    $indexCount = count($dirArray);

    sort($dirArray);

    for ($index = 0; $index < $indexCount; $index++)
    {
      if (substr("$dirArray[$index]", 0, 1) != $hide)
      {
        $name = $dirArray[$index];
        $namehref = $dirArray[$index];
        echo("

            $name

        ");
      }
    }
  } else {
    echo("

Couldn't open the directory specified.

    ");
  }
}

Adjust the error message styling

Adjust the error message styling


<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Attention extends Model {

	//

}

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Attention extends Model {

	protected $fillable = [];

	public function post()
	{
		return $this->belongsTo('Post');
	}

	public function user()
	{
		return $this->belongsTo('User');
	}

}

Set the relations of attention.

Set the relations of attention.


<?php

use Symfony\Component\Debug\Debug;

if (!file_exists(dirname(__DIR__) . "/vendor/autoload.php")) {
  die(
    'Set up the project dependencies using the following commands:' . PHP_EOL .
    'curl -s http://getcomposer.org/installer | php' . PHP_EOL .
    'php composer.phar install' . PHP_EOL
  );
}
$loader = require_once dirname(__DIR__) . "/vendor/autoload.php";
/* @var $loader Composer\Autoload\ClassLoader */
$loader->add("Apnet\\Dev\\", __DIR__ . "/src");

chdir(dirname(__DIR__));
Debug::enable();

<?php

use Symfony\Component\Debug\Debug;

if (!file_exists(dirname(__DIR__) . "/vendor/autoload.php")) {
  die(
    'Set up the project dependencies using the following commands:' . PHP_EOL .
    'curl -s http://getcomposer.org/installer | php' . PHP_EOL .
    'php composer.phar install' . PHP_EOL
  );
}
require_once dirname(__DIR__) . "/vendor/autoload.php";

$loader = new Composer\Autoload\ClassLoader();
$loader->add("Apnet\\Dev\\", __DIR__ . "/src");
$loader->register();

chdir(dirname(__DIR__));
Debug::enable();

Create and register new autoloader

Create and register new autoloader


<?php defined('SYSPATH') or die('No direct script access.');

class Kohana_Error_Exception {

	public static function handler(Exception $e)
	{
		if (Kohana::$environment === Kohana::DEVELOPMENT)
		{
			Kohana_Exception::handler($e);
		}

		// It's a nice time to log :)
		Kohana::$log->add(Kohana_Log::ERROR, Kohana_Exception::text($e));

		if ( ! defined('SUPPRESS_REQUEST'))
		{
			$request = array(
				// Get status from current request
				'action'  => Request::current()->status(),

				// If exception has a message this can be passed on
				'message' => rawurlencode($e->getMessage()),
			);

			// Override status if HTTP_Exception thrown
			if ($e instanceof HTTP_Exception)
			{
				$request['action'] = $e->getCode();
			}

			echo Request::factory(Route::get('kohana_error')->uri($request))
				->execute()
				->send_headers()
				->response;
		}
	}

}

<?php defined('SYSPATH') or die('No direct script access.');

class Kohana_Error_Exception {

	public static function handler(Exception $e)
	{
		if (Kohana::$environment === Kohana::DEVELOPMENT)
		{
			Kohana_Exception::handler($e);
		}

		// It's a nice time to log :)
		Kohana::$log->add(Kohana_Log::ERROR, Kohana_Exception::text($e));

		if ( ! defined('SUPPRESS_REQUEST'))
		{
			$request = array(
				// Get status from current request
				'action'  => Request::initial()->response()->status(),

				// If exception has a message this can be passed on
				'message' => rawurlencode($e->getMessage()),
			);

			// Override status if HTTP_Exception thrown
			if ($e instanceof HTTP_Exception)
			{
				$request['action'] = $e->getCode();
			}

			echo Request::factory(Route::get('kohana_error')->uri($request))
				->execute()
				->send_headers()
				->response;
		}
	}

}

Fix to actually get status from request

Fix to actually get status from request


<?php

function html_escape_value($data)
{
    if (!is_array($data)) {
        return htmlspecialchars($data, ENT_QUOTES, 'UTF-8', false);
    }

    $escapedData = array();

    foreach ($data as $key => $value) {
        $escapedData[html_escape_value($key)] = html_escape_value($value);
    }

    return $escapedData;
}

/**
 * Dumps a value for consumption in tests
 *
 * The output format does not use any HTML special chars in boilerplate, to make
 * it simpler to write assertion on the HTML content generated based on it (no change
 * in the boilerplate parts during escaping).
 *
 * @param mixed $value
 *
 * @return string
 */
function mink_dump($value)
{
    if (null === $value) {
        return 'null';
    }

    if (is_string($value)) {
        return sprintf('`%s`', $value);
    }

    if (is_bool($value)) {
        return $value ? 'true' : 'false';
    }

    if (is_int($value) || is_float($value)) {
        return var_export($value, true);
    }

    if (is_array($value)) {
        if (empty($value)) {
            return 'array()';
        }

        $output = array('array(');

        foreach ($value as $k => $v) {
            $output[] = sprintf('%s = %s,', $k, str_replace("\n", "\n  ", mink_dump($v)));
        }

        return implode("\n  ", $output)."\n)";
    }

    return gettype($value); // We don't have full dumping of resource and object, as we don't need them
}

<?php

function html_escape_value($data)
{
    return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}

/**
 * Dumps a value for consumption in tests
 *
 * The output format does not use any HTML special chars in boilerplate, to make
 * it simpler to write assertion on the HTML content generated based on it (no change
 * in the boilerplate parts during escaping).
 *
 * @param mixed $value
 *
 * @return string
 */
function mink_dump($value)
{
    if (null === $value) {
        return 'null';
    }

    if (is_string($value)) {
        return sprintf('`%s`', $value);
    }

    if (is_bool($value)) {
        return $value ? 'true' : 'false';
    }

    if (is_int($value) || is_float($value)) {
        return var_export($value, true);
    }

    if (is_array($value)) {
        if (empty($value)) {
            return 'array()';
        }

        $output = array('array(');

        foreach ($value as $k => $v) {
            $output[] = sprintf('%s = %s,', $k, str_replace("\n", "\n  ", mink_dump($v)));
        }

        return implode("\n  ", $output)."\n)";
    }

    return gettype($value); // We don't have full dumping of resource and object, as we don't need them
}

Remove the array HTML escaping

Remove the array HTML escaping

Escaping must be performed on the rendered string. It does not make sense
to escape each array value separately.


<?php

/**
 * Copyright 2015 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\StepupGateway\U2fVerificationBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

final class U2fController extends Controller
{
    public function appIdAction()
    {
        return new JsonResponse(
            [
                "trustedFacets" => [
                    [
                        "version" => ["major" => 1, "minor" => 0],
                        "ids"     => [
                            "https://ss-dev.stepup.coin.surf.net",
                            "https://ra-dev.stepup.coin.surf.net",
                        ],
                    ],
                ],
            ],
            Response::HTTP_OK
        );
    }
}

<?php

/**
 * Copyright 2015 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\StepupGateway\U2fVerificationBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

final class U2fController extends Controller
{
    /**
     * @return Response
     *
     * @see https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-appid-and-facets.html#trustedfacets-structure
     */
    public function appIdAction()
    {
        return new JsonResponse(
            [
                "trustedFacets" => [
                    [
                        "version" => ["major" => 1, "minor" => 0],
                        "ids"     => [
                            "https://ss-dev.stepup.coin.surf.net",
                            "https://ra-dev.stepup.coin.surf.net",
                        ],
                    ],
                ],
            ],
            Response::HTTP_OK
        );
    }
}

Document what structure the trusted facets list is based on


<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title><?php isset($title) ? $this->title($title) : $this->title(); ?></title>

  <link rel="stylesheet" type="text/css" href="/css/style.css" />

<?php
  if (isset($error)) {
    echo ''.$error.'';
  }
?>

AWESOME

<!DOCTYPE html>
<html lang="<?php echo __('@ISO639-1'); ?>">

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title><?php isset($title) ? $this->title($title) : $this->title(); ?></title>

  <link rel="stylesheet" type="text/css" href="/css/style.css" />

<?php
  if (isset($error)) {
    echo ''.$error.'';
  }
?>

AWESOME

Change HTML lang attrib with i18n

Change HTML lang attrib with i18n


<?php
namespace Tpg\ExtjsBundle\Annotation;

use Doctrine\ORM\Mapping\Annotation;

/**
 * @Annotation
 * @Target("CLASS")
 */
final class ModelProxy implements Annotation {
    public $name = 'memory';
    public $option = array();
    public $reader = array();
    public $writer = array();

    public function __construct($values) {
        if (isset($values['value'])) {
            $this->name = "rest";
            $this->option = array(
                "url"=>$values['value'],
                "format"=>"json",
            );
            $this->writer = array(
                "type"=>"json",
                "writeRecordId"=>false,
            );
        } else {
            if (isset($values['name'])) $this->name = $values['name'];
            if (isset($values['option'])) $this->option = $values['option'];
            if (isset($values['reader'])) $this->reader = $values['reader'];
            if (isset($values['writer'])) $this->writer = $values['writer'];
        }
    }
}

<?php
namespace Tpg\ExtjsBundle\Annotation;

use Doctrine\ORM\Mapping\Annotation;

/**
 * @Annotation
 * @Target("CLASS")
 */
final class ModelProxy implements Annotation {
    public $name = 'memory';
    public $option = array();
    public $reader = array();
    public $writer = array();

    public function __construct($values) {
        if (isset($values['value'])) {
            $this->name = "rest";
            $this->option = array(
                "url"=>$values['value'],
                "format"=>"json",
            );
            $this->writer = array(
                "type"=>"json",
                "writeRecordId"=>false,
            );
        } else {
            if (isset($values['name'])) $this->name = $values['name'];
        }
        if (isset($values['option'])) $this->option = array_merge($this->option, $values['option']);
        if (isset($values['writer'])) $this->writer = array_merge($this->writer, $values['writer']);
        if (isset($values['reader'])) $this->reader = $values['reader'];
    }
}

Fix bug option, reader and writer parameters was not being apply if value is set.


<?php

namespace Scheb\TwoFactorBundle\Tests;

use Scheb\TwoFactorBundle\DependencyInjection\Compiler\ProviderCompilerPass;
use Scheb\TwoFactorBundle\SchebTwoFactorBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class SchebTwoFactorBundleTest extends TestCase
{
    /**
     * @test
     */
    public function build_initializeBundle_addCompilerPass()
    {
        $containerBuilder = new ContainerBuilder();
        $bundle = new SchebTwoFactorBundle();
        $bundle->build($containerBuilder);

        $foundIt = false;
        foreach ($containerBuilder->getCompilerPassConfig()->getPasses() as $pass) {
            if ($pass instanceof ProviderCompilerPass) {
                $foundIt = true;
                continue;
            }
        }

        $this->assertTrue($foundIt);
    }
}

<?php

namespace Scheb\TwoFactorBundle\Tests;

use Scheb\TwoFactorBundle\DependencyInjection\Compiler\ProviderCompilerPass;
use Scheb\TwoFactorBundle\SchebTwoFactorBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class SchebTwoFactorBundleTest extends TestCase
{
    /**
     * @test
     */
    public function build_initializeBundle_addCompilerPass()
    {
        $containerBuilder = new ContainerBuilder();
        $bundle = new SchebTwoFactorBundle();
        $bundle->build($containerBuilder);

        $foundIt = false;
        foreach ($containerBuilder->getCompilerPassConfig()->getPasses() as $pass) {
            if ($pass instanceof ProviderCompilerPass) {
                $foundIt = true;
                break;
            }
        }

        $this->assertTrue($foundIt);
    }
}

Break loop when ProviderCompilerPass is found


<?php
defined('C5_EXECUTE') or die("Access Denied.");
Loader::model('user_list');
$av = Loader::helper('concrete/avatar');
$ul = new UserList();
$ul->filterByGroup('Staff');
$ul->sortBy('ak_order','asc');
$content = $controller->getContent();
print $content;
?>

  <?php foreach($ul->get(100) as $staffMember) { ?>

      <?php if($avatar = $av->getImagePath($staffMember)) { ?>
        <div class='u-avatar' style='background-image:url(<?=$avatar?>)'>

      <?php } else { ?>
        <div class='u-avatar placeholder<?=ord($staffMember->getUserID()) % 3?>'>

      <?php } ?>

<?="{$staffMember->getAttribute('first_name')} {$staffMember->getAttribute('last_name')}, " . ($staffMember->getAttribute('job_title') ?: 'Jane\'s Walk');?>

        <a href="mailto:<?=($email = $staffMember->getUserEmail())?>"><?=$email?>

<?=$staffMember->getAttribute('bio')?>

  <?php } ?>

<?php
defined('C5_EXECUTE') or die("Access Denied.");
Loader::model('user_list');
$av = Loader::helper('concrete/avatar');
$ul = new UserList();
$ul->filterByGroup((string)$this->getBlockObject()->getBlockName() ?: 'Staff');
$ul->sortBy('ak_order','asc');
$content = $controller->getContent();
print $content;
?>

  <?php foreach($ul->get(100) as $staffMember) { ?>

      <?php if($avatar = $av->getImagePath($staffMember)) { ?>
        <div class='u-avatar' style='background-image:url(<?= $avatar ?>)'>

      <?php } else { ?>
        <div class='u-avatar placeholder<?= ord($staffMember->getUserID()) % 3 ?>'>

      <?php } ?>

<?= "{$staffMember->getAttribute('first_name')} {$staffMember->getAttribute('last_name')}, " . ($staffMember->getAttribute('job_title') ?: 'Jane\'s Walk'); ?>

        <a href="mailto:<?= ($email = $staffMember->getUserEmail()) ?>"><?= $email ?>

<?= $staffMember->getAttribute('bio') ?>

  <?php } ?>

Allow other groups if set in block name

Allow other groups if set in block name


<?php
namespace DreadLabs\VantomasWebsite\SecretSanta\Pair;

use DreadLabs\VantomasWebsite\SecretSanta\Donee\DoneeInterface;
use DreadLabs\VantomasWebsite\SecretSanta\Donor\DonorInterface;

interface RepositoryInterface
{

    /**
     * Finds a pair for the given donor
     *
     * @param DonorInterface $donor
     * @return PairInterface
     */
    public function findPairFor(DonorInterface $donor);

    /**
     * Determines if the given donor/donee pair is mutual
     *
     * @param DonorInterface $donor
     * @param DoneeInterface $donee
     * @return bool
     */
    public function isPairMutually(DonorInterface $donor, DoneeInterface $donee);

    /**
     * @param PairInterface $pair
     * @return void
     */
    public function add(PairInterface $pair);
}

<?php
namespace DreadLabs\VantomasWebsite\SecretSanta\Pair;

use DreadLabs\VantomasWebsite\SecretSanta\Donee\DoneeInterface;
use DreadLabs\VantomasWebsite\SecretSanta\Donor\DonorInterface;

interface RepositoryInterface
{

    /**
     * Finds a pair for the given donor
     *
     * @param DonorInterface $donor
     * @return PairInterface
     */
    public function findPairFor(DonorInterface $donor);

    /**
     * Determines if the given donor/donee pair is mutual
     *
     * @param DonorInterface $donor
     * @param DoneeInterface $donee
     * @return bool
     */
    public function isPairMutually(DonorInterface $donor, DoneeInterface $donee);

    /**
     * Flags if the incoming donor / donee pair is already existing
     *
     * @param DonorInterface $donor
     * @param DoneeInterface $donee
     * @return bool
     */
    public function isPairExisting(DonorInterface $donor, DoneeInterface $donee);

    /**
     * @param PairInterface $pair
     * @return void
     */
    public function add(PairInterface $pair);
}

[TASK] Add missing method to the PairRepository


<?php
/**
 * Created by PhpStorm.
 * User: Fabian
 * Date: 29.05.17
 * Time: 16:50.
 */

return [

    'breadcrumb' => [
        'root' => 'Files',
    ],

    'routes' => [
        'middleware' => [],
        'prefix'     => env('MEDIA_MANAGER_ROUTE_PREFIX', '/admin/'),
    ],

    'disk'   => env('MEDIA_MANAGER_STORAGE_DISK', 'public'),
    'access' => env('MEDIA_MANAGER_ACCESS', 'public'),
];

<?php
/**
 * Created by PhpStorm.
 * User: Fabian
 * Date: 29.05.17
 * Time: 16:50.
 */

return [

    /**
     * Change the bread crumb behaviour.
     * Here you can configure the text output for the root folder of the media-manager...
     */
    'breadcrumb' => [
        'root' => 'Files',
    ],

    /**
     * Change the route behaviour.
     * Here you can apply additional middleware to be applied to media-manager routes
     * as well as setting a custom path prefix for the media-manager routes to be
     * accessible from...
     */
    'routes' => [
        'middleware' => [],
        'prefix'     => env('MEDIA_MANAGER_ROUTE_PREFIX', '/admin/'),
    ],

    /**
     * Set the disk for the media manager to use, this can be one of the disks defined
     * within your projects `config/filesystems.php` file...
     */
    'disk'   => env('MEDIA_MANAGER_STORAGE_DISK', 'public'),

    /**
     * Configure the Access Mode of the uploaded files.
     * By default S3 uploads are private, we're setting them to public here.
     */
    'access' => env('MEDIA_MANAGER_ACCESS', 'public'),
];

Add comments for the config file

Add comments for the config file


<?php
//this plugin replaces %redirect% dynamic (so viewCache can be enabled)
class Kwc_User_Login_Plugin extends Kwf_Component_Plugin_Abstract
    implements Kwf_Component_Plugin_Interface_ViewAfterChildRender
{
    public function processOutput($output, $renderer)
    {
        if (strpos($output, '%redirect%') !== false) {
            $r = isset($_GET['redirect']) ? $_GET['redirect'] : '';
            $output = str_replace('%redirect%', $r, $output);
        }
        return $output;
    }
}

<?php
//this plugin replaces %redirect% dynamic (so viewCache can be enabled)
class Kwc_User_Login_Plugin extends Kwf_Component_Plugin_Abstract
    implements Kwf_Component_Plugin_Interface_ViewAfterChildRender
{
    public function processOutput($output, $renderer)
    {
        if (strpos($output, '%redirect%') !== false) {
            $r = isset($_GET['redirect']) ? $_GET['redirect'] : '';
            $output = str_replace('%redirect%', htmlspecialchars($r), $output);
        }
        return $output;
    }
}

Fix XSS issue with redirects parameter

Fix XSS issue with redirects parameter


<?php namespace Neomerx\JsonApi\Contracts\Integration;

/**
 * Copyright 2015 info@neomerx.com (www.neomerx.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.
 */

/**
 * @package Neomerx\JsonApi
 */
interface ExceptionThrowerInterface
{
    /**
     * Throw 'Bad request' exception (HTTP code 400).
     *
     * @return void
     */
    public function throwBadRequest();

    /**
     * Throw 'Not Acceptable' exception (HTTP code 406).
     *
     * @return void
     */
    public function throwNotAcceptable();

    /**
     * Throw 'Unsupported Media Type' exception (HTTP code 415).
     *
     * @return void
     */
    public function throwUnsupportedMediaType();
}

<?php namespace Neomerx\JsonApi\Contracts\Integration;

/**
 * Copyright 2015 info@neomerx.com (www.neomerx.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.
 */

/**
 * @package Neomerx\JsonApi
 */
interface ExceptionThrowerInterface
{
    /**
     * Throw 'Bad request' exception (HTTP code 400).
     *
     * @return void
     */
    public function throwBadRequest();

    /**
     * Throw 'Forbidden' exception (HTTP code 403).
     *
     * @return void
     */
    public function throwForbidden();
    /**
     * Throw 'Not Acceptable' exception (HTTP code 406).
     *
     * @return void
     */
    public function throwNotAcceptable();

    /**
     * Throw 'Conflict' exception (HTTP code 409).
     *
     * @return void
     */
    public function throwConflict();

    /**
     * Throw 'Unsupported Media Type' exception (HTTP code 415).
     *
     * @return void
     */
    public function throwUnsupportedMediaType();
}

Add methods for 403 and 409 HTTP errors

Add methods for 403 and 409 HTTP errors


<?php namespace Picqer\Carriers\SendCloud\Query;

use Picqer\Carriers\SendCloud\Connection;

/**
 * Trait FindOne
 *
 * @method Connection connection()
 *
 * @package Picqer\Carriers\SendCloud\Persistance
 */
trait FindOne {

    public function find($id)
    {
        $result = $this->connection()->get($this->url . '/' . urlencode($id));

        if (!array_key_exists($this->namespaces['singular'], $result)) {
            return null;
        }

        return new self($this->connection(), $result[$this->namespaces['singular']]);
    }

}

<?php namespace Picqer\Carriers\SendCloud\Query;

use Picqer\Carriers\SendCloud\Connection;
use Picqer\Carriers\SendCloud\Model;

/**
 * Trait FindOne
 *
 * @method Connection connection()
 *
 * @package Picqer\Carriers\SendCloud\Persistance
 */
trait FindOne {

    /**
     * @param $id
     * @return Model|FindOne
     */
    public function find($id)
    {
        $result = $this->connection()->get($this->url . '/' . urlencode($id));

        if (!array_key_exists($this->namespaces['singular'], $result)) {
            return null;
        }

        return new self($this->connection(), $result[$this->namespaces['singular']]);
    }

}

Add return type to annotations for find method


<?
    $board = json_decode($_POST['board']);
    $done = false;
    foreach($board as $x => $col) {
        foreach($col as $y => $cell) {
            if($cell == 0) {
                $done = true;
                break;
            }
        }
        if($done) break;
    }

    if($done) echo json_encode(array($x, $y));
    else echo 'fail';
?>

<?
    $board = json_decode($_POST['board']);

    if($_POST['player'] == 2) {
        foreach($board as $x => $col) {
            foreach($col as $y => $cell) {
                if($cell == 1) {
                    $x1 = $x;
                    $y1 = $y;
                } elseif($cell == 2) {
                    $x2 = $x;
                    $y2 = $y;
                }
            }
        }

        $dx = $x1 - $x2;
        $dy = $y1 - $y2;

        if(abs($dx) > abs($dy)) {
            if($dx > 0) {
                echo 2;
            } else {
                echo 0;
            }
        } else {
            if($dy > 0) {
                echo 3;
            } else {
                echo 1;
            }
        }

    } else {
        echo rand(0, 3);
    }
?>

Update example client to process new game rules


<?php
$sConfigFile = 'conf/production/config-itop.php';
$sStartPage = './pages/UI.php';
$sSetupPage = './setup/index.php';

/**
 * Check that the configuration file exists and has the appropriate access rights
 * If the file does not exist, launch the configuration wizard to create it
 */
if (file_exists($sConfigFile))
{
	if (!is_readable($sConfigFile))
	{
		echo "
Error: Unable to read the configuration file: '$sConfigFile'. Please check the access rights on this file.
";
	}
	else if (is_writable($sConfigFile))
	{
		echo "
Security Warning: the configuration file '$sConfigFile' should be read-only.
";
		echo "
Please modify the access rights to this file.
";
		echo "
Click here to ignore this warning and continue to run iTop.
";
	}
	else
	{
		header("Location: $sStartPage");
	}
}
else
{
	// Config file does not exist, need to run the setup wizard to create it
	header("Location: $sSetupPage");
}
?>

<?php
$sConfigFile = 'conf/production/config-itop.php';
$sStartPage = './pages/UI.php';
$sSetupPage = './setup/index.php';

/**
 * Check that the configuration file exists and has the appropriate access rights
 * If the file does not exist, launch the configuration wizard to create it
 */
if (file_exists(dirname(__FILE__).'/'.$sConfigFile))
{
	if (!is_readable($sConfigFile))
	{
		echo "
Error: Unable to read the configuration file: '$sConfigFile'. Please check the access rights on this file.
";
	}
	else if (is_writable($sConfigFile))
	{
		echo "
Security Warning: the configuration file '$sConfigFile' should be read-only.
";
		echo "
Please modify the access rights to this file.
";
		echo "
Click here to ignore this warning and continue to run iTop.
";
	}
	else
	{
		header("Location: $sStartPage");
	}
}
else
{
	// Config file does not exist, need to run the setup wizard to create it
	header("Location: $sSetupPage");
}
?>

Make sure that we reference the config file using an absolute path... just in case...


<?php

require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/config_sample.php';

require_once __DIR__.'/util/utils-loader.php';
require_once __DIR__.'/models/models-loader.php';
require_once __DIR__.'/controllers/controllers-loader.php';

$appConfig = [
	'settings' => [
		'displayErrorDetails' => true
	],
	'config' 	=> $config,
	'dbManager' => new \Utility\DatabaseManager($config['db']['hostname'], $config['db']['username'], $config['db']['password'], $config['db']['dbname'])
];

$app = new Slim\App($appConfig);

require_once './router.php';

$app->run();

<?php

require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/config.php';

require_once __DIR__.'/util/utils-loader.php';
require_once __DIR__.'/models/models-loader.php';
require_once __DIR__.'/controllers/controllers-loader.php';

$appConfig = [
	'settings' => [
		'displayErrorDetails' => true
	],
	'config' 	=> $config,
	'dbManager' => new \Utility\DatabaseManager($config['db']['hostname'], $config['db']['username'], $config['db']['password'], $config['db']['dbname'])
];

$app = new Slim\App($appConfig);

require_once './router.php';

$app->run();

Change config from sample file to actually file.


<title>Number Counter</title>

Counting to <?php echo "$numend".":"."
"."
";

	$numstart=0;
	$numend=255;

			for ($num=$numstart; $num<=$numend; $num++)
			{
			echo $num."
";
			}
	?>

Counting backwards from <?php echo $numend.":"?>

	<?php
			for ($num=$numend; $num>=$numstart; $num--)
			{
			echo $num."
";
			}

	?>

<title>Number Counter</title>

<?php
echo"
Counting to "$numend".":"."
"."
"";

	$numstart=0;
	$numend=255;

			for ($num=$numstart; $num<=$numend; $num++)
			{
			echo $num."
";
			}
	?>

Counting backwards from <?php echo $numend.":"?>

	<?php
			for ($num=$numend; $num>=$numstart; $num--)
			{
			echo $num."
";
			}

	?>

Include variables for all counts.

Include variables for all counts.


<?php

namespace Edujugon\GoogleAds\Providers;

use Edujugon\GoogleAds\Console\RefreshTokenCommand;
use Edujugon\GoogleAds\GoogleAds;
use Illuminate\Support\ServiceProvider;

class GoogleAdsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $config_path = function_exists('config_path') ? config_path('google-ads.php') : 'google-ads.php';

        $this->publishes([
            __DIR__.'/../Config/config.php' => $config_path,
        ], 'config');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        // Console commands
        $this->commands([
            RefreshTokenCommand::class,
        ]);

        $this->app->bind('edujugonGoogleAds', function ($app) {
            return new GoogleAds();
        });

    }
}

<?php

namespace Edujugon\GoogleAds\Providers;

use Edujugon\GoogleAds\Console\RefreshTokenCommand;
use Edujugon\GoogleAds\GoogleAds;
use Illuminate\Support\ServiceProvider;

class GoogleAdsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $config_path = function_exists('config_path') ? config_path('google-ads.php') : 'google-ads.php';

        $this->publishes([
            __DIR__.'/../Config/config.php' => $config_path,
        ], 'config');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        // Console commands
        $this->commands([
            RefreshTokenCommand::class,
        ]);

        $this->app->singleton('edujugonGoogleAds', function ($app) {
            return new GoogleAds();
        });

    }
}

Update Register from bind to singleton

Update
Register from bind to singleton


<?
require "../../../lib.php";
require_once "{$root}/lib/Twig/Autoloader.php";

Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem("{$root}/admin/tpl/");
$twig = new Twig_Environment($loader, array());

$template = $twig->loadTemplate('questionaire/results/modules.html');

$questionaireID = $_GET["questionaireID"];
$alerts = array();

$stmt = new tidy_sql($db, "
SELECT Modules.ModuleID,Modules.ModuleTitle,(
	SELECT COUNT(DISTINCT Answers.AnswerID)
	FROM Answers
	JOIN AnswerGroup ON AnswerGroup.QuestionaireID=(SELECT Modules.QuestionaireID)
	WHERE Answers.ModuleID=Modules.ModuleID
) as NumAnswers
FROM Modules
WHERE Modules.QuestionaireID=?
ORDER BY NumAnswers DESC
	", "i");
$modules = $stmt->query($questionaireID);

echo $template->render(array(
	"url"=>$url, "questionaireID"=> $questionaireID, "alerts"=>$alerts,
	"modules"=>$modules
));

<?
require "../../../lib.php";
require_once "{$root}/lib/Twig/Autoloader.php";

Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem("{$root}/admin/tpl/");
$twig = new Twig_Environment($loader, array());

$template = $twig->loadTemplate('questionaire/results/modules.html');

$questionaireID = $_GET["questionaireID"];
$alerts = array();

$stmt = new tidy_sql($db, "
SELECT Modules.ModuleID,Modules.ModuleTitle,(
	SELECT COUNT(DISTINCT Answers.AnswerID)
	FROM Answers
	JOIN AnswerGroup ON Answers.AnswerID=AnswerGroup.AnswerID
	WHERE Answers.ModuleID=Modules.ModuleID AND
	AnswerGroup.QuestionaireID=Modules.QuestionaireID
) as NumAnswers
FROM Modules
WHERE Modules.QuestionaireID=?
ORDER BY NumAnswers DESC
	", "i");
$modules = $stmt->query($questionaireID);

echo $template->render(array(
	"url"=>$url, "questionaireID"=> $questionaireID, "alerts"=>$alerts,
	"modules"=>$modules
));

Fix answer count if multiple questionaires


<?php

/**
 * @file
 * Contains \Eloqua\Api\Assets\Email\Deployment.
 */

namespace Eloqua\Api\Assets\Email;

use Eloqua\Api\AbstractApi;
use Eloqua\Api\CreatableInterface;
use Eloqua\Api\ReadableInterface;
use Eloqua\Api\SearchableInterface;
use Eloqua\Exception\InvalidArgumentException;

/**
 * Eloqua e-mail group.
 */
class Deployment extends AbstractApi implements CreatableInterface, ReadableInterface, SearchableInterface {

  /**
   * {@inheritdoc}
   */
  public function search($search, array $options = array()) {
    return $this->get('assets/email/deployments', array_merge(array(
      'search' => $search,
    ), $options));
  }

  /**
   * {@inheritdoc}
   */
  public function show($id, $depth = 'complete', $extensions = null) {
    return $this->get('assets/email/deployment/' . rawurlencode($id), array(
      'depth' => $depth,
      'extensions' => $extensions,
    ));
  }

  /**
   * {@inheritdoc}
   */
  public function create($data) {
    // Validate the request before sending it.
    $required = array('name', 'email', 'contacts');

    foreach ($required as $key) {
      if (!array_key_exists($key, $data) || empty($data[$key])) {
        throw new InvalidArgumentException("You must specify a non-empty value for $key.");
      }
    }

    return $this->post('assets/email/deployment', $data);
  }

}

<?php

/**
 * @file
 * Contains \Eloqua\Api\Assets\Email\Deployment.
 */

namespace Eloqua\Api\Assets\Email;

use Eloqua\Api\AbstractApi;
use Eloqua\Api\CreatableInterface;
use Eloqua\Api\ReadableInterface;
use Eloqua\Api\SearchableInterface;
use Eloqua\Exception\InvalidArgumentException;

/**
 * Eloqua e-mail group.
 */
class Deployment extends AbstractApi implements CreatableInterface, ReadableInterface, SearchableInterface {

  /**
   * {@inheritdoc}
   */
  public function search($search, array $options = array()) {
    return $this->get('assets/email/deployments', array_merge(array(
      'search' => $search,
    ), $options));
  }

  /**
   * {@inheritdoc}
   */
  public function show($id, $depth = 'complete', $extensions = null) {
    return $this->get('assets/email/deployment/' . rawurlencode($id), array(
      'depth' => $depth,
      'extensions' => $extensions,
    ));
  }

  /**
   * {@inheritdoc}
   */
  public function create($data) {
    // Validate the request before sending it.
    $required = array('name', 'email', 'contacts', 'type');

    foreach ($required as $key) {
      if (!array_key_exists($key, $data) || empty($data[$key])) {
        throw new InvalidArgumentException("You must specify a non-empty value for $key.");
      }
    }

    return $this->post('assets/email/deployment', $data);
  }

}

Add a missing required param to deployment create


<?php

require_once("database.php");

$db = connect_save();

if ($db === null)
{
	echo "Result:4";
	die();
}

if ($_REQUEST["myl"] != "")
{
  $temp = split(":", $_REQUEST["myl"]);
  $mcc = $temp[0];
  $mnc = $temp[1];
  $lac = $temp[2];
  $cid = $temp[3];
} else
{
  $mcc = $_REQUEST["mcc"];
  $mnc = $_REQUEST["mnc"];
  $lac = $_REQUEST["lac"];
  $cid = $_REQUEST["cid"];
}

if ( $mcc == "" || $mnc == "" || $lac == "" || $cid == "" )
{
		echo "Result:7"; // CellID not specified
	 	die();
}

$result = $db->exec_sql("SELECT Latitude, Longitude FROM cellids WHERE CellID=? ORDER BY DateAdded DESC LIMIT 0,1", "$mcc-$mnc-$lac-$cid");

if ( $row=$result->fetch() )
        echo "Result:0|$row[Latitude]|$row[Longitude]";
else
	echo "Result:6"; // No lat/long for specified CellID

die();

?>

<?php

require_once("config.php");

if(!@mysql_connect("$DBIP","$DBUSER","$DBPASS"))
{
	echo "Result:4";
	die();
}

mysql_select_db("$DBNAME");

if ($_REQUEST["myl"] != "")
{
  $temp = split(":", $_REQUEST["myl"]);
  $mcc = $temp[0];
  $mnc = $temp[1];
  $lac = $temp[2];
  $cid = $temp[3];
} else
{
  $mcc = $_REQUEST["mcc"];
  $mnc = $_REQUEST["mnc"];
  $lac = $_REQUEST["lac"];
  $cid = $_REQUEST["cid"];
}

if ( $mcc == "" || $mnc == "" || $lac == "" || $cid == "" )
{
		echo "Result:7"; // CellID not specified
	 	die();
}

$result=mysql_query("Select latitude,longitude FROM cellids WHERE cellid='$mcc-$mnc-$lac-$cid' order by dateadded desc limit 0,1");

if ( $row=mysql_fetch_array($result) )
	echo "Result:0|".$row['latitude']."|".$row['longitude'];
else
	echo "Result:6"; // No lat/long for specified CellID

die();

?>

Revert "Use PDO in the local cellid script"


<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @package Zigra
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    const VERSION = '0.7.4';
}

<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @package Zigra
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    const VERSION = '0.7.5';
}

Set release version to 0.7.5

Set release version to 0.7.5


<?php
namespace Scat;

class Payment extends \Model {
  public static $methods= array(
    'cash' => "Cash",
    'change' => "Change",
    'credit' => "Credit Card",
    'square' => "Square",
    'stripe' => "Stripe",
    'gift' => "Gift Card",
    'check' => "Check",
    'dwolla' => "Dwolla",
    'paypal' => "PayPal",
    'discount' => "Discount",
    'bad' => "Bad Debt",
    'donation' => "Donation",
    'withdrawal' => "Withdrawal",
    'internal' => "Internal",
  );
}

<?php
namespace Scat;

class Payment extends \Model {
  public static $methods= array(
    'cash' => "Cash",
    'change' => "Change",
    'credit' => "Credit Card",
    'square' => "Square",
    'stripe' => "Stripe",
    'gift' => "Gift Card",
    'check' => "Check",
    'dwolla' => "Dwolla",
    'paypal' => "PayPal",
    'amazon' => "Amazon Pay",
    'discount' => "Discount",
    'bad' => "Bad Debt",
    'donation' => "Donation",
    'withdrawal' => "Withdrawal",
    'internal' => "Internal",
  );
}

Add Amazon Pay payment method

Add Amazon Pay payment method


<?php
/**
 * App Core Framework Version
 **/

namespace App;

define('APP_CORE_VERSION', '20160922');
define('APP_CORE_RELEASE', 'Alpha');

class Version
{
    public static function getVersion()
    {
        return APP_CORE_VERSION;
    }

    public static function getVersionText()
    {
        return 'v'.APP_CORE_VERSION.' '.APP_CORE_RELEASE;
    }

}

<?php
/**
 * App Core Framework Version
 **/

namespace App;

define('APP_CORE_VERSION', '0.3.0-20160923');
define('APP_CORE_RELEASE', 'Alpha');

class Version
{
    public static function getVersion()
    {
        return APP_CORE_VERSION;
    }

    public static function getVersionText()
    {
        return 'v'.APP_CORE_VERSION.' '.APP_CORE_RELEASE;
    }

}

Update version to match new tagged release system.


<?php
// check if groups are not empty
foreach ($groups as $key => $group) {
    $exists = false;
    foreach ($group as $action => $config) {
        $subaction = is_array($config) ? $action : $config;
        if (array_key_exists($subaction, $links)) {
            $exists = true;
        }
    }
    if (!$exists) {
        unset($groups[$key]);
    }
}
?>

<?php foreach ($groups as $key => $group) : ?>

        <?= $this->Html->link(
            sprintf("%s %s", $key, $this->Html->tag('span', '', ['class' => 'caret'])),
            '#',
            ['class' => 'btn btn-default dropdown-toggle', 'escape' => false, 'data-toggle' => 'dropdown', 'aria-haspopup' => true, 'aria-expanded' => false]
        ) ?>

            <?php foreach ($group as $action => $config) : ?>
                <?php $subaction = is_array($config) ? $action : $config; ?>
                <?php if (array_key_exists($subaction, $links)): ?>

<?= $this->element('action-button', ['config' => $links[$subaction]]); ?>

                <?php endif; ?>
            <?php endforeach; ?>

<?php
endforeach;

Fix class in button group dropdown

Fix class in button group dropdown


<?php
declare(strict_types=1);
/**
 * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

namespace OCA\OAuth2\Settings;

use OCP\AppFramework\Http\TemplateResponse;
use OCP\Settings\ISettings;

class Admin implements ISettings {

	public function getForm(): TemplateResponse {
		return new TemplateResponse(
			'oauth2',
			'admin',
			[],
			''
		);
	}

	public function getSection(): string {
		return 'security';
	}

	public function getPriority(): int {
		return 0;
	}
}

<?php
declare(strict_types=1);
/**
 * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

namespace OCA\OAuth2\Settings;

use OCP\AppFramework\Http\TemplateResponse;
use OCP\Settings\ISettings;

class Admin implements ISettings {

	public function getForm(): TemplateResponse {
		return new TemplateResponse(
			'oauth2',
			'admin',
			[],
			''
		);
	}

	public function getSection(): string {
		return 'security';
	}

	public function getPriority(): int {
		return 100;
	}
}

Move OAuth down in admin security settings

For #16076

Signed-off-by: Roeland Jago Douma <982d370f7dc34a05b4abe8788f899578d515262d@famdouma.nl>