<?php declare(strict_types=1);

namespace hollodotme\Readis;

use hollodotme\Readis\Application\Configs\AppConfig;
use hollodotme\Readis\Infrastructure\Redis\ServerConnection;
use hollodotme\Readis\Infrastructure\Redis\ServerManager;
use hollodotme\Readis\Interfaces\ProvidesServerConfig;

final class Env extends AbstractObjectPool
{
	public function getAppConfig() : AppConfig
	{
		return $this->getSharedInstance(
			'appConfig',
			function ()
			{
				return new AppConfig();
			}
		);
	}

	public function getServerManager( ProvidesServerConfig $serverConfig ) : ServerManager
	{
		$name = sprintf( 'serverManager-%s:%d', $serverConfig->getHost(), $serverConfig->getPort() );

		return $this->getSharedInstance(
			$name,
			function () use ( $serverConfig )
			{
				$connection = new ServerConnection( $serverConfig );

				return new ServerManager( $connection );
			}
		);
	}
}

<?php declare(strict_types=1);

namespace hollodotme\Readis;

use hollodotme\Readis\Application\Configs\AppConfig;
use hollodotme\Readis\Infrastructure\Configs\ServerConfigList;
use hollodotme\Readis\Infrastructure\Interfaces\ProvidesServerConfig;
use hollodotme\Readis\Infrastructure\Interfaces\ProvidesServerConfigList;
use hollodotme\Readis\Infrastructure\Redis\ServerConnection;
use hollodotme\Readis\Infrastructure\Redis\ServerManager;

final class Env extends AbstractObjectPool
{
	public function getAppConfig() : AppConfig
	{
		return $this->getSharedInstance(
			'appConfig',
			function ()
			{
				return new AppConfig();
			}
		);
	}

	public function getServerConfigList() : ProvidesServerConfigList
	{
		return $this->getSharedInstance(
			'serverConfigList',
			function ()
			{
				return new ServerConfigList();
			}
		);
	}

	public function getServerManager( ProvidesServerConfig $serverConfig ) : ServerManager
	{
		$name = sprintf( 'serverManager-%s:%d', $serverConfig->getHost(), $serverConfig->getPort() );

		return $this->getSharedInstance(
			$name,
			function () use ( $serverConfig )
			{
				$connection = new ServerConnection( $serverConfig );

				return new ServerManager( $connection );
			}
		);
	}
}

Add getter for server config list

Add getter for server config list


					© <?php echo esc_html( date( 'Y' ) ); ?> Copyright <?php bloginfo( 'name' ); ?>. <?php esc_html_e( 'Powered by', 'html5blank' ); ?>
					WordPress & HTML5 Blank.

		<?php wp_footer(); ?>

Make WordPress link open in new window

Make WordPress link open in new window


<?php
/**
 * @version		$Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Weblinks
 * @copyright	Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://www.nooku.org
 */

/**
 * Weblinks Toolbar Class
 *
 * @author    	Jeremy Wilken <http://nooku.assembla.com/profile/gnomeontherun>
 * @category 	Nooku
 * @package     Nooku_Server
 * @subpackage  Weblinks
 */
class ComWeblinksControllerToolbarWeblinks extends ComDefaultControllerToolbarDefault
{
    public function __construct(KConfig $config)
    {
        parent::__construct($config);

        $this->addSeperator()
			 ->addEnable()
			 ->addDisable()
			 ->addSeperator()
			 ->addPreferences();
    }
}

<?php
/**
 * @version		$Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Weblinks
 * @copyright	Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://www.nooku.org
 */

/**
 * Weblinks Toolbar Class
 *
 * @author    	Jeremy Wilken <http://nooku.assembla.com/profile/gnomeontherun>
 * @category 	Nooku
 * @package     Nooku_Server
 * @subpackage  Weblinks
 */
class ComWeblinksControllerToolbarWeblinks extends ComDefaultControllerToolbarDefault
{
    public function getCommands()
    {
        $this->addSeperator()
			 ->addEnable()
			 ->addDisable()
			 ->addSeperator()
			 ->addPreferences();

	    return parent::getCommands();
    }
}

Insert custom commands through the getCommands() function.


<time class="published" datetime="<?php echo get_the_time('c'); ?>"><?php echo get_the_date(); ?></time>

<?php echo __('By', 'roots'); ?> <a href="<?php echo get_author_posts_url(get_the_author_meta('ID')); ?>" rel="author" class="fn"><?php echo get_the_author(); ?>

<time class="updated" datetime="<?php echo get_the_time('c'); ?>"><?php echo get_the_date(); ?></time>

<?php echo __('By', 'roots'); ?> <a href="<?php echo get_author_posts_url(get_the_author_meta('ID')); ?>" rel="author" class="fn"><?php echo get_the_author(); ?>

Update hEntry schema to use `updated` instead of `published` on the time element


<?php

namespace Amp\Test\Thread;

use Amp\Promise;
use Amp\Future;
use Amp\Thread\Thread;
use Amp\Thread\Dispatcher;

function multiply($x, $y) {
    return $x * $y;
}

function exception() {
    throw new \Exception('test');
}

function fatal() {
    $nonexistentObj->nonexistentMethod();
}

class FatalStackable extends \Stackable {
    public function run() {
        $nonexistentObj->nonexistentMethod();
    }
}

class ThrowingStackable extends \Stackable {
    public function run() {
        throw new \Exception('test');
    }
}

class TestAutoloaderStackable extends \Stackable {
    public function run() {
        spl_autoload_register(function() {
            require_once __DIR__ . '/AutoloadableClassFixture.php';
        });
    }
}

class TestStreamStackable extends \Stackable {
    public function run() {
        $this->worker->updateProgress(1);
        $this->worker->updateProgress(2);
        $this->worker->updateProgress(3);
        $this->worker->updateProgress(4);
        $this->worker->registerResult(Thread::SUCCESS, null);
    }
}

function testUpdate($reactor) {
    $dispatcher = new Dispatcher($reactor);
    $promise = $dispatcher->execute(new TestStreamStackable);
    $promise->watch(function($update) {
        echo "$update\n";
    });
    $promise->when(function($error, $result) use ($reactor) {
        assert($result === null);
        $reactor->stop();
    });
}

<?php

namespace Amp\Test\Thread;

use Amp\Promise;
use Amp\Future;
use Amp\Thread\Thread;
use Amp\Thread\Dispatcher;

function multiply($x, $y) {
    return $x * $y;
}

function exception() {
    throw new \Exception('test');
}

function fatal() {
    $nonexistentObj->nonexistentMethod();
}

class FatalStackable extends \Stackable {
    public function run() {
        $nonexistentObj->nonexistentMethod();
    }
}

class ThrowingStackable extends \Stackable {
    public function run() {
        throw new \Exception('test');
    }
}

class TestAutoloaderStackable extends \Stackable {
    public function run() {
        spl_autoload_register(function() {
            require_once __DIR__ . '/AutoloadableClassFixture.php';
        });
    }
}

class TestStreamStackable extends \Stackable {
    public function run() {
        $this->worker->update(1);
        $this->worker->update(2);
        $this->worker->update(3);
        $this->worker->update(4);
        $this->worker->registerResult(Thread::SUCCESS, null);
    }
}

function testUpdate($reactor) {
    $dispatcher = new Dispatcher($reactor);
    $promise = $dispatcher->execute(new TestStreamStackable);
    $promise->watch(function($update) {
        echo "$update\n";
    });
    $promise->when(function($error, $result) use ($reactor) {
        assert($result === null);
        $reactor->stop();
    });
}

Fix bad method name in test task

Fix bad method name in test task


<?php

/**
 * This file is part of the Krystal Framework
 *
 * Copyright (c) No Global State Lab
 *
 * For the full copyright and license information, please view
 * the license file that was distributed with this source code.
 */

namespace Krystal\Db\Sql\Connector;

use PDO;

final class MySQL implements ConnectorInterface
{
    /**
     * {@inheritDoc}
     */
    public function getArgs(array $config)
    {
        $dsn = 'mysql:host='.$config['host'];

        if (isset($config['dbname'])) {
            $dsn .= ';dbname='.$config['dbname'];
        }

        return array($dsn, $config['username'], $config['password'], array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8',
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => true,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            // Disable STRICT mode
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"'
        ));
    }
}

<?php

/**
 * This file is part of the Krystal Framework
 *
 * Copyright (c) No Global State Lab
 *
 * For the full copyright and license information, please view
 * the license file that was distributed with this source code.
 */

namespace Krystal\Db\Sql\Connector;

use PDO;

final class MySQL implements ConnectorInterface
{
    /**
     * {@inheritDoc}
     */
    public function getArgs(array $config)
    {
        $dsn = 'mysql:host='.$config['host'];

        if (isset($config['dbname'])) {
            $dsn .= ';dbname='.$config['dbname'];
        }

        $dsn .= ';charset=utf8';

        return array($dsn, $config['username'], $config['password'], array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => true,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            // Disable STRICT mode
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"'
        ));
    }
}

Set charset in DSN string

Set charset in DSN string


<?php

namespace ScottRobertson\Scrutiny;

class Client
{
    private $services = array();
    private $reporters = array();

    public function addService($service)
    {
        $this->services[] = $service;
    }

    public function addReporter($reporter)
    {
        $this->reporters[] = $reporter;
    }

    public function watch($global_interval = 20)
    {
        while (true) {
            foreach ($this->services as $service) {
                if ($service->checkable()) {
                    $this->report($service->getStatus());
                }
            }

            sleep($global_interval);
        }
    }

    public function report(\ScottRobertson\Scrutiny\Service\Base $service)
    {
        foreach ($this->reporters as $report) {
            if ($report->subscribed($service->getEvent())) {
                $report->report($service, $this->hostname);
            }
        }
    }
}

<?php

namespace ScottRobertson\Scrutiny;

class Client
{
    private $services = array();
    private $reporters = array();

    public function addService($service)
    {
        $this->services[] = $service;
    }

    public function addReporter($reporter)
    {
        $this->reporters[] = $reporter;
    }

    public function getServices()
    {
        return $this->services;
    }

    public function getReporters()
    {
        return $this->reporters;
    }

    public function watch($global_interval = 20)
    {
        while (true) {
            foreach ($this->services as $service) {
                if ($service->checkable()) {
                    $this->report($service->getStatus());
                }
            }

            sleep($global_interval);
        }
    }

    public function report(\ScottRobertson\Scrutiny\Service\Base $service)
    {
        foreach ($this->reporters as $report) {
            if ($report->subscribed($service->getEvent())) {
                $report->report($service, $this->hostname);
            }
        }
    }
}

Add the ability to list services and reporters


<?php

$app = require __DIR__ . '/../app/app.php';

if ($app instanceof Silex\Application) {
    $app->run();
} else {
    echo 'Failed to initialize application.';
}

<?php

$filename = __DIR__.preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
    return false;
}

$app = require __DIR__ . '/../app/app.php';

if ($app instanceof Silex\Application) {
    $app->run();
} else {
    echo 'Failed to initialize application.';
}

Add support for PHP 5.4 built-in webserver


<?php
namespace Dynamo\Mapper;

use Fixtures\Person;

class MapperTest extends \PHPUnit_Framework_TestCase
{
    public function testShouldBuildEntityWithDataArray()
    {
        $data = [
            'Items' => [
                [
                    'id' => ['N' => '1'],
                    'name' => ['S' => 'Foo'],
                    'gender' => ['S' => 'male'],
                ],
                [
                    'id' => ['N' => '2'],
                    'name' => ['S' => 'Bar'],
                    'gender' => ['S' => 'female'],
                ],
            ],
            'Count' => 2,
            'ScannedCount' => 2,
            '@metadata' => []
        ];

        $entities = (new Mapper())->setEntityClass(new Person)
            ->setData($data)
            ->getMappedEntity();

        $this->assertCount(2, $entities);
    }
}

<?php
namespace Dynamo\Mapper;

use Fixtures\Person;

class MapperTest extends \PHPUnit_Framework_TestCase
{
    public function testShouldBuildEntityWithDataArray()
    {
        $data = [
            'Items' => [
                [
                    'id' => ['N' => '1'],
                    'name' => ['S' => 'Foo'],
                    'gender' => ['S' => 'male'],
                ],
                [
                    'id' => ['N' => '2'],
                    'name' => ['S' => 'Bar'],
                    'gender' => ['S' => 'female'],
                ],
            ],
            'Count' => 2,
            'ScannedCount' => 2,
            '@metadata' => []
        ];

        $entities = (new Mapper())->setEntityClass(new Person)
            ->setData($data)
            ->getMappedEntity();

        $this->assertCount(2, $entities);

        $result1 = $entities[0];
        $result2 = $entities[1];

        $this->assertEquals(1, $result1->getId());
        $this->assertEquals('Foo', $result1->getName());
        $this->assertEquals('male', $result1->gender);

        $this->assertEquals(2, $result2->getId());
        $this->assertEquals('Bar', $result2->getName());
        $this->assertEquals('female', $result2->gender);
    }
}

Add a little bit of tests

Add a little bit of tests


<?php

function dephendency($class) {
    if (is_file(__DIR__.'/../'.$class.'.php')) {
        require_once(__DIR__.'/../'.$class.'.php');
    }
    else {
        require_once(__DIR__.'/../../../'.$class.'.php');
    }
}

spl_autoload_register('dephendency');

<?php

function dephendency($class) {
    $class = str_replace("\\", '/', $class);
    if (is_file(__DIR__.'/../'.$class.'.php')) {
        require_once(__DIR__.'/../'.$class.'.php');
    }
    else {
        require_once(__DIR__.'/../../../'.$class.'.php');
    }
}

spl_autoload_register('dephendency');

Convert backslash to fowardslah for unix support.


<?php
	require("bin/fw.php");
	define('N', "\n");
	define('BR', "
");
	define('BRN', "
\n");

# plg_visitor
	echo "You are using ".browserName." ver ".browserVer." on ".platformFamily." ".(is64bit ? "64 bit" : "32 bit")." from ".getIP().BRN;

# plg_dump
	$arr = array("Defined Variables"=>get_defined_vars(), "Defined Constants"=>get_defined_constants());
	echo dump($arr, TRUE, TRUE).BRN;

# plg_system
	echo 'echo clean_number(\'4f32k91025\'); # will output '.clean_number('4f32k91025').''.BRN;
	echo 'echo decimal_to_fraction(\'.125\'); # will output '.decimal_to_fraction ('.125').''.BRN;
	echo 'echo fraction_to_decimal(\'1/8\'); # will output '.fraction_to_decimal ('1/8').''.BRN;
	echo 'echo is_whole_number(\'1/8\'); # will output '.is_whole_number (45.21).''.BRN;

Update ver 0.1 Beta (Build 9) plg_system examples


<?php

// Centers the plugin content in the wiki page
// Usage
// {CENTER()}
//  data
// {CENTER}
function wikiplugin_center_help() {
	return tra("Centers the plugin content in the wiki page").":
~np~{CENTER()}".tra("text")."{CENTER}~/np~";
}

function wikiplugin_center_info() {
	return array(
		'name' => tra('Center'),
		'documentation' => 'PluginCenter',
		'description' => tra("Centers the plugin content in the wiki page"),
		'prefs' => array('wikiplugin_center'),
		'body' => tra('text'),
		'params' => array(
		),
	);
}

function wikiplugin_center($data, $params) {
	global $tikilib;

	extract ($params,EXTR_SKIP);
	$data = '
' . trim($data). '
';
	return $data;
}

<?php

// Centers the plugin content in the wiki page
// Usage
// {CENTER()}
//  data
// {CENTER}
function wikiplugin_center_help() {
	return tra("Centers the plugin content in the wiki page").":
~np~{CENTER()}".tra("text")."{CENTER}~/np~";
}

function wikiplugin_center_info() {
	return array(
		'name' => tra('Center'),
		'documentation' => 'PluginCenter',
		'description' => tra("Centers the plugin content in the wiki page"),
		'prefs' => array('wikiplugin_center'),
		'body' => tra('text'),
		'icon' => 'pics/icons/text_align_center.png',
		'params' => array(
		),
	);
}

function wikiplugin_center($data, $params) {
	global $tikilib;

	extract ($params,EXTR_SKIP);
	$data = '
' . trim($data). '
';
	return $data;
}

Add missing icon to PluginCenter

[ENH] Add missing icon to PluginCenter

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@20876 b456876b-0849-0410-b77d-98878d47e9d5


<?php

declare(strict_types=1);

namespace Linio\Common\Logging;

use Linio\Common\Exception\CriticalError;

class CriticalErrorProcessor
{
    public function __invoke(array $record): array
    {
        $exception = $record['context']['exception'] ?? null;

        if (!$exception instanceof CriticalError) {
            return $record;
        }

        // Monolog doesn't use psr\log\LogLevel values internally
        $record['level'] = 500;
        $record['levelName'] = 'CRITICAL';

        return $record;
    }
}

<?php

declare(strict_types=1);

namespace Linio\Common\Logging;

use Linio\Common\Exception\CriticalError;
use Monolog\Logger;
use Psr\Log\LogLevel;

class CriticalErrorProcessor
{
    public function __invoke(array $record): array
    {
        $exception = $record['context']['exception'] ?? null;

        if (!$exception instanceof CriticalError) {
            return $record;
        }

        $record['level'] = Logger::toMonologLevel(LogLevel::CRITICAL);
        $record['levelName'] = Logger::getLevelName($record['level']);

        return $record;
    }
}

Use Monolog's PSR 3 level conversion.

Use Monolog's PSR 3 level conversion.


<?php

// Switch PhabricatorWorkerActiveTask from autoincrement IDs to counter IDs.
// Set the initial counter ID to be larger than any known task ID.

$active_table = new PhabricatorWorkerActiveTask();
$archive_table = new PhabricatorWorkerArchiveTask();

$conn_w = $active_table->establishConnection('w');

$active_auto = head(queryfx_one(
  $conn_w,
  'SELECT auto_increment FROM information_schema.tables
    WHERE table_name = %s
    AND table_schema = DATABASE()',
  $active_table->getTableName()));

$active_max = head(queryfx_one(
  $conn_w,
  'SELECT MAX(id) FROM %T',
  $active_table->getTableName()));

$archive_max = head(queryfx_one(
  $conn_w,
  'SELECT MAX(id) FROM %T',
  $archive_table->getTableName()));

$initial_counter = max((int)$active_auto, (int)$active_max, (int)$archive_max);

queryfx(
  $conn_w,
  'INSERT IGNORE INTO %T (counterName, counterValue)
    VALUES (%s, %d)',
  LiskDAO::COUNTER_TABLE_NAME,
  $active_table->getTableName(),
  $initial_counter + 1);

// Drop AUTO_INCREMENT from the ID column.
queryfx(
  $conn_w,
  'ALTER TABLE %T CHANGE id id INT UNSIGNED NOT NULL',
  $active_table->getTableName());

<?php

// Switch PhabricatorWorkerActiveTask from autoincrement IDs to counter IDs.
// Set the initial counter ID to be larger than any known task ID.

$active_table = new PhabricatorWorkerActiveTask();
$archive_table = new PhabricatorWorkerArchiveTask();

$conn_w = $active_table->establishConnection('w');

$active_auto = head(queryfx_one(
  $conn_w,
  'SELECT auto_increment FROM information_schema.tables
    WHERE table_name = %s
    AND table_schema = DATABASE()',
  $active_table->getTableName()));

$active_max = head(queryfx_one(
  $conn_w,
  'SELECT MAX(id) FROM %T',
  $active_table->getTableName()));

$archive_max = head(queryfx_one(
  $conn_w,
  'SELECT MAX(id) FROM %T',
  $archive_table->getTableName()));

$initial_counter = max((int)$active_auto, (int)$active_max, (int)$archive_max);

queryfx(
  $conn_w,
  'INSERT INTO %T (counterName, counterValue)
    VALUES (%s, %d)
    ON DUPLICATE KEY UPDATE counterValue = %d',
  LiskDAO::COUNTER_TABLE_NAME,
  $active_table->getTableName(),
  $initial_counter + 1,
  $initial_counter + 1);

// Drop AUTO_INCREMENT from the ID column.
queryfx(
  $conn_w,
  'ALTER TABLE %T CHANGE id id INT UNSIGNED NOT NULL',
  $active_table->getTableName());

Make Lisk counters patch more robust

Make Lisk counters patch more robust

Summary:
We need to revert this patch and we will need to re-apply it later.
We can't drop the table and delete these rows as we need to run both versions for a temporary period.

Test Plan: Applied it.

Reviewers: epriestley, nh

Reviewed By: epriestley

CC: aran, Korvin

Differential Revision: https://secure.phabricator.com/D3924


<?php
class RecaptchaWidget extends Widget{
	function render($name, $value, $options = array()){
		global $ATK14_GLOBAL;
		$lang = $ATK14_GLOBAL->getLang(); // TODO: https://developers.google.com/recaptcha/docs/language
		$out = array();
		$out[] = ''; // TODO: Paste this snippet before the closing  tag on your HTML template:
		$out[] = '
'; // TODO: Do I like the inline style?
		$out[] = '

';
		$out[] = '
';
		$out[] = '

';

		// This is a fake hidden field which makes the Form framework in thinking that the value is submitted as usually.
		// It is important for the Field::clean() method.
		$out[] = sprintf('<input type="hidden" name="%s" value="sent">',$name);

		return join("\n",$out);
	}
}

<?php
class RecaptchaWidget extends Widget{
	function render($name, $value, $options = array()){
		global $ATK14_GLOBAL;
		$lang = $ATK14_GLOBAL->getLang(); // TODO: https://developers.google.com/recaptcha/docs/language
		$out = array();
		$out[] = ''; // TODO: Paste this snippet before the closing  tag on your HTML template:
		$out[] = '

';

		// This is a fake hidden field which makes the Form framework in thinking that the value is submitted as usually.
		// It is important for the Field::clean() method.
		$out[] = sprintf('<input type="hidden" name="%s" value="sent">',$name);

		return join("\n",$out);
	}
}

Remove obsolete unused floating wrappers and cleaners.


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Console\Commands;

use Illuminate\Console\Command;
use Rinvex\Support\Traits\SeederHelper;

class SeedCommand extends Command
{
    use SeederHelper;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:seed:foundation';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Seed Cortex Foundation Data.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $this->warn('Seed cortex/foundation:');

        if ($this->ensureExistingDatabaseTables('rinvex/fort')) {
            $this->seedResources(app('rinvex.fort.ability'), realpath(__DIR__.'/../../../resources/data/abilities.json'), ['name', 'description']);
        }
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Foundation\Console\Commands;

use Illuminate\Console\Command;
use Rinvex\Support\Traits\SeederHelper;

class SeedCommand extends Command
{
    use SeederHelper;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:seed:foundation';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Seed Cortex Foundation Data.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $this->warn('Seed cortex/foundation:');

        if ($this->ensureExistingDatabaseTables('rinvex/fort')) {
            $this->seedResources(app('rinvex.fort.ability'), realpath(__DIR__.'/../../../resources/data/abilities.json'), ['name', 'description', 'policy']);
        }
    }
}

Exclude policy from existing ability seeder query check


<?php

namespace Huntie\JsonApi\Http\Requests;

use Huntie\JsonApi\Http\JsonApiResponse;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Response;

abstract class JsonApiRequest extends FormRequest
{
    /**
     * Format the errors from the given Validator instance.
     *
     * {@inheritdoc}
     */
    protected function formatErrors(Validator $validator)
    {
        $errors = [];

        foreach ($validator->getMessageBag()->messages() as $field => $messages) {
            foreach ($messages as $message) {
                $errors[] = [
                    'source' => [
                        'pointer' => str_replace('.', '/', $field),
                    ],
                    'title' => 'Invalid attribute',
                    'detail' => $message,
                ];
            }
        }

        return compact('errors');
    }

    /**
     * Get the proper failed validation response for the request.
     *
     * @param array $errors
     *
     * @return JsonApiResponse
     */
    public function response(array $errors)
    {
        return new JsonApiResponse($errors, Response::HTTP_UNPROCESSABLE_ENTITY);
    }
}

<?php

namespace Huntie\JsonApi\Http\Requests;

use Huntie\JsonApi\Http\JsonApiResponse;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Response;

abstract class JsonApiRequest extends FormRequest
{
    /**
     * Format the errors from the given Validator instance.
     *
     * {@inheritdoc}
     */
    protected function formatErrors(Validator $validator)
    {
        $errors = [];

        foreach ($validator->getMessageBag()->messages() as $field => $messages) {
            foreach ($messages as $message) {
                $errors[] = [
                    'source' => [
                        'pointer' => str_replace('.', '/', $field),
                    ],
                    'title' => 'Invalid attribute',
                    'detail' => str_replace('data.attributes.', '', $message),
                ];
            }
        }

        return compact('errors');
    }

    /**
     * Get the proper failed validation response for the request.
     *
     * @param array $errors
     *
     * @return JsonApiResponse
     */
    public function response(array $errors)
    {
        return new JsonApiResponse($errors, Response::HTTP_UNPROCESSABLE_ENTITY);
    }
}

Adjust returned field name in validation error response


<?php
namespace Composer\Installers;

class KirbyInstaller extends BaseInstaller
{
    protected $locations = array(
        'plugin'    => 'site/plugins/{$name}/',
    );
}

<?php
namespace Composer\Installers;

class KirbyInstaller extends BaseInstaller
{
    protected $locations = array(
        'plugin'    => 'site/plugins/{$name}/',
        'field'    => 'site/fields/{$name}/',
        'tag'    => 'site/tags/{$name}/'
    );
}

Add field and tag types

Add field and tag types


<?php
/*
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

namespace ZfTwitterWidgetTests\View;

use ZfTwitterWidget\View\OneTimeJsViewHelper;

class OneTimeJsViewHelperTest extends \PHPUnit_Framework_TestCase
{
    public function testOneTimeJsViewHelper()
    {
        $oneTimeJsVH = new OneTimeJsViewHelper();

        $this->assertGreaterThan(0, strpos($oneTimeJsVH(), 'window.twttr'));
    }
}

<?php
/*
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

namespace ZfTwitterWidgetTests\View;

use ZfTwitterWidget\View\OneTimeJsViewHelper;

class OneTimeJsViewHelperTest extends \PHPUnit_Framework_TestCase
{
    public function testOneTimeJsViewHelper()
    {
        $oneTimeJsVH = new OneTimeJsViewHelper();

        $this->assertGreaterThan(0, strpos($oneTimeJsVH(), 'widgets.js'));
    }
}

Change string to check in test

Change string to check in test


<?php

/**
  * Gets various Metrolink variables
  **/
class Metrolink
{
    /**
     * Checks peak hours: if it is, then post normal service tweets as well
     * @return bool
     */
    public function isPeak()
    {
        if (true == MMS_DEBUG) {
            return true;
        }

        // Always off-peak during weekends
        if (date('N') == 6 || date('N') == 7) return false;

        $date = date('H');
        if ($date >= 6 && $date <= 10) return true;
        if ($date >= 17 && $date <= 19) return true;
        return false;
    }
}

<?php

/**
  * Gets various Metrolink variables
  **/
class Metrolink
{
    /**
     * Checks peak hours: if it is, then post normal service tweets as well
     * @return bool
     */
    public function isPeak()
    {
        // Always off-peak during weekends
        if (date('N') == 6 || date('N') == 7) return false;

        $date = date('H');
        if ($date >= 6 && $date <= 10) return true;
        if ($date >= 17 && $date <= 19) return true;
        return false;
    }
}

Remove peak debug, at least for now.

Remove peak debug, at least for now.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
	protected $hidden = [
		'user_id', 'updated_at', 'deleted_at',
	];

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
	use SoftDeletes;

	protected $hidden = [
		'user_id', 'updated_at', 'deleted_at',
	];

	protected $dates = ['deleted_at'];

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

Add SoftDelete trait to post model

Add SoftDelete trait to post model


<?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\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;

/**
 * @author Grzegorz Sadowski <grzegorz.sadowski@lakion.com>
 */
interface ImageInterface extends ResourceInterface
{
    /**
     * @return string
     */
    public function getCode();

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

    /**
     * @return bool
     */
    public function hasFile();

    /**
     * @return null|\SplFileInfo
     */
    public function getFile();

    /**
     * @param \SplFileInfo $file
     */
    public function setFile(\SplFileInfo $file);

    /**
     * @return string
     */
    public function getPath();

    /**
     * @param string $path
     */
    public function setPath($path);

    /**
     * @return ImageAwareInterface
     */
    public function getOwner();

    /**
     * @param ImageAwareInterface $owner
     */
    public function setOwner(ImageAwareInterface $owner = null);
}

<?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\Resource\Model\CodeAwareInterface;
use Sylius\Component\Resource\Model\ResourceInterface;

/**
 * @author Grzegorz Sadowski <grzegorz.sadowski@lakion.com>
 */
interface ImageInterface extends ResourceInterface, CodeAwareInterface
{
    /**
     * @return bool
     */
    public function hasFile();

    /**
     * @return null|\SplFileInfo
     */
    public function getFile();

    /**
     * @param \SplFileInfo $file
     */
    public function setFile(\SplFileInfo $file);

    /**
     * @return string
     */
    public function getPath();

    /**
     * @param string $path
     */
    public function setPath($path);

    /**
     * @return ImageAwareInterface
     */
    public function getOwner();

    /**
     * @param ImageAwareInterface $owner
     */
    public function setOwner(ImageAwareInterface $owner = null);
}

[Taxon][Image] Add validation for taxon image code uniqueness


<?php

namespace ajax\listing;

use \PDO as PDO;

/**
 * Web Service.
 * Returns Trait informatio
 */
class Traits extends \WebService {

    /**
     * @param $querydata[]
     * @returns array of traits
     */
    public function execute($querydata) {
        global $db;
        $data = array();
        $search = "%%";
        if(in_array('search', array_keys($querydata))){
            $search = "%".$querydata['search']."%";
        }
        $query_get_traits = <<<EOF
SELECT name, tci.type_cvterm_id FROM (SELECT DISTINCT type_cvterm_id FROM trait_entry) AS tci, trait_cvterm WHERE tci.type_cvterm_id=trait_cvterm.trait_cvterm_id;
EOF;
        $stm_get_traits = $db->prepare($query_get_traits);
        $stm_get_traits->execute();

        while ($row = $stm_get_traits->fetch(PDO::FETCH_ASSOC)) {
            $result=array();
            $result['name']=$row['name'];
            $data[]=$result;
        }
        return data;
    }
}

?>

<?php

namespace ajax\listing;

use \PDO as PDO;

/**
 * Web Service.
 * Returns Trait informatio
 */
class Traits extends \WebService {

    /**
     * @param $querydata[]
     * @returns array of traits
     */
    public function execute($querydata) {
        global $db;
        $search = "%%";
        if(in_array('search', array_keys($querydata))){
            $search = "%".$querydata['search']."%";
        }
        $query_get_traits = <<<EOF
SELECT name, tci.type_cvterm_id FROM (SELECT DISTINCT type_cvterm_id FROM trait_entry) AS tci, trait_cvterm WHERE tci.type_cvterm_id=trait_cvterm.trait_cvterm_id AND name LIKE :search;
EOF;
        $stm_get_traits = $db->prepare($query_get_traits);
        $stm_get_traits->bindValue('search', $search);
        $stm_get_traits->execute();

        $data = array();
        while ($row = $stm_get_traits->fetch(PDO::FETCH_ASSOC)) {
            $result = array();
            $result['name'] = $row['name'];
            $data[] = $result;
        }
        return $data;
    }
}

?>

Return trait names according to a search term


<?php

namespace Spatie\Activitylog\Test\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $table = 'articles';

    protected $guarded = [];

    public function User()
    {
        return $this->belongsTo(User::class);
    }
}

<?php

namespace Spatie\Activitylog\Test\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $table = 'articles';

    protected $guarded = [];

    public function User()
    {
        return $this->belongsTo(User::class);
    }

    public function SnakeUser()
    {
    	return $this->belongsTo(User::class, 'user_id');
    }
}

Add a snake cased relationship

Add a snake cased relationship

In order to test correct behaviour of "snake case" defined relationships, we need a relationship which can be snake cased in this test model.


<?php

namespace App\Bootstrap\Test;

use Core\ParameterWire;
use PHPUnit\Framework\TestCase;
use Core\Bootstrap\Bootstrap;
use Prob\Handler\Parameter\Named;
use Prob\Handler\ParameterMap;
use Prob\Handler\Proc\ClosureProc;

class ParameterWiringBootstrap extends TestCase
{
    public function testBoot()
    {
        $bootstrap = new Bootstrap([
            'App\\Bootstrap\\ParameterWiringBootstrap',
        ]);
        $bootstrap->boot([
            'parameter' => [
                [
                    'key' => new Named('test'),
                    'value' => 'hello!'
                ]
            ]
        ]);

        $map = new ParameterMap();
        ParameterWire::injectParameter($map);

        $proc = new ClosureProc(function($test) {
            return $test;
        });

        $this->assertEquals('hello!', $proc->execWithParameterMap($map));
    }
}

<?php

namespace App\Bootstrap\Test;

use Core\ParameterWire;
use Core\Utils\Parameter\Parameter;
use PHPUnit\Framework\TestCase;
use Core\Bootstrap\Bootstrap;
use Prob\Handler\Parameter\Named;
use Prob\Handler\ParameterMap;
use Prob\Handler\Proc\ClosureProc;

class ParameterWiringBootstrap extends TestCase
{
    public function testBoot()
    {
        $bootstrap = new Bootstrap([
            'App\\Bootstrap\\ParameterWiringBootstrap',
        ]);
        $bootstrap->boot([
            'parameter' => [
                [
                    'key' => new Named('test'),
                    'value' => 'hello!'
                ],
                ParameterWire::lazyCallback(function() {
                    return [
                        [
                            'key' => new Named('test2'),
                            'value' => 'world!'
                        ]
                    ];
                })
            ]
        ]);

        $map = new ParameterMap();
        ParameterWire::injectParameter($map);

        $proc = new ClosureProc(function($test, $test2) {
            return $test.$test2;
        });

        $this->assertEquals('hello!world!', $proc->execWithParameterMap($map));
    }
}

Add a test case of lazyCallbackWiring in ParameterBootstrap


<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use SensioLabs\Security\SecurityChecker;

class SecurityCheck extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'security:check';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run the SensioLab’s Security Check tool';

    /**
     * The Security Checker intergation service.
     *
     * @var SecurityChecker
     */
    protected $securityChecker;

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

        $this->securityChecker = $securityChecker;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        return $this->securityChecker->check(base_path() . '/composer.lock');
    }
}

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use SensioLabs\Security\SecurityChecker;

class SecurityCheck extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'security:check';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run the SensioLab’s Security Check tool';

    /**
     * The Security Checker intergation service.
     *
     * @var SecurityChecker
     */
    protected $securityChecker;

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

        $this->securityChecker = $securityChecker;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $alerts = $this->securityChecker->check(base_path() . '/composer.lock');
        if (count($alerts) === 0) {
            $this->info('No security vulnerabilities found.');

            return 0;
        }
        $this->error('vulnerabilities found');

        return 1;
    }
}

Improve command output from nothing

Improve command output from nothing


<?php

namespace hceudevs\RateLimitBundle\Service\Storage;

use Noxlogic\RateLimitBundle\Service\RateLimitInfo;
use Predis\Client;

class Redis implements StorageInterface
{
    /**
     * @var \Predis\Client
     */
    protected $client;

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

    public function getRateInfo($key)
    {
        $info = $this->client->hgetall($key);

        $rateLimitInfo = new RateLimitInfo();
        $rateLimitInfo->setLimit($info['limit']);
        $rateLimitInfo->setCalls($info['calls']);
        $rateLimitInfo->setResetTimestamp($info['reset']);

        return $rateLimitInfo;
    }

    public function limitRate($key)
    {
        if (! $this->client->hexists($key, 'limit')) {
            return false;
        }

        $this->client->hincrby($key, 'calls', 1);

        return $this->getRateInfo($key);
    }

    public function createRate($key, $limit, $period)
    {
        $this->client->hset($key, 'limit', $limit);
        $this->client->hset($key, 'calls', 1);
        $this->client->hset($key, 'reset', time() + $period);
        $this->client->expire($key, $period);

        return $this->getRateInfo($key);
    }

    public function resetRate($key)
    {
        $this->client->hdel($key);
        return true;
    }
}

<?php

namespace hceudevs\RateLimitBundle\Service\Storage;

use Noxlogic\RateLimitBundle\Service\RateLimitInfo;
use Predis\Client;

class Redis implements StorageInterface
{
    /**
     * @var \Predis\Client
     */
    protected $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function getRateInfo($key)
    {
        $info = $this->client->hgetall($key);

        $rateLimitInfo = new RateLimitInfo();
        $rateLimitInfo->setLimit($info['limit']);
        $rateLimitInfo->setCalls($info['calls']);
        $rateLimitInfo->setResetTimestamp($info['reset']);

        return $rateLimitInfo;
    }

    public function limitRate($key)
    {
        if (! $this->client->hexists($key, 'limit')) {
            return false;
        }

        $this->client->hincrby($key, 'calls', 1);

        return $this->getRateInfo($key);
    }

    public function createRate($key, $limit, $period)
    {
        $this->client->hset($key, 'limit', $limit);
        $this->client->hset($key, 'calls', 1);
        $this->client->hset($key, 'reset', time() + $period);
        $this->client->expire($key, $period);

        return $this->getRateInfo($key);
    }

    public function resetRate($key)
    {
        $this->client->hdel($key);
        return true;
    }
}

Revert "update to remove client type hinting"

This reverts commit a73a6e688d7bcaa17b6c3ba2688291dfa878ea5d.


<?
define('E_REPORTING', E_ALL & ~E_NOTICE);
error_reporting(E_REPORTING);
ini_set('display_errors', 'On');
define('TIME_START', microtime(true));
define('ROOT', dirname(dirname(__FILE__)));
define('CONFIG_ROOT', dirname(dirname(dirname(__FILE__))).'/config');
define('PROJECT', strtolower(isset($_ENV["PROJECT"]) ? $_ENV["PROJECT"] : null));
define('PROJECT_ROOT', PROJECT ? dirname(ROOT).'/appers/'.PROJECT : null);
define('PROJECTS_ROOT', dirname(ROOT).'/appers');
define('EXEC_PATH', __FILE__);
require ROOT.'/lib/application/loader.php';
loader::init();
config::init();
if(config::get('restartWorkersOnChange')) {
	if(loader::isFilesChanged()) {
		bg::restartWorkers();
	}
}

<?
define('E_REPORTING', E_ALL & ~E_NOTICE);
error_reporting(E_REPORTING);
ini_set('display_errors', 'On');
define('TIME_START', microtime(true));
define('ROOT', dirname(dirname(__FILE__)));
define('CONFIG_ROOT', dirname(dirname(dirname(__FILE__))).'/config');
define('PROJECT', strtolower(isset($_ENV["PROJECT"]) ? $_ENV["PROJECT"] : null));
define('PROJECT_ROOT', PROJECT ? dirname(ROOT).'/appers/'.PROJECT : null);
define('PROJECTS_ROOT', dirname(ROOT).'/appers');
define('EXEC_PATH', dirname(__FILE__).'/exec.php');
require ROOT.'/lib/application/loader.php';
loader::init();
config::init();
if(config::get('restartWorkersOnChange')) {
	if(loader::isFilesChanged()) {
		bg::restartWorkers();
	}
}

Fix bug with cli scripts

Fix bug with cli scripts


<?php

namespace Drupal\wmcontroller\Annotation;

use Drupal\Component\Annotation\Plugin;

/**
 * @Annotation
 */
class Controller extends Plugin
{
    /** @var string */
    public $entity_type;
    /** @var string */
    public $bundle;

    public function getId()
    {
        if (isset($this->definition['entity_type'], $this->definition['bundle'])) {
            return implode('.', [
                $this->definition['entity_type'],
                $this->definition['bundle'],
            ]);
        }

        return parent::getId();
    }
}

<?php

namespace Drupal\wmcontroller\Annotation;

use Drupal\Component\Annotation\Plugin;

/**
 * @Annotation
 */
class Controller extends Plugin
{
    /** @var string */
    public $entity_type;
    /** @var string */
    public $bundle;

    public function getId()
    {
        if (isset($this->definition['entity_type'], $this->definition['bundle'])) {
            return implode('.', [
                $this->definition['entity_type'],
                $this->definition['bundle'],
            ]);
        }

        if (isset($this->definition['entity_type'])) {
            return implode('.', [
                $this->definition['entity_type'],
                $this->definition['entity_type'],
            ]);
        }

        return parent::getId();
    }
}

Fix annotation for entities without bundle


<?php

namespace App\Models;

class Player extends \Pragma\ORM\Model
{
    const GENOME_HOST       = 0;
    const GENOME_NORMAL     = 1;
    const GENOME_RESISTANT  = 2;

	private $name;
	private $keyId;
	private $genome;
	private $role;
	private $paralysed;
	private $mutated;
	private $alive;

	public function __construct($name)
	{
		return parent::__construct('player');
		$this->name=$name;
	}

	public function setGenome($genome){
		if($genome>0){
			$genome=1;
		}elseif($genome<0){
			$genome=-1;
		}else{
			$genome=0;
		}
		$this->genome=$genome;
	}

	public function mutate() {
		if ($this->genome != self::GENOME_RESISTANT) {
			$this->mutated=1;
			return true;
		}
		return false;
	}

	public function cure() {
		if ($this->genome != self::GENOME_HOST || !$this->mutated) {
			$this->mutated=0;
			return true;
		}
		return false;
	}

}

<?php

namespace App\Models;

class Player extends \Pragma\ORM\Model
{
    const GENOME_HOST       = 0;
    const GENOME_NORMAL     = 1;
    const GENOME_RESISTANT  = 2;

	private $name;
	private $keyId;
	private $genome;
	private $role;
	private $paralysed;
	private $mutated;
	private $alive;

	public function __construct($name)
	{
		return parent::__construct('player');
		$this->name=$name;
	}

	public function setGenome($genome){
		if($genome>0){
			$genome=1;
		}elseif($genome<0){
			$genome=-1;
		}else{
			$genome=0;
		}
		$this->genome=$genome;
	}

	public function mutate() {
		if ($this->genome != self::GENOME_RESISTANT) {
			$this->mutated = 1;
		}

		return $this->mutated;
	}

	public function cure() {
		if ($this->genome != self::GENOME_HOST) {
			$this->mutated = 0;
		}

        return !$this->mutated;
	}

}

Simplify mutate() & cure() methods

Simplify mutate() & cure() methods


<?php

namespace App\Sharp;

use App\User;
use Code16\Sharp\Form\Layout\FormLayoutColumn;
use Code16\Sharp\Show\Fields\SharpShowTextField;
use Code16\Sharp\Show\Layout\ShowLayoutSection;
use Code16\Sharp\Show\SharpSingleShow;

class AccountSharpShow extends SharpSingleShow
{
    function buildShowFields()
    {
        $this
            ->addField(
                SharpShowTextField::make("name")
                    ->setLabel("Name:")
            )->addField(
                SharpShowTextField::make("email")
                    ->setLabel("Email:")
            )->addField(
                SharpShowTextField::make("group")
                    ->setLabel("Groups:")
            );
    }

    function buildShowLayout()
    {
        $this
            ->addSection('Identity', function(ShowLayoutSection $section) {
                $section
                    ->addColumn(7, function(FormLayoutColumn $column) {
                        $column
                            ->withSingleField("name")
                            ->withSingleField("email")
                            ->withSingleField("groups");
                    });
            });
    }

    function findSingle(): array
    {
        return $this->transform(User::findOrFail(auth()->id()));
    }
}

<?php

namespace App\Sharp;

use App\User;
use Code16\Sharp\Form\Layout\FormLayoutColumn;
use Code16\Sharp\Show\Fields\SharpShowTextField;
use Code16\Sharp\Show\Layout\ShowLayoutSection;
use Code16\Sharp\Show\SharpSingleShow;

class AccountSharpShow extends SharpSingleShow
{
    function buildShowFields()
    {
        $this
            ->addField(
                SharpShowTextField::make("name")
                    ->setLabel("Name:")
            )->addField(
                SharpShowTextField::make("email")
                    ->setLabel("Email:")
            )->addField(
                SharpShowTextField::make("groups")
                    ->setLabel("Groups:")
            );
    }

    function buildShowLayout()
    {
        $this
            ->addSection('Identity', function(ShowLayoutSection $section) {
                $section
                    ->addColumn(7, function(FormLayoutColumn $column) {
                        $column
                            ->withSingleField("name")
                            ->withSingleField("email")
                            ->withSingleField("groups");
                    });
            });
    }

    function findSingle(): array
    {
        return $this->transform(User::findOrFail(auth()->id()));
    }
}

Fix field key in saturn

Fix field key in saturn


<?php

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

use igorw\edn;

$person = new edn\Map();
$person[edn\keyword('name')] = 'igorw';

$list = new edn\LinkedList();
$list->push(edn\symbol('foo'));
$list->push(edn\symbol('bar'));
$list->push(edn\symbol('baz'));
$list->push(edn\keyword('qux'));
$list->push(1.0);
$list->push($person);

$edn = edn\encode([$list]);
echo "$edn\n";

<?php

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

use igorw\edn;

$person = new edn\Map();
$person[edn\keyword('name')] = 'igorw';

$list = new edn\LinkedList([
    edn\symbol('foo'),
    edn\symbol('bar'),
    edn\symbol('baz'),
    edn\keyword('qux'),
    1.0,
    $person,
]);

$edn = edn\encode([$list]);
echo "$edn\n";

Fix example to not use push

Fix example to not use push


<?php

namespace Illuminate\Http;

use Symfony\Component\HttpFoundation\Cookie;

trait ResponseTrait
{
    /**
     * Get the status code for the response.
     *
     * @return int
     */
    public function status()
    {
        return $this->getStatusCode();
    }

    /**
     * Get the content of the response.
     *
     * @return string
     */
    public function content()
    {
        return $this->getContent();
    }

    /**
     * Set a header on the Response.
     *
     * @param  string  $key
     * @param  string  $value
     * @param  bool    $replace
     * @return $this
     */
    public function header($key, $value, $replace = true)
    {
        $this->headers->set($key, $value, $replace);

        return $this;
    }

    /**
     * Add a cookie to the response.
     *
     * @param  \Symfony\Component\HttpFoundation\Cookie  $cookie
     * @return $this
     */
    public function withCookie(Cookie $cookie)
    {
        $this->headers->setCookie($cookie);

        return $this;
    }
}

<?php

namespace Illuminate\Http;

use Symfony\Component\HttpFoundation\Cookie;

trait ResponseTrait
{
    /**
     * Get the status code for the response.
     *
     * @return int
     */
    public function status()
    {
        return $this->getStatusCode();
    }

    /**
     * Get the content of the response.
     *
     * @return string
     */
    public function content()
    {
        return $this->getContent();
    }

    /**
     * Set a header on the Response.
     *
     * @param  string  $key
     * @param  string  $value
     * @param  bool    $replace
     * @return $this
     */
    public function header($key, $value, $replace = true)
    {
        $this->headers->set($key, $value, $replace);

        return $this;
    }

    /**
     * Add a cookie to the response.
     *
     * @param  \Symfony\Component\HttpFoundation\Cookie|dynamic  $cookie
     * @return $this
     */
    public function withCookie($cookie)
    {
        if (is_string($cookie) && function_exists('cookie')) {
            $cookie = call_user_func_array('cookie', func_get_args());
        }

        $this->headers->setCookie($cookie);

        return $this;
    }
}

Allow passing a dynamic argument list to withCookie.


<?php

	class DeviceAndroid extends MobileDevice {
		static protected $instance;

		public function initialize() {
			$this->{'name'} = 'Android';
			$this->{'user-agent'} = 'Mozilla/5.0 (Linux; U; Android 2.2; en-us; sdk Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1';

			// Positive matching:
			$this->allow(
				'%android%i'
			);

			// Version matching:
			$this->capture(
				'software-version',
				'%Android ([0-9]\.[0-9]);%',
				'\1'
			);
		}
	}

	MobileDevice::instance('DeviceAndroid');

?>

<?php

	class DeviceAndroid extends MobileDevice {
		static protected $instance;

		public function initialize() {
			$this->{'name'} = 'Android';
			$this->{'user-agent'} = 'Mozilla/5.0 (Linux; U; Android 2.2; en-us; sdk Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1';

			// Positive matching:
			$this->allow(
				'%android%i'
			);

			// Version matching:
			$this->capture(
				'software-version',
				'%Android ([0-9\.]*);%',
				'\1'
			);
		}
	}

	MobileDevice::instance('DeviceAndroid');

?>

Fix Android version so that it can support major/minor/hotfix releases, eg. 4.2.1


<?php

use AspectMock\Test as test;
use Robo\Robo;

class RsyncTest extends \Codeception\TestCase\Test
{
    /**
     * @var \CodeGuy
     */
    protected $guy;

    // tests
    public function testRsync()
    {
        verify(
            (new \Robo\Task\Remote\Rsync())
                ->fromPath('src/')
                ->toHost('localhost')
                ->toUser('dev')
                ->toPath('/var/www/html/app/')
                ->recursive()
                ->excludeVcs()
                ->checksum()
                ->wholeFile()
                ->verbose()
                ->progress()
                ->humanReadable()
                ->stats()
                ->getCommand()
        )->equals(
                'rsync --recursive --exclude .git --exclude .svn --exclude .hg --checksum --whole-file --verbose --progress --human-readable --stats src/ \'dev@localhost:/var/www/html/app/\''
        );

        verify(
            (new \Robo\Task\Remote\Rsync())
                ->fromPath('src/foo bar/baz')
                ->toHost('localhost')
                ->toUser('dev')
                ->toPath('/var/path/with/a space')
                ->getCommand()
        )->equals(
                'rsync \'src/foo bar/baz\' \'dev@localhost:/var/path/with/a space\''
        );
    }
}

<?php

use AspectMock\Test as test;
use Robo\Robo;

class RsyncTest extends \Codeception\TestCase\Test
{
    /**
     * @var \CodeGuy
     */
    protected $guy;

    // tests
    public function testRsync()
    {
        verify(
            (new \Robo\Task\Remote\Rsync())
                ->fromPath('src/')
                ->toHost('localhost')
                ->toUser('dev')
                ->toPath('/var/www/html/app/')
                ->recursive()
                ->excludeVcs()
                ->checksum()
                ->wholeFile()
                ->verbose()
                ->progress()
                ->humanReadable()
                ->stats()
                ->getCommand()
        )->equals(
                'rsync --recursive --exclude .git --exclude .svn --exclude .hg --checksum --whole-file --verbose --progress --human-readable --stats src/ \'dev@localhost:/var/www/html/app/\''
        );

        // From the folder 'foo bar' (with space) in 'src' directory
        verify(
            (new \Robo\Task\Remote\Rsync())
                ->fromPath('src/foo bar/baz')
                ->toHost('localhost')
                ->toUser('dev')
                ->toPath('/var/path/with/a space')
                ->getCommand()
        )->equals(
                'rsync \'src/foo bar/baz\' \'dev@localhost:/var/path/with/a space\''
        );

        // Copy two folders, 'src/foo' and 'src/bar'
        verify(
            (new \Robo\Task\Remote\Rsync())
                ->fromPath(['src/foo', 'src/bar'])
                ->toHost('localhost')
                ->toUser('dev')
                ->toPath('/var/path/with/a space')
                ->getCommand()
        )->equals(
                'rsync src/foo src/bar \'dev@localhost:/var/path/with/a space\''
        );
    }
}

Add a test for the multi-location Rsync::fromPath.


<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'djpeedee1@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@djpeedee.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'dewar1@djpeedee.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@djpeedee.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

Update contact form to send email inquiries


<?php

class CspReport
{
    public function process($post)
    {
        $report = json_decode($post);

        if ($report) {
            $report->{'user-agent'} = $_SERVER['HTTP_USER_AGENT'];

            $data = json_encode(
                $report,
                JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
            );

            $this->log($data);
        }
    }

    private function log($data)
    {
        $logfile = dirname(__DIR__) . '/csp-report.log';
        file_put_contents($logfile, $data . "\n", LOCK_EX | FILE_APPEND);
    }
}

<?php

class CspReport
{
    public function process($post)
    {
        $report = json_decode($post);

        if ($report) {
            $report->date = date("Y-m-d H:i:s");

            foreach (getallheaders() as $name => $value) {
                $report->headers[$name] = $value;
            }

            $data = json_encode(
                $report,
                JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
            );

            $this->log($data);
        }
    }

    private function log($data)
    {
        $logfile = dirname(__DIR__) . '/csp-report.log';
        file_put_contents($logfile, $data . "\n", LOCK_EX | FILE_APPEND);
    }
}

Add date and request headers in CSP report log


<?php

namespace staticsquish;

/**
*  @license 3-clause BSD
*/
class TemporaryFolder
{

  protected $folder;

  public function get() {
    if (!$this->folder) {
      $this->folder = '/tmp/openacalendarstaticweb'.rand();
      while(file_exists($this->folder)) {
        $this->folder = '/tmp/openacalendarstaticweb'.rand();
      }
      mkdir($this->folder);
    }
    return $this->folder;
  }

}

<?php

namespace staticsquish;

/**
*  @license 3-clause BSD
*/
class TemporaryFolder
{

  protected $folder;

  public function get() {
    if (!$this->folder) {
      $this->folder = '/tmp/staticsquish'.rand();
      while(file_exists($this->folder)) {
        $this->folder = '/tmp/staticsquish'.rand();
      }
      mkdir($this->folder);
    }
    return $this->folder;
  }

}

Correct name on temporary folder

Correct name on temporary folder


<?php

namespace Jorenvh\Share\Providers;

use Illuminate\Support\ServiceProvider;
use Jorenvh\Share\Share;

class ShareServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../../config/laravel-share.php' => config_path('laravel-share.php'),
        ], 'config');

        $this->publishes([
            __DIR__ . '/../../public/js/share.js' => public_path('js/share.js')
        ], 'assets');

        $this->publishes([
            __DIR__ . '/../../resources/lang/' => resource_path('lang')
        ], 'translations');

        $this->loadTranslationsFrom(__DIR__ . '/../../resources/lang/', 'laravel-share');
    }

    /**
     * Register the application services.
     */
    public function register()
    {
        $this->app->bind('share', function () {
            return new Share();
        });

        $this->mergeConfigFrom(__DIR__ . '/../../config/laravel-share.php', 'laravel-share');
    }
}

<?php

namespace Jorenvh\Share\Providers;

use Illuminate\Support\ServiceProvider;
use Jorenvh\Share\Share;

class ShareServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot()
    {
        $this->loadTranslationsFrom(__DIR__ . '/../../resources/lang/', 'laravel-share');

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

        $this->publishes([
            __DIR__ . '/../../public/js/share.js' => public_path('js/share.js')
        ], 'assets');

        $this->publishes([
            __DIR__ . '/../../resources/lang/' => resource_path('lang/vendor/laravel-share')
        ], 'translations');

    }

    /**
     * Register the application services.
     */
    public function register()
    {
        $this->app->bind('share', function () {
            return new Share();
        });

        $this->mergeConfigFrom(__DIR__ . '/../../config/laravel-share.php', 'laravel-share');
    }
}

Fix the publishes path for translations

Fix the publishes path for translations


<?php

namespace PragmaRX\Sdk\Services\View\Service;

use PragmaRX\Support\ServiceProvider;
use PragmaRX\Sdk\Services\View\Compilers\BladeCompiler;

class Provider extends ServiceProvider {

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

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$app = $this->app;

		$app->bindShared('blade.compiler', function($app)
		{
			$cache = $app['path.storage'].'/views';

			return new BladeCompiler($app['files'], $cache);
		});

		$this->app->make('view')->addExtension('blade.jsx', 'blade');
		$this->app->make('view')->addExtension('blade.js', 'blade');
	}

	/**
	 * Get the current package directory.
	 *
	 * @return string
	 */
	public function getPackageDir()
	{
		return __DIR__;
	}

}

<?php

namespace PragmaRX\Sdk\Services\View\Service;

use PragmaRX\Support\ServiceProvider;
use PragmaRX\Sdk\Services\View\Compilers\BladeCompiler;

class Provider extends ServiceProvider {

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

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$app = $this->app;

		$app->bindShared('blade.compiler', function($app)
		{
			$cache = $app['config']['view.compiled'] ?: $app['path.storage'].'/views';

			return new BladeCompiler($app['files'], $cache);
		});

		$this->app->make('view')->addExtension('blade.jsx', 'blade');
		$this->app->make('view')->addExtension('blade.js', 'blade');
	}

	/**
	 * Get the current package directory.
	 *
	 * @return string
	 */
	public function getPackageDir()
	{
		return __DIR__;
	}

}

Fix views folder for L5.1

Fix views folder for L5.1


<?php
// kwtest library
require_once('kwtest/kw_web_tester.php');
require_once('kwtest/kw_db.php');

class CreatePublicDashboardTestCase extends KWWebTestCase
{
  var $url = null;
  var $db  = null;

  function __construct()
   {
   parent::__construct();
   require('config.test.php');
   $this->url = $configure['urlwebsite'];
   $this->db  =& new database($db['type']);
   $this->db->setDb($db['name']);
   $this->db->setHost($db['host']);
   $this->db->setUser($db['login']);
   $this->db->setPassword($db['pwd']);
   }

  function testCreatePublicDashboard()
    {
    $content = $this->connect($this->url);
    if(!$content)
      {
      return;
      }

    $this->login();
    if(!$this->analyse($this->clickLink('[Create new project]')))
      {
      return;
      }

    $this->setField('name', 'PublicDashboard');
    $this->setField('description', 'This project is for CMake dashboards run on this machine to submit to from their test suites... CMake dashboards on this machine should set CMAKE_TESTS_CDASH_SERVER to "'.$this->url.'"');
    $this->setField('public', '1');
    $this->clickSubmitByName('Submit');

    $this->checkErrors();
    $this->assertText('The project PublicDashboard has been created successfully.');
    }
}

?>

<?php
// kwtest library
require_once('kwtest/kw_web_tester.php');
require_once('kwtest/kw_db.php');

class CreatePublicDashboardTestCase extends KWWebTestCase
{
  var $url = null;
  var $db  = null;

  function __construct()
   {
   parent::__construct();
   require('config.test.php');
   $this->url = $configure['urlwebsite'];
   $this->db  =& new database($db['type']);
   $this->db->setDb($db['name']);
   $this->db->setHost($db['host']);
   $this->db->setUser($db['login']);
   $this->db->setPassword($db['pwd']);
   }

  function testCreatePublicDashboard()
    {
    $content = $this->connect($this->url);
    if(!$content)
      {
      return;
      }

    $this->login();
    if(!$this->analyse($this->clickLink('[Create new project]')))
      {
      return;
      }

    $this->setField('name', 'PublicDashboard');
    $this->setField('description', 'This project is for CMake dashboards run on this machine to submit to from their test suites... CMake dashboards on this machine should set CMAKE_TESTS_CDASH_SERVER to "'.$this->url.'"');
    $this->setField('public', '1');
    $this->setField('emailAdministrator','1');
    $this->clickSubmitByName('Submit');

    $this->checkErrors();
    $this->assertText('The project PublicDashboard has been created successfully.');
    }
}

?>

ENH: Use emailadministrator in createpublicdashboard test

git-svn-id: 496ab2bd9c9a782235c11388890d59de1024c1f0@2575 91079597-3006-4846-9bd3-4f3fb3d139a7


<?php  defined('C5_EXECUTE') or die("Access Denied."); ?>

        <?php $ah = new GlobalArea('Footer'); $ah->display($c); ?>

  <?php Loader::element('footer_required'); ?>

Add analytics tracker to all pages on .org


<?php

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

namespace Symfony\Component\Security\Core\Signature;

use Psr\Cache\CacheItemPoolInterface;

/**
 * @author Ryan Weaver <ryan@symfonycasts.com>
 *
 * @experimental in 5.2
 *
 * @final
 */
final class ExpiredSignatureStorage
{
    private $cache;
    private $lifetime;

    public function __construct(CacheItemPoolInterface $cache, int $lifetime)
    {
        $this->cache = $cache;
        $this->lifetime = $lifetime;
    }

    public function countUsages(string $hash): int
    {
        $key = rawurlencode($hash);
        if (!$this->cache->hasItem($key)) {
            return 0;
        }

        return $this->cache->getItem($key)->get();
    }

    public function incrementUsages(string $hash): void
    {
        $item = $this->cache->getItem(rawurlencode($hash));

        if (!$item->isHit()) {
            $item->expiresAfter($this->lifetime);
        }

        $item->set($this->countUsages($hash) + 1);
        $this->cache->save($item);
    }
}

<?php

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

namespace Symfony\Component\Security\Core\Signature;

use Psr\Cache\CacheItemPoolInterface;

/**
 * @author Ryan Weaver <ryan@symfonycasts.com>
 *
 * @final
 */
final class ExpiredSignatureStorage
{
    private $cache;
    private $lifetime;

    public function __construct(CacheItemPoolInterface $cache, int $lifetime)
    {
        $this->cache = $cache;
        $this->lifetime = $lifetime;
    }

    public function countUsages(string $hash): int
    {
        $key = rawurlencode($hash);
        if (!$this->cache->hasItem($key)) {
            return 0;
        }

        return $this->cache->getItem($key)->get();
    }

    public function incrementUsages(string $hash): void
    {
        $item = $this->cache->getItem(rawurlencode($hash));

        if (!$item->isHit()) {
            $item->expiresAfter($this->lifetime);
        }

        $item->set($this->countUsages($hash) + 1);
        $this->cache->save($item);
    }
}

Remove experimental flag from the authenticator system 🚀


<?php

use GeneaLabs\LaravelCaffeine\Http\Controllers\LaravelCaffeineController;

if (isset(Route::getMiddleware()['web'])) {
    Route::group(['middleware' => ['web']], function () {
        Route::get('genealabs/laravel-caffeine/drip', LaravelCaffeineController::class . '@drip');
    });
} else {
    Route::get('genealabs/laravel-caffeine/drip', LaravelCaffeineController::class . '@drip');
}

<?php

use GeneaLabs\LaravelCaffeine\Http\Controllers\LaravelCaffeineController;

if (hasWebMiddleware()) {
    Route::group(['middleware' => ['web']], function () {
        Route::get('genealabs/laravel-caffeine/drip', LaravelCaffeineController::class . '@drip');
    });
} else {
    Route::get('genealabs/laravel-caffeine/drip', LaravelCaffeineController::class . '@drip');
}

function hasWebMiddleware()
{
    $routes = Route::getRoutes()->getRoutes();

    foreach ($routes as $route) {
        if (in_array('web', $route->getAction()['middleware'])) {
            return true;
        }
    }

    return false;
}

Add method to detect web middleware

Add method to detect web middleware


<?php

namespace Jorenvh\Share;

use Illuminate\Support\Facades\Facade;

class ShareFacade extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return static::$app['share'];
        return 'share';
    }
}

<?php

namespace Jorenvh\Share;

use Illuminate\Support\Facades\Facade;

class ShareFacade extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return static::$app['share'];
    }
}

Use new instance every time the facade is called


<?php

namespace BryanCrowe\Growl;

use BryanCrowe\Growl\Builder\BuilderAbstract;

class Growl
{
    /**
     * The Builder to use for building the command.
     *
     * @var BuilderAbstract
     */
    protected $builder;

    /**
     * An array of options to use for building commands.
     *
     * @var array
     */
    protected $options = array();

    /**
     * Constructor.
     *
     * Accepts a Builder object to be used in building the command.
     *
     * @param BuilderAbstract $builder
     *
     * @return void
     */
    public function __construct(BuilderAbstract $builder)
    {
        $this->builder = $builder;
    }

    /**
     * Executes the built command.
     *
     * @return string
     */
    public function execute()
    {
        $command = $this->builder->build($this->options);

        return exec($command);
    }

    /**
     * Implement the __call magic method to provide an expressive way of setting
     * options for commands.
     *
     * @param string $name The name of the method called.
     * @param array $args An array of the supplied arguments.
     *
     * @return $this
     */
    public function __call($name, $args)
    {
        $this->options[$name] = $args[0];

        return $this;
    }
}

<?php

namespace BryanCrowe\Growl;

use BryanCrowe\Growl\Builder\BuilderAbstract;

class Growl
{
    /**
     * The Builder to use for building the command.
     *
     * @var BuilderAbstract
     */
    protected $builder;

    /**
     * An array of options to use for building commands.
     *
     * @var array
     */
    protected $options = array();

    /**
     * Constructor.
     *
     * Accepts a Builder object to be used in building the command.
     *
     * @param BuilderAbstract $builder
     *
     * @return void
     */
    public function __construct(BuilderAbstract $builder)
    {
        $this->builder = $builder;
    }

    /**
     * Executes the built command.
     *
     * @return string
     */
    public function execute()
    {
        $command = $this->builder->build($this->options);

        return exec($command);
    }

    /**
     * Set options for Builders with a key/value.
     *
     * @param string $key The key.
     * @param array $value The value of the key.
     *
     * @return $this
     */
    public function set($key, $value)
    {
        $this->options[$key] = $value;

        return $this;
    }
}

Use set() method instead of __call magic method


<?php

namespace Northstar\Console\Commands;

use Illuminate\Console\Command;
use DFurnes\Environmentalist\ConfiguresApplication;

class SetupCommand extends Command
{
    use ConfiguresApplication;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'northstar:setup {--reset}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Configure your application.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $this->createEnvironmentFile($this->option('reset'));

        $this->runCommand('key:generate', 'Creating application key');

        $this->runCommand('northstar:keys', 'Creating public/private key');

        $this->runCommand('migrate', 'Running database migrations');
    }
}

<?php

namespace Northstar\Console\Commands;

use Defuse\Crypto\Key;
use Illuminate\Console\Command;
use DFurnes\Environmentalist\ConfiguresApplication;

class SetupCommand extends Command
{
    use ConfiguresApplication;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'northstar:setup {--reset}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Configure your application.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $this->createEnvironmentFile($this->option('reset'));

        // Generate key and save to APP_AUTH_KEY in .env file
        $key = Key::createNewRandomKey();
        $this->writeEnvironmentVariable('APP_AUTH_KEY', $key->saveToAsciiSafeString());

        $this->runCommand('key:generate', 'Creating application key');

        $this->runCommand('northstar:keys', 'Creating public/private key');

        $this->runCommand('migrate', 'Running database migrations');
    }
}

Add generating & saving APP_AUTH_KEY to setup script


<?php

namespace App\Nova\Actions;

use Laravel\Nova\Fields\Date;
use Laravel\Nova\Actions\Action;
use Illuminate\Support\Collection;
use Laravel\Nova\Fields\ActionFields;

class ExportAttendance extends Action
{
    /**
     * The displayable name of the action.
     *
     * @var string
     */
    public $name = 'Export for CoC';

    /**
     * Indicates if this action is available to run against the entire resource.
     *
     * @var bool
     */
    public $availableForEntireResource = true;

    public function __construct()
    {
        /*
        $this->withFilename('RoboJacketsAttendance.csv')
            ->withWriterType(\Maatwebsite\Excel\Excel::CSV)
            ->withChunkCount(10000)
            ->only('gtid');
         */
    }

    /**
     * Perform the action on the given models.
     *
     * @param  \Laravel\Nova\Fields\ActionFields  $fields
     * @param  \Illuminate\Support\Collection  $models
     * @return mixed
     */
    public function handle(ActionFields $fields, Collection $models)
    {
        \Log::debug('fdsa'.$fields->start_date.'.'.$fields->end_date);
        \Log::debug($fields);
        return Action::message('Test!');
    }

    /**
     * Get the fields available on the action.
     *
     * @return array
     */
    public function fields()
    {
        return [
            Date::make('Start Date')
                ->format('MM/DD/YYYY')
                ->help('Leave blank for two weeks ago'),

            Date::make('End Date')
                ->format('MM/DD/YYYY')
                ->help('Leave blank for today'),
        ];
    }
}

<?php

namespace App\Nova\Actions;

use Laravel\Nova\Fields\Date;
use Laravel\Nova\Actions\Action;
use Illuminate\Support\Collection;
use Laravel\Nova\Fields\ActionFields;

class ExportAttendance extends Action
{
    /**
     * The displayable name of the action.
     *
     * @var string
     */
    public $name = 'Export for CoC';

    /**
     * Indicates if this action is available to run against the entire resource.
     *
     * @var bool
     */
    public $availableForEntireResource = true;

    public function __construct()
    {
        /*
        $this->withFilename('RoboJacketsAttendance.csv')
            ->withWriterType(\Maatwebsite\Excel\Excel::CSV)
            ->withChunkCount(10000)
            ->only('gtid');
         */
    }

    /**
     * Perform the action on the given models.
     *
     * @param  \Laravel\Nova\Fields\ActionFields  $fields
     * @param  \Illuminate\Support\Collection  $models
     * @return mixed
     */
    public function handle(ActionFields $fields, Collection $models)
    {
        \Log::debug('fdsa'.$fields->start_date.'.'.$fields->end_date);
        \Log::debug($fields);
        return Action::message('Test!');
    }

    /**
     * Get the fields available on the action.
     *
     * @return array
     */
    public function fields()
    {
        return [];
    }
}

Remove fields, users can just use filters


<?php namespace Krucas\Notification;

use Illuminate\Support\ServiceProvider;

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

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['config']->package('edvinaskrucas/notification', __DIR__.'/../config');

        $this->app['notification'] = $this->app->share(function ($app) {
            $config = $app['config'];

            $notification = new Notification(
                $config->get('notification::default_container'),
                $config->get('notification::default_format'),
                $config->get('notification::default_formats'),
                $config->get('notification::default_types')
            );

            return $notification;
        });
    }

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

<?php namespace Krucas\Notification;

use Illuminate\Support\ServiceProvider;

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

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['config']->package('edvinaskrucas/notification', __DIR__.'/../config');

        $this->app['notification'] = $this->app->share(function ($app) {
            $config = $app['config'];

            $notification = new Notification(
                $config->get('notification::default_container'),
                $config->get('notification::default_types'),
                $config->get('notification::default_format'),
                $config->get('notification::default_formats')
            );

            return $notification;
        });
    }

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

Fix service provider when initializing notification library


<?php

namespace Douche\Entity;

use Douche\Value\Bid;

class Auction
{
    private $id;
    private $name;
    private $bids = [];

    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }

    public function getId()
    {
        return $this->id;
    }

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

    public function bid(User $user, Bid $bid)
    {
        $this->bids[] = [$user, $bid];
    }
}

<?php

namespace Douche\Entity;

use Douche\Value\Bid;

class Auction
{
    private $id;
    private $name;
    private $bids = [];

    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }

    public function getId()
    {
        return $this->id;
    }

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

    public function bid(User $bidder, Bid $bid)
    {
        $this->bids[] = [$bidder, $bid];
    }

    public function getHighestBid()
    {
        list($bidder, $bid) = $this->getHighestBidTuple();

        return $bid;
    }

    public function getHighestBidder()
    {
        list($bidder, $bid) = $this->getHighestBidTuple();

        return $bidder;
    }

    private function getHighestBidTuple()
    {
        return end($this->bids);
    }
}

Allow getting highest bid from auction

Allow getting highest bid from auction


<?php

namespace React\Curry;

use React\Curry\Placeholder;

function bind(/*$fn, $args...*/)
{
    $args = func_get_args();
    $fn = array_shift($args);

    return function () use ($fn, $args) {
        return call_user_func_array($fn, mergeParameters($args, func_get_args()));
    };
}

function …()
{
    return Placeholder::create();
}

function placeholder()
{
    return …();
}

/** @internal */
function mergeParameters(array $left, array $right)
{
    foreach ($left as $position => &$param) {
        if ($param instanceof Placeholder) {
            $param = $param->resolve($right, $position);
        }
    }

    return array_merge($left, $right);
}

<?php

declare(encoding='UTF-8');

namespace React\Curry;

use React\Curry\Placeholder;

function bind(/*$fn, $args...*/)
{
    $args = func_get_args();
    $fn = array_shift($args);

    return function () use ($fn, $args) {
        return call_user_func_array($fn, mergeParameters($args, func_get_args()));
    };
}

function …()
{
    return Placeholder::create();
}

function placeholder()
{
    return …();
}

/** @internal */
function mergeParameters(array $left, array $right)
{
    foreach ($left as $position => &$param) {
        if ($param instanceof Placeholder) {
            $param = $param->resolve($right, $position);
        }
    }

    return array_merge($left, $right);
}

Declare UTF-8 encoding in funtions.php

Declare UTF-8 encoding in funtions.php

This prevents breakage with --enable-zend-multibyte and customly configured
encoding.


<?php

namespace App\Http\Controllers;

use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use SocialAuth;
use SocialNorm\Exceptions\ApplicationRejectedException;
use SocialNorm\Exceptions\InvalidAuthorizationCodeException;
use Toastr;

class LoginController extends Controller
{
    public function showLogin()
    {
        return view('login');
    }

    public function authorizeUser()
    {
        return SocialAuth::authorize('github');
    }

    public function loginUser(Request $request)
    {
        try {
            SocialAuth::login('github', function ($user, $details) {
                $user->email = $details->email;
                $user->name = $details->full_name;
                $user->token = $details->access_token;
                $user->github_username = $details->nickname;
                $user->save();
            });
        } catch (ApplicationRejectedException $e) {
            return redirect('login');
        } catch (InvalidAuthorizationCodeException $e) {
            return redirect('login');
        }
        $request->session()->regenerate();
    // Current user is now available via Auth facade
    $user = Auth::user();
        Toastr::success(trans('alerts.loggedin'), trans('alerts.success'));

        return redirect('dashboard');
    }

    public function logoutUser()
    {
        Auth::logout();

        return redirect('');
    }
}

<?php

namespace App\Http\Controllers;

use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use SocialAuth;
use SocialNorm\Exceptions\ApplicationRejectedException;
use SocialNorm\Exceptions\InvalidAuthorizationCodeException;
use Toastr;

class LoginController extends Controller
{
    public function showLogin()
    {
        return view('login');
    }

    public function authorizeUser()
    {
        return SocialAuth::authorize('github');
    }

    public function loginUser(Request $request)
    {
        try {
            SocialAuth::login('github', function ($user, $details) {
                $user->email = $details->email;
                $user->name = $details->full_name;
                $user->token = $details->access_token;
                $user->github_username = $details->nickname;
                $user->api_token = str_random(60);
                $user->save();
            });
        } catch (ApplicationRejectedException $e) {
            return redirect('login');
        } catch (InvalidAuthorizationCodeException $e) {
            return redirect('login');
        }
        $request->session()->regenerate();
    // Current user is now available via Auth facade
    $user = Auth::user();
        Toastr::success(trans('alerts.loggedin'), trans('alerts.success'));

        return redirect('dashboard');
    }

    public function logoutUser()
    {
        Auth::logout();

        return redirect('');
    }
}

Add API token on registration

Add API token on registration


<?php

namespace Becklyn\SearchBundle\Elasticsearch;

abstract class ElasticsearchRequest
{
    /**
     * @var string
     */
    protected $index;

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

    /**
     * @var string|null
     */
    protected $actionNamespace;

    /**
     * @param string      $index
     * @param string      $action
     * @param string|null $actionNamespace
     */
    protected function __construct (string $index, string $action, string $actionNamespace = null)
    {
        $this->index = $index;
        $this->action = $action;
        $this->actionNamespace = $actionNamespace;
    }

    /**
     * Returns the request data
     *
     * @return array
     */
    public function getData () : array
    {
        return [
            "index" => $this->index,
        ];
    }

    /**
     * The name of the action that is called on the elastic search client
     *
     * @return string
     */
    public function getAction () : string
    {
        return $this->action;
    }

    /**
     * Returns the namespace of the action
     *
     * @return string|null
     */
    public function getActionNamespace ()
    {
        return $this->actionNamespace;
    }

    /**
     * Returns, whether a missing error should be ignored
     *
     * @return bool
     */
    public function ignoreMissing ()
    {
        return false;
    }
}

<?php

namespace Becklyn\SearchBundle\Elasticsearch;

abstract class ElasticsearchRequest
{
    /**
     * @var string
     */
    private $index;

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

    /**
     * @var string|null
     */
    private $actionNamespace;

    /**
     * @param string      $index
     * @param string      $action
     * @param string|null $actionNamespace
     */
    protected function __construct (string $index, string $action, string $actionNamespace = null)
    {
        $this->index = $index;
        $this->action = $action;
        $this->actionNamespace = $actionNamespace;
    }

    /**
     * Returns the request data
     *
     * @return array
     */
    public function getData () : array
    {
        return [
            "index" => $this->index,
        ];
    }

    /**
     * The name of the action that is called on the elastic search client
     *
     * @return string
     */
    public function getAction () : string
    {
        return $this->action;
    }

    /**
     * Returns the namespace of the action
     *
     * @return string|null
     */
    public function getActionNamespace ()
    {
        return $this->actionNamespace;
    }

    /**
     * Returns, whether a missing error should be ignored
     *
     * @return bool
     */
    public function ignoreMissing ()
    {
        return false;
    }
}

Make elastic search request more restrictive


<?php

namespace eien\Http\Controllers;

use Illuminate\Http\Request;
use ParagonIE\ConstantTime\Base32;
use PragmaRX\Google2FA\Vendor\Laravel\Facade as Google2FA;

class TFAController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function enable(Request $request)
    {
        $secret = $this->generateSecret();
        $user = $request->user();

        $user->twofa_secret = $secret;
        $user->save();

        $qrUri = Google2FA::getQRCodeInline('永遠', $user->email, $secret);

        return view('TFA.enable', ['image' => $qrUri, 'secret' => $secret]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function disable(Request $request)
    {
        $user = $request->user();
        $user->twofa_secret = null;
        $user->save();

        return view('TFA.disable');
    }

    /**
     * Generate a secure secret with the constant time library.
     *
     * @return string
     */
    public function generateSecret()
    {
        $randomBytes = random_bytes(10);

        return Base32::encode($randomBytes);
    }
}

<?php

namespace eien\Http\Controllers;

use Illuminate\Http\Request;
use ParagonIE\ConstantTime\Base32;
use PragmaRX\Google2FA\Vendor\Laravel\Facade as Google2FA;

class TFAController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function enable(Request $request)
    {
        $secret = $this->generateSecret();
        $user = $request->user();

        $user->twofa_secret = $secret;
        $user->save();

        $qrUri = Google2FA::getQRCodeInline('永遠', $user->email, $secret, 666);

        return view('TFA.enable', ['image' => $qrUri, 'secret' => $secret]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function disable(Request $request)
    {
        $user = $request->user();
        $user->twofa_secret = null;
        $user->save();

        return view('TFA.disable');
    }

    /**
     * Generate a secure secret with the constant time library.
     *
     * @return string
     */
    public function generateSecret()
    {
        $randomBytes = random_bytes(10);

        return Base32::encode($randomBytes);
    }
}

Make generated QR code larger

Make generated QR code larger


<?php
/*
 * Example 6 - How to get the currently activated payment methods.
 */
try
{
    /*
     * Initialize the Mollie API library with your API key.
     *
     * See: https://www.mollie.com/dashboard/settings/profiles
     */
    require "initialize.php";
    /*
     * Get all the activated methods for this API key.
     */
    $methods = $mollie->methods->all();
    foreach ($methods as $method)
    {
        echo '
';
        echo 'image->size1x) . '"> ';
        echo htmlspecialchars($method->description) . ' (' .  htmlspecialchars($method->id) . ')';
        echo '
';
    }
}
catch (Mollie_API_Exception $e)
{
    echo "API call failed: " . htmlspecialchars($e->getMessage());
}

<?php
/*
 * Example 6 - How to get the currently activated payment methods.
 */
try
{
    /*
     * Initialize the Mollie API library with your API key.
     *
     * See: https://www.mollie.com/dashboard/settings/profiles
     */
    require "initialize.php";
    /*
     * Get all the activated methods for this API key.
     */
    $methods = $mollie->methods->all();
    foreach ($methods as $method)
    {
        echo '
';
        echo 'image->size1x) . '" srcset="' . htmlspecialchars($method->image->size2x) .' 2x"> ';
        echo htmlspecialchars($method->description) . ' (' .  htmlspecialchars($method->id) . ')';
        echo '
';
    }
}
catch (Mollie_API_Exception $e)
{
    echo "API call failed: " . htmlspecialchars($e->getMessage());
}

Add 2x in the example

Add 2x in the example


<?php
declare(strict_types=1);

namespace LotGD\Core\Console;

use LotGD\Core\Console\Command\ModuleValidateCommand;
use LotGD\Core\Console\Command\ModuleRegisterCommand;
use Symfony\Component\Console\Application;

class Main {
    public static function main()
    {
        $application = new Application();

        $application->setName("daenerys 🐲 ");
        $application->setVersion("0.0.1");

        $application->add(new ModuleValidateCommand());
        $application->add(new ModuleRegisterCommand());
        $application->run();
    }
}

<?php
declare(strict_types=1);

namespace LotGD\Core\Console;

use LotGD\Core\Console\Command\ModuleValidateCommand;
use LotGD\Core\Console\Command\ModuleRegisterCommand;
use Symfony\Component\Console\Application;

class Main {
    public static function main()
    {
        $application = new Application();

        $application->setName("daenerys 🐲 ");
        $application->setVersion("0.0.1 (lotgd/core version " . \LotGD\Core\Game::getVersion() . ")");

        $application->add(new ModuleValidateCommand());
        $application->add(new ModuleRegisterCommand());
        $application->run();
    }
}

Print core verison along with daenerys version


<?php

require_once('config.php');
global $config;

require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');

?>

        Edit Election
        Optional description

 Level

Here

<?php

require_once('page_template_dash_foot.php');

?>

<?php

require_once('config.php');
global $config;

require_once('page_template_dash_head.php');
require_once('page_template_dash_sidebar.php');

$stmt = $pdo->prepare("SELECT `name` FROM `elections` WHERE `id`= ?");
$stmt->bindParam(1, $row["election"]);
$stmt->execute();
$election_name = $stmt->fetch(PDO::FETCH_NUM)[0];

?>

        Edit Election
        <?php echo $election_name; ?>

 Elections

<?php echo $election_name; ?>

<?php

require_once('page_template_dash_foot.php');

?>

Add in election title to content pane

Add in election title to content pane