<?php
/**
 * @version     $Id$
 * @category    Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 * @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
 */

/**
 * Newsfeeds Database Table Class
 *
 * @author      Babs Gsgens <http://nooku.assembla.com/profile/babsgosgens>
 * @category    Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 */

class ComNewsfeedsDatabaseTableNewsfeeds extends KDatabaseTableDefault
{
    public function _initialize(KConfig $config)
    {
         $sluggable = KDatabaseBehavior::factory('sluggable', array('columns' => array('name')));

         $config->append(array(
            'identity_column'    => 'id',
            'base'               => 'newsfeeds',
            'name'               => 'newsfeeds',
            'behaviors'          => array('lockable', 'orderable', $sluggable),
            'column_map'         => array(
                'enabled'   => 'published',
                'locked_on' => 'checked_out_time',
                'locked_by' => 'checked_out',
                'slug'      => 'alias'
            )
        ));

        parent::_initialize($config);
    }
}

<?php
/**
 * @version     $Id$
 * @category    Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 * @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
 */

/**
 * Newsfeeds Database Table Class
 *
 * @author      Babs Gsgens <http://nooku.assembla.com/profile/babsgosgens>
 * @category    Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 */

class ComNewsfeedsDatabaseTableNewsfeeds extends KDatabaseTableDefault
{
    public function _initialize(KConfig $config)
    {
         $sluggable = $this->getBehavior('sluggable', array('columns' => array('name')));

         $config->append(array(
            'identity_column'    => 'id',
            'base'               => 'newsfeeds',
            'name'               => 'newsfeeds',
            'behaviors'          => array('lockable', 'orderable', $sluggable),
            'column_map'         => array(
                'enabled'   => 'published',
                'locked_on' => 'checked_out_time',
                'locked_by' => 'checked_out',
                'slug'      => 'alias'
            )
        ));

        parent::_initialize($config);
    }
}

Use KDatabaseTableAbstract::getBehavior() to create behaviors using the behavior name instead of the full identifier. Component specific behaviors can now also be loaded using behavior names instead of identifier strings.


<?php namespace Riari\Forum\Models\Observers;

use Carbon\Carbon;
use Riari\Forum\Models\Thread;
use Riari\Forum\Support\Stats;

class ThreadObserver
{
    public function created($thread)
    {
        // Increment thread count on the category
        $thread->category->increment('thread_count');
    }

    public function deleted($thread)
    {
        // Delete the thread's posts
        if ($thread->deleted_at != Carbon::now()) {
            // The thread was force-deleted, so the posts should be too
            $thread->posts()->withTrashed()->forceDelete();

            // Also detach readers
            $thread->readers()->detach();
        } else {
            // The thread was soft-deleted, so just soft-delete its posts
            $thread->posts()->delete();
        }

        Stats::updateCategory($thread->category);
    }

    public function restored($thread)
    {
        // Restore the thread's posts
        $thread->posts()->withTrashed()->restore();

        Stats::updateThread($thread);
        Stats::updateCategory($thread->category);
    }
}

<?php namespace Riari\Forum\Models\Observers;

use Carbon\Carbon;
use Riari\Forum\Models\Category;
use Riari\Forum\Models\Thread;
use Riari\Forum\Support\Stats;

class ThreadObserver
{
    public function created($thread)
    {
        // Increment thread count on the category
        $thread->category->increment('thread_count');
    }

    public function updating($thread)
    {
        $oldCategory = Category::find($thread->getOriginal('category_id'));
        $postCount = $thread->posts->count();

        // Decrement the old category's thread and post counts
        $oldCategory->decrement('thread_count');
        $oldCategory->decrement('post_count', $postCount);

        // Increment the new category's thread and post counts
        $thread->category->increment('thread_count');
        $thread->category->increment('post_count', $postCount);
    }

    public function deleted($thread)
    {
        // Delete the thread's posts
        if ($thread->deleted_at != Carbon::now()) {
            // The thread was force-deleted, so the posts should be too
            $thread->posts()->withTrashed()->forceDelete();

            // Also detach readers
            $thread->readers()->detach();
        } else {
            // The thread was soft-deleted, so just soft-delete its posts
            $thread->posts()->delete();
        }

        Stats::updateCategory($thread->category);
    }

    public function restored($thread)
    {
        // Restore the thread's posts
        $thread->posts()->withTrashed()->restore();

        Stats::updateThread($thread);
        Stats::updateCategory($thread->category);
    }
}

Update category stats when moving a thread


<?php
namespace Criterion;
class Application
{
    public static $app;

    public $config = false;
    public $config_file = false;
    public $mongo = false;
    public $db = false;

    public function __construct()
    {
        $this->config_file = dirname(dirname(__DIR__)) . '/config.json';

        if (file_exists($this->config_file))
        {
            $this->config = json_decode(file_get_contents($this->config_file), true);
        }

        $db = getenv('APP_ENV') ? 'criterion_testing' : 'criterion';
        $this->mongo = new \MongoMinify\Client();
        $this->db = $this->mongo->{$db};
        return $this;
    }
}

<?php
namespace Criterion;
class Application
{
    public static $app;

    public $config = false;
    public $config_file = false;
    public $mongo = false;
    public $db = false;

    public function __construct()
    {
        $this->config_file = dirname(dirname(__DIR__)) . '/config.json';

        if (file_exists($this->config_file))
        {
            $this->config = json_decode(file_get_contents($this->config_file), true);
        }

        $db = getenv('APP_ENV') === 'testing' ? 'criterion_testing' : 'criterion';
        $this->mongo = new \MongoMinify\Client();
        $this->db = $this->mongo->{$db};
        return $this;
    }
}

Make sure the APP_ENV is "testing" when switching db for tests


<?php

/*
 * This file is part of Rocketeer
 *
 * (c) Maxime Fabre <ehtnam6@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

namespace Rocketeer\Tasks\Plugins;

use Rocketeer\Tasks\AbstractTask;

class Installer extends AbstractTask
{
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Installs plugins';

    /**
     * Whether to run the commands locally
     * or on the server.
     *
     * @var bool
     */
    protected $local = true;

    /**
     * {@inheritdoc}
     */
    public function execute()
    {
        // Get package and destination folder
        $package = $this->command->argument('package');
        $folder = $this->paths->getRocketeerConfigFolder();

        $command = $this->composer()->require($package, [
            '--working-dir' => $folder,
        ]);

        // Install plugin
        $this->explainer->line('Installing '.$package);
        $this->run($this->shellCommand($command));

        // Prune duplicate Rocketeer
        $this->files->deleteDir($folder.'/vendor/anahkiasen/rocketeer');
    }
}

<?php

/*
 * This file is part of Rocketeer
 *
 * (c) Maxime Fabre <ehtnam6@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

namespace Rocketeer\Tasks\Plugins;

use Rocketeer\Tasks\AbstractTask;

class Installer extends AbstractTask
{
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Installs plugins';

    /**
     * Whether to run the commands locally
     * or on the server.
     *
     * @var bool
     */
    protected $local = true;

    /**
     * {@inheritdoc}
     */
    public function execute()
    {
        // Get package and destination folder
        $package = $this->command->argument('package');
        $folder = $this->paths->getRocketeerConfigFolder();

        // Create composer manifest if it does not exist
        $manifest = $folder.'/composer.json';
        if (!$this->files->has($manifest)) {
            $contents = json_encode(['minimum-stability' => 'dev', 'prefer-stable' => true], JSON_PRETTY_PRINT);
            $this->files->put($manifest, $contents);
        }

        $command = $this->composer()->require($package, [
            '--working-dir' => $folder,
        ]);

        // Install plugin
        $this->explainer->line('Installing '.$package);
        $this->run($this->shellCommand($command));

        // Prune duplicate Rocketeer
        $this->files->deleteDir($folder.'/vendor/anahkiasen/rocketeer');
    }
}

Create rocketeer plugins file with minimum stability dev/prefer-stable true


<?php

namespace WPMissing;

class Util {
  static function excerpt($text, $length, $more='…') {

    $text = strip_shortcodes( $text );

    $text = apply_filters('the_content', $text);
    $text = str_replace(']]>', ']]>', $text);
    $text = wp_trim_words( $text, $length, $more );

    return $text;
  }

  static function strftime($date_string, $format, $else, $tz=null) {
    if ($tz === null) {
      $tz = get_option('timezone_string');
    }

    return \Missing\Date::strftime($date_string, $format, $else, $tz);
  }
}

<?php

namespace WPMissing;

class Util {
  static function excerpt($text, $length, $more='…') {

    $text = strip_shortcodes( $text );

    $text = apply_filters('the_content', $text);
    $text = str_replace(']]>', ']]>', $text);
    $text = wp_trim_words( $text, $length, $more );

    return $text;
  }

  static function strftime($date_string, $format, $else, $tz=null) {
    if ($tz === null) {
      $tz = get_option('timezone_string');

      if (empty($tz)) {
        $tz = 'Etc/UTC';
      }
    }

    return \Missing\Date::strftime($date_string, $format, $else, $tz);
  }
}

Handle timezone_string not being set

Handle timezone_string not being set


<?php
/**
 * Class Google\Site_Kit\Modules\Analytics\Plugin_Detector
 *
 * @package   Google\Site_Kit\Modules\Analytics
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Modules\Analytics;

/**
 * Detects the user's current active plugins that ShirshuClass supports
 *
 * Class Plugin_Detector
 */
class Plugin_Detector {

	/**
	 * A list of Shirshu_Class supported plugins
	 *
	 * @var array
	 */
	private $supported_plugins = array();

	/**
	 * Plugin_Detector constructor.
	 *
	 * @param array $supported_plugins list of supported plugins.
	 */
	public function __construct( $supported_plugins ) {
		$this->supported_plugins = $supported_plugins;
	}

	/**
	 * Determines the user's current active plugins that Shirshu_Class supports
	 *
	 * @return array
	 */
	public function get_active_plugins() {
		foreach ( $this->supported_plugins as $key => $function_name ) {
			if ( defined( $function_name ) || function_exists( $function_name ) ) {
				array_push( $active_plugins, $key );
			}
		}
		return $active_plugins;
	}
}

<?php
/**
 * Class Google\Site_Kit\Modules\Analytics\Plugin_Detector
 *
 * @package   Google\Site_Kit\Modules\Analytics
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Modules\Analytics;

/**
 * Detects the user's current active plugins that ShirshuClass supports
 *
 * Class Plugin_Detector
 */
class Plugin_Detector {

	/**
	 * A list of Shirshu_Class supported plugins
	 *
	 * @var array
	 */
	private $supported_plugins = array();

	/**
	 * Plugin_Detector constructor.
	 *
	 * @param array $supported_plugins list of supported plugins.
	 */
	public function __construct( $supported_plugins ) {
		$this->supported_plugins = $supported_plugins;
	}

	/**
	 * Determines the user's current active plugins that Shirshu_Class supports
	 *
	 * @return array
	 */
	public function get_active_plugins() {
		$active_plugins = array();
		foreach ( $this->supported_plugins as $key => $function_name ) {
			if ( defined( $function_name ) || function_exists( $function_name ) ) {
				array_push( $active_plugins, $key);
			}
		}
		return $active_plugins;
	}
}

Fix the bug of initializing the active plugin array.


<?php
style('dav', 'schedule-response');
?>

	<form action="" method="post">
		<fieldset id="partStat">

<?php p($l->t('Are you accepting the invitation?')); ?>

				<input type="radio" id="partStatAccept" name="partStat" value="ACCEPTED" checked />

					<?php p($l->t('Accept')); ?>

				<input type="radio" id="partStatTentative" name="partStat" value="TENTATIVE" />

					<?php p($l->t('Tentative')); ?>

				<input type="radio" class="declined" id="partStatDeclined" name="partStat" value="DECLINED" />

					<?php p($l->t('Decline')); ?>

		</fieldset>
		<fieldset id="more_options">
			<input type="number" min="0" name="guests" placeholder="Guests" />
			<input type="text" name="comment" placeholder="Comment" />
		</fieldset>
		<fieldset>
			<input type="submit" value="<?php p($l->t('Save'));?>">
		</fieldset>
	</form>

<?php
style('dav', 'schedule-response');
?>

	<form action="" method="post">
		<fieldset id="partStat">

<?php p($l->t('Are you accepting the invitation?')); ?>

				<input type="radio" id="partStatAccept" name="partStat" value="ACCEPTED" checked />

					<?php p($l->t('Accept')); ?>

				<input type="radio" id="partStatTentative" name="partStat" value="TENTATIVE" />

					<?php p($l->t('Tentative')); ?>

				<input type="radio" class="declined" id="partStatDeclined" name="partStat" value="DECLINED" />

					<?php p($l->t('Decline')); ?>

		</fieldset>
		<fieldset id="more_options">
			<input type="number" min="0" name="guests" placeholder="<?php p($l->t('Number of guests')); ?>" />
			<input type="text" name="comment" placeholder="<?php p($l->t('Comment')); ?>" />
		</fieldset>
		<fieldset>
			<input type="submit" value="<?php p($l->t('Save'));?>">
		</fieldset>
	</form>

Make calendar schedule options translatable

Signed-off-by: Julius Härtl <bf353fa4999f2f148afcc6d8ee6cb1ee74cc07c3@bitgrid.net>


<?php

namespace RabbitMQ\Management\Entity;

class Exchange extends AbstractEntity
{
    public $name;
    public $vhost;
    public $type;
    public $durable = false;
    public $auto_delete = false;
    public $internal = false;
    public $arguments = array();

    protected function getJsonParameters()
    {
        return array('type', 'auto_delete', 'durable', 'internal', 'arguments', 'vhost', 'name');
    }
}

<?php

namespace RabbitMQ\Management\Entity;

class Exchange extends AbstractEntity
{
    public $name;
    public $vhost;
    public $type;
    public $incoming;
    public $message_stats_in;
    public $durable = false;
    public $auto_delete = false;
    public $internal = false;
    public $arguments = array();

    protected function getJsonParameters()
    {
        return array('type', 'auto_delete', 'durable', 'internal', 'arguments', 'vhost', 'name');
    }
}

Update to rabbitMQ 3 informations

Update to rabbitMQ 3 informations


                <button type="button" class="close" data-dismiss="modal">×</button>

Updating Canvas

To upgrade your installation of Canvas to the latest available, just run the following command from a terminal:

php artisan canvas:update

                <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>

                <button type="button" class="close" data-dismiss="modal">×</button>

Updating Canvas

Minor/Patch Version Upgrade

Example: Upgrading from v3.1.0 to v3.1.1

Run php artisan canvas:update from a terminal to upgrade your installation of Canvas to the latest version.

Major Version Upgrade

Example: Upgrading from v3.0.5 to v3.1.0

We attempt to document every possible breaking change to ensure a smooth transition between versions. To begin a major version upgrade, visit the Official Upgrade Guide and follow the steps.

More Information

Find out more information about Semantic Versioning. Canvas follows SemVer 2.0.0 in its software release cycle.

                <button type="button" class="btn btn-link" data-dismiss="modal">Close</button>

Update modal now includes SemVer specifics


<?php
class FlickrTagElasticaIndexingExtension extends Extension implements ElasticaIndexingHelperInterface {

	/**
	 * Add a mapping for the location of the photograph
	 */
	public static function updateElasticsearchMapping(\Elastica\Type\Mapping $mapping)
    {
    	// get the properties of the individual fields as an array
    	$properties = $mapping->getProperties();

    	// enable tags to be faceted
    	$properties['RawValue'] = array(
    		'type' => 'string',
    		'index' => 'not_analyzed'
		);

    	// set the new properties on the mapping
    	$mapping->setProperties($properties);

        return $mapping;
    }

	/**
	 * Populate elastica with the location of the photograph
	 * @param  \Elastica\Document $document Representation of an Elastic Search document
	 * @return \Elastica\Document modified version of the document
	 */
	public function updateElasticsearchDocument(\Elastica\Document $document)
	{
		// No alterations made, so just pass through the document
	    return $document;
	}
}

<?php
class FlickrTagElasticaIndexingExtension extends Extension implements ElasticaIndexingHelperInterface {

	/**
	 * Add a mapping for the location of the photograph
	 */
	public function updateElasticsearchMapping(\Elastica\Type\Mapping $mapping)
    {
    	// get the properties of the individual fields as an array
    	$properties = $mapping->getProperties();

    	// enable tags to be faceted
    	$properties['RawValue'] = array(
    		'type' => 'string',
    		'index' => 'not_analyzed'
		);

    	// set the new properties on the mapping
    	$mapping->setProperties($properties);

        return $mapping;
    }

	/**
	 * Populate elastica with the location of the photograph
	 * @param  \Elastica\Document $document Representation of an Elastic Search document
	 * @return \Elastica\Document modified version of the document
	 */
	public function updateElasticsearchDocument(\Elastica\Document $document)
	{
		// No alterations made, so just pass through the document
	    return $document;
	}

	public function updateElasticHTMLFields(array $htmlFields) {
		return $htmlFields;
	}
}

FIX: Change of interface, removing the static method


                <form class="form-inline">
                    <input type="checkbox" class="check" ng-model="item.packed">
                    <input ng-model='item.name'> (added {{item.created_at|date}})
                </form>

Already Packed

                <form class="form-inline">
                    <input type="checkbox" class="check" ng-model="item.packed">
                    <input ng-model='item.name'> (added {{item.created_at|date}})
                </form>

                <form class="form-inline">
                    <input type="checkbox" class="check" ng-model="item.packed">
                    <input ng-model='item.name'>
                </form>

Already Packed

                <form class="form-inline">
                    <input type="checkbox" class="check" ng-model="item.packed">
                    <input ng-model='item.name'>
                </form>

Remove the created_at date from the list view


<?php

namespace DrupalVmGenerator\Command;

use DrupalVmGenerator\Style\DrupalVmStyle;
use Symfony\Component\Console\Command\Command as BaseCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Twig_Environment;

abstract class Command extends BaseCommand
{
    /**
     * @var InputInterface
     */
    protected $input;

    /**
     * @var OutputInterface
     */
    protected $output;

    /**
     * @var Filesystem
     */
    protected $filesystem;

    /**
     * @var Twig_Environment
     */
    protected $twig;

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

    /**
     * @var DrupalVmStyle
     */
    protected $io;

    /**
     * {@inheritdoc}
     */
    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $this->projectDir = getcwd();

        $this->input = $input;
        $this->output = $output;

        $this->filesystem = new Filesystem();

        $this->io = new DrupalVmStyle($input, $output);
    }
}

<?php

namespace DrupalVmGenerator\Command;

use DrupalVmGenerator\Style\DrupalVmStyle;
use Symfony\Component\Console\Command\Command as BaseCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Twig_Environment;

abstract class Command extends BaseCommand
{
    /**
     * @var InputInterface
     */
    protected $input;

    /**
     * @var OutputInterface
     */
    protected $output;

    /**
     * @var Filesystem
     */
    protected $filesystem;

    /**
     * @var Twig_Environment
     */
    protected $twig;

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

    /**
     * @var DrupalVmStyle
     */
    protected $io;

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

        parent::__construct();
    }

    /**
     * {@inheritdoc}
     */
    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $this->projectDir = getcwd();

        $this->input = $input;
        $this->output = $output;

        $this->filesystem = new Filesystem();

        $this->io = new DrupalVmStyle($input, $output);
    }
}

Add the constructor and inject Twig

Add the constructor and inject Twig


<?php

namespace Laravel\Lumen\Routing;

use Orchestra\Routing\VersionedHelpers;
use Dingo\Api\Routing\Helpers as BaseHelpers;

trait Helpers
{
    use BaseHelpers, VersionedHelpers;

    /**
     * Get versioned resource class name.
     *
     * @param  string  $group
     * @param  string  $name
     *
     * @return string
     */
    protected function getVersionedResourceClassName($group, $name)
    {
        $class = \str_replace('.', '\\', $name);
        $version = $this->getVersionNamespace();

        return \sprintf('%s\%s\%s\%s', $this->namespace, $group, $version, $class);
    }

    /**
     * Get the version namespace.
     *
     * @return string
     */
    protected function getVersionNamespace()
    {
        $version = $this->api()->getVersion();
        $supported = $this->getSupportedVersionNamespace();

        if (isset($supported[$version])) {
            return $supported[$version];
        }

        return 'Base';
    }

    /**
     * Get supported version namespace.
     *
     * @return array
     */
    abstract protected function getSupportedVersionNamespace();
}

<?php

namespace Laravel\Lumen\Routing;

use Orchestra\Routing\VersionedHelpers;
use Dingo\Api\Routing\Helpers as BaseHelpers;

trait Helpers
{
    use BaseHelpers, VersionedHelpers;

    /**
     * Get versioned resource class name.
     *
     * @param  string  $group
     * @param  string  $name
     *
     * @return string
     */
    protected function getVersionedResourceClassName($group, $name)
    {
        $class = \str_replace('.', '\\', $name);
        $version = $this->getVersionNamespace();

        return \sprintf('%s\%s\%s\%s', $this->namespace, $group, $version, $class);
    }

    /**
     * Get the version namespace.
     *
     * @return string
     */
    protected function getVersionNamespace()
    {
        $version = \app('request')->version() ?? 'v1';
        $supported = $this->getSupportedVersionNamespace();

        if (isset($supported[$version])) {
            return $supported[$version];
        }

        return 'Base';
    }

    /**
     * Get supported version namespace.
     *
     * @return array
     */
    abstract protected function getSupportedVersionNamespace();
}

Allow to use laravie/api without internal request support.

Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<form name="loginform" action="<?php bloginfo("wpurl");?>/wp-login.php" method="post">
	<input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" />
	<input type="hidden" name="user-cookie" value="1" />

	<input type="text" name="log" placeholder="E-postadress eller nick"
		<?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?>
		 />

	<input type="password" name="pwd" placeholder="Lösenord" />

		<input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" />
		Håll mig inloggad

		<input type="submit" name="submit" class="small" value="Logga in" />

		<a href="<?php echo wp_lostpassword_url();?>">Glömt lösenord

</form>

<form name="loginform" action="<?php bloginfo("wpurl");?>/wp-login.php" method="post">
	<input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" />
	<input type="hidden" name="user-cookie" value="1" />

	<input type="text" name="log" placeholder="E-postadress eller nick"
		<?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?>
		 />

	<input type="password" name="pwd" placeholder="Lösenord" />

		<input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" />
		Håll mig inloggad

		<input type="submit" name="submit" class="small" value="Logga in" />

</form>

Remove 'Forgot password' from sign in form'


<?php
/**
 * This file is part of the Elephant.io package
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 *
 * @copyright Wisembly
 * @license   http://www.opensource.org/licenses/MIT-License MIT License
 */

namespace ElephantIO\Exception;

use Exception;
use RuntimeException;

class ServerConnectionFailureException extends RuntimeException
{
    public function __construct(Exception $previous = null)
    {
        parent::__construct('An error occurred while trying to establish a connection to the server', 0, $previous);
    }
}

<?php
/**
 * This file is part of the Elephant.io package
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 *
 * @copyright Wisembly
 * @license   http://www.opensource.org/licenses/MIT-License MIT License
 */

namespace ElephantIO\Exception;

use Exception;
use RuntimeException;

class ServerConnectionFailureException extends RuntimeException
{
    /** @var string php error message */
    private $errorMessage;

    public function __construct($errorMessage, Exception $previous = null)
    {
        parent::__construct('An error occurred while trying to establish a connection to the server', 0, $previous);

        $this->errorMessage = $errorMessage;
    }

    public function getErrorMessage()
    {
        return $this->errorMessage;
    }
}

Add more information on the server connection failure exception

Use `$e->getErrorMessage()` to get more information on the error


--TEST--
Test response
--FILE--
<?php

use php\io\Stream;
use php\net\ServerSocket;
use php\webserver\WebServer;

class Foobar {

}

spl_autoload_register(function ($class) {
    var_dump($class);
});

$server = new WebServer(function() {
    try {
        new Foobar();
    } catch (EngineException $e) {
        echo $e->getMessage();
    }
});

$server->importAutoloaders = true;

$server->port = ServerSocket::findAvailableLocalPort();
$server->run();

$conn = null;

echo Stream::getContents("http://localhost:{$server->port}/");

?>
--EXPECT--
string(6) "Foobar"
Class 'Foobar' not found

--TEST--
Test response
--FILE--
<?php

use php\io\Stream;
use php\net\ServerSocket;
use php\webserver\WebServer;

class Foobar {

}

spl_autoload_register(function ($class) {
    var_dump($class);
});

$server = new WebServer(function() {
    try {
        new Foobar();
    } catch (Error $e) {
        echo $e->getMessage();
    }
});

$server->importAutoloaders = true;

$server->port = ServerSocket::findAvailableLocalPort();
$server->run();

$conn = null;

echo Stream::getContents("http://localhost:{$server->port}/");

?>
--EXPECT--
string(6) "Foobar"
Class 'Foobar' not found

Fix tests of webserver ext.

Fix tests of webserver ext.


<?php

namespace Code16\Sharp\Tests\Feature;

use Code16\Sharp\Tests\Feature\Api\BaseApiTest;

class AssetViewComposerTest extends BaseApiTest
{
    /** @test */
    public function we_can_define_assets_to_render_in_views()
    {
        $this->withoutExceptionHandling();
        $this->buildTheWorld();

        $this->app['config']->set(
            'sharp.extensions.assets.head',
            ['/path/to/asset.css']
        );

        $this->get(route('code16.sharp.login'))
            ->assertViewHas('injectedAssets')
            ->assertSee('<link rel="stylesheet" href="/path/to/asset.css">');
    }
}

<?php

namespace Code16\Sharp\Tests\Feature;

use Code16\Sharp\Tests\Feature\Api\BaseApiTest;

class AssetViewComposerTest extends BaseApiTest
{
    /** @test */
    public function we_can_define_assets_to_render_in_views()
    {
        $this->withoutExceptionHandling();
        $this->buildTheWorld();

        $this->app['config']->set(
            'sharp.extensions.assets.head',
            ['/path/to/asset.css']
        );

        $this->get(route('code16.sharp.login'))
            ->assertViewHas('injectedAssets')
            ->assertSee('<link rel="stylesheet" href="/path/to/asset.css">', false);
    }
}

Fix test for Laravel 7

Fix test for Laravel 7


<?php
date_default_timezone_set('Europe/Rome');

$settings = array(
    'displayErrorDetails' => true,

    'db' => array(
        'host' => 'CHOOSE_YOUR_SOURCE_HOST',
        'user' => 'CHOOSE_YOUR_DB_USER',
        'pass' => 'CHOOSE_YOUR_DB_PASSWORD',
        'dbname' => 'wallet_logger',
    )
);

<?php
date_default_timezone_set('Europe/Rome');

$settings = array(
    'displayErrorDetails' => true,

    'db' => array(
        'host' => 'CHOOSE_YOUR_SOURCE_HOST',
        'user' => 'CHOOSE_YOUR_DB_USER',
        'pass' => 'CHOOSE_YOUR_DB_PASSWORD',
        'dbname' => 'wallet_logger',
    ),

    'item_types' => array(
        'wallets',
        'accounts',
        'transactions'
    )
);

Add items types to settings

Add items types to settings


<?php

/**
 * @file
 * template.php
 */

/**
 * Implements hook_preprocess_HOOK().
 */
function bootstrap_serchilo_preprocess_block(&$vars) {

  switch ($vars['block_html_id']) {

  case 'block-serchilo-namespaces':

    // Put a well around namespaces block.
    $vars['classes_array'][] = 'well';
    $vars['classes_array'][] = 'well-sm';

    break;
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function bootstrap_serchilo_preprocess_button(&$vars) {

  switch ($vars['element']['#id']) {
  case 'edit-submit-shortcuts':
    // Make Go button a primary button.
    $vars['element']['#attributes']['class'][] = 'btn-primary';
    break;
  }
}

<?php

/**
 * @file
 * template.php
 */

/**
 * Implements hook_preprocess_HOOK().
 */
function bootstrap_serchilo_preprocess_block(&$vars) {

  switch ($vars['block_html_id']) {

  case 'block-serchilo-namespaces':

    // Put a well around namespaces block.
    $vars['classes_array'][] = 'well';
    $vars['classes_array'][] = 'well-sm';

    break;
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function bootstrap_serchilo_preprocess_button(&$vars) {

  switch ($vars['element']['#id']) {
  case 'edit-submit-shortcuts':
    // Make Go button a primary button.
    $vars['element']['#attributes']['class'][] = 'btn-primary';
    break;
  case 'edit-reset':
    // Make Reset button a warning button.
    $vars['element']['#attributes']['class'][] = 'btn-warning';
    break;
  }
}

Make Reset button a warning button.

Make Reset button a warning button.


<?php
/**
 * Created by PhpStorm.
 * @author Tareq Mahmood <tareqtms@yahoo.com>
 * Created at 8/19/16 7:40 PM UTC+06:00
 *
 * @see https://help.shopify.com/api/reference/smartcollection Shopify API Reference for SmartCollection
 */

namespace PHPShopify;

/**
 * --------------------------------------------------------------------------
 * SmartCollection -> Child Resources
 * --------------------------------------------------------------------------
 * @property-read Event $Event
 *
 * @method Event Event(integer $id = null)
 *
 * --------------------------------------------------------------------------
 * SmartCollection -> Custom actions
 * --------------------------------------------------------------------------
 *
 */
class SmartCollection extends ShopifyResource
{
    /**
     * @inheritDoc
     */
    protected $resourceKey = 'smart_collection';

    /**
     * @inheritDoc
     */
    protected $childResource = array(
        'Event',
        'Metafield',
    );

    /**
     * Set the ordering type and/or the manual order of products in a smart collection
     *
     * @param array $params
     *
     * @return array
     */
    public function sortOrder($params)
    {
        $url = $this->generateUrl($params, 'order');

        return $this->put(array(), $url);
    }
}

<?php
/**
 * Created by PhpStorm.
 * @author Tareq Mahmood <tareqtms@yahoo.com>
 * Created at 8/19/16 7:40 PM UTC+06:00
 *
 * @see https://help.shopify.com/api/reference/smartcollection Shopify API Reference for SmartCollection
 */

namespace PHPShopify;

/**
 * --------------------------------------------------------------------------
 * SmartCollection -> Child Resources
 * --------------------------------------------------------------------------
 * @property-read Event $Event
 * @property-read Metafield $Metafield
 *
 * @method Event Event(integer $id = null)
 * @method Metafield Metafield(integer $id = null)
 *
 * --------------------------------------------------------------------------
 * SmartCollection -> Custom actions
 * --------------------------------------------------------------------------
 *
 */
class SmartCollection extends ShopifyResource
{
    /**
     * @inheritDoc
     */
    protected $resourceKey = 'smart_collection';

    /**
     * @inheritDoc
     */
    protected $childResource = array(
        'Event',
        'Metafield',
    );

    /**
     * Set the ordering type and/or the manual order of products in a smart collection
     *
     * @param array $params
     *
     * @return array
     */
    public function sortOrder($params)
    {
        $url = $this->generateUrl($params, 'order');

        return $this->put(array(), $url);
    }
}

Add Metafield property and method to docblock

SmartCollection has Metafield support, but static analysis will complain unless it is described in the docblock.


<?php

namespace Liuggio\Fastest\Doctrine\DBAL;

use Doctrine\Bundle\DoctrineBundle\ConnectionFactory as BaseConnectionFactory;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
use Liuggio\Fastest\Process\EnvCommandCreator;

/**
 * Creates a connection taking the db name from the env, this is great if you want to run parallel functional tests.
 */
class ConnectionFactory extends BaseConnectionFactory
{
    /**
     * Create a connection by name.
     *
     * @param array         $params
     * @param Configuration $config
     * @param EventManager  $eventManager
     * @param array         $mappingTypes
     *
     * @return \Doctrine\DBAL\Connection
     */
    public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = array())
    {
        $params['dbname'] = $this->getDbNameFromEnv($params['dbname']);

        return parent::createConnection($params, $config, $eventManager, $mappingTypes);
    }

    private function getDbNameFromEnv($dbName)
    {
        if ($this->issetDbNameEnvValue()) {
            return $dbName.'_'.$this->getDbNameEnvValue();
        }

        return $dbName;
    }

    private function issetDbNameEnvValue()
    {
        $dbName = $this->getDbNameEnvValue();

        return (!empty($dbName));
    }

    private function getDbNameEnvValue()
    {
        return getenv(EnvCommandCreator::ENV_TEST_CHANNEL_READABLE);
    }
}

<?php

namespace Liuggio\Fastest\Doctrine\DBAL;

use Doctrine\Bundle\DoctrineBundle\ConnectionFactory as BaseConnectionFactory;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
use Liuggio\Fastest\Process\EnvCommandCreator;

/**
 * Creates a connection taking the db name from the env, this is great if you want to run parallel functional tests.
 */
class ConnectionFactory extends BaseConnectionFactory
{
    /**
     * Create a connection by name.
     *
     * @param array         $params
     * @param Configuration $config
     * @param EventManager  $eventManager
     * @param array         $mappingTypes
     *
     * @return \Doctrine\DBAL\Connection
     */
    public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = array())
    {
        $dbName = $this->getDbNameFromEnv($params['dbname']);

        if ($params['driver'] === 'pdo_sqlite') {
            $params['path'] = str_replace("__DBNAME__", $dbName, $params['path']);
        } else {
            $params['dbname'] = $dbName;
        }

        return parent::createConnection($params, $config, $eventManager, $mappingTypes);
    }

    private function getDbNameFromEnv($dbName)
    {
        if ($this->issetDbNameEnvValue()) {
            return $dbName.'_'.$this->getDbNameEnvValue();
        }

        return $dbName;
    }

    private function issetDbNameEnvValue()
    {
        $dbName = $this->getDbNameEnvValue();

        return (!empty($dbName));
    }

    private function getDbNameEnvValue()
    {
        return getenv(EnvCommandCreator::ENV_TEST_CHANNEL_READABLE);
    }
}

Change path instead of dbName for SQLite driver

SQLite does not have `dbname` parameter (in fact, SQLite databases do not have names - it's always one database per 1 file). So, if useing sqlite, you should

```

doctrine:
    dbal:
        driver:   pdo_sqlite
        path:     "%kernel.cache_dir%/__DBNAME__.db"
```

Where dbName will be replaced with ENV_TEST_CHANNEL_READABLE.


<?php
include('classLoad.php');
//classes loading end
session_start();
//post input processing
$action = htmlentities($_POST['action']);//this parameter's used to let the dispatcher decide the action to take
$sourceName = htmlentities($_POST['source']);//this parameter's used to know from which view comes this request
$pageNumber = "";//this parameter is used in case of views with pagination, we added it to our source
if ( isset($_POST['pageNumber']) ) { $pageNumber = "?p=".htmlentities($_POST['pageNumber']); }
//Components Porcessing
//Step 1: Generate components names
$component = ucfirst($sourceName);
$componentController = ucfirst($component)."ActionController";
//Step 2 : Create new components
$componentController = new AppController($sourceName);
$componentController->$action($_POST);
$source = $componentController->source();
//Step 3 : Send response
$_SESSION['actionMessage'] = $componentController->actionMessage();
$_SESSION['typeMessage'] = $componentController->typeMessage();
$_SESSION['form'] = $_POST; //this session is used to store form's fields for backwards actions
$_SESSION['form']['name'] = $sourceName;
header('Location:../'.$source.$pageNumber);

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('classLoad.php');
//classes loading end
session_start();
//post input processing
$action = htmlentities($_POST['action']);//this parameter's used to let the dispatcher decide the action to take
$sourceName = htmlentities($_POST['source']);//this parameter's used to know from which view comes this request
$pageNumber = "";//this parameter is used in case of views with pagination, we added it to our source
if ( isset($_POST['pageNumber']) ) { $pageNumber = "?p=".htmlentities($_POST['pageNumber']); }
//Components Porcessing
//Step 1: Generate components names
$component = ucfirst($sourceName);
$componentController = ucfirst($component)."ActionController";
//Step 2 : Create new components
$componentController = new AppController($sourceName);
$componentController->$action($_POST);
$source = $componentController->source();
//Step 3 : Send response
$_SESSION['actionMessage'] = $componentController->actionMessage();
$_SESSION['typeMessage'] = $componentController->typeMessage();
$_SESSION['form'] = $_POST; //this session is used to store form's fields for backwards actions
$_SESSION['form']['name'] = $sourceName;
header('Location:../'.$source.$pageNumber);

Fix some bugs - Date : 04/07/2017

Fix some bugs - Date : 04/07/2017


<?php

class ExPage_Index extends ExPage_Abstract
{
    public function isLastPage()
    {
        return (count($this->find('td.ptds + td.ptdd')) > 0);
    }

    public function getGalleries()
    {
        $ret = array();

        $links = $this->find('td.itd .it5 a');
        foreach ($links as $linkElem) {
            $gallery = new stdClass();

            $link = pq($linkElem);
            $gallery->name = $link->text();

            preg_match("~https://exhentai.org/g/(\d*)/(\w*)/~", $link->attr('href'), $matches);

            if (isset($matches[1]) && isset($matches[2])) {
                $gallery->exhenid = $matches[1];
                $gallery->hash = $matches[2];

                $ret[] = $gallery;
            }
        }

        return $ret;
    }
}

<?php

class ExPage_Index extends ExPage_Abstract
{
    public function isLastPage()
    {
        return (count($this->find('td.ptds + td.ptdd')) > 0);
    }

    public function getGalleries()
    {
        $ret = array();

        $links = $this->find('.itg.gld .gl1t .glname a');
        foreach ($links as $linkElem) {
            $gallery = new stdClass();

            $link = pq($linkElem);
            $gallery->name = $link->text();

            preg_match("~https://exhentai.org/g/(\d*)/(\w*)/~", $link->attr('href'), $matches);

            if (isset($matches[1]) && isset($matches[2])) {
                $gallery->exhenid = $matches[1];
                $gallery->hash = $matches[2];

                $ret[] = $gallery;
            }
        }

        return $ret;
    }
}

Update CSS Selector to Match ExHentai Changes


<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * TaskListsRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class TaskListsRepository extends EntityRepository
{

  public function findAll()
  {
    $today = new \DateTime();
    return $this
            ->createQueryBuilder('tl')
            ->select('tl, t')
            ->leftJoin('tl.tasks', 't')
            ->orderBy("tl.createdAt", "ASC")
            ->getQuery()
            ->getResult();
  }

  public function findAllWithActiveTasks()
  {
    $today = new \DateTime();
    return $this
            ->createQueryBuilder('tl')
            ->select('tl, t')
            ->leftJoin('tl.tasks', 't')
            ->where('t.completedAt > :today')
            ->orWhere('t.completed <> true')
            ->addOrderBy("t.completed", "ASC")
            ->addOrderBy("t.order", "ASC")
            ->setParameter(':today', $today->format('Y-m-d'))
            ->getQuery()
            ->getResult();
  }

  public function search($searchTerm)
  {
    return $this
            ->createQueryBuilder('tl')
            ->select()
            ->where('tl.name LIKE :searchTerm')
            ->setParameter(":searchTerm", '%' . $searchTerm . '%')
            ->getQuery()
            ->getResult();
  }

}

<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * TaskListsRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class TaskListsRepository extends EntityRepository
{

  public function findAll()
  {
    $today = new \DateTime();
    return $this
            ->createQueryBuilder('tl')
            ->select('tl, t, a, c, w')
            ->leftJoin('tl.tasks', 't')
            ->leftJoin('tl.account', 'a')
            ->leftJoin('a.client', 'c')
            ->leftJoin('t.workLog', 'w')
            ->orderBy("tl.createdAt", "ASC")
            ->getQuery()
            ->getResult();
  }

  public function findAllWithActiveTasks()
  {
    $today = new \DateTime();
    return $this
            ->createQueryBuilder('tl')
            ->select('tl, t')
            ->leftJoin('tl.tasks', 't')
            ->where('t.completedAt > :today')
            ->orWhere('t.completed <> true')
            ->addOrderBy("t.completed", "ASC")
            ->addOrderBy("t.order", "ASC")
            ->setParameter(':today', $today->format('Y-m-d'))
            ->getQuery()
            ->getResult();
  }

  public function search($searchTerm)
  {
    return $this
            ->createQueryBuilder('tl')
            ->select()
            ->where('tl.name LIKE :searchTerm')
            ->setParameter(":searchTerm", '%' . $searchTerm . '%')
            ->getQuery()
            ->getResult();
  }

}

Increase taskList performance by reducing queries


<?php
/**
 * Created by IntelliJ IDEA.
 * User: nikolayyotsov
 * Date: 5/21/17
 * Time: 3:40 PM
 */

namespace App\Http\Controllers;

use App\Http\Client\TransltrClient;
use App\Word;
use Illuminate\Http\Request;

class TranslateController extends Controller
{
    /**
     * @var array
     */
    private $validationRules
        = [
            'words' => 'required',
        ];

    /**
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function translate(Request $request)
    {
        $this->validate($request, $this->validationRules);

        $words  = explode(' ', $request->only('words')['words']);

        $meaning = [];
        foreach ($words as $word) {
            $meaning[$word] = TransltrClient::transalte($word, 'en', 'bg')['translationText'];
        }

        return view('welcome', ['translated' => $meaning]);
    }
}

<?php
/**
 * Created by IntelliJ IDEA.
 * User: nikolayyotsov
 * Date: 5/21/17
 * Time: 3:40 PM
 */

namespace App\Http\Controllers;

use App\Word;
use Illuminate\Http\Request;

class TranslateController extends Controller
{
    /**
     * @var array
     */
    private $validationRules
        = [
            'words' => 'required',
        ];

    /**
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function translate(Request $request)
    {
        $this->validate($request, $this->validationRules);

        $words  = explode(' ', $request->only('words')['words']);

        $meaning = [];
        foreach ($words as $word) {
            /** @var \Illuminate\Database\Eloquent\Builder $wordCollection */
            if(!($entity = Word::where(['word' => $word])->get()->first())){
                $meaning[$word] = $word;
                continue;
            }

            $entity = $entity->toArray();

            $meaning[$word] = isset($entity['meaning'])
                ? $entity['meaning']
                : $word;
        }

        return view('welcome', ['translated' => $meaning]);
    }
}

Revert "translate via api call"

Revert "translate via api call"


<?php
if (!isset($_GET['url'])) die();
$url = urldecode($_GET['url']);
if (strpos($url, 'http://', 0) !== 0 && strpos($url, 'https://', 0) !== 0) die();

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$content = curl_exec($ch);
curl_close($ch);

if ($content === false) echo 'Import failed.';
else echo $content;

<?php
if (!isset($_GET['url'])) die();
$url = urldecode($_GET['url']);
if (strpos($url, 'http://', 0) !== 0 && strpos($url, 'https://', 0) !== 0) die();

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("User-Agent: Run-PHP-Code"));
$content = curl_exec($ch);
curl_close($ch);

if ($content === false) echo 'Import failed.';
else echo $content;

Set User-Agent to fix gist imports

Set User-Agent to fix gist imports


@extends('layouts.master')

@section('title', 'Admin Dashboard')

@section('content')

                    Admin

Server List

                                    ID
                                    Name
                                    Created At
                                    Actions

                                @foreach($servers as $server)

                                        {{$server->id}}
                                        {{$server->name}}
                                        {{$server->created_at}}

                                                $server->id])}}"> Manage

                                @endforeach

@endsection

Fix admin table on mobile devices

Fix admin table on mobile devices


<?php

/**
 * Call pages by their filename like:
 * {{ pages['page2'].title }}
 *
 * @author James Doyle
 * @link http://ohdoylerules.com/
 * @license http://opensource.org/licenses/MIT
 */
class Pico_Get_By_Filename {

  private function _make_filename($url)
  {
    $filename = substr($url, (strrpos($url, '/')));
    $filename = str_replace('/', '', $filename);
    // need to find a way around files with the same name
    if (strlen($filename) <= 1) {
      $filename .= 'index';
    }
    return $filename;
  }

  public function get_pages(&$pages, &$current_page, &$prev_page, &$next_page) {
    $temp = array();
    foreach ($pages as $page) {
      $filename = $this->_make_filename($page['url']);
      $page['filename'] = $filename;
      $temp[$filename] = $page;
    }
    $pages = $temp;
  }

}

// End of file

<?php

/**
 * Call pages by their filename like:
 * {{ pages['page2'].title }}
 *
 * @author James Doyle
 * @link http://ohdoylerules.com/
 * @license http://opensource.org/licenses/MIT
 */
class Pico_Get_By_Filename {

  private function _make_filename($url)
  {
    $filename = substr($url, (strrpos($url, '/')));
    $filename = str_replace('/', '', $filename);
    // need to find a way around files with the same name
    if (strlen($filename) <= 1) {
      $filename .= 'index';
    }
    return $filename;
  }

  public function get_pages(&$pages, &$current_page, &$prev_page, &$next_page) {
    $temp = array();
    foreach ($pages as $page) {
      $filename = $this->_make_filename($page['url']);
      $page['filename'] = $filename;
      $temp[$filename] = $page;
    }
    $filename = $this->_make_filename($current_page['url']);
    $current_page['filename'] = $filename;
    $pages = $temp;
  }

}

// End of file

Fix - filename not showed for current_page


<?php

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

foreach (glob(__DIR__.'/includes/*.php') as $file) {
	require_once $file;
}

$config = [
	'rootDir'       => __DIR__,
	'password'      => $credentials['password'],
	'title'         => 'SCReddit QDB',
	'enableCaptcha' => false,
	'latest'        => 10,
	'top'           => 25,
	'browsePP'      => 50,
	'random'        => 25,
	'search'        => 25,
];

$app = new Application($config);

$app->connectMysql($credentials['mysqlUser'], $credentials['mysqlPass'], 'bash');

$app->run();

<?php

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

foreach (glob(__DIR__.'/includes/*.php') as $file) {
	require_once $file;
}

$config = [
	'rootDir'       => __DIR__,
	'password'      => $credentials['password'],
	'title'         => 'SCReddit QDB',
	'enableCaptcha' => $credentials['enableCaptcha'],
	'latest'        => 10,
	'top'           => 25,
	'browsePP'      => 50,
	'random'        => 25,
	'search'        => 25,
];

$app = new Application($config);

$app->connectMysql($credentials['mysqlUser'], $credentials['mysqlPass'], 'bash');

$app->run();

Allow CAPTCHA from config file

Allow CAPTCHA from config file


<?php

/*
 * This file is part of HtmlCompress.
 *
 ** (c) 2014 Cees-Jan Kiewiet
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace WyriHaximus\HtmlCompress\Compressor;

/**
 * Class HtmlCompressor
 *
 * @package WyriHaximus\HtmlCompress\Compressor
 */
class HtmlCompressor extends Compressor
{
    /**
     * {@inheritdoc}
     */
    protected function execute($string)
    {
        // Replace newlines, returns and tabs with nothing
        $string = str_replace(["\r", "\n", "\t"], '', $string);
        // Replace multiple spaces with a single space
        $string = preg_replace('/(\s+)/m', ' ', $string);

        // Remove spaces that are followed by either > or <
        $string = preg_replace('/ (>)/', '$1', $string);
        // Remove spaces that are preceded by either > or <
        $string = preg_replace('/(<) /', '$1', $string);

        return trim($string);
    }
}

<?php

/*
 * This file is part of HtmlCompress.
 *
 ** (c) 2014 Cees-Jan Kiewiet
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace WyriHaximus\HtmlCompress\Compressor;

/**
 * Class HtmlCompressor
 *
 * @package WyriHaximus\HtmlCompress\Compressor
 */
class HtmlCompressor extends Compressor
{
    /**
     * {@inheritdoc}
     */
    protected function execute($string)
    {
        // Replace newlines, returns and tabs with nothing
        $string = str_replace(["\r", "\n", "\t"], '', $string);
        // Replace multiple spaces with a single space
        $string = preg_replace('/(\s+)/m', ' ', $string);

        // Remove spaces that are followed by either > or <
        $string = preg_replace('/ (>)/', '$1', $string);
        // Remove spaces that are preceded by either > or <
        $string = preg_replace('/(<) /', '$1', $string);
        // Remove spaces that are between > and <
        $string = preg_replace('/(>) (<)/', '>$2', $string);

        return trim($string);
    }
}

Remove spaces that are between > and <

Remove spaces that are between > and <


<?php

/**
 * LICENSE: This file is subject to the terms and conditions defined in
 * file 'LICENSE', which is part of this source code package.
 *
 * @copyright 2016 Copyright(c) - All rights reserved.
 */

namespace Rafrsr\DoctrineExtraBundle\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;

/**
 * EncryptedTrait
 */
trait EncryptedTrait
{

    /**
     * @inheritdoc
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if ($value !== null) {
            $value = Encryptor::get()->decrypt($value);
        }

        return parent::convertToPHPValue($value, $platform);
    }

    /**
     * @inheritdoc
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if ($value !== null) {
            $value = parent::convertToDatabaseValue($value, $platform);
        }

        return Encryptor::get()->encrypt($value);
    }
}

<?php

/**
 * LICENSE: This file is subject to the terms and conditions defined in
 * file 'LICENSE', which is part of this source code package.
 *
 * @copyright 2016 Copyright(c) - All rights reserved.
 */

namespace Rafrsr\DoctrineExtraBundle\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;

/**
 * EncryptedTrait
 */
trait EncryptedTrait
{

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if ($value !== null) {
            $value = Encryptor::get()->decrypt($value);
        }

        return parent::convertToPHPValue($value, $platform);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if ($value !== null) {
            $value = parent::convertToDatabaseValue($value, $platform);
        }

        return Encryptor::get()->encrypt($value);
    }

    /**
     * {@inheritdoc}
     */
    public function requiresSQLCommentHint(AbstractPlatform $platform)
    {
        return true;
    }
}

Mark as commented explicitly all encrypted types by default


<?php

namespace SilverShop\ORM\FieldType;

use SilverShop\Extension\ShopConfigExtension;
use SilverStripe\Core\Convert;
use SilverStripe\ORM\FieldType\DBVarchar;

class ShopCountry extends DBVarchar
{
    public function __construct($name = null, $size = 3, $options = [])
    {
        parent::__construct($name, $size = 3, $options);
    }

    public function forTemplate()
    {
        return $this->Nice();
    }

    /**
     * Convert ISO abbreviation to full, translated country name
     */
    public function Nice()
    {
        $val = ShopConfigExtension::countryCode2name($this->value);
        if (!$val) {
            $val = $this->value;
        }
        return _t(__CLASS__ . '.' . $this->value, $val);
    }

    public function XML()
    {
        return Convert::raw2xml($this->Nice());
    }
}

<?php

namespace SilverShop\ORM\FieldType;

use SilverShop\Extension\ShopConfigExtension;
use SilverStripe\Core\Convert;
use SilverStripe\ORM\FieldType\DBVarchar;

class ShopCountry extends DBVarchar
{
    public function __construct($name = null, $size = 3, $options = [])
    {
        parent::__construct($name, $size = 3, $options);
    }

    public function forTemplate()
    {
        return $this->Nice();
    }

    /**
     * Convert ISO abbreviation to full, translated country name
     */
    public function Nice()
    {
        return IntlLocales::singleton()->countryName($this->value);
    }

    public function XML()
    {
        return Convert::raw2xml($this->Nice());
    }
}

Use IntlLocales to get the localized country name

Use IntlLocales to get the localized country name. This saves having to keep a file with translated country names.


<?php

/*
 * This file is part of the Tadcka package.
 *
 * (c) Tadas Gliaubicas <tadcka89@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Tadcka\Component\Tree\Event;

use Symfony\Component\EventDispatcher\Event;
use Tadcka\Component\Tree\Model\NodeInterface;

/**
 * @author Tadas Gliaubicas <tadcka89@gmail.com>
 *
 * @since 9/6/14 2:12 PM
 */
class TreeNodeEvent extends Event
{
    /**
     * @var NodeInterface
     */
    private $node;

    /**
     * Constructor.
     *
     * @param NodeInterface $node
     */
    public function __construct(NodeInterface $node)
    {
        $this->node = $node;
    }

    /**
     * Get node.
     *
     * @return NodeInterface
     */
    public function getNode()
    {
        return $this->node;
    }
}

<?php

/*
 * This file is part of the Tadcka package.
 *
 * (c) Tadas Gliaubicas <tadcka89@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Tadcka\Component\Tree\Event;

use Symfony\Component\EventDispatcher\Event;
use Tadcka\Component\Tree\Model\NodeInterface;

/**
 * @author Tadas Gliaubicas <tadcka89@gmail.com>
 *
 * @since 9/6/14 2:12 PM
 */
class TreeNodeEvent extends Event
{
    /**
     * @var NodeInterface
     */
    private $node;

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

    /**
     * Constructor.
     *
     * @param string $locale
     * @param NodeInterface $node
     */
    public function __construct($locale, NodeInterface $node)
    {
        $this->locale = $locale;
        $this->node = $node;
    }

    /**
     * Get locale.
     *
     * @return string
     */
    public function getLocale()
    {
        return $this->locale;
    }

    /**
     * Get node.
     *
     * @return NodeInterface
     */
    public function getNode()
    {
        return $this->node;
    }
}

Add locale to tree node event.

Add locale to tree node event.


<?php

use mageekguy\atoum\reports;

$runner
	->addTestsFromDirectory(__DIR__ . '/tests/units/classes')
	->disallowUndefinedMethodInInterface()
;

$travis = getenv('TRAVIS');

if ($travis)
{
	$script->addDefaultReport();

	$coverallsToken = getenv('COVERALLS_REPO_TOKEN');

	if ($coverallsToken)
	{
		$coverallsReport = new reports\asynchronous\coveralls(__DIR__ . '/classes', $coverallsToken);

		$defaultFinder = $coverallsReport->getBranchFinder();

		$coverallsReport
			->setBranchFinder(function() use ($defaultFinder) {
					if (($branch = getenv('TRAVIS_BRANCH')) === false)
					{
						$branch = $defaultFinder();
					}

					return $branch;
				}
			)
			->setServiceName('travis-ci')
			->setServiceJobId(getenv('TRAVIS_JOB_ID'))
			->addDefaultWriter()
		;

		$runner->addReport($coverallsReport);
	}
}

<?php

use mageekguy\atoum\reports;

$runner
	->addTestsFromDirectory(__DIR__ . '/tests/units/classes')
	->disallowUndefinedMethodInInterface()
;

$travis = getenv('TRAVIS');

if ($travis)
{
	$script->addDefaultReport();

	$coverallsToken = getenv('COVERALLS_REPO_TOKEN');

	if ($coverallsToken)
	{
		$coverallsReport = new reports\asynchronous\coveralls('classes', $coverallsToken);

		$defaultFinder = $coverallsReport->getBranchFinder();

		$coverallsReport
			->setBranchFinder(function() use ($defaultFinder) {
					if (($branch = getenv('TRAVIS_BRANCH')) === false)
					{
						$branch = $defaultFinder();
					}

					return $branch;
				}
			)
			->setServiceName('travis-ci')
			->setServiceJobId(getenv('TRAVIS_JOB_ID'))
			->addDefaultWriter()
		;

		$runner->addReport($coverallsReport);
	}
}

Update source directory in coveralls configuration.


<?php

class CM_Clockwork_Storage_FileSystem extends CM_Clockwork_Storage_Abstract implements CM_Service_ManagerAwareInterface {

    use CM_Service_ManagerAwareTrait;

    protected function _load() {
        $data = [];
        $file = $this->_getStorageFile();
        if ($file->exists()) {
            $values = CM_Params::decode($file->read(), true);
            $data = \Functional\map($values, function ($timeStamp) {
                return new DateTime('@' . $timeStamp);
            });
        }
        return $data;
    }

    protected function _save(array $data) {
        $values = \Functional\map($data, function (DateTime $dateTime) {
            return $dateTime->getTimestamp();
        });
        $content = CM_Params::jsonEncode($values, true);
        $file = $this->_getStorageFile();
        if (!$file->exists()) {
            $file->ensureParentDirectory();
        }
        $file->write($content);
    }

    /**
     * @return CM_File
     */
    private function _getStorageFile() {
        $filename = md5($this->_context);
        return new CM_File("clockwork/{$filename}.json", $this->getServiceManager()->getFilesystems()->getData());
    }
}

<?php

class CM_Clockwork_Storage_FileSystem extends CM_Clockwork_Storage_Abstract implements CM_Service_ManagerAwareInterface {

    use CM_Service_ManagerAwareTrait;

    protected function _load() {
        $data = [];
        $file = $this->_getStorageFile();
        if ($file->exists()) {
            $values = CM_Params::jsonDecode($file->read(), true);
            $data = \Functional\map($values, function ($timeStamp) {
                return new DateTime('@' . $timeStamp);
            });
        }
        return $data;
    }

    protected function _save(array $data) {
        $values = \Functional\map($data, function (DateTime $dateTime) {
            return $dateTime->getTimestamp();
        });
        $content = CM_Params::jsonEncode($values, true);
        $file = $this->_getStorageFile();
        if (!$file->exists()) {
            $file->ensureParentDirectory();
        }
        $file->write($content);
    }

    /**
     * @return CM_File
     */
    private function _getStorageFile() {
        $filename = md5($this->_context);
        return new CM_File("clockwork/{$filename}.json", $this->getServiceManager()->getFilesystems()->getData());
    }
}

Use just "jsonDecode" instead of "decode"


<?php

namespace DelayedJobs\Worker;

use Cake\Console\Shell;
use DelayedJobs\DelayedJob\DelayedJob;

/**
 * Interface for delayed job workers
 */
interface JobWorkerInterface
{
    /**
     * @param \DelayedJobs\DelayedJob\DelayedJob $job The job that is being run.
     * @param \Cake\Console\Shell|null $shell An instance of the shell that the job is run in
     * @return bool
     */
    public function __invoke(DelayedJob $job, Shell $shell = null);
}

<?php

namespace DelayedJobs\Worker;

use Cake\Console\Shell;
use DelayedJobs\DelayedJob\DelayedJob;

/**
 * Interface for delayed job workers
 */
interface JobWorkerInterface
{
    /**
     * @param \DelayedJobs\DelayedJob\DelayedJob $job The job that is being run.
     * @param \Cake\Console\Shell|null $shell An instance of the shell that the job is run in
     * @return null|bool|\Cake\I18n\Time|string
     */
    public function __invoke(DelayedJob $job, Shell $shell = null);
}

Correct docblock for __invoke method

Correct docblock for __invoke method


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

declare(strict_types=1);

namespace Sylius\Component\Core\Calculator;

use Sylius\Component\Core\Exception\MissingChannelConfigurationException;
use Sylius\Component\Core\Model\ProductVariantInterface;

/**
 * @deprecated
 */
interface ProductVariantPriceCalculatorInterface
{
    /**
     * @throws MissingChannelConfigurationException when price for given channel does not exist
     */
    public function calculate(ProductVariantInterface $productVariant, array $context): int;
}

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

declare(strict_types=1);

namespace Sylius\Component\Core\Calculator;

use Sylius\Component\Core\Exception\MissingChannelConfigurationException;
use Sylius\Component\Core\Model\ProductVariantInterface;

/**
 * @deprecated since Sylius 1.8, use ProductVariantPricesCalculatorInterface instead
 */
interface ProductVariantPriceCalculatorInterface
{
    /**
     * @throws MissingChannelConfigurationException when price for given channel does not exist
     */
    public function calculate(ProductVariantInterface $productVariant, array $context): int;
}

Add details to price calculator interface deprecation annotation


<?php

namespace AppBundle\Command;

use AppBundle\Service\DBVersion;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ListUserCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
        // the name of the command (the part after "bin/console")
        ->setName('app:list-user')

        // the short description shown while running "php bin/console list"
        ->setDescription('Lists existing users.')

        // the full command description shown when running the command with
        // the "--help" option
        ->setHelp("This command allows you to list all existing users...")
        ->addOption('connection', 'c', InputOption::VALUE_REQUIRED, 'The database version')
    ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $connection_name = $input->getOption('connection');
        if($connection_name == null) {
            $connection_name = $this->getContainer()->get('doctrine')->getDefaultConnectionName();
        }
        $em  = $this->getContainer()->get(DBVersion::class)->getEntityManager();
        $users = $em->getRepository('AppBundle:FennecUser')->findAll();
        $table = new Table($output);
        $table->setHeaders(['user_id', 'firstName', 'lastName', 'username']);
        foreach($users as $user){
            $table->addRow([$user->getId(), $user->getFirstName(), $user->getLastName(), $user->getUsername()]);
        }
        $table->render();
    }
}

<?php

namespace AppBundle\Command;

use AppBundle\Service\DBVersion;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ListUserCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
        // the name of the command (the part after "bin/console")
        ->setName('app:list-user')

        // the short description shown while running "php bin/console list"
        ->setDescription('Lists existing users.')

        // the full command description shown when running the command with
        // the "--help" option
        ->setHelp("This command allows you to list all existing users...")
        ->addOption('connection', 'c', InputOption::VALUE_REQUIRED, 'The database version')
    ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em  = $this->getContainer()->get(DBVersion::class)->getUserEntityManager();
        $users = $em->getRepository('AppBundle:FennecUser')->findAll();
        $table = new Table($output);
        $table->setHeaders(['user_id', 'firstName', 'lastName', 'username']);
        foreach($users as $user){
            $table->addRow([$user->getId(), $user->getFirstName(), $user->getLastName(), $user->getUsername()]);
        }
        $table->render();
    }
}

Use user em in list users command

Use user em in list users command


<?php

namespace Isaac\Services\Filesystem;

use League\Flysystem\Adapter\Local;

/**
 * A fork of the Local adapter that grants us permissions to any absolute path
 * instead of working with relative paths.
 */
class AbsoluteLocal extends Local
{
    /**
     * LooseLocal constructor.
     */
    public function __construct()
    {
        $this->permissionMap = static::$permissions;
        $this->writeFlags = LOCK_EX;
    }
}

<?php

namespace Isaac\Services\Filesystem;

use League\Flysystem\Adapter\Local;

/**
 * A fork of the Local adapter that grants us permissions to any absolute path
 * instead of working with relative paths.
 */
class AbsoluteLocal extends Local
{
    /**
     * LooseLocal constructor.
     */
    public function __construct()
    {
        $this->permissionMap = static::$permissions;
        $this->writeFlags = LOCK_EX;
    }

    /**
     * {@inheritdoc}
     */
    public function applyPathPrefix($path)
    {
        return $path;
    }
}

Fix path prefixing on unix

Fix path prefixing on unix


<?php namespace TightenCo\Jigsaw\Console;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ServeCommand extends Command
{
    public function __construct()
    {
        parent::__construct();
    }

    protected function configure()
    {
        $this->setName('serve')
            ->setDescription('Serve local site with php built-in server.')
            ->addArgument(
                'environment',
                InputArgument::OPTIONAL,
                'What environment should we serve?'
            )
            ->addArgument(
                'port',
                InputArgument::OPTIONAL,
                'What port should we use?'
            );
    }

    protected function fire()
    {
        $environment = $this->input->getArgument('environment') ?: 'local';
        $port = $this->input->getArgument('port') ?: '8000';

        $this->info("Server started on http://localhost:{$port}");

        passthru("php -S localhost:{$port} -t build_{$environment}");
    }
}

<?php namespace TightenCo\Jigsaw\Console;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ServeCommand extends Command
{
    public function __construct()
    {
        parent::__construct();
    }

    protected function configure()
    {
        $this->setName('serve')
            ->setDescription('Serve local site with php built-in server.')
            ->addArgument(
                'environment',
                InputArgument::OPTIONAL,
                'What environment should we serve?'
            )
            ->addOption(
                'port',
                'p',
                InputOption::VALUE_REQUIRED,
                'What port should we use?'
            );
    }

    protected function fire()
    {
        $environment = $this->input->getArgument('environment') ?: 'local';
        $port = $this->input->getOption('port') ?: '8000';

        $this->info("Server started on http://localhost:{$port}");

        passthru("php -S localhost:{$port} -t build_{$environment}");
    }
}

Change port from argument to option

Change port from argument to option


<?php

namespace Ifensl\Bundle\PadManagerBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Ifensl\Bundle\PadManagerBundle\Entity\Subject;

class LoadSubjectData implements FixtureInterface
{
    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        $algo = new Subject();
        $algo->setName("Algorithmique");
        $manager->persist($algo);

        $gestion = new Subject();
        $gestion->setName("Gestion");
        $manager->persist($gestion);

        $algebre = new Subject();
        $algebre->setName("Algèbre");
        $manager->persist($algebre);

        $manager->flush();
    }
}

<?php

namespace Ifensl\Bundle\PadManagerBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Ifensl\Bundle\PadManagerBundle\Entity\Subject;

class LoadSubjectData implements FixtureInterface
{
    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        $algo = new Subject();
        $algo->setName("Algorithmique");
        $manager->persist($algo);

        $gestion = new Subject();
        $gestion->setName("Gestion");
        $manager->persist($gestion);

        $algebre = new Subject();
        $algebre->setName("Algèbre");
        $manager->persist($algebre);

        $prisDeNote = new Subject();
        $prisDeNote->setName("Prise de notes");
        $manager->persist($prisDeNote);

        $manager->flush();
    }
}

Add "prise de note" subject fixture

Add "prise de note" subject fixture


{{-- Block Type: Call To Action --}}

block_title) }} class="segment segment--cta">

  @if (!empty($block->block_title))

{{ $block->block_title }}

  @endif

    @if (!empty($block->block_body_html))
      {{ $block->block_body_html }}
    @endif

    @if($url === 'home' && !Scholarship::isClosed())

        @if (Auth::guest())
          {{ link_to_route('registration.create', 'Start Application', null, ['class' => 'button -default']) }}
          {{ link_to_route('status', 'or continue an application') }}
        @else
          {{ link_to_route('status', 'Continue Application', null, ['class' => 'button -default']) }}
        @endif

    @endif

{{-- Block Type: Call To Action --}}

block_title) }} class="segment segment--cta">

  @if (!empty($block->block_title))

{{ $block->block_title }}

  @endif

    @if (!empty($block->block_body_html))
      {{ $block->block_body_html }}
    @endif

    @if($url === 'home' && !Scholarship::isClosed() && Scholarship::isOpen())

        @if (Auth::guest())
          {{ link_to_route('registration.create', 'Start Application', null, ['class' => 'button -default']) }}
          {{ link_to_route('status', 'or continue an application') }}
        @else
          {{ link_to_route('status', 'Continue Application', null, ['class' => 'button -default']) }}
        @endif

    @endif

Check if scholarship is open before rendering cta block


<?php
/**
 * Complex example of REST controller
 *
 * @category Example
 *
 * @author   Anton Shevchuk
 * @created  19.02.15 16:27
 */
namespace Application;

use Application\Test;
use Bluz\Application\Exception\ForbiddenException;
use Bluz\Controller\Controller;
use Bluz\Controller\Mapper\Rest;

/**
 * @accept HTML
 * @accept JSON
 * @acl Read
 * @acl Create
 * @acl Update
 * @acl Delete
 *
 * @return mixed
 * @throws ForbiddenException
 * @internal param Controller $this
 */
return function () {
    /**
     * @var Controller $this
     */
    $this->disableLayout();

    $rest = new Rest();

    $rest->setCrud(Test\Crud::getInstance());

    $rest->addMap('HEAD', 'system', 'rest/head', 'Read');
    $rest->addMap('GET', 'system', 'rest/get', 'Read');
    $rest->addMap('POST', 'system', 'rest/post', 'Create');
    $rest->addMap('PUT', 'system', 'rest/put', 'Update');
    $rest->addMap('DELETE', 'system', 'rest/delete', 'Delete');

    return $rest->run();
};

<?php
/**
 * Complex example of REST controller
 *
 * @category Example
 *
 * @author   Anton Shevchuk
 * @created  19.02.15 16:27
 */
namespace Application;

use Application\Test;
use Bluz\Application\Exception\ForbiddenException;
use Bluz\Controller\Controller;
use Bluz\Controller\Mapper\Rest;

/**
 * @accept HTML
 * @accept JSON
 * @acl Read
 * @acl Create
 * @acl Update
 * @acl Delete
 *
 * @return mixed
 * @throws ForbiddenException
 */
return function () {
    /**
     * @var Controller $this
     */
    $rest = new Rest();

    $rest->setCrud(Test\Crud::getInstance());

    $rest->head('system', 'rest/head', 'Read');
    $rest->get('system', 'rest/get', 'Read');
    $rest->post('system', 'rest/post', 'Create');
    $rest->put('system', 'rest/put', 'Update');
    $rest->delete('system', 'rest/delete', 'Delete');

    return $rest->run();
};

Migrate to usage Mapper aliases

Migrate to usage Mapper aliases


<?php

/**
 * Your Project
 *
 * @copyright 2014 YourCompany
 * @package   \YourCompany\YourProject
 * @license   All Rights Reserved
 */

// Load Escher
require "escher.php";

// Instantiate a router
$router = new TDM\Escher\Router();

// Set up the routing table
$router->addStaticRoute('/', 'YourCompany\YourProject\Presenters\Homepage::request');

// Identify how to route this request
$route = $router->route($_SERVER["DOCUMENT_URI"], $_SERVER["REQUEST_METHOD"]);

// If this request is not routable, call a 404
if (!is_callable($route["callable"])) {
    TDM\Escher\HTTP\StatusCode::returnCode(404);
    exit;
}

// Pass the request on to the Presenter
call_user_func_array($route["callable"], $route["arguments"]);

<?php

/**
 * Your Project
 *
 * @copyright 2014 YourCompany
 * @package   \YourCompany\YourProject
 * @license   All Rights Reserved
 */

// Load Escher
require "escher.php";

// Instantiate a router
$router = new TDM\Escher\Router();

// Set up the routing table
$router->map('/', 'YourCompany\YourProject\Presenters\Homepage::request');

// Identify how to route this request
$route = $router->route($_SERVER["REQUEST_METHOD"], $_SERVER["DOCUMENT_URI"]);

// If this request is not routable, call a 404
if (!is_callable($route)) {
    TDM\Escher\HTTP\StatusCode::returnCode(404);
    exit;
}

// Pass the request on to the Presenter
call_user_func($route);

Update routing table for new Router

Update routing table for new Router


<?php
namespace SepomexPhp;

class Locations implements \IteratorAggregate, \Countable
{
    /** @var Location[] */
    private $collection;

    public function __construct(Location ...$location)
    {
        $this->collection = $location;
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->collection);
    }

    public function count(): int
    {
        return count($this->collection);
    }

    /**
     * @return Cities|City[]
     */
    public function cities(): Cities
    {
        $cities = [];
        foreach ($this->collection as $location) {
            if ($location->hasCity()) {
                $city = $location->city();
                if (! array_key_exists($city->id(), $cities)) {
                    $cities[$city->id()] = $location->city();
                }
            }
        }
        return new Cities(...$cities);
    }

    public function asArray(): array
    {
        $array = [];
        foreach ($this->collection as $location) {
            $array[] = $location->asArray();
        }
        return $array;
    }
}

<?php
namespace SepomexPhp;

class Locations implements \IteratorAggregate, \Countable
{
    /** @var Location[] */
    private $collection;

    public function __construct(Location ...$location)
    {
        $this->collection = $location;

    public static function extractUniqueCities(Location ...$locations): Cities
    {
        // This method is static because it does not use $this
        $cities = [];
        foreach ($locations as $location) {
            if ($location->hasCity()) {
                $city = $location->city();
                if (! array_key_exists($city->id(), $cities)) {
                    $cities[$city->id()] = $location->city();
                }
            }
        }
        return new Cities(...$cities);
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->collection);
    }

    public function count(): int
    {
        return count($this->collection);
    }

    /**
     * @return Cities|City[]
     */
    public function cities(): Cities
    {
        $cities = [];
        foreach ($this->collection as $location) {
            if ($location->hasCity()) {
                $city = $location->city();
                if (! array_key_exists($city->id(), $cities)) {
                    $cities[$city->id()] = $location->city();
                }
            }
        }
        return new Cities(...$cities);
    }

    public function asArray(): array
    {
        $array = [];
        foreach ($this->collection as $location) {
            $array[] = $location->asArray();
        }
        return $array;
    }
}

Add method to extract unique cities from locations array


<?php

use Sami\Sami;
use Sami\Version\GitVersionCollection;
use Symfony\Component\Finder\Finder;

$iterator = Finder::create()
    ->files()
    ->name('*.php')
    ->exclude('Resources')
    ->in($dir = 'src');

$versions = GitVersionCollection::create($dir)
    ->add('develop', 'develop branch')
    ->add('master', 'master branch')
    ->addFromTags('3.*')
    ->addFromTags('4.*');

return new Sami($iterator, [
    'theme' => 'default',
    'versions' => $versions,
    'title' => 'AuthBucket\Bundle\OAuth2Bundle API',
    'build_dir' => __DIR__.'/build/sami/%version%',
    'cache_dir' => __DIR__.'/build/cache/sami/%version%',
    'include_parent_data' => false,
    'default_opened_level' => 3,
]);

<?php

use Sami\Sami;
use Sami\Version\GitVersionCollection;
use Symfony\Component\Finder\Finder;

$iterator = Finder::create()
    ->files()
    ->name('*.php')
    ->exclude('Resources')
    ->in($dir = 'src');

$versions = GitVersionCollection::create($dir)
    ->add('develop', 'develop branch')
    ->add('master', 'master branch')
    ->addFromTags('3.*')
    ->addFromTags('4.*');

return new Sami($iterator, array(
    'theme' => 'default',
    'versions' => $versions,
    'title' => 'AuthBucket\Bundle\OAuth2Bundle API',
    'build_dir' => __DIR__.'/build/sami/%version%',
    'cache_dir' => __DIR__.'/build/cache/sami/%version%',
    'include_parent_data' => false,
    'default_opened_level' => 3,
]);

Update Sami theme as default.

Update Sami theme as default.


<?php

    define("SECONDS_BETWEEN_ALERTS", rand(10, 60));
    define("SOURCE_NAME", "David's Alerts");

    $alerts = array(
        "Coldest Air of the Season Sweeping Through Central and Southern States",
        "Belgium on 'high alert'",
        "Multiple raids in Brussels as police seek ISIS terrorists",
        "Syria fighters may be fueled by amphetamines",
        "Alien invasion? Strange sightings in Hong Kong",
        "Experts criticise WHO delay in sounding alarm over Ebola outbreak"
    );

    $alerts_levels = array("low", "medium", "high");

    date_default_timezone_set("Europe/Madrid");
    header("Content-Type: text/event-stream\n\n");

    while (true) {
        sleep(SECONDS_BETWEEN_ALERTS);

        sendAlert($alerts[rand(0, sizeof($alerts) - 1)],
                $alerts_levels[rand(0, sizeof($alerts_levels) - 1)]);

        ob_end_flush();
        flush();
    }

    function sendAlert($message, $alert_level) {
        $date = date_create();
        $timestamp = date_timestamp_get($date);

        echo "data: { \"source\": \"$SOURCE_NAME\", \"message\": \"$message\", " .
                "\"alertLevel\": \"$alert_level\", \"timestamp\": $timestamp }\n\n";
    }

?>

<?php

    define("SECONDS_BETWEEN_ALERTS", rand(10, 60));
    define("SOURCE_NAME", "David's Alerts");

    $alerts = array(
        "Coldest Air of the Season Sweeping Through Central and Southern States",
        "Belgium on 'high alert'",
        "Multiple raids in Brussels as police seek ISIS terrorists",
        "Syria fighters may be fueled by amphetamines",
        "Alien invasion? Strange sightings in Hong Kong",
        "Experts criticise WHO delay in sounding alarm over Ebola outbreak"
    );

    $alerts_levels = array("low", "medium", "high");

    date_default_timezone_set("Europe/Madrid");
    header("Content-Type: text/event-stream\n\n");

    while (true) {
        sleep(SECONDS_BETWEEN_ALERTS);

        sendAlert($alerts[rand(0, sizeof($alerts) - 1)],
                $alerts_levels[rand(0, sizeof($alerts_levels) - 1)]);

        ob_end_flush();
        flush();
    }

    function sendAlert($message, $alert_level) {
        $date = date_create();
        $timestamp = date_timestamp_get($date);

        echo "data: { \"source\": \"" . SOURCE_NAME . "\", \"message\": \"$message\", " .
                "\"alertLevel\": \"$alert_level\", \"timestamp\": $timestamp }\n\n";
    }

?>

Fix echo to print SOURCE_NAME

Fix echo to print SOURCE_NAME


<?php

namespace Orchestra\View;

use BadMethodCallException;

class Decorator
{
    /**
     * The registered custom macros.
     *
     * @var array
     */
    protected $macros = [];

    /**
     * Registers a custom macro.
     *
     * @param  string  $name
     * @param  \Closure  $macro
     *
     * @return void
     */
    public function macro($name, $macro)
    {
        $this->macros[$name] = $macro;
    }

    /**
     * Render the macro.
     *
     * @param  string  $name
     * @param  mixed  $parameters
     *
     * @return string
     *
     * @throws \BadMethodCallException
     */
    public function render($name, ...$parameters)
    {
        if (! isset($this->macros[$name])) {
            throw new BadMethodCallException("Method [$name] does not exist.");
        }

        return $this->macros[$name](...$parameters);
    }

    /**
     * Dynamically handle calls to custom macros.
     *
     * @param  string  $method
     * @param  array   $parameters
     *
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        array_unshift($parameters, $method);

        return $this->render(...$parameters);
    }
}

<?php

namespace Orchestra\View;

use BadMethodCallException;

class Decorator
{
    /**
     * The registered custom macros.
     *
     * @var array
     */
    protected $macros = [];

    /**
     * Registers a custom macro.
     *
     * @param  string  $name
     * @param  \Closure  $macro
     *
     * @return void
     */
    public function macro($name, $macro)
    {
        $this->macros[$name] = $macro;
    }

    /**
     * Render the macro.
     *
     * @param  string  $name
     * @param  mixed  $parameters
     *
     * @return string
     *
     * @throws \BadMethodCallException
     */
    public function render($name, ...$parameters)
    {
        if (! isset($this->macros[$name])) {
            throw new BadMethodCallException("Method [$name] does not exist.");
        }

        return $this->macros[$name](...$parameters);
    }

    /**
     * Dynamically handle calls to custom macros.
     *
     * @param  string  $method
     * @param  array   $parameters
     *
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        array_unshift($parameters, $method);

        return $this->render($method, ...$parameters);
    }
}

Tweak argument unpacking for rendering decorator.

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


<?php

namespace FOS\ElasticaBundle;

use Elastica\Client as ElasticaClient;
use Elastica\Request;

/**
 * @author Gordon Franke <info@nevalon.de>
 */
class Client extends ElasticaClient
{
    public function request($path, $method = Request::GET, $data = array(), array $query = array())
    {
        $start = microtime(true);
        $response = parent::request($path, $method, $data, $query);

        if (null !== $this->_logger) {
            $time = microtime(true) - $start;

            $connection = $this->getLastRequest()->getConnection();

            $connection_array = array(
                'host'      => $connection->getHost(),
                'port'      => $connection->getPort(),
                'transport' => $connection->getTransport(),
            );

            $this->_logger->logQuery($path, $method, $data, $time, $connection_array);
        }

        return $response;
    }
}

<?php

namespace FOS\ElasticaBundle;

use Elastica\Client as ElasticaClient;
use Elastica\Request;
use FOS\ElasticaBundle\Logger\ElasticaLogger;

/**
 * @author Gordon Franke <info@nevalon.de>
 */
class Client extends ElasticaClient
{
    public function request($path, $method = Request::GET, $data = array(), array $query = array())
    {
        $start = microtime(true);
        $response = parent::request($path, $method, $data, $query);

        if (null !== $this->_logger and $this->_logger instanceof ElasticaLogger) {
            $time = microtime(true) - $start;

            $connection = $this->getLastRequest()->getConnection();

            $connection_array = array(
                'host'      => $connection->getHost(),
                'port'      => $connection->getPort(),
                'transport' => $connection->getTransport(),
            );

            $this->_logger->logQuery($path, $method, $data, $time, $connection_array);
        }

        return $response;
    }
}

Fix issue with logger not having logQuery method


<?php

namespace Ramsey\Uuid\Test\Generator;

use Ramsey\Uuid\Generator\RandomLibAdapter;
use Ramsey\Uuid\Test\TestCase;
use Mockery;

class RandomLibAdapterTest extends TestCase
{
    public function tearDown()
    {
        parent::tearDown();
        Mockery::close();
    }

    /**
     * @runInSeparateProcess
     * @preserveGlobalState disabled
     */
    public function testAdapterWithGeneratorDoesNotCreateGenerator()
    {
        $factory = Mockery::mock('overload:RandomLib\Factory');
        $factory->shouldNotReceive('getMediumStrengthGenerator')
                ->getMock();

        $generator = $this->getMockBuilder('RandomLib\Generator')
                          ->disableOriginalConstructor()
                          ->getMock();
        new RandomLibAdapter($generator);
    }

    public function testAdapterWithoutGeneratorGreatesGenerator()
    {
        $factory = Mockery::mock('overload:RandomLib\Factory');
        $factory->shouldReceive('getMediumStrengthGenerator')
                ->once()
                ->getMock();

        new RandomLibAdapter();
    }
}

<?php

namespace Ramsey\Uuid\Test\Generator;

use Ramsey\Uuid\Generator\RandomLibAdapter;
use Ramsey\Uuid\Test\TestCase;
use Mockery;

class RandomLibAdapterTest extends TestCase
{
    public function tearDown()
    {
        parent::tearDown();
        Mockery::close();
    }

    /**
     * @runInSeparateProcess
     * @preserveGlobalState disabled
     */
    public function testAdapterWithGeneratorDoesNotCreateGenerator()
    {
        $factory = Mockery::mock('overload:RandomLib\Factory');
        $factory->shouldNotReceive('getMediumStrengthGenerator')
                ->getMock();

        $generator = $this->getMockBuilder('RandomLib\Generator')
                          ->disableOriginalConstructor()
                          ->getMock();
        new RandomLibAdapter($generator);
    }

    public function testAdapterWithoutGeneratorGreatesGenerator()
    {
        $factory = Mockery::mock('overload:RandomLib\Factory');
        $factory->shouldReceive('getMediumStrengthGenerator')
                ->once()
                ->getMock();

        new RandomLibAdapter();
    }

    public function testGenerateUsesGenerator()
    {
        $length    = 10;
        $generator = $this->getMockBuilder('RandomLib\Generator')
                          ->disableOriginalConstructor()
                          ->getMock();
        $generator->expects($this->once())
                  ->method('generate')
                  ->with($length);

        $adapter = new RandomLibAdapter($generator);
        $adapter->generate($length);
    }

    public function testGenerateReturnsString()
    {
        $generator = $this->getMockBuilder('RandomLib\Generator')
                          ->disableOriginalConstructor()
                          ->getMock();
        $generator->expects($this->once())
                  ->method('generate')
                  ->willReturn('random-string');

        $adapter = new RandomLibAdapter($generator);
        $result  = $adapter->generate(1);
        $this->assertEquals('random-string', $result);
    }
}

Add coverage of generate method

Add coverage of generate method


#!/usr/bin/env php
<?php

use Symfony\Component\Console\Application;

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

date_default_timezone_set('Europe/Madrid');

$loader = new \Ontic\Yaes\Loaders\SoftwarePackagesLoader();
$softwarePackages = $loader->findSoftwarePackages(
    __DIR__ . '/src/SoftwarePackages',
    'Ontic\Yaes\SoftwarePackages'
);

$locale = 'es_ES';
putenv('LC_ALL=' . $locale);
setlocale(LC_ALL, $locale.'.UTF-8');
bindtextdomain("messages", "locale");
textdomain("messages");

$application = new Application();
foreach($softwarePackages as $package)
{
    $application->addCommands($package->getCommands());
}

$application->add(new \Ontic\Yaes\Command\IdentifyCommand($softwarePackages));
$application->add(new \Ontic\Yaes\Command\ScanCommand($softwarePackages));
$application->run();

#!/usr/bin/env php
<?php

use Symfony\Component\Console\Application;

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

date_default_timezone_set('Europe/Madrid');

$loader = new \Ontic\Yaes\Loaders\SoftwarePackagesLoader();
$softwarePackages = $loader->findSoftwarePackages(
    __DIR__ . '/src/SoftwarePackages',
    'Ontic\Yaes\SoftwarePackages'
);

bindtextdomain("messages", "locale");
textdomain("messages");

$application = new Application();
foreach($softwarePackages as $package)
{
    $application->addCommands($package->getCommands());
}

$application->add(new \Ontic\Yaes\Command\IdentifyCommand($softwarePackages));
$application->add(new \Ontic\Yaes\Command\ScanCommand($softwarePackages));
$application->run();

Read locale from the environment

Read locale from the environment


<?php

function collect_cpuUsage($debug, $log) {
    $usage = explode(" ", exec('vmstat 1 2'));

	print_r($usage);

    if ($debug == TRUE) {
        debug("[DEBUG_COLLECT] ", $log);
    }

    $return = "";

    return $return;

}
?>

<?php

function collect_cpuUsage($debug, $log) {
    $usage = explode(" ", exec('vmstat 1 2'));

	print_r($usage);

	// Get CPU usage
	$cpu = 100 - $usage[43];

	// Get WA CPU usage
	$wa = $usage[44];

    if ($debug == TRUE) {
        debug("[DEBUG_COLLECT] CPU Usage: ".$cpu." WA CPU Usage: ".$wa."\n", $log);
    }

    $return = $cpu.",".$wa;

    return $return;

}
?>

Add correct debugging text. Fetch and reeturn CPU and WA CPU


<?php
// src/JoBeetBundle/Tests/Utils/JoBeetTest.php

namespace JoBeetBundle\Tests\Utils;
use JoBeetBundle\Utils\JoBeet;

class JoBeetTest extends \PHPUnit_Framework_TestCase
{
  public function testSlugify()
  {
    $this->assertEquals('sensio', Jobeet::slugify('Sensio'));
    $this->assertEquals('sensio-labs', Jobeet::slugify('sensio labs'));
    $this->assertEquals('sensio-labs', Jobeet::slugify('sensio   labs'));
    $this->assertEquals('paris-france', Jobeet::slugify('paris,france'));
    $this->assertEquals('sensio', Jobeet::slugify('  sensio'));
    $this->assertEquals('sensio', Jobeet::slugify('sensio  '));
    $this->assertEquals('n-a', Jobeet::slugify(''));
  }
}

<?php
// src/JoBeetBundle/Tests/Utils/JoBeetTest.php

namespace JoBeetBundle\Tests\Utils;
use JoBeetBundle\Utils\JoBeet;

class JoBeetTest extends \PHPUnit_Framework_TestCase
{
  public function testSlugify()
  {
    $this->assertEquals('sensio', Jobeet::slugify('Sensio'));
    $this->assertEquals('sensio-labs', Jobeet::slugify('sensio labs'));
    $this->assertEquals('sensio-labs', Jobeet::slugify('sensio   labs'));
    $this->assertEquals('paris-france', Jobeet::slugify('paris,france'));
    $this->assertEquals('sensio', Jobeet::slugify('  sensio'));
    $this->assertEquals('sensio', Jobeet::slugify('sensio  '));
    $this->assertEquals('n-a', Jobeet::slugify(''));
    $this->assertEquals('developpeur-web', Jobeet::slugify('Dveloppeur Web'));
  }
}

Add assert for uni code charactor of JoBeet