<!-- Twitter sharing -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="{{ $title ?? config('app.name') }}">
<meta name="twitter:creator" content="@laravelio" />
<!-- /Twitter sharing -->

<!-- Facebook sharing -->
<meta property="og:url" content="{{ url()->current() }}" />
<meta property="og:title" content="{{ $title ?? config('app.name') }}" />
<meta property="og:image" content="{{ asset('images/laravelio-share.png') }}" />
<!-- /Facebook sharing -->

<!-- Twitter sharing -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="{{ isset($title) ? $title.' | ' : '' }}{{ config('app.name') }}">
<meta name="twitter:creator" content="@laravelio" />
<!-- /Twitter sharing -->

<!-- Facebook sharing -->
<meta property="og:url" content="{{ url()->current() }}" />
<meta property="og:title" content="{{ isset($title) ? $title.' | ' : '' }}{{ config('app.name') }}" />
<meta property="og:image" content="{{ asset('images/laravelio-share.png') }}" />
<!-- /Facebook sharing -->

Append app name to title

Append app name to title


<?= t('Keyboard shortcuts') ?>

<?= t('Download content') ?> = d

<?= t('Previous item') ?> = p <?= t('or') ?> j

<?= t('Next item') ?> = n <?= t('or') ?> k

<?= t('Mark as read or unread') ?> = m

<?= t('Open original link') ?> = v

<?= t('Open item') ?> = o

<?= t('Bookmark item') ?> = f

<?= t('Previous page') ?> = h

<?= t('Next page') ?> = l

<?= t('Show help') ?> = ?

<?= t('Close help') ?> = q

<?= t('Keyboard shortcuts') ?>

<?= t('Go to unread') ?> = gu

<?= t('Go to bookmarks') ?> = gb

<?= t('Go to history') ?> = gh

<?= t('Go to subscriptions') ?> = gs

<?= t('Go to preferences') ?> = gp

<?= t('Download content') ?> = d

<?= t('Previous item') ?> = p <?= t('or') ?> j

<?= t('Next item') ?> = n <?= t('or') ?> k

<?= t('Mark as read or unread') ?> = m

<?= t('Open original link') ?> = v

<?= t('Open item') ?> = o

<?= t('Bookmark item') ?> = f

<?= t('Previous page') ?> = h

<?= t('Next page') ?> = l

<?= t('Show help') ?> = ?

<?= t('Close help') ?> = q

Add Google Style 2 key shortcuts for main pages


<?php

namespace Structr\Tree\Composite;

use Structr\Tree\Base\PrototypeNode;

use Structr\Exception;

class MapKeyNode extends PrototypeNode
{
    private $_required = true;
    private $_optional = false;
    private $_defaultValue = null;

    private $_name;

    public function setName($name) {
        $this->_name = $name;
    }

    public function getName() {
        return $this->_name;
    }

    public function defaultValue($value) {
        $this->_required = false;
        $this->_defaultValue = $value;

        return $this;
    }

    public function optional() {
        $this->_optional = true;

        return $this;
    }

    public function isOptional() {
        return $this->_optional;
    }

    public function endKey() {
        return $this->parent();
    }

    public function _walk_value_unset() {
        if ($this->_required) {
            throw new Exception("Missing key '{$this->_name}'");
        }

        return $this->_defaultValue;
    }
}

<?php

namespace Structr\Tree\Composite;

use Structr\Tree\Base\PrototypeNode;

use Structr\Exception;

class MapKeyNode extends PrototypeNode
{
    private $_required = true;
    private $_optional = false;
    private $_defaultValue = null;

    private $_name;

    public function setName($name) {
        $this->_name = $name;
    }

    public function getName() {
        return $this->_name;
    }

    public function defaultValue($value) {
        $this->_required = false;
        $this->_defaultValue = $value;

        return $this;
    }

    public function optional($optional = true) {
        $this->_optional = $optional;

        return $this;
    }

    public function isOptional() {
        return $this->_optional;
    }

    public function endKey() {
        return $this->parent();
    }

    public function _walk_value_unset() {
        if ($this->_required) {
            throw new Exception("Missing key '{$this->_name}'");
        }

        return $this->_defaultValue;
    }
}

Add optional parameter to optional()

Add optional parameter to optional()


<?php

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

namespace Picodexter\ParameterEncryptionBundle\Console\Processor;

use Picodexter\ParameterEncryptionBundle\Configuration\AlgorithmConfigurationContainerInterface;
use Symfony\Component\Console\Helper\Table;

/**
 * AlgorithmListProcessor.
 */
class AlgorithmListProcessor implements AlgorithmListProcessorInterface
{
    /**
     * @var AlgorithmConfigurationContainerInterface
     */
    private $algorithmConfigContainer;

    /**
     * Constructor.
     *
     * @param AlgorithmConfigurationContainerInterface $algorithmContainer
     */
    public function __construct(AlgorithmConfigurationContainerInterface $algorithmContainer)
    {
        $this->algorithmConfigContainer = $algorithmContainer;
    }

    /**
     * @inheritDoc
     */
    public function renderAlgorithmListTable(Table $table)
    {
        $table->setHeaders(['Algorithm ID', 'Encryption class', 'Decryption class']);

        foreach ($this->algorithmConfigContainer->getAlgorithmConfigurations() as $algorithm) {
            $table->addRow([
                $algorithm->getId(),
                get_class($algorithm->getEncrypter()),
                get_class($algorithm->getDecrypter())
            ]);
        }

        $table->render();
    }
}

<?php

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

namespace Picodexter\ParameterEncryptionBundle\Console\Processor;

use Picodexter\ParameterEncryptionBundle\Configuration\AlgorithmConfigurationContainerInterface;
use Symfony\Component\Console\Helper\Table;

/**
 * AlgorithmListProcessor.
 */
class AlgorithmListProcessor implements AlgorithmListProcessorInterface
{
    /**
     * @var AlgorithmConfigurationContainerInterface
     */
    private $algorithmConfigContainer;

    /**
     * Constructor.
     *
     * @param AlgorithmConfigurationContainerInterface $algorithmContainer
     */
    public function __construct(AlgorithmConfigurationContainerInterface $algorithmContainer)
    {
        $this->algorithmConfigContainer = $algorithmContainer;
    }

    /**
     * @inheritDoc
     */
    public function renderAlgorithmListTable(Table $table)
    {
        $table->setHeaders(['Algorithm ID', 'Encryption service name', 'Decryption service name']);

        foreach ($this->algorithmConfigContainer->getAlgorithmConfigurations() as $algorithm) {
            $table->addRow([
                $algorithm->getId(),
                $algorithm->getEncrypterServiceName(),
                $algorithm->getDecrypterServiceName()
            ]);
        }

        $table->render();
    }
}

Change output for algorithm list to service name instead of class name


<?php
class Layout
{
	private $cache;

	private function mime($path)
	{
		switch(pathinfo($path, PATHINFO_EXTENSION))
		{
		case 'css': return 'text/css';
		case 'png': return 'image/png';
		case 'ttf': return 'application/x-font-ttf';
		default:    return (new finfo(FILEINFO_MIME_TYPE))->file($path);
		}
	}

	private function embed($path)
	{
		return preg_replace_callback
		(
			'/«([^«»]++)»/',
			function($match)
			{
				$mime = $this->mime($match[1]);
				$data = base64_encode((strpos($mime, 'text/') === 0) ? $this->embed($match[1]) : file_get_contents($match[1]));
				return "data:$mime;base64,$data";
			},
			file_get_contents($path)
		);
	}

	function test_embed($path)
	{
		echo $this->embed($path);
	}

	/**
	 * Creates a new instance based on the given folder.
	 * @param string $dir
	 */
	function __construct($dir)
	{
		$cache = "$dir/.cache/";

		if(!is_dir($cache) && !mkdir($cache, 0700))
			trigger_error('Cannot create cache directory. Performance will be affected.');
		else
			$this->cache = $cache;
	}
}

<?php
class Layout
{
	private $cache;

	private function mime($path)
	{
		switch(pathinfo($path, PATHINFO_EXTENSION))
		{
		case 'css': return 'text/css';
		case 'png': return 'image/png';
		case 'ttf': return 'application/x-font-ttf';
		default:    return (new finfo(FILEINFO_MIME_TYPE))->file($path);
		}
	}

	private function uri($path)
	{
		$mime = $this->mime($path);
		$data = base64_encode((strpos($mime, 'text/') === 0) ? $this->embed($path) : file_get_contents($path));
		return "data:$mime;base64,$data";
	}

	private function embed($path)
	{
		return preg_replace_callback
		(
			'/«([^«»]++)»/',
			function($match)
			{
				return $this->uri($match[1]);
			},
			file_get_contents($path)
		);
	}

	/**
	 * Creates a new instance based on the given folder.
	 * @param string $dir
	 */
	function __construct($dir)
	{
		$cache = "$dir/.cache/";

		if(!is_dir($cache) && !mkdir($cache, 0700))
			trigger_error('Cannot create cache directory. Performance will be affected.');
		else
			$this->cache = $cache;
	}
}

Make data URI in a separate method and remove some litter


<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php';

/**
 * @backupGlobals disabled
 */
class DetailsTest extends PHPUnit_Framework_TestCase
{
    public function testExecute()
    {
        list($service) = \WebService::factory('listing/Details');
        $results = ($service->execute(array('id' => 13)));
        $this->assertEquals(13, $results['organism_id']);
    }
}
?>

<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php';

/**
 * @backupGlobals disabled
 */
class DetailsTest extends PHPUnit_Framework_TestCase
{
    public function testExecute()
    {
        list($service) = \WebService::factory('details/Organisms');
        $results = ($service->execute(array('id' => 13)));
        $this->assertEquals(13, $results['organism_id']);
    }
}
?>

Update path to webservice in test

Update path to webservice in test


<?php

namespace wcf\system\cache\command;

use wcf\data\option\OptionEditor;
use wcf\data\package\update\server\PackageUpdateServer;
use wcf\system\cache\CacheHandler;
use wcf\system\cache\event\CacheCleared;
use wcf\system\event\EventHandler;
use wcf\system\language\LanguageFactory;
use wcf\system\style\StyleHandler;
use wcf\system\user\storage\UserStorageHandler;

/**
 * Performs a full cache clear.
 *
 * @author  Tim Duesterhus
 * @copyright   2001-2021 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Cache\Event
 * @since   6.0
 */
final class ClearCache
{
    private EventHandler $eventHandler;

    public function __construct()
    {
        $this->eventHandler = EventHandler::getInstance();
    }

    public function __invoke()
    {
        OptionEditor::resetCache();

        UserStorageHandler::getInstance()->clear();

        StyleHandler::resetStylesheets();

        LanguageFactory::getInstance()->deleteLanguageCache();

        CacheHandler::getInstance()->flushAll();

        PackageUpdateServer::resetAll();

        $this->eventHandler->fire(
            new CacheCleared()
        );
    }
}

<?php

namespace wcf\system\cache\command;

use wcf\data\option\OptionEditor;
use wcf\data\package\update\server\PackageUpdateServer;
use wcf\system\cache\CacheHandler;
use wcf\system\cache\event\CacheCleared;
use wcf\system\event\EventHandler;
use wcf\system\language\LanguageFactory;
use wcf\system\style\StyleHandler;
use wcf\system\user\storage\UserStorageHandler;

/**
 * Performs a full cache clear.
 *
 * @author  Tim Duesterhus
 * @copyright   2001-2021 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Cache\Command
 * @since   6.0
 */
final class ClearCache
{
    private EventHandler $eventHandler;

    public function __construct()
    {
        $this->eventHandler = EventHandler::getInstance();
    }

    public function __invoke()
    {
        OptionEditor::resetCache();

        UserStorageHandler::getInstance()->clear();

        StyleHandler::resetStylesheets();

        LanguageFactory::getInstance()->deleteLanguageCache();

        CacheHandler::getInstance()->flushAll();

        PackageUpdateServer::resetAll();

        $this->eventHandler->fire(
            new CacheCleared()
        );
    }
}

Fix `@package` annotation in ClearCache command


<?php

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

namespace Sylius\Component\Core\Model;

use Sylius\Component\Taxonomy\Model\Taxonomy as BaseTaxonomy;

class Taxonomy extends BaseTaxonomy
{
    /**
     * {@inheritdoc}
     */
    public function __construct()
    {
        parent::__construct();
        $this->setRoot(new Taxon());
    }
}

Fix the issue with not generating slugs

Fix the issue with not generating slugs


<?php

namespace App\Providers;

use Facebook\WebDriver\WebDriverBy;
use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\Browser;

class DuskServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Browser::macro('vuetifySelect', function (string $selector, string $value) {
            $xpath = "//div[contains(concat(' ', normalize-space(@class), ' '), 'v-menu__content') and contains(concat(' ', normalize-space(@class), ' '), 'menuable__content__active')]//div[text()='$value']";
            $this->with("$selector", function (Browser $element) {
                $element->click('.v-select');
            })->waitFor('.menuable__content__active')
                ->driver->findElement(WebDriverBy::xpath($xpath))->click();
            $this->waitUntilMissing('.menuable__content__active');

            return $this;
        });
    }
}

<?php

namespace App\Providers;

use Facebook\WebDriver\WebDriverBy;
use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\Browser;
use PHPUnit\Framework\Assert as PHPUnit;

class DuskServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Browser::macro('vuetifySelect', function (string $selector, string $value) {
            $xpath = "//div[contains(concat(' ', normalize-space(@class), ' '), 'v-menu__content') and contains(concat(' ', normalize-space(@class), ' '), 'menuable__content__active')]//div[text()='$value']";
            $this->with("$selector", function (Browser $element) {
                $element->click('.v-select');
            })->waitFor('.menuable__content__active')
                ->driver->findElement(WebDriverBy::xpath($xpath))->click();
            $this->waitUntilMissing('.menuable__content__active');

            return $this;
        });

        Browser::macro('assertAttribute', function (string $selector, string $attribute, string $value) {
            $actual = $this->resolver->findOrFail($selector)->getAttribute($attribute);

            PHPUnit::assertEquals(
                $value, $actual,
                "Expected attribute [{$attribute}] does not equal actual attribute [{$actual}]."
            );

            return $this;
        });
    }
}

Add assertAttribute macro for Dusk testing


<?php
include __DIR__ . '/../src/psr4autoload.php';
class Psr4AutoloaderTest extends PHPUnit_Framework_TestCase
{
    public static function setupBeforeClass()
    {
        $content = "<?php
        namespace sample1\sample2;

        class TestClass {
        public static function testFunctionPleaseDelete() { return true; }
        }
        ";
        file_put_contents(__DIR__ . '/TestClass.php', $content);
    }

    public function testAutoload()
    {
        tunalaruan\psr\psr0autoload(__DIR__);
        sample1\sample2\TestClass::testFunctionPleaseDelete();
        $this->assertTrue(class_exists('sample1\sample2\TestClass'));
    }

    public static function tearDownAfterClass()
    {
        unlink(__DIR__ . '/TestClass.php');
    }
}

<?php
include __DIR__ . '/../src/psr4autoload.php';
class Psr4AutoloaderTest extends PHPUnit_Framework_TestCase
{
    public static function setupBeforeClass()
    {
        $content = "<?php
        namespace subdirnamespace1\subdirnamespace2;

        class TestClass {
        public static function testFunctionPleaseDelete() { return true; }
        }
        ";
        mkdir(__DIR__ . "/subdir1/", 0777, true);
        file_put_contents(__DIR__ . '/subdir1/TestClass.php', $content);
    }

    public function testAutoload()
    {
        \tunalaruan\psr\psr4autoload("subdirnamespace1\subdirnamespace2", __DIR__ . "/subdir1");
        try {
            \subdirnamespace1\subdirnamespace2\TestClass::testFunctionPleaseDelete();
        } catch (Exception $e) {
            $this->fail("Failure to autoload");
        }
        $this->assertTrue(class_exists('subdirnamespace1\subdirnamespace2\TestClass'));
    }

    public static function tearDownAfterClass()
    {
        unlink(__DIR__ . '/subdir1/TestClass.php');
        rmdir(__DIR__ . '/subdir1');
    }
}

Update test to psr4autoload. Before it was testing ps0autoload due to copy pasting shit.


<?php

/* GNU FM -- a free network service for sharing your music listening habits

   Copyright (C) 2009 Free Software Foundation, Inc

   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/>.

*/

/**
 * Encodes an URL component in a mod_rewrite friendly way, handling plus,
 * ampersand, hash and slash signs.
 *
 * @param string The text to encode
 * @return string A mod_rewrite compatible encoding of the given text.
 */
function rewrite_encode($url) {
	$url = urlencode($url);
	$url = preg_replace('/%2B/', '%252B', $url); // +
	$url = preg_replace('/%2F/', '%252F', $url); // /
	$url = preg_replace('/%26/', '%2526', $url); // &
	$url = preg_replace('/%23/', '%2523', $url); // #
	return $url;
}

<?php

/* GNU FM -- a free network service for sharing your music listening habits

   Copyright (C) 2009 Free Software Foundation, Inc

   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/>.

*/

/**
 * Encodes an URL component in a mod_rewrite friendly way, handling plus,
 * ampersand, hash and slash signs.
 *
 * @param string The text to encode
 * @return string A mod_rewrite compatible encoding of the given text.
 */
function rewrite_encode($url) {
	if (preg_match('/Apache/', $_SERVER['SERVER_SOFTWARE'])) {
		$url = urlencode($url);
		$url = preg_replace('/%2B/', '%252B', $url); // +
		$url = preg_replace('/%2F/', '%252F', $url); // /
		$url = preg_replace('/%26/', '%2526', $url); // &
		$url = preg_replace('/%23/', '%2523', $url); // #
	} else {
		$url = rawurlencode($url);
	}

	return $url;
}

Fix url rewrites in nginx

Fix url rewrites in nginx


<?php

namespace SymfonyBundles\JsonRequestBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use SymfonyBundles\JsonRequestBundle\EventListener\RequestTransformerListener;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $builder = new TreeBuilder('sb_json_request');

        $builder->getRootNode()
            ->children()
                ->arrayNode('listener')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('request_transformer')
                            ->defaultValue(RequestTransformerListener::class)
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $builder;
    }
}

<?php

namespace SymfonyBundles\JsonRequestBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use SymfonyBundles\JsonRequestBundle\EventListener\RequestTransformerListener;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $builder = new TreeBuilder('sb_json_request');

        if (\method_exists($builder, 'getRootNode')) {
            $rootNode = $builder->getRootNode();
        } else {
            // BC layer for symfony/config 4.1 and older
            $rootNode = $builder->root('maker');
        }

        $rootNode
            ->children()
                ->arrayNode('listener')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('request_transformer')
                            ->defaultValue(RequestTransformerListener::class)
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $builder;
    }
}

Add a compatibility layer for symfony/config < 4.2

Based on https://github.com/symfony/maker-bundle/pull/324


        @foreach($items as $key => $item)

        @endforeach

        @foreach($items as $key => $item)

                {{$item['caption']}}

        @endforeach

Fix carousel next and prev buttons

Fix carousel next and prev buttons


<?php

use Illuminate\Http\Request;
use App\Job;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::get('/jobs', function (){
	return Job::all();
});

<?php

use Illuminate\Http\Request;
use App\Job;
use App\User;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::get('/jobs', function (){
	return Job::all();
});

Route::get('/users', function (){
	return User::all();
});

Return all Users for testing purposes

Return all Users for testing purposes


<?php

class DatabaseSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Eloquent::unguard();

		// $this->call('UserTableSeeder');
	}

}

<?php

class DatabaseSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Eloquent::unguard();

		$this->call('AthomesTableSeeder');
	}

}

class AthomesTableSeeder extends Seeder
{
	public function run()
	{
		Athomes::create(array(
			'temperature'=>'19.8',
			'sensors1'=>'22.2',
			'sensors2'=>'7.5',
			'led1'=>False
		));
		Athomes::create(array(
			'temperature'=>'18.8',
			'sensors1'=>'22.0',
			'sensors2'=>'7.6',
			'led1'=>False
		));
	}
}

Add the seed of athomes

Add the seed of athomes


<?php

namespace Rogue\Http\Requests;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'campaign_id' => 'required',
            'campaign_run_id' => 'integer',
            'northstar_id' => 'nullable|objectid',
            'type' => 'required|string|in:photo,voter-reg,text',
            'action' => 'required|string',
            'why_participated' => 'nullable|string',
            'text' => 'nullable|string|max:256',
            'quantity' => 'nullable|integer',
            'file' => 'image|dimensions:min_width=400,min_height=400',
            'status' => 'in:pending,accepted,rejected',
            'details'=> 'json',
        ];
    }
}

<?php

namespace Rogue\Http\Requests;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'campaign_id' => 'required',
            'campaign_run_id' => 'integer',
            'northstar_id' => 'nullable|objectid',
            'type' => 'required|string|in:photo,voter-reg,text',
            'action' => 'required|string',
            'why_participated' => 'nullable|string',
            'text' => 'nullable|string|max:256',
            'quantity' => 'nullable|integer',
            'file' => 'image|dimensions:min_width=400,min_height=400',
            'status' => 'in:pending,accepted,rejected,register-form,register-OVR,confirmed,ineligible,uncertain',
            'details'=> 'json',
        ];
    }
}

Update status validation to allow for new voter-reg statuses


<?php
/**
 * Kodekit Component - http://www.timble.net/kodekit
 *
 * @copyright	Copyright (C) 2011 - 2016 Johan Janssens and Timble CVBA. (http://www.timble.net)
 * @license		MPL v2.0 <https://www.mozilla.org/en-US/MPL/2.0>
 * @link		https://github.com/timble/kodekit-application for the canonical source repository
 */

namespace Kodekit\Component\Application;

use Kodekit\Library;

/**
 * Html Document View
 *
 * @author      Johan Janssens <http://github.com/johanjanssens>
 * @package Kodekit\Component\Application
 */
class ViewDocumentHtml extends ViewHtml
{
    protected function _initialize(Library\ObjectConfig $config)
    {
        $config->append(array(
            'template_filters'	=> array('style', 'link', 'meta', 'script', 'title', 'message'),
        ));

        parent::_initialize($config);
    }

    protected function _fetchData(Library\ViewContext $context)
    {
        if($this->getObject('manager')->isRegistered('dispatcher')) {
            $context->data->component = $this->getObject('dispatcher')->getIdentifier()->package;
        } else {
            $context->data->component = '';
        }

        parent::_fetchData($context);
    }
}

<?php
/**
 * Kodekit Component - http://www.timble.net/kodekit
 *
 * @copyright	Copyright (C) 2011 - 2016 Johan Janssens and Timble CVBA. (http://www.timble.net)
 * @license		MPL v2.0 <https://www.mozilla.org/en-US/MPL/2.0>
 * @link		https://github.com/timble/kodekit-application for the canonical source repository
 */

namespace Kodekit\Component\Application;

use Kodekit\Library;

/**
 * Html Document View
 *
 * @author      Johan Janssens <http://github.com/johanjanssens>
 * @package Kodekit\Component\Application
 */
class ViewDocumentHtml extends ViewHtml
{
    protected function _initialize(Library\ObjectConfig $config)
    {
        $config->append(array(
            'template_filters'	=> array('style', 'link', 'meta', 'script', 'title', 'message'),
        ));

        parent::_initialize($config);
    }
}

Set the component name through the documentable behavior


<?php

/**
 * This file is part of the Tarantool Client package.
 *
 * (c) Eugene Leonovich <gen.work@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Tarantool\Client\Tests\Integration;

use Tarantool\Client\Request\PingRequest;

final class PacketSyncTest extends TestCase
{
    /**
     * @dataProvider provideValidSync
     */
    public function testSameSync(int $sync) : void
    {
        $handler = $this->client->getHandler();
        $connection = $handler->getConnection();
        $packer = $handler->getPacker();

        $packet = $packer->pack(new PingRequest(), $sync);
        $connection->open();
        $packet = $connection->send($packet);

        $response = $packer->unpack($packet);

        self::assertSame($sync, $response->getSync());
    }

    public function provideValidSync() : iterable
    {
        return [
            [0],
            [128],
            [65535],
            [4294967295],
            [9223372036854775807], // PHP_INT_MAX
        ];
    }
}

<?php

/**
 * This file is part of the Tarantool Client package.
 *
 * (c) Eugene Leonovich <gen.work@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Tarantool\Client\Tests\Integration;

use Tarantool\Client\Request\PingRequest;

final class PacketSyncTest extends TestCase
{
    /**
     * @dataProvider provideValidSync
     */
    public function testSameSync(int $sync) : void
    {
        $handler = $this->client->getHandler();
        $connection = $handler->getConnection();
        $packer = $handler->getPacker();

        $packet = $packer->pack(new PingRequest(), $sync);
        $connection->open();
        $packet = $connection->send($packet);

        $response = $packer->unpack($packet);

        self::assertSame($sync, $response->getSync());
    }

    public function provideValidSync() : iterable
    {
        return [
            [0],
            [127],
            [255],
            [65535],
            [4294967295],
            [9223372036854775807], // PHP_INT_MAX
        ];
    }
}

Add more test cases for sync

Add more test cases for sync


<?php

/**
 * BluePay Create Credit Card Request.
 */
namespace Omnipay\BluePay\Message;

/**
 * BluePay Create Credit Card Request.
 *
 * We do this by running an authorization for $0.
 */
class CreateCardRequest extends AuthRequest
{
    public function getData()
    {
        $data = parent::getData();
        $data['AMOUNT'] = '0.00';
        return $data;
    }
}

<?php

/**
 * BluePay Create Credit Card Request.
 */
namespace Omnipay\BluePay\Message;

/**
 * BluePay Create Credit Card Request.
 *
 * We do this by running an authorization for $0.
 */
class CreateCardRequest extends AbstractRequest
{
    protected $action = 'AUTH';
    public function getData()
    {
        $action = $this->getParameter('action');
        if ('Purchase' == $action) {
            $this->action = 'SALE';
        }
        $data = $this->getBaseData();
        $this->getCard()->validate();
        $data['PAYMENT_ACCOUNT'] = $this->getCard()->getNumber();
        $data['CARD_EXPIRE'] = $this->getCard()->getExpiryDate('my');
        $data['CARD_CVV2'] = $this->getCard()->getCvv();
        $data = array_merge($data, $this->getBillingData());
        if ($this->action == 'AUTH') {
          $data['AMOUNT'] = '0.00';
        }
        return $data;
    }
}

Allow create card request to use parameter action = Purchase


<?php

namespace Algolia\AlgoliaSearch\Response;

abstract class AbstractResponse implements \ArrayAccess
{
    /**
     * @var array Full response from Algolia API
     */
    protected $apiResponse;

    abstract public function wait($requestOptions = array());

    /**
     * {@inheritdoc}
     */
    public function offsetExists($offset)
    {
        return isset($this->apiResponse[$offset]);
    }

    /**
     * {@inheritdoc}
     */
    public function offsetGet($offset)
    {
        return $this->apiResponse[$offset];
    }

    /**
     * {@inheritdoc}
     */
    public function offsetSet($offset, $value)
    {
        $this->apiResponse[$offset] = $value;
    }

    /**
     * {@inheritdoc}
     */
    public function offsetUnset($offset)
    {
        unset($this->apiResponse[$offset]);
    }
}

<?php

namespace Algolia\AlgoliaSearch\Response;

abstract class AbstractResponse implements \ArrayAccess
{
    /**
     * @var array Full response from Algolia API
     */
    protected $apiResponse;

    abstract public function wait($requestOptions = array());

    /**
     * @return array The actual response from Algolia API
     */
    public function getBody()
    {
        return $this->apiResponse;
    }

    /**
     * {@inheritdoc}
     */
    public function offsetExists($offset)
    {
        return isset($this->apiResponse[$offset]);
    }

    /**
     * {@inheritdoc}
     */
    public function offsetGet($offset)
    {
        return $this->apiResponse[$offset];
    }

    /**
     * {@inheritdoc}
     */
    public function offsetSet($offset, $value)
    {
        $this->apiResponse[$offset] = $value;
    }

    /**
     * {@inheritdoc}
     */
    public function offsetUnset($offset)
    {
        unset($this->apiResponse[$offset]);
    }
}

Add `getBody()` on all responses

Add `getBody()` on all responses


<?php

class Cache {
    private static $_config = false;

    private static function getConfig() {
        if(static::$_config)
            return static::$_config;

        static::$_config = require(__DIR__ . '/../../../config/cache.php');
    }

    public static function store($key, $value, $ttl) {
        $dir = static::getConfig()['dir'];
        if(!$dir)
            return false;

        $data = [
            'expires' => time() + $ttl,
            'data' => $value,
        ];

        mkdir($dir, 0777, true);
        $file = fopen($dir . strval($key) . '.tmp', 'w');
        fwrite($file, json_encode($data));
        fclose($file);

        return true;
    }

    public static function fetch($key) {
        $dir = static::getConfig()['dir'];
        if(!$dir)
            return false;

        $data = json_decode(file_get_contents($dir . strval($key) . '.tmp'), true);

        if($data['expires'] < time()) {
            return false;
        } else {
            return $data['data'];
        }
    }
}

<?php

class Cache {
    private static $_config = false;

    private static function getConfig() {
        if(static::$_config)
            return static::$_config;

        static::$_config = require(__DIR__ . '/../../../config/cache.php');
    }

    public static function store($key, $value, $ttl) {
        $dir = static::getConfig()['dir'];
        if(!$dir)
            return false;

        $data = [
            'expires' => time() + $ttl,
            'data' => $value,
        ];

        mkdir($dir, 0777, true);
        $file = fopen($dir . strval($key) . '.json.tmp', 'w');
        fwrite($file, json_encode($data));
        fclose($file);

        return true;
    }

    public static function fetch($key) {
        $dir = static::getConfig()['dir'];
        if(!$dir)
            return false;

        $data = json_decode(file_get_contents($dir . strval($key) . '.json.tmp'), true);

        if($data['expires'] < time()) {
            return false;
        } else {
            return $data['data'];
        }
    }
}

Change cached file extension to .json.tmp


<?php

namespace Liuggio\StatsDClientBundle\StatsCollector;

use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class TimeStatsCollector extends StatsCollector
{
    /**
     * startTime
     *
     * @var float
     * @access private
     */
    private $startTime;

    /**
     * __construct
     *
     * @access public
     * @return void
     */
    public function __construct($stat_key = __CLASS__, StatsdDataFactoryInterface $stats_data_factory = null, $only_on_master_response = false)
    {
        parent::__construct($stat_key, $stats_data_factory, $only_on_master_response);

        $this->startTime = microtime(true);
    }

    /**
     * Collects data for the given Response.
     *
     * @param Request    $request   A Request instance
     * @param Response   $response  A Response instance
     * @param \Exception $exception An exception instance if the request threw one
     *
     * @return Boolean
     */
    public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        $time = microtime(true) - $this->startTime;
        $time = round($time * 1000);
        $statData = $this->getStatsdDataFactory()->timing($this->getStatsDataKey(), $time);
        $this->addStatsData($statData);

        return true;
    }

}

<?php

namespace Liuggio\StatsDClientBundle\StatsCollector;

use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class TimeStatsCollector extends StatsCollector
{
    /**
     * Collects data for the given Response.
     *
     * @param Request    $request   A Request instance
     * @param Response   $response  A Response instance
     * @param \Exception $exception An exception instance if the request threw one
     *
     * @return Boolean
     */
    public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        $startTime = $request->server->get('REQUEST_TIME_FLOAT', $request->server->get('REQUEST_TIME'));

        $time = microtime(true) - $startTime;
        $time = round($time * 1000);

        $statData = $this->getStatsdDataFactory()->timing($this->getStatsDataKey(), $time);
        $this->addStatsData($statData);

        return true;
    }

}

Use $request->server information for more precision


<?php
/**
 * @file
 */

namespace CultuurNet\UDB3;

class XmlStringTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function it_does_not_accept_invalid_xml()
    {
        $this->setExpectedException(XMLSyntaxException::class);

        new XmlString('this is not xml');
    }
}

III-461: Test XmlString construction with invalid xml


<?php

namespace Ekyna\Bundle\CmsBundle\Entity;

use Ekyna\Component\Resource\Doctrine\ORM\TranslatableResourceRepositoryInterface;
use Ekyna\Component\Resource\Doctrine\ORM\Util\TranslatableResourceRepositoryTrait;
use Gedmo\Tree\Entity\Repository\NestedTreeRepository;

/**
 * Class PageRepository
 * @package Ekyna\Bundle\CmsBundle\Entity
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class PageRepository extends NestedTreeRepository implements TranslatableResourceRepositoryInterface
{
    use TranslatableResourceRepositoryTrait;

    /**
     * {@inheritdoc}
     */
    public function createQueryBuilder($alias, $indexBy = null)
    {
        return parent::createQueryBuilder($alias, $indexBy)
            ->innerJoin($alias.'.seo', 'seo');
    }

    /**
     * Finds a page by request.
     *
     * @param string $routeName
     * @return null|\Ekyna\Bundle\CmsBundle\Model\PageInterface
     */
    public function findOneByRoute($routeName)
    {
        $qb = $this->createQueryBuilder('p');

        return $qb
            ->andWhere($qb->expr()->eq('p.route', $qb->expr()->literal($routeName)))
            ->setMaxResults(1)
            ->getQuery()
            ->useResultCache(true, 3600, 'ekyna_cms.page[route:'.$routeName.']')
            ->getOneOrNullResult()
        ;
    }
}

<?php

namespace Ekyna\Bundle\CmsBundle\Entity;

use Ekyna\Component\Resource\Doctrine\ORM\TranslatableResourceRepositoryInterface;
use Ekyna\Component\Resource\Doctrine\ORM\Util\TranslatableResourceRepositoryTrait;
use Gedmo\Tree\Entity\Repository\NestedTreeRepository;

/**
 * Class PageRepository
 * @package Ekyna\Bundle\CmsBundle\Entity
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class PageRepository extends NestedTreeRepository implements TranslatableResourceRepositoryInterface
{
    use TranslatableResourceRepositoryTrait;

    /**
     * {@inheritdoc}
     */
    public function createQueryBuilder($alias, $indexBy = null)
    {
        return parent::createQueryBuilder($alias, $indexBy)
            ->innerJoin($alias.'.seo', 'seo');
    }

    /**
     * Finds a page by request.
     *
     * @param string $routeName
     * @return null|\Ekyna\Bundle\CmsBundle\Model\PageInterface
     */
    public function findOneByRoute($routeName)
    {
        $qb = $this->createQueryBuilder('p');

        return $qb
            ->andWhere($qb->expr()->eq('p.route', $qb->expr()->literal($routeName)))
            ->setMaxResults(1)
            ->getQuery()
            ->useQueryCache(true)
            ->useResultCache(true, 3600, 'ekyna_cms.page[route:'.$routeName.']')
            ->getOneOrNullResult()
        ;
    }
}

Use query cache for find page by route.

[Cms] Use query cache for find page by route.


<?php

class Create_Appointments_Table {

	/**
	 * Make changes to the database.
	 *
	 * @return void
	 */
	public function up()
	{
		//
		Schema::table('appointments', function($table)
		{
			$table->create();
			$table->increments('id');
			$table->string('name')->nullable();
			$table->integer('place_id')->unsigned()->nullable();
			$table->integer('a_date_ts')->unsigned();
			$table->string('added_by', 50);
			$table->string('tweet', 140);
			$table->string('tweet_id', 64);
			$table->text('link')->nullable();
			$table->blob('votes')->nullable();
			$table->tinyint('enabled')->default(1);
			$table->timestamps();
			$table->index(array('a_date_ts', 'enabled'));
			$table->index(array('updated_at', 'enabled'));
			$table->index('place_id');
			$table->foreign('place_id')->references('id')->on('places');
			$table->engine = 'InnoDB';
		});
	}

	/**
	 * Revert the changes to the database.
	 *
	 * @return void
	 */
	public function down()
	{
		//
		Schema::drop('appointments');
	}

}

<?php

class Create_Appointments_Table {

	/**
	 * Make changes to the database.
	 *
	 * @return void
	 */
	public function up()
	{
		//
		Schema::table('appointments', function($table)
		{
			$table->create();
			$table->increments('id');
			$table->string('name')->nullable();
			$table->integer('place_id')->unsigned()->nullable();
			$table->integer('a_date_ts')->unsigned();
			$table->string('added_by', 50);
			$table->string('tweet', 140);
			$table->string('tweet_id', 64);
			$table->text('link')->nullable();
			$table->blob('votes')->nullable();
			$table->tinyint('enabled')->default(1);
			$table->timestamps();
			$table->index(array('a_date_ts', 'name', 'enabled'));
			$table->index(array('updated_at', 'enabled'));
			$table->index('place_id');
			$table->foreign('place_id')->references('id')->on('places');
			$table->engine = 'InnoDB';
		});
	}

	/**
	 * Revert the changes to the database.
	 *
	 * @return void
	 */
	public function down()
	{
		//
		Schema::drop('appointments');
	}

}

Modify one of the indexes on the appointments table.


<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::auth();

Route::get('/home', 'HomeController@index');

Route::auth();

Route::get('/home', 'HomeController@index');

Route::auth();

Route::get('/home', 'HomeController@index');

Revert "delete un needed route"

Revert "delete un needed route"

This reverts commit a58cbd7a9dc531e38bc2ec6425bd76ad9ff16c6d.


<?php

namespace BinSoul\Net\Mqtt;

/**
 * Matches a topic filter with an actual topic.
 *
 * @author  Alin Eugen Deac <ade@vestergaardcompany.com>
 */
class TopicMatcher
{
    /**
     * Check if the given topic matches the filter.
     *
     * @param string $filter e.g. A/B/+, A/B/#
     * @param string $topic  e.g. A/B/C, A/B/foo/bar/baz
     *
     * @return bool true if topic matches the pattern
     */
    public function matches($filter, $topic)
    {
        // Created by Steffen (https://github.com/kernelguy)
        $tokens = explode('/', $filter);
        $parts = [];
        for ($i = 0, $count = count($tokens); $i < $count; ++$i) {
            $token = $tokens[$i];
            switch ($token) {
                case '+':
                    $parts[] = '[^/#\+]*';

                    break;
                case '#':
                    if ($i === 0) {
                        $parts[] = '[^\+\$]*';
                    } else {
                        $parts[] = '[^\+]*';
                    }

                    break;
                default:
                    $parts[] = str_replace('+', '\+', $token);

                    break;
            }
        }

        $regex = implode('/', $parts);
        $regex = str_replace('$', '\$', $regex);
        $regex = ';^'.$regex.'$;';

        return preg_match($regex, $topic) === 1;
    }
}

<?php

namespace BinSoul\Net\Mqtt;

/**
 * Matches a topic filter with an actual topic.
 *
 * @author  Alin Eugen Deac <ade@vestergaardcompany.com>
 */
class TopicMatcher
{
    /**
     * Check if the given topic matches the filter.
     *
     * @param string $filter e.g. A/B/+, A/B/#
     * @param string $topic  e.g. A/B/C, A/B/foo/bar/baz
     *
     * @return bool true if topic matches the pattern
     */
    public function matches($filter, $topic)
    {
        // Created by Steffen (https://github.com/kernelguy)
        $tokens = explode('/', $filter);
        $parts = [];
        foreach ($tokens as $index => $token) {
            switch ($token) {
                case '+':
                    $parts[] = '[^/#\+]*';

                    break;
                case '#':
                    if ($index === 0) {
                        $parts[] = '[^\+\$]*';
                    } else {
                        $parts[] = '[^\+]*';
                    }

                    break;
                default:
                    $parts[] = str_replace('+', '\+', $token);

                    break;
            }
        }

        $regex = implode('/', $parts);
        $regex = str_replace('$', '\$', $regex);
        $regex = ';^'.$regex.'$;';

        return preg_match($regex, $topic) === 1;
    }
}

Replace for loop with foreach

Replace for loop with foreach


<?php

namespace Refinery29\ApiOutput;

use Refinery29\ApiOutput\Resource\TopLevelResource;
use Refinery29\ApiOutput\Serializer\Serializer;

class ResponseBody
{
    /**
     * @var TopLevelResource[]
     */
    protected $members = [];

    /**
     * @param TopLevelResource $member
     *
     * @throws \Exception
     */
    public function addMember(TopLevelResource $member)
    {
        $this->members[] = $member;
    }

    /**
     * @return Serializer[]
     */
    public function getMembers()
    {
        return $this->members;
    }

    /**mae
     * @return string JSON representation of the response.
     */

    public function getOutput()
    {
        $response = [];
        reset($this->members);
        $member = current($this->getMembers());

        if ($member->getTopLevelName() === '') {
            return json_encode((object) $member->getOutput(), JSON_UNESCAPED_SLASHES);
        }

        foreach ($this->members as $member) {
            $response[$member->getTopLevelName()] = $member->getOutput();
        }

        return json_encode((object) $response, JSON_UNESCAPED_SLASHES);
    }
}

<?php

namespace Refinery29\ApiOutput;

use Refinery29\ApiOutput\Resource\TopLevelResource;
use Refinery29\ApiOutput\Serializer\Serializer;
use Refinery29\ApiOutput\Serializer\CustomResult;

class ResponseBody
{
    /**
     * @var TopLevelResource[]
     */
    protected $members = [];

    /**
     * @param TopLevelResource $member
     *
     * @throws \Exception
     */
    public function addMember(TopLevelResource $member)
    {
        $this->members[] = $member;
    }

    /**
     * @return Serializer[]
     */
    public function getMembers()
    {
        return $this->members;
    }

    /**mae
     * @return string JSON representation of the response.
     */

    public function getOutput()
    {
        $response = [];
        reset($this->members);
        $member = current($this->getMembers());

        if ($member instanceof CustomResult) {
            return json_encode((object) $member->getOutput(), JSON_UNESCAPED_SLASHES);
        }

        foreach ($this->members as $member) {
            $response[$member->getTopLevelName()] = $member->getOutput();
        }

        return json_encode((object) $response, JSON_UNESCAPED_SLASHES);
    }
}

Check for the class of the member as opposed to the toplevel name of the member


<?php

namespace Craft;

class RedirectmanagerPlugin extends BasePlugin
{
	public function getName()
	{
		return Craft::t('Redirect Manager');
	}

	public function getVersion()
	{
		return 'Beta';
	}

	public function getDeveloper()
	{
		return 'Roi Kingon';
	}

	public function getDeveloperUrl()
	{
		return 'http://www.roikingon.com';
	}

	public function hasCpSection()
	{
		return true;
	}

	public function init()
	{
		// redirects only take place out of the CP
		if(craft()->request->isSiteRequest()){
			$path = craft()->request->getPath();
			if( $location = craft()->redirectmanager->processRedirect($path) )
			{
				header("Location: ".$location['url'], true, $location['type']);
				exit();
			}
		}
	}

	public function registerCpRoutes()
	{
		return array(
			'redirectmanager\/new' => 'redirectmanager/_edit',
			'redirectmanager\/(?P<redirectId>\d+)' => 'redirectmanager/_edit'
		);
	}
	public function onAfterInstall()
	{
		$redirects = array(
			array('uri' => '#^bad(.*)$#', 'location' => 'good$1', 'type' => "302")
		);

		foreach ($redirects as $redirect) {
			craft()->db->createCommand()->insert('redirectmanager', $redirect);
		}
	}
}

<?php

namespace Craft;

class RedirectmanagerPlugin extends BasePlugin
{
	public function getName()
	{
		return Craft::t('Redirect Manager');
	}

	public function getVersion()
	{
		return 'Beta';
	}

	public function getDeveloper()
	{
		return 'Roi Kingon';
	}

	public function getDeveloperUrl()
	{
		return 'http://www.roikingon.com';
	}

	public function hasCpSection()
	{
		return true;
	}

	public function init()
	{
		// redirects only take place out of the CP (and should not happen in live preview)
		if(craft()->request->isSiteRequest() && !craft()->request->isLivePreview()){
			$path = craft()->request->getPath();
			if( $location = craft()->redirectmanager->processRedirect($path) )
			{
				header("Location: ".$location['url'], true, $location['type']);
				exit();
			}
		}
	}

	public function registerCpRoutes()
	{
		return array(
			'redirectmanager\/new' => 'redirectmanager/_edit',
			'redirectmanager\/(?P<redirectId>\d+)' => 'redirectmanager/_edit'
		);
	}
	public function onAfterInstall()
	{
		$redirects = array(
			array('uri' => '#^bad(.*)$#', 'location' => 'good$1', 'type' => "302")
		);

		foreach ($redirects as $redirect) {
			craft()->db->createCommand()->insert('redirectmanager', $redirect);
		}
	}
}

Disable redirects when using Live Preview


<?php
/**
 * Created by PhpStorm.
 * User: Michal
 * Date: 8.1.14
 * Time: 19:02
 */

namespace AnnotateCms\Themes\DI;

use AnnotateCms\Framework\DI\CompilerExtension;
use AnnotateCms\Themes\Loaders\ThemesLoader;
use Kdyby\Events\DI\EventsExtension;

class ThemesExtension extends CompilerExtension
{

    function getServices()
    {
        $config = $this->getConfig();
        return [
            "themeLoader" => [
                "class" => ThemesLoader::classname,
                "tags" => [EventsExtension::SUBSCRIBER_TAG],
                "setup" => [
                    "setFrontendTheme" => ["name" => $config["frontend"]],
                    "setBackendTheme" => ["name" => $config["backend"]],
                ],
            ],
        ];
    }

    function getFactories()
    {
        // TODO: Implement getFactories() method.
    }

    function  getDefaults()
    {
        return [
            "frontend" => "Sandbox",
            "backend" => "Flatty",
        ];
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: Michal
 * Date: 8.1.14
 * Time: 19:02
 */

namespace AnnotateCms\Themes\DI;

use AnnotateCms\Themes\Loaders\ThemesLoader;
use Kdyby\Events\DI\EventsExtension;
use Nette\DI\CompilerExtension;

class ThemesExtension extends CompilerExtension
{
    public function loadConfiguration()
    {
        $configuration = $this->getConfig($this->getDefaults());

        $this->getContainerBuilder()->addDefinition($this->prefix('themeLoader'))
            ->setClass(ThemesLoader::classname)
            ->addTag(EventsExtension::SUBSCRIBER_TAG)
            ->addSetup('setFrontendTheme', ['name' => $configuration['frontend']])
            ->addSetup('setBackendTheme', ['name' => $configuration['backend']]);
    }

    function  getDefaults()
    {
        return [
            'frontend' => '',
            'backend' => '',
        ];
    }
}

Remove custom compiler extension class

Remove custom compiler extension class


<?php

namespace Heyday\CacheInclude;

use Symfony\Component\ExpressionLanguage\ExpressionLanguage as SymfonyExpressionLanguage;

/**
 * Class ExpressionLanguage
 * @package Heyday\CacheInclude
 */
class ExpressionLanguage extends SymfonyExpressionLanguage
{
    /**
     *
     */
    protected function registerFunctions()
    {
        parent::registerFunctions();

        $this->register(
            'list',
            function ($arg) {
                return sprintf('%s::get()', $arg);
            },
            function (array $variables, $value) {
                return \DataList::create($value);
            }
        );

        $this->register(
            'instanceof',
            function ($arg0, $arg1) {
                return sprintf('%s instanceof %s', $arg0, $arg1);
            },
            function (array $variables, $arg0, $arg1) {
                return $arg0 instanceof $arg1;
            }
        );
    }
}

<?php

namespace Heyday\CacheInclude;

use Symfony\Component\ExpressionLanguage\ExpressionLanguage as SymfonyExpressionLanguage;

/**
 * Class ExpressionLanguage
 * @package Heyday\CacheInclude
 */
class ExpressionLanguage extends SymfonyExpressionLanguage
{
    protected function registerFunctions()
    {
        parent::registerFunctions();

        $this->register(
            'list',
            array($this, 'listCompiler'),
            array($this, 'listEvaluator')
        );

        $this->register(
            'instanceof',
            array($this, 'instanceofCompiler'),
            array($this, 'instanceofEvaluator')
        );
    }

    /**
     * @param $arg
     * @return string
     */
    public function listCompiler($arg)
    {
        return sprintf('%s::get()', $arg);
    }

    /**
     * @param array $variables
     * @param $value
     * @return static
     */
    public function listEvaluator(array $variables, $value)
    {
        return \DataList::create($value);
    }

    /**
     * @param $arg0
     * @param $arg1
     * @return string
     */
    public function instanceofCompiler($arg0, $arg1)
    {
        return sprintf('%s instanceof %s', $arg0, $arg1);
    }

    /**
     * @param array $variables
     * @param $arg0
     * @param $arg1
     * @return bool
     */
    public function instanceofEvaluator(array $variables, $arg0, $arg1)
    {
        return $arg0 instanceof $arg1;
    }
}

Remove closures from Expression language


<?php
declare(strict_types = 1);

namespace DASPRiD\Formidable\Mapping\Formatter;

use Assert\Assertion;
use DASPRiD\Formidable\Data;
use DASPRiD\Formidable\FormError\FormError;
use DASPRiD\Formidable\Mapping\BindResult;

final class IntegerFormatter implements FormatterInterface
{
    /**
     * {@inheritdoc}
     */
    public function bind(string $key, Data $data) : BindResult
    {
        if (!$data->hasKey($key)) {
            return BindResult::fromFormErrors(new FormError(
                $key,
                'error.required'
            ));
        }

        $value = $data->getValue($key);

        if (!preg_match('(^-?[1-9]\d*$)', $value)) {
            return BindResult::fromFormErrors(new FormError(
                $key,
                'error.integer'
            ));
        }

        return BindResult::fromValue((int) $data->getValue($key));
    }

    /**
     * {@inheritdoc}
     */
    public function unbind(string $key, $value) : Data
    {
        Assertion::integer($value);
        return Data::fromFlatArray([$key => (string) $value]);
    }
}

<?php
declare(strict_types = 1);

namespace DASPRiD\Formidable\Mapping\Formatter;

use Assert\Assertion;
use DASPRiD\Formidable\Data;
use DASPRiD\Formidable\FormError\FormError;
use DASPRiD\Formidable\Mapping\BindResult;

final class IntegerFormatter implements FormatterInterface
{
    /**
     * {@inheritdoc}
     */
    public function bind(string $key, Data $data) : BindResult
    {
        if (!$data->hasKey($key)) {
            return BindResult::fromFormErrors(new FormError(
                $key,
                'error.required'
            ));
        }

        $value = $data->getValue($key);

        if (!preg_match('(^-?[1-9]*\d+$)', $value)) {
            return BindResult::fromFormErrors(new FormError(
                $key,
                'error.integer'
            ));
        }

        return BindResult::fromValue((int) $data->getValue($key));
    }

    /**
     * {@inheritdoc}
     */
    public function unbind(string $key, $value) : Data
    {
        Assertion::integer($value);
        return Data::fromFlatArray([$key => (string) $value]);
    }
}

Fix integer formatter to accept zero value


<?php

namespace Maghead\Schema\Column;

use Maghead\Schema\DeclareColumn;
use Maghead\Schema\DeclareSchema;

class UUIDPrimaryKeyColumn extends DeclareColumn
{
    /**
     * TODO: the best type for UUID in mysql is BINARY(36).
     */
    public function __construct(DeclareSchema $schema, $name = 'uuid', $type = 'binary', $length = 36)
    {
        parent::__construct($schema, $name);
        $this->type($type)
            ->isa('str')
            ->length($length)
            ->notNull()
            ->primary()
            ;
    }
}

<?php

namespace Maghead\Schema\Column;

use Maghead\Schema\DeclareColumn;
use Maghead\Schema\DeclareSchema;

class UUIDPrimaryKeyColumn extends DeclareColumn
{
    /**
     * BINARY(16) is the best column type for UUID.
     *
     * @see http://mysqlserverteam.com/storing-uuid-values-in-mysql-tables/
     */
    public function __construct(DeclareSchema $schema, $name = 'uuid', $type = 'BINARY', $length = 16)
    {
        parent::__construct($schema, $name);
        $this->type($type)
            ->isa('str')
            ->length($length)
            ->notNull()
            ->primary()
            ;
    }
}

Update UUID type to BINARY(16)

Update UUID type to BINARY(16)


<!DOCTYPE HTML>

	<?php
	include("config.php");
	if ('Production' != constant('DEPLOY_MODE')) {
		echo '
Site is running in ' . constant('DEPLOY_MODE') . ': all warnings and errors will be displayed!
';
		echo "
";
		require 'dump-errors.php';
		echo "
";
	}

	require_once('functions.php');
	LogPostValuesToLog($_POST['this_log'], 'cl_income');

	// Everything that was collected in the previous forms
	$cl_input = array();
	foreach($_POST as $key => $value) {
		$cl_input[$key] = $value;
	}

	?>

	<?php var_dump($cl_input); ?>

<!DOCTYPE HTML>

	<?php
	include("config.php");
	if ('Production' != constant('DEPLOY_MODE')) {
		echo '
Site is running in ' . constant('DEPLOY_MODE') . ': all warnings and errors will be displayed!
';
		echo "
";
		require 'dump-errors.php';
		echo "
";
	}

	require_once('functions.php');
	LogPostValuesToLog($_POST['this_log'], 'cl_income');

	// Everything that was collected in the previous forms
	$cl_input = array();
	foreach($_POST as $key => $value) {
		$cl_input[$key] = $value;
	}

	?>

Summary

Here's all the data you've provided:

		<?php var_dump($cl_input); ?>

Click here to download all the data you've provided for offline use.

Go to the results page.

Add links to download JSON and go to summary page


<?php
namespace Movim\Task;

use Clue\React\Buzz\Browser;
use Psr\Http\Message\ResponseInterface;

class CheckSmallPicture extends Engine {

    private $_client;

    public function __construct()
    {
        $engine = parent::start();
        $browser = new Browser($engine->_loop);

        $this->_client = $browser->withOptions([
            'timeout' => 2
        ]);
    }

    public function run($url)
    {
        return $this->_client->head($url)
            ->then(function (ResponseInterface $response) {
                $length = $response->getHeader('content-length');

                $size = 300000;

                if($length) {
                    $length = (int)$length[0];
                    $type   = (string)$response->getHeader('content-type')[0];
                    $typearr = explode('/', $type);
                    return ($typearr[0] == 'image'
                        && $length <= $size
                        && $length >= 10000);
                }

                return false;
            },
            function (\Exception $error) {
                return false;
            })
            ->always(function() { writeOut(); });
    }
}

<?php
namespace Movim\Task;

use Clue\React\Buzz\Browser;
use Psr\Http\Message\ResponseInterface;

class CheckSmallPicture extends Engine {

    private $_client;

    public function __construct()
    {
        $engine = parent::start();
        $browser = new Browser($engine->_loop);

        $this->_client = $browser->withOptions([
            'timeout' => 2
        ]);
    }

    public function run($url)
    {
        return $this->_client->head($url)
            ->then(function (ResponseInterface $response) {
                $length = $response->getHeader('content-length');

                $size = 300000;

                if($length) {
                    $length = (int)$length[0];
                    $type   = (string)$response->getHeader('content-type')[0];
                    $typearr = explode('/', $type);
                    return ($typearr[0] == 'image'
                        && $length <= $size
                        && $length >= 5000);
                }

                return false;
            },
            function (\Exception $error) {
                return false;
            })
            ->always(function() { writeOut(); });
    }
}

Allow smaller pictures to be declared as valid pictures


<?php

namespace Yajra\CMS\Console;

use Illuminate\Console\Command;
use Yajra\CMS\Repositories\Extension\Repository;

class WidgetPublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'widget:install {name}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Install YajraCMS widget extension.';

    /**
     * @var \Yajra\CMS\Repositories\Extension\Repository
     */
    private $extensions;

    /**
     * Create a new command instance.
     *
     * @param \Yajra\CMS\Repositories\Extension\Repository $extensions
     */
    public function __construct(Repository $extensions)
    {
        parent::__construct();
        $this->extensions = $extensions;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $path = app_path('Widgets') . DIRECTORY_SEPARATOR . $this->argument('name') . '.json';

        $this->extensions->registerManifest($path);

        $this->info($this->argument('name') . ' widget extension installed!');
    }
}

<?php

namespace Yajra\CMS\Console;

use Illuminate\Console\Command;
use Yajra\CMS\Repositories\Extension\Repository;

class WidgetPublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'widget:install {name}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Install YajraCMS widget extension.';

    /**
     * @var \Yajra\CMS\Repositories\Extension\Repository
     */
    private $extensions;

    /**
     * Create a new command instance.
     *
     * @param \Yajra\CMS\Repositories\Extension\Repository $extensions
     */
    public function __construct(Repository $extensions)
    {
        parent::__construct();
        $this->extensions = $extensions;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $path = app_path('Widgets') . DIRECTORY_SEPARATOR . $this->argument('name') . '.json';

        $this->extensions->registerManifest($path);
        $this->laravel->make('cache.store')->forget('extensions.widgets');
        $this->laravel->make('cache.store')->forget('extensions.all');

        $this->info($this->argument('name') . ' widget extension installed!');
    }
}

Clear cache when installing a widget.

Clear cache when installing a widget.


<?php

namespace App\Models;
use App\DeviantArt;

class Cutiemark extends AbstractFillable {
	/** @var int */
	public $cmid, $ponyid;
	/** @var string */
	public $facing, $favme, $preview, $preview_src;
	/** @var int */
	public $favme_rotation;

	/** @param array|object */
	public function __construct($iter = null){
		parent::__construct($this, $iter);
	}

	/**
	 * @return string|null
	 */
	function getPreviewURL(){
		return $this->preview ?? DeviantArt::getCachedDeviation($this->favme)['preview'] ?? null;
	}
}

<?php

namespace App\Models;
use App\DeviantArt;
use App\Exceptions\CURLRequestException;

class Cutiemark extends AbstractFillable {
	/** @var int */
	public $cmid, $ponyid;
	/** @var string */
	public $facing, $favme, $preview, $preview_src;
	/** @var int */
	public $favme_rotation;

	/** @param array|object */
	public function __construct($iter = null){
		parent::__construct($this, $iter);
	}

	/**
	 * @return string|null
	 */
	function getPreviewURL(){
		try {
			return $this->preview ?? DeviantArt::getCachedDeviation($this->favme)['preview'] ?? null;
		}
		catch (CURLRequestException $e){
			error_log('Failed to get preview URL: '.$e->getMessage()."\nStack trace:\n".$e->getTraceAsString());
			return null;
		}
	}
}

Add cURL exception handler to CM preview URL fetcher


<?php

namespace Plummer\Calendarful\Recurrence;

class RecurrenceFactory implements RecurrenceFactoryInterface
{
	protected $recurrenceTypes = [];

	public function addRecurrenceType($type, $recurrenceType)
	{
		if(is_string($recurrenceType) and !class_exists($recurrenceType)) {
			throw new \InvalidArgumentException("Class {$recurrenceType} des not exist.");
		}
		else if(!in_array('Plummer\Calendarful\Recurrence\RecurrenceInterface', class_implements($recurrenceType))) {
			throw new \InvalidArgumentException('File or File path required.');
		}

		$this->recurrenceTypes[$type] = is_string($recurrenceType) ?
			$recurrenceType :
			get_class($recurrenceType);
	}

	public function getRecurrenceTypes()
	{
		return $this->recurrenceTypes;
	}

	public function createRecurrenceType($type)
	{
		if(!isset($this->recurrenceTypes[$type])) {
			throw new \OutOfBoundsException("A recurrence type called {$type} does not exist within the factory.");
		}

		return $this->recurrenceTypes[$type];
	}
}

<?php

namespace Plummer\Calendarful\Recurrence;

class RecurrenceFactory implements RecurrenceFactoryInterface
{
	protected $recurrenceTypes = [];

	public function addRecurrenceType($type, $recurrenceType)
	{
		if(is_string($recurrenceType) and !class_exists($recurrenceType)) {
			throw new \InvalidArgumentException("Class {$recurrenceType} des not exist.");
		}
		else if(!in_array('Plummer\Calendarful\Recurrence\RecurrenceInterface', class_implements($recurrenceType))) {
			throw new \InvalidArgumentException('File or File path required.');
		}

		$this->recurrenceTypes[$type] = is_string($recurrenceType) ?
			$recurrenceType :
			get_class($recurrenceType);
	}

	public function getRecurrenceTypes()
	{
		return $this->recurrenceTypes;
	}

	public function createRecurrenceType($type)
	{
		if(!isset($this->recurrenceTypes[$type])) {
			throw new \OutOfBoundsException("A recurrence type called {$type} does not exist within the factory.");
		}

		$recurrenceType = new $this->recurrenceTypes[$type]();

		return $recurrenceType;
	}
}

Return in instance of a recurrence type from the recurrence factory rather than a class path.


<?php

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

$app = new Silex\Application();

$app->get('/issuers/{id}', function($id) use ($app) {

});

$app->get('/badges', function() use ($app) {

});

$app->run();

<?php

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

$app = new Silex\Application();

$app->get('/issuers/{id}', function($id) use ($app) {

});

$app->get('/badges', function() use ($app) {
  $body = array();
  $json_body = json_encode($body);

  return $json_body;
});

$app->run();

Return JSON for /badges to make test pass


<?php namespace Modules\Workshop\Tests;

use Orchestra\Testbench\TestCase;

abstract class BaseTestCase extends TestCase
{
    public function setUp()
    {
        parent::setUp();
    }

    protected function getPackageProviders($app)
    {
        return [
            'Modules\Workshop\Providers\WorkshopServiceProvider',
            'Pingpong\Modules\ModulesServiceProvider'
        ];
    }

    protected function getEnvironmentSetUp($app)
    {
        $app['path.base'] = __DIR__ . '/..';
    }
}

<?php namespace Modules\Workshop\Tests;

use Orchestra\Testbench\TestCase;

abstract class BaseTestCase extends TestCase
{
    public function setUp()
    {
        parent::setUp();
    }

    protected function getPackageProviders($app)
    {
        return [
            'Modules\Workshop\Providers\WorkshopServiceProvider',
            'Pingpong\Modules\ModulesServiceProvider'
        ];
    }

    protected function getEnvironmentSetUp($app)
    {
        $app->setBasePath(__DIR__ . '/..');
    }
}

Set the base application path

Set the base application path


<?php

namespace Yajra\CMS\Themes;

use Closure;

class ThemeChanger
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->query('tmpl')) {
            $finder   = app('themes.view.finder');
            $basePath = config('themes.path.frontend', base_path('themes')) . DIRECTORY_SEPARATOR . $request->query('tmpl');
            $finder->setBasePath($basePath);
        }

        return $next($request);
    }
}

<?php

namespace Yajra\CMS\Themes;

use Closure;

class ThemeChanger
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($theme = $request->query('cms-theme')) {
            $finder   = app('themes.view.finder');
            $basePath = config('themes.path.frontend', base_path('themes/frontend'));
            $finder->removeBasePath();
            $finder->setBasePath($basePath . DIRECTORY_SEPARATOR . $theme);

            config(['themes.frontend' => $theme]);
        }

        return $next($request);
    }
}

Fix theme changer. Use cms-theme as query param. Set default theme on config.


<?php

namespace Milax\Mconsole\Models;

use Illuminate\Database\Eloquent\Model;

class MconsoleOption extends Model
{
    use \Cacheable;

    protected $fillable = ['group', 'label', 'key', 'value', 'type', 'options', 'enabled', 'rules'];

    protected $casts = [
        'options' => 'array',
        'rules' => 'array',
    ];

    /**
     * Get option value by its key
     *
     * @param  string $key
     * @return mixed
     */
    public static function getByKey($key)
    {
        if ($option = self::getCached()->where('key', $key)->first()) {
            if (count($option->options) == 2) {
                if (isset($option->options[0]) && isset($option->options[1])) {
                    switch ($option->value) {
                        case '1':
                            return true;
                        case '0':
                            return false;
                    }
                } else {
                    return $option->value;
                }
            } else {
                if (in_array('integer', $option->rules)) {
                    return (int) $option->value;
                } else {
                    return $option->value;
                }
            }
        } else {
            return null;
        }
    }
}

<?php

namespace Milax\Mconsole\Models;

use Illuminate\Database\Eloquent\Model;

class MconsoleOption extends Model
{
    use \Cacheable;

    protected $fillable = ['group', 'label', 'key', 'value', 'type', 'options', 'enabled', 'rules'];

    protected $casts = [
        'options' => 'array',
        'rules' => 'array',
    ];

    /**
     * Get option value by its key
     *
     * @param  string $key
     * @return mixed
     */
    public static function getByKey($key)
    {
        if ($option = self::getCached()->where('key', $key)->first()) {
            if (count($option->options) >= 2) {
                if (isset($option->options[0]) && isset($option->options[1])) {
                    switch ($option->value) {
                        case '1':
                            return true;
                        case '0':
                            return false;
                    }
                } else {
                    return $option->value;
                }
            } else {
                if (is_array($option->rules) && in_array('integer', $option->rules)) {
                    return (int) $option->value;
                } else {
                    return $option->value;
                }
            }
        } else {
            return null;
        }
    }
}

Fix mconsole options array values

Fix mconsole options array values


<?php
require_once("libs/sendgrid-php/sendgrid-php.php");

// Simple class to send email notifications.
class Mailer {

    public static function sendMail($clientAddress, $body) {
        $request_body = json_decode('{
          "personalizations": [
            {
            "to": [
                {
                "email": "'.$clientAddress.'"
                }
            ],
            "cc": [
                {
                "email": "icedaq@bluewin.ch"
                }
            ],
            "subject": "Your order!"
            }
        ],
        "from": {
            "email": "noreply@projweb1.herokuapp.com"
        },
        "content": [
            {
            "type": "text/plain",
            "value": "'.$body.'"
            }
        ]
        }');

        if (Mailer::getWeb1Env() == "PROD")
        {
            $apiKey = getenv('SENDGRID_API');
            $sg = new SendGrid($apiKey);

            $response = $sg->client->mail()->send()->post($request_body);

            // DEBUG
            //echo $request_body."\n";
            //echo $response->statusCode();
            //echo $response->headers();
            //echo $response->body();
            return $response->statusCode();
        } else {
            // We do not send mails in dev and test.
            // Maybe print some debug output here.
        }
    }

    private static function getWeb1Env() {
        $env = getenv('WEB1_ENV');
        if ( $env != "") {
            return $env;
        } else {
            die("WEB1_ENV environment variable is not set!");
        }
    }
}

<?php
require_once(__DIR__ . "/../libs/sendgrid-php/sendgrid-php.php");

// Simple class to send email notifications.
class Mailer {

    public static function sendMail($clientAddress, $body) {
        $request_body = json_decode('{
          "personalizations": [
            {
            "to": [
                {
                "email": "'.$clientAddress.'"
                }
            ],
            "cc": [
                {
                "email": "icedaq@bluewin.ch"
                }
            ],
            "subject": "Your order!"
            }
        ],
        "from": {
            "email": "noreply@projweb1.herokuapp.com"
        },
        "content": [
            {
            "type": "text/plain",
            "value": "'.$body.'"
            }
        ]
        }');

        if (Mailer::getWeb1Env() == "PROD")
        {
            $apiKey = getenv('SENDGRID_API');
            $sg = new \SendGrid($apiKey);

            $response = $sg->client->mail()->send()->post($request_body);

            // DEBUG
            //echo $request_body."\n";
            //echo $response->statusCode();
            //echo $response->headers();
            //echo $response->body();
            return $response->statusCode();
        } else {
            // We do not send mails in dev and test.
            // Maybe print some debug output here.
        }
    }

    private static function getWeb1Env() {
        $env = getenv('WEB1_ENV');
        if ( $env != "") {
            return $env;
        } else {
            die("WEB1_ENV environment variable is not set!");
        }
    }
}

Test something with the mailer.

Test something with the mailer.


<?php
namespace Ratchet\Session\Serialize;

class PhpHandler implements HandlerInterface {
    /**
     * Simply reverse behaviour of unserialize method.
     * {@inheritdoc}
     */
    function serialize(array $data) {
        $preSerialized = [];
        $serialized = '';

        if (count($data)) {
            foreach ($data as $bucket => $bucketData) {
                $preSerialized[] = $bucket . '|' . serialize($bucketData);
            }
            $serialized = implode('',$preSerialized);
        }

        return $serialized;
    }

    /**
     * {@inheritdoc}
     * @link http://ca2.php.net/manual/en/function.session-decode.php#108037 Code from this comment on php.net
     * @throws \UnexpectedValueException If there is a problem parsing the data
     */
    public function unserialize($raw) {
        $returnData = array();
        $offset     = 0;

        while ($offset < strlen($raw)) {
            if (!strstr(substr($raw, $offset), "|")) {
                throw new \UnexpectedValueException("invalid data, remaining: " . substr($raw, $offset));
            }

            $pos     = strpos($raw, "|", $offset);
            $num     = $pos - $offset;
            $varname = substr($raw, $offset, $num);
            $offset += $num + 1;
            $data    = unserialize(substr($raw, $offset));

            $returnData[$varname] = $data;
            $offset += strlen(serialize($data));
        }

        return $returnData;
    }
}

<?php
namespace Ratchet\Session\Serialize;

class PhpHandler implements HandlerInterface {
    /**
     * Simply reverse behaviour of unserialize method.
     * {@inheritdoc}
     */
    function serialize(array $data) {
        $preSerialized = array();
        $serialized = '';

        if (count($data)) {
            foreach ($data as $bucket => $bucketData) {
                $preSerialized[] = $bucket . '|' . serialize($bucketData);
            }
            $serialized = implode('',$preSerialized);
        }

        return $serialized;
    }

    /**
     * {@inheritdoc}
     * @link http://ca2.php.net/manual/en/function.session-decode.php#108037 Code from this comment on php.net
     * @throws \UnexpectedValueException If there is a problem parsing the data
     */
    public function unserialize($raw) {
        $returnData = array();
        $offset     = 0;

        while ($offset < strlen($raw)) {
            if (!strstr(substr($raw, $offset), "|")) {
                throw new \UnexpectedValueException("invalid data, remaining: " . substr($raw, $offset));
            }

            $pos     = strpos($raw, "|", $offset);
            $num     = $pos - $offset;
            $varname = substr($raw, $offset, $num);
            $offset += $num + 1;
            $data    = unserialize(substr($raw, $offset));

            $returnData[$varname] = $data;
            $offset += strlen(serialize($data));
        }

        return $returnData;
    }
}

Create array in old manner (PHP 5.3)

Create array in old manner (PHP 5.3)


<?php

namespace Oro\Bundle\MigrationBundle\Migration;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;

use Oro\Bundle\MigrationBundle\Entity\DataFixture;

class UpdateDataFixturesFixture extends AbstractFixture
{
    /**
     * @var array
     *  key - class name
     *  value - current loaded version
     */
    protected $dataFixturesClassNames;

    /**
     * Set a list of data fixtures to be updated
     *
     * @param array $classNames
     */
    public function setDataFixtures($classNames)
    {
        $this->dataFixturesClassNames = $classNames;
    }

    /**
     * @inheritdoc
     */
    public function load(ObjectManager $manager)
    {return;
        if (!empty($this->dataFixturesClassNames)) {
            $loadedAt = new \DateTime('now', new \DateTimeZone('UTC'));
            foreach ($this->dataFixturesClassNames as $className => $version) {
                $dataFixture = null;
                if ($version !== null) {
                    $dataFixture = $manager
                        ->getRepository('OroMigrationBundle:DataFixture')
                        ->findOneBy(['className' => $className]);
                }
                if (!$dataFixture) {
                    $dataFixture = new DataFixture();
                    $dataFixture->setClassName($className);
                }

                $dataFixture
                    ->setVersion($version)
                    ->setLoadedAt($loadedAt);
                $manager->persist($dataFixture);
            }
            $manager->flush();
        }
    }
}

<?php

namespace Oro\Bundle\MigrationBundle\Migration;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;

use Oro\Bundle\MigrationBundle\Entity\DataFixture;

class UpdateDataFixturesFixture extends AbstractFixture
{
    /**
     * @var array
     *  key - class name
     *  value - current loaded version
     */
    protected $dataFixturesClassNames;

    /**
     * Set a list of data fixtures to be updated
     *
     * @param array $classNames
     */
    public function setDataFixtures($classNames)
    {
        $this->dataFixturesClassNames = $classNames;
    }

    /**
     * @inheritdoc
     */
    public function load(ObjectManager $manager)
    {
        if (!empty($this->dataFixturesClassNames)) {
            $loadedAt = new \DateTime('now', new \DateTimeZone('UTC'));
            foreach ($this->dataFixturesClassNames as $className => $version) {
                $dataFixture = null;
                if ($version !== null) {
                    $dataFixture = $manager
                        ->getRepository('OroMigrationBundle:DataFixture')
                        ->findOneBy(['className' => $className]);
                }
                if (!$dataFixture) {
                    $dataFixture = new DataFixture();
                    $dataFixture->setClassName($className);
                }

                $dataFixture
                    ->setVersion($version)
                    ->setLoadedAt($loadedAt);
                $manager->persist($dataFixture);
            }
            $manager->flush();
        }
    }
}

CRM-2199: Create search handler for A/CI field autocomplete
   -revert changes


<?php

use ApiClients\Client\Github\Authentication\Token;

$keyFile = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'token.php';

if (!file_exists($keyFile)) {
    echo 'No key file find, copy token.sample.php to token.php and add a token from https://github.com/settings/tokens to run examples.', PHP_EOL;
    exit(1);
}

return new Token(require $keyFile);

<?php

use ApiClients\Client\Github\Authentication\Anonymous;
use ApiClients\Client\Github\Authentication\Token;

$keyFile = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'token.php';

if (!file_exists($keyFile)) {
    echo 'No key file find, copy token.sample.php to token.php and add a token from https://github.com/settings/tokens to run examples.', PHP_EOL;
    echo 'We\'ll make Anonymous calls to Github, add a token to token.sample.php to authenticated requests.', PHP_EOL;
    echo '-----------------------------------------------------------------------------------------------------------------------------', PHP_EOL;
    return new Anonymous();
}

return new Token(require $keyFile);

Support anonymous requests, but with a warning


<?php

namespace App\Http\Controllers;

use App\mailingUsers;
use Illuminate\Http\Request;

use App\Http\Requests;

class MailingController extends Controller
{
    /**
     * MailingController constructor.
     *
     * Here the following middleware will be set.
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Get the index page for the mailing module.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $data['title'] = 'Mailing';
        $data['query'] = mailingUsers::with('tag')->paginate(15);

        return view('backend.mailing.index', $data);
    }

    public function mail()
    {

    }

    public function mailGroup()
    {

    }

    public function send()
    {

    }

    public function insert()
    {

    }

    public function store()
    {

    }

    public function update($id)
    {

    }

    /**
     * Delete a user out off the mailing module.
     *
     * @param  int, $id, the user his id in the data table.
     * @return \Illuminate\Http\RedirectResponse
     */
    public function deleteUser($id)
    {
        mailingUsers::find($id)->tag()->sync([]);
        mailingUsers::destroy($id);

        session()->flash('message', '');

        return redirect()->back(302);
    }
}

<?php

namespace App\Http\Controllers;

use App\mailingUsers;
use Illuminate\Http\Request;

use App\Http\Requests;

class MailingController extends Controller
{
    /**
     * MailingController constructor.
     *
     * Here the following middleware will be set.
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Get the index page for the mailing module.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $data['title'] = 'Mailing';
        $data['query'] = mailingUsers::with('tag')->paginate(15);

        return view('backend.mailing.index', $data);
    }

    public function mail()
    {

    }

    public function mailGroup()
    {

    }

    public function send()
    {

    }

    public function insert()
    {

    }

    public function store()
    {

    }

    /**
     * Show the update form off the mailing module.
     *
     * @param  int, $id, the user his id in the data table.
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function update($id)
    {
        $data['title'] = 'mailing';
        $data['query'] = mailingUsers::find($id);

        return view('backend.mailing.update', $data);
    }

    /**
     * Delete a user out off the mailing module.
     *
     * @param  int, $id, the user his id in the data table.
     * @return \Illuminate\Http\RedirectResponse
     */
    public function deleteUser($id)
    {
        mailingUsers::find($id)->tag()->sync([]);
        mailingUsers::destroy($id);

        session()->flash('message', '');

        return redirect()->back(302);
    }
}

Implement the ypdate form controller

Implement the ypdate form controller


@inject('user', 'Illuminate\Contracts\Auth\Authenticatable')

@if(get_meta('navigation::usernav', true))

			 {{ ! is_null($user) ? $user->fullname : trans('orchestra/foundation::title.login') }}

		@unless(is_null($user))

					{{ trans('orchestra/foundation::title.account.profile') }}

					{{ trans('orchestra/foundation::title.account.password') }}

					{{ trans('orchestra/foundation::title.logout') }}

		@endunless

@endif

Add caret to signify dropdown menu

Add caret to signify dropdown menu

Sorry, don't know how to merge commits! :P


<?php
/**
 * CodeIgniter PHP-Development Server Rewrite Rules
 *
 * This script works with serve.php to help run a seamless
 * development server based around PHP's built-in development
 * server. This file simply tries to mimic Apache's mod_rewrite
 * functionality so the site will operate as normal.
 */

$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

$path = __DIR__.'/public/'.ltrim($uri,'/');

// If $path is an existing file or folder within the public folder
// then let the request handle it like normal.
if ($uri !== '/' && (is_file($path) || is_dir($path)))
{
    return false;
}

// Otherwise, we'll load the index file and let
// the framework handle the request from here.

// If we're serving the site locally, then we need
// to let the application know that we're in development mode
$_SERVER['CI_ENVIRONMENT'] = 'development';

require_once __DIR__.'/public/index.php';

<?php
/**
 * CodeIgniter PHP-Development Server Rewrite Rules
 *
 * This script works with serve.php to help run a seamless
 * development server based around PHP's built-in development
 * server. This file simply tries to mimic Apache's mod_rewrite
 * functionality so the site will operate as normal.
 */

// If we're serving the site locally, then we need
// to let the application know that we're in development mode
$_SERVER['CI_ENVIRONMENT'] = 'development';

$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

$path = __DIR__.'/public/'.ltrim($uri,'/');

// If $path is an existing file or folder within the public folder
// then let the request handle it like normal.
if ($uri !== '/' && (is_file($path) || is_dir($path)))
{
    return false;
}

// Otherwise, we'll load the index file and let
// the framework handle the request from here.
require_once __DIR__.'/public/index.php';

Set CI_ENVIRONMENT before return false if uri is /index.php


<?php

use Hoa\Router;

$router = new Router\Http();
$router
    ->get(
        'c',
        '(?<vendor>)/(?<chapter>)\.html'
    )
    ->get(
        'hack',
        '(?<chapter>)\.html'
    )
    ->get(
        'full',
        '/(?<vendor>)/(?<chapter>)\.html'
    )

    ->_get(
        'literature',
        'http://hoa-project.net/Literature\.html'
    )
    ->_get(
        'learn',
        'http://hoa-project.net/Literature/Learn/(?<chapter>)\.html'
    )
    ->get(
        '_resource',
        'http://static.hoa-project.net/(?<resource>)'
    )
    ->_get(
        'central_resource',
        'http://central.hoa-project.net/Resource/(?<path>)'
    )
    ->_get(
        'board',
        'https://waffle.io/hoaproject/(?<repository>)'
    )
    ->_get(
        'git',
        'http://git.hoa-project.net/(?<repository>).git/'
    )
    ->_get(
        'github',
        'https://github.com/hoaproject/(?<repository>)'
    );

<?php

use Hoa\Router;

$router = new Router\Http();
$router
    ->get(
        'c',
        '(?<vendor>)/(?<chapter>)\.html'
    )
    ->get(
        'hack',
        '(?<chapter>)\.html'
    )
    ->get(
        'full',
        '/(?<vendor>)/(?<chapter>)\.html'
    )

    ->_get(
        'literature',
        'http://hoa-project.net/Literature\.html'
    )
    ->_get(
        'learn',
        'http://hoa-project.net/Literature/Learn/(?<chapter>)\.html'
    )
    ->get(
        '_resource',
        'http://static.hoa-project.net/(?<resource>)'
    )
    ->_get(
        'central_resource',
        'http://central.hoa-project.net/Resource/(?<path>)'
    )
    ->_get(
        'board',
        'https://waffle.io/hoaproject/(?<repository>)'
    )
    ->_get(
        'git',
        'http://git.hoa-project.net/(?<repository>).git/'
    )
    ->_get(
        'github',
        'https://github.com/hoaproject/(?<repository>)'
    )
    ->_get(
        'research',
        'http://hoa-project.net/Literature/Research/(?<article>[\w\d]+)\.pdf',
        'Literature\Research'
    )
    ->_get(
        'event',
        'http://hoa-project.net/Event/(?<event>\w+)\.html',
        'Generic'
    )
    ->_get(
        'keynote',
        'http://keynote.hoa-project.net/(?<keynote>)'
    );

Add more rules in the documentation router.


<?php

	# $Id: logout.php,v 1.3 2011-10-02 18:58:36 dan Exp $
	#
	# Copyright (c) 1998-2003 DVL Software Limited

	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');

        syslog(LOG_ERROR, 'you clicked logout');

	freshports_CookieClear();

        syslog(LOG_ERROR, 'logging out');
        if (IsSet($_COOKIE["visitor"])) {
                $visitor = $_COOKIE["visitor"];

                $sql = "UPDATE users SET cookie = 'nocookie' WHERE cookie = '" . pg_escape_string($_COOKIE["visitor"]) . "'";
#                echo $sql;
		syslog(LOG_ERROR, $sql);
		$result = pg_exec($db, $sql);
		if (!$result) {
		  syslog(LOG_ERROR, "$sql -> " . pg_errormessage());
                }
        }

	if (IsSet($_GET['origin'])) {
		$origin = $_GET['origin'];
	} else {
		$origin = '';
	}

	if ($origin == '/index.php') {
		$origin = '';
	}

	header("Location: /$origin");  /* Redirect browser to PHP web site */
	exit;  /* Make sure that code below does not get executed when we redirect. */

<?php

	# $Id: logout.php,v 1.3 2011-10-02 18:58:36 dan Exp $
	#
	# Copyright (c) 1998-2003 DVL Software Limited

	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');

	freshports_CookieClear();

        if (IsSet($_COOKIE["visitor"])) {
                $visitor = $_COOKIE["visitor"];

                $sql = "UPDATE users SET cookie = 'nocookie' WHERE cookie = '" . pg_escape_string($_COOKIE["visitor"]) . "'";
#                echo $sql;
		$result = pg_exec($db, $sql);
		if (!$result) {
                }
        }

	if (IsSet($_GET['origin'])) {
		$origin = $_GET['origin'];
	} else {
		$origin = '';
	}

	if ($origin == '/index.php') {
		$origin = '';
	}

	header("Location: /$origin");  /* Redirect browser to PHP web site */
	exit;  /* Make sure that code below does not get executed when we redirect. */

Remove syslog entries which used an invalid first parameter.


<?php

namespace Bugsnag\BugsnagLaravel\Tests\Request;

use Bugsnag\BugsnagLaravel\Request\LaravelRequest;
use Bugsnag\BugsnagLaravel\Request\LaravelResolver;
use Bugsnag\Request\NullRequest;
use Bugsnag\Request\RequestInterface;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Mockery;
use PHPUnit_Framework_TestCase as TestCase;

class LaravelRequestTest extends TestCase
{
    public function testCanResolveNullRequest()
    {
        $resolver = new LaravelResolver($app = Mockery::mock(Application::class));

        $app->shouldReceive('runningInConsole')->once()->andReturn(true);

        $request = $resolver->resolve();

        $this->assertInstanceOf(RequestInterface::class, $request);
        $this->assertInstanceOf(NullRequest::class, $request);
    }

    public function testCanResolveLaravelRequest()
    {
        $resolver = new LaravelResolver($app = Mockery::mock(Application::class));

        $app->shouldReceive('runningInConsole')->once()->andReturn(false);
        $app->shouldReceive('make')->once()->with(Request::class)->andReturn($request = Mockery::mock(Request::class));

        $request = $resolver->resolve();

        $this->assertInstanceOf(RequestInterface::class, $request);
        $this->assertInstanceOf(LaravelRequest::class, $request);
    }
}

<?php

namespace Bugsnag\BugsnagLaravel\Tests\Request;

use Bugsnag\BugsnagLaravel\Request\LaravelRequest;
use Bugsnag\BugsnagLaravel\Request\LaravelResolver;
use Bugsnag\Request\NullRequest;
use Bugsnag\Request\RequestInterface;
use GrahamCampbell\TestBenchCore\MockeryTrait;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Mockery;
use PHPUnit_Framework_TestCase as TestCase;

class LaravelRequestTest extends TestCase
{
    use MockeryTrait;

    public function testCanResolveNullRequest()
    {
        $resolver = new LaravelResolver($app = Mockery::mock(Application::class));

        $app->shouldReceive('runningInConsole')->once()->andReturn(true);

        $request = $resolver->resolve();

        $this->assertInstanceOf(RequestInterface::class, $request);
        $this->assertInstanceOf(NullRequest::class, $request);
    }

    public function testCanResolveLaravelRequest()
    {
        $resolver = new LaravelResolver($app = Mockery::mock(Application::class));

        $app->shouldReceive('runningInConsole')->once()->andReturn(false);
        $app->shouldReceive('make')->once()->with(Request::class)->andReturn($request = Mockery::mock(Request::class));

        $request = $resolver->resolve();

        $this->assertInstanceOf(RequestInterface::class, $request);
        $this->assertInstanceOf(LaravelRequest::class, $request);
    }
}

Load in the mockery trait

Load in the mockery trait