<?php

namespace Bernard;

use Bernard\Event\EnvelopeEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class Producer
{
    protected $queues;
    protected $dispatcher;

    /**
     * @param QueueFactory             $queues
     * @param EventDispatcherInterface $dispatcher
     */
    public function __construct(QueueFactory $queues, EventDispatcherInterface $dispatcher)
    {
        $this->queues = $queues;
        $this->dispatcher = $dispatcher;
    }

    /**
     * @param Message     $message
     * @param string|null $queueName
     */
    public function produce(Message $message, $queueName = null)
    {
        $queueName = $queueName ?: Util::guessQueue($message);

        $queue = $this->queues->create($queueName);
        $queue->enqueue($envelope = new Envelope($message));

        $this->dispatcher->dispatch(BernardEvents::PRODUCE, new EnvelopeEvent($envelope, $queue));
    }
}

<?php

namespace Bernard;

use Bernard\Event\EnvelopeEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class Producer
{
    protected $queues;
    protected $dispatcher;

    /**
     * @param QueueFactory             $queues
     * @param EventDispatcherInterface $dispatcher
     */
    public function __construct(QueueFactory $queues, EventDispatcherInterface $dispatcher)
    {
        $this->queues = $queues;
        $this->dispatcher = $dispatcher;
    }

    /**
     * @param Message     $message
     * @param string|null $queueName
     */
    public function produce(Message $message, $queueName = null)
    {
        $queueName = $queueName ?: Util::guessQueue($message);

        $queue = $this->queues->create($queueName);
        $queue->enqueue($envelope = new Envelope($message));

        $this->dispatch(BernardEvents::PRODUCE, new EnvelopeEvent($envelope, $queue));
    }

    private function dispatch($eventName, EnvelopeEvent $event)
    {
        $this->dispatcher instanceof \Symfony\Contracts\EventDispatcher\EventDispatcherInterface
           ? $this->dispatcher->dispatch($event, $eventName)
           : $this->dispatcher->dispatch($eventName, $event);
    }
}

Increase compatibility with Symfony 4.3 by using proper order of parameters


<?php namespace Devfactory\Media\Models;

use Illuminate\Support\Facades\URL;

class Media extends \Eloquent {

  protected $table = 'media';

  protected $fillable = [
    'filename',
    'mime',
    'size',
    'name',
    'alt',
    'title',
    'group',
    'status',
    'weight',
  ];

  public function mediable() {
    return $this->morphTo();
  }

  public function getUrlAttribute() {
    return Url::asset(config('media.config.files_directory') . $this->filename);
  }

  public function getTitleAttribute($value) {
    if (empty($value)) {
      return basename($this->attributes['filename']);
    }

    return $value;
  }

}

<?php namespace Devfactory\Media\Models;

use Illuminate\Support\Facades\URL;
use Illuminate\Database\Eloquent\Model;

class Media extends Model {

  protected $table = 'media';

  protected $fillable = [
    'filename',
    'mime',
    'size',
    'name',
    'alt',
    'title',
    'group',
    'status',
    'weight',
  ];

  public function mediable() {
    return $this->morphTo();
  }

  public function getUrlAttribute() {
    return Url::asset(config('media.config.files_directory') . $this->filename);
  }

  public function getTitleAttribute($value) {
    if (empty($value)) {
      return basename($this->attributes['filename']);
    }

    return $value;
  }

}

Replace eloquent by the model with the good namespace


<?php

/*
 * This file is part of WordPlate.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

// Remove menu items.
add_action('admin_menu', function () {
    $items = get_theme_support('plate-menu');

    foreach (reset($items) as $item) {
        remove_menu_page($item);
    }
});

<?php

/*
 * This file is part of WordPlate.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

// Remove menu and submenu items.
add_action('admin_menu', function () {
    $items = get_theme_support('plate-menu');

    foreach (reset($items) as $item) {
        if (strpos($item, '?') !== false) {
            // edit.php?post_type=foo should be removed with remove_menu_page('edit.php?post_type=foo')
            if (strpos($item, 'edit.php?post_type=') === 0) {
                remove_menu_page($item);
            } else {

                $path = parse_url($item,  PHP_URL_PATH);
                $query = parse_url($item,  PHP_URL_QUERY);
                $query_value = explode('=', $query);
                if (isset($query_value[1])) {
                    $pageName = $query_value[1];

                    // admin.php?page=foo should be removed with remove_menu_page('foo')
                    if (strpos($item, 'admin.php') === 0) {
                        remove_menu_page($pageName);
                    } else {
                        remove_submenu_page($path, $pageName);
                    }
                }
            }
        } else {
            remove_menu_page($item);
        }
    }
}, PHP_INT_MAX);

Add support for plugin pages, increase priority

Issues:
This helper didn't work for `'tools.php?page=wp-migrate-db'` or 'admin.php?page=theseoframework-settings'.
The SEO Framework added it's menu item with a higher priority than this helper.


<?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\Formatter;

use function Symfony\Component\String\u;

final class StringInflector
{
    public static function nameToCode(string $value): string
    {
        return str_replace([' ', '-', '\''], '_', $value);
    }

    public static function nameToSlug(string $value): string
    {
        return str_replace(['_'], '-', self::nameToLowercaseCode($value));
    }

    public static function nameToLowercaseCode(string $value): string
    {
        return strtolower(self::nameToCode($value));
    }

    public static function nameToUppercaseCode(string $value): string
    {
        return strtoupper(self::nameToCode($value));
    }

    public static function nameToCamelCase(string $value): string
    {
        return (string) u($value)->camel();
    }

    private function __construct()
    {
    }
}

<?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\Formatter;

use function Symfony\Component\String\u;

final class StringInflector
{
    public static function codeToName(string $value): string
    {
        return ucfirst(str_replace('_', ' ', $value));
    }

    public static function nameToCode(string $value): string
    {
        return str_replace([' ', '-', '\''], '_', $value);
    }

    public static function nameToSlug(string $value): string
    {
        return str_replace(['_'], '-', self::nameToLowercaseCode($value));
    }

    public static function nameToLowercaseCode(string $value): string
    {
        return strtolower(self::nameToCode($value));
    }

    public static function nameToUppercaseCode(string $value): string
    {
        return strtoupper(self::nameToCode($value));
    }

    public static function nameToCamelCase(string $value): string
    {
        return (string) u($value)->camel();
    }

    private function __construct()
    {
    }
}

Add resouces and serialization groups for Order and OrderItem


<?php

namespace Kanboard\Model;

use Kanboard\Core\Base;

/**
 * Class SubtaskTaskConversionModel
 *
 * @package Kanboard\Model
 * @author  Frederic Guillot
 */
class SubtaskTaskConversionModel extends Base
{
    /**
     * Convert a subtask to a task
     *
     * @access public
     * @param  integer $project_id
     * @param  integer $subtask_id
     * @return integer
     */
    public function convertToTask($project_id, $subtask_id)
    {
        $subtask = $this->subtaskModel->getById($subtask_id);

        $task_id = $this->taskCreationModel->create(array(
            'project_id' => $project_id,
            'title' => $subtask['title'],
            'time_estimated' => $subtask['time_estimated'],
            'time_spent' => $subtask['time_spent'],
            'owner_id' => $subtask['user_id'],
        ));

        if ($task_id !== false) {
            $this->subtaskModel->remove($subtask_id);
        }

        return $task_id;
    }
}

<?php

namespace Kanboard\Model;

use Kanboard\Core\Base;

/**
 * Class SubtaskTaskConversionModel
 *
 * @package Kanboard\Model
 * @author  Frederic Guillot
 */
class SubtaskTaskConversionModel extends Base
{
    /**
     * Convert a subtask to a task
     *
     * @access public
     * @param  integer $project_id
     * @param  integer $subtask_id
     * @return integer
     */
    public function convertToTask($project_id, $subtask_id)
    {
        $subtask = $this->subtaskModel->getById($subtask_id);
        $parent_task = $this->taskFinderModel->getById($subtask['task_id']);

        $task_id = $this->taskCreationModel->create(array(
            'project_id' => $project_id,
            'title' => $subtask['title'],
            'time_estimated' => $subtask['time_estimated'],
            'time_spent' => $subtask['time_spent'],
            'owner_id' => $subtask['user_id'],
            'category_id' => $parent_task['category_id']
        ));

        if ($task_id !== false) {
            $this->subtaskModel->remove($subtask_id);
        }

        return $task_id;
    }
}

Copy category on new task when create a task from sub-task


<?php

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

class CreateProjectIndividualTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('project_individual', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('project_id');
            $table->string('reminders');
            $table->softDeletes();
            $table->timestamps();
        });
    }

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

<?php

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

class CreateIndividualProjectTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('individual_project', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('project_id');
            $table->string('reminders');
            $table->softDeletes();
            $table->timestamps();
        });
    }

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

Change project migration table name

Change project migration table name


<?php

namespace ContentTranslator;

class WpApi
{
    public function __construct()
    {
        add_action('rest_api_init', array($this, 'endpoints'));
    }

    public function endpoints()
    {
        register_rest_route('content-translator/v1', 'active', array(
            'methods' => 'GET',
            'callback' => '\ContentTranslator\Language::active',
        ));

        register_rest_route('content-translator/v1', 'default', array(
            'methods' => 'GET',
            'callback' => '\ContentTranslator\Language::default',
        ));
    }
}

<?php

namespace ContentTranslator;

class WpApi
{
    public function __construct()
    {
        add_action('rest_api_init', array($this, 'endpoints'));
    }

    public function endpoints()
    {
        register_rest_route('content-translator/v1', 'available', array(
            'methods' => 'GET',
            'callback' => '\ContentTranslator\Language::active',
        ));

        register_rest_route('content-translator/v1', 'default', array(
            'methods' => 'GET',
            'callback' => '\ContentTranslator\Language::default',
        ));
    }
}

Rename endpoint from active to available


<?php
namespace Pragma\Router;

class RouterException extends \Exception{

	const GET_CONFIG_ERROR = 1;
	const POST_CONFIG_ERROR = 2;
	const DELETE_CONFIG_ERROR = 3;
	const PATCH_CONFIG_ERROR = 4;
	const PUT_CONFIG_ERROR = 5;
	const NO_ROUTE_CODE = 6;
	const NO_ROUTE_FOR_CODE = 7;
	const WRONG_NUMBER_PARAMS_CODE = 8;
	const ALREADY_USED_ALIAS_CODE = 9;
	const CLI_CONFIG_ERROR = 10;

	const WRONG_MAPPING = 'Wrong number of args for route mapping';
	const NO_ROUTE = 'No route found';
	const NO_ROUTE_FOR = 'This alias doesn\'t seem to exists';
	const WRONG_NUMBER_PARAMS = 'Wrong number of parameters for the url_for call';
	const ALREADY_USED_ALIAS = 'Alias already used';

	public function __constructor($message, $code = 0, \Exception $previous = null){
		parent::__constructor($message, $code, $previous);
	}

	public function __toString(){
		return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
	}
}

<?php
namespace Pragma\Router;

class RouterException extends \Exception{

	const GET_CONFIG_ERROR = 1;
	const POST_CONFIG_ERROR = 2;
	const DELETE_CONFIG_ERROR = 3;
	const PATCH_CONFIG_ERROR = 4;
	const PUT_CONFIG_ERROR = 5;
	const NO_ROUTE_CODE = 6;
	const NO_ROUTE_FOR_CODE = 7;
	const WRONG_NUMBER_PARAMS_CODE = 8;
	const ALREADY_USED_ALIAS_CODE = 9;
	const CLI_CONFIG_ERROR = 10;

	const WRONG_MAPPING = 'Wrong number of args for route mapping';
	const NO_ROUTE = 'No route found';
	const NO_ROUTE_FOR = 'This alias doesn\'t seem to exists';
	const WRONG_NUMBER_PARAMS = 'Wrong number of parameters for the url_for call';
	const ALREADY_USED_ALIAS = 'Alias already used';

	public function __construct($message, $code = 0, \Exception $previous = null){
		parent::__construct($message, $code, $previous);
	}

	public function __toString(){
		return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
	}
}

Fix typo on constructor method name

Fix typo on constructor method name

refs #31


<?// Just the slug field for the display module?>

<?
$url_link = 'deep link';
if (!empty($item->slug)) {
	$prepend = '/';
	$span = isset($related) ? 'span4' : 'span7'; // If related is set, this is on a 2 columned form
	if ($url = $item->deepLink()) {
		$url_link = 'deep link';
		$prepend = preg_replace('#/[\w-]+$#', '/', parse_url($url, PHP_URL_PATH));
	}
	echo Former::text('slug')->blockHelp('Used to form the '.$url_link.' to this content')->prepend($prepend)->class($span);
}
?>

<?// Just the slug field for the display module?>

<?
$url_link = 'deep link';
if (!empty($item->slug)) {
	$prepend = '/';
	$span = isset($related) ? 'span4' : 'span7'; // If related is set, this is on a 2 columned form
	if ($url = $item->deepLink()) {
		$url_link = 'deep link';
		$prepend = preg_replace('#/[\w-]+$#', '/', parse_url(rtrim($url,'/'), PHP_URL_PATH));
	}
	echo Former::text('slug')->blockHelp('Used to form the '.$url_link.' to this content')->prepend($prepend)->class($span);
}
?>

Trim trailing slashes from the url before caclulating the prended path

Most sites don't have trailing slashes, but one did ...


<?php

namespace OpenDominion\Http\Requests\Dominion\Actions;

use OpenDominion\Http\Requests\Dominion\AbstractDominionRequest;

class CastSpellRequest extends AbstractDominionRequest
{
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            'spell' => 'required',
            'target' => 'integer|exists:dominions', // todo: not in own realm && not cross round?
        ];
    }
}

<?php

namespace OpenDominion\Http\Requests\Dominion\Actions;

use OpenDominion\Http\Requests\Dominion\AbstractDominionRequest;

class CastSpellRequest extends AbstractDominionRequest
{
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            'spell' => 'required',
            'target_dominion' => 'integer|exists:dominions,id', // todo: not in own realm && not cross round?
        ];
    }
}

Fix cast spell request rule

Fix cast spell request rule


<?php

	namespace LiftKit\Session;

	use LiftKit\Session\Exception\Session as SessionException;
	use ArrayAccess;

	class Session implements ArrayAccess
	{

		public function __construct ($name = null)
		{
			$this->start($name);
		}

		public function start ($name)
		{
			if ($name) {
				session_name($name);
			}

			if (! isset($_SESSION)) {
				if (! headers_sent($file, $line)) {
			    	if (! session_start()) {
			           throw new SessionException(__METHOD__ . ' session_start failed.');
			        }
				} else {
					throw new SessionException(__METHOD__ . ' session started after headers sent. Output began at: ' . $file . ':' . $line);
				}
			}
		}

		public function offsetExists ($variable)
		{
			return isset($_SESSION[$variable]);
		}

		public function offsetGet ($variable)
		{
			return $_SESSION[$variable];
		}

		public function offsetSet ($variable, $value)
		{
			$_SESSION[$variable] = $value;
		}

		public function offsetUnset ($variable)
		{
			unset($_SESSION[$variable]);
		}

		public function destroy ()
		{
			session_destroy();
		}
	}

<?php

	namespace LiftKit\Session;

	use LiftKit\Session\Exception\Session as SessionException;
	use ArrayAccess;

	class Session implements ArrayAccess
	{

		public function __construct ($name = null)
		{
			$this->start($name);
		}

		public function start ($name)
		{
			if ($name) {
				session_name($name);
			}

			if (! isset($_SESSION)) {
				if (! headers_sent($file, $line)) {
			    	if (! session_start()) {
			           throw new SessionException(__METHOD__ . ' session_start failed.');
			        }
				} else {
					throw new SessionException(__METHOD__ . ' session started after headers sent. Output began at: ' . $file . ':' . $line);
				}
			}
		}

		public function offsetExists ($variable)
		{
			return isset($_SESSION[$variable]);
		}

		public function & offsetGet ($variable)
		{
			return $_SESSION[$variable];
		}

		public function offsetSet ($variable, $value)
		{
			$_SESSION[$variable] = $value;
		}

		public function offsetUnset ($variable)
		{
			unset($_SESSION[$variable]);
		}

		public function destroy ()
		{
			session_destroy();
		}
	}

Return reference from offset get

Return reference from offset get


<?php

namespace SocialiteProviders\Vercel;

use SocialiteProviders\Manager\OAuth2\AbstractProvider;
use SocialiteProviders\Manager\OAuth2\User;

class Provider extends AbstractProvider
{
    /**
     * Unique Provider Identifier.
     */
    public const IDENTIFIER = 'vercel';

    /**
     * {@inheritdoc}
     */
    protected function getAuthUrl($state)
    {
        return $this->buildAuthUrlFromBase('https://vercel.com/oauth/authorize', $state);
    }

    /**
     * {@inheritdoc}
     */
    protected function getTokenUrl()
    {
        return 'https://api.vercel.com/v2/oauth/access_token';
    }

    /**
     * {@inheritdoc}
     */
    protected function getUserByToken($token)
    {
        $response = $this->getHttpClient()->get('https://api.vercel.com/www/user', [
            'headers' => [
                'Authorization' => 'Bearer '.$token,
            ],
        ]);

        return json_decode($response->getBody()->getContents(), true);
    }

    /**
     * {@inheritdoc}
     */
    protected function mapUserToObject(array $user)
    {
        return (new User())->setRaw($user['user'])->map([
            'id'       => $user['user']['uid'],
            'nickname' => $user['user']['username'],
            'name'     => $user['user']['name'],
            'email'    => $user['user']['email'],
            'avatar'   => 'https://api.vercel.com/www/avatar/'.$user['user']['uid'],
        ]);
    }
}

<?php

namespace SocialiteProviders\Vercel;

use SocialiteProviders\Manager\OAuth2\AbstractProvider;
use SocialiteProviders\Manager\OAuth2\User;

class Provider extends AbstractProvider
{
    /**
     * Unique Provider Identifier.
     */
    public const IDENTIFIER = 'vercel';

    protected static $authUrl = 'https://vercel.com/oauth/authorize';

    /**
     * {@inheritdoc}
     */
    protected function getAuthUrl($state)
    {
        return $this->buildAuthUrlFromBase(static::$authUrl, $state);
    }

    /**
     * {@inheritdoc}
     */
    protected function getTokenUrl()
    {
        return 'https://api.vercel.com/v2/oauth/access_token';
    }

    /**
     * {@inheritdoc}
     */
    protected function getUserByToken($token)
    {
        $response = $this->getHttpClient()->get('https://api.vercel.com/www/user', [
            'headers' => [
                'Authorization' => 'Bearer '.$token,
            ],
        ]);

        return json_decode($response->getBody()->getContents(), true);
    }

    /**
     * {@inheritdoc}
     */
    protected function mapUserToObject(array $user)
    {
        return (new User())->setRaw($user['user'])->map([
            'id'       => $user['user']['uid'],
            'nickname' => $user['user']['username'],
            'name'     => $user['user']['name'],
            'email'    => $user['user']['email'],
            'avatar'   => 'https://api.vercel.com/www/avatar/'.$user['user']['uid'],
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public static function setAuthUrl(string $url)
    {
        static::$authUrl = $url;
    }
}

Allow updating the default Vercel authURL


<?php

class SPM_ShopyMind_DataMapper_OrderItem
{
    public function format(Mage_Sales_Model_Order_Item $orderItem)
    {
        $product = $orderItem->getProduct();
        $combinationId = $this->getCombinationId($orderItem, $product);

        return array(
            'id_product' => $product->getId(),
            'id_combination' => $combinationId,
            'id_manufacturer' => Mage::helper('shopymind')->manufacturerIdOf($product),
            'price' => $orderItem->getPriceInclTax(),
            'qty' => $orderItem->getQtyOrdered()
        );
    }

    private function getCombinationId(Mage_Sales_Model_Order_Item $orderItem)
    {
        $Product = Mage::getModel('catalog/product');
        $combinationId = $orderItem->getHasChildren() ? $Product->getIdBySku($orderItem->getSku()) : $orderItem->getProductId();

        return $combinationId;
    }
}

<?php

class SPM_ShopyMind_DataMapper_OrderItem
{
    public function format(Mage_Sales_Model_Order_Item $orderItem)
    {
        $product = $orderItem->getProduct();
        $combinationId = $this->getCombinationId($orderItem, $product);

        return array(
            'id_product' => $orderItem->getProductId(),
            'id_combination' => $combinationId,
            'id_manufacturer' => Mage::helper('shopymind')->manufacturerIdOf($product),
            'price' => $orderItem->getPriceInclTax(),
            'qty' => $orderItem->getQtyOrdered()
        );
    }

    private function getCombinationId(Mage_Sales_Model_Order_Item $orderItem)
    {
        $Product = Mage::getModel('catalog/product');
        $combinationId = $orderItem->getHasChildren() ? $Product->getIdBySku($orderItem->getSku()) : $orderItem->getProductId();

        return $combinationId;
    }
}

Use product_id stored in order item instead of getting it from product instance.


<?php

namespace Mixdinternet\Admix\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class EditUsersRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => 'required|max:150'
            , 'email' => 'required|email|unique:users,email,' . auth()->id()
            , 'password' => 'min:8|same:password-confirmation'
        ];
    }

    public function authorize()
    {
        return true;
    }
}

<?php

namespace Mixdinternet\Admix\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class EditUsersRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => 'required|max:150'
            , 'email' => 'required|email|unique:users,email,' .  request()->route()->user->id
            , 'password' => 'min:8|same:password-confirmation'
        ];
    }

    public function authorize()
    {
        return true;
    }
}

Fix na edição do usuário

Fix na edição do usuário


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

namespace Darvin\ContentBundle\Slug;

use Darvin\Utils\Sluggable\SlugHandlerInterface;
use Doctrine\ORM\EntityManager;

/**
 * Unique slug handler
 */
class UniqueSlugHandler implements SlugHandlerInterface
{
    /**
     * {@inheritdoc}
     */
    public function handle(&$slug, &$suffix, EntityManager $em)
    {
        $similarSlugs = $this->getSlugMapItemRepository($em)->getSimilarSlugs($slug);

        if (empty($similarSlugs) || !in_array($slug, $similarSlugs)) {
            return;
        }

        $originalSlug = $slug;
        $index = 0;

        do {
            $index++;
            $slug = $originalSlug.'-'.$index;
        } while (in_array($slug, $similarSlugs));

        $suffix.='-'.$index;
    }

    /**
     * @param \Doctrine\ORM\EntityManager $em Entity manager
     *
     * @return \Darvin\ContentBundle\Repository\SlugMapItemRepository
     */
    private function getSlugMapItemRepository(EntityManager $em)
    {
        return $em->getRepository('DarvinContentBundle:SlugMapItem');
    }
}

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

namespace Darvin\ContentBundle\Slug;

use Darvin\ContentBundle\Entity\SlugMapItem;
use Darvin\Utils\Sluggable\SlugHandlerInterface;
use Doctrine\ORM\EntityManager;

/**
 * Unique slug handler
 */
class UniqueSlugHandler implements SlugHandlerInterface
{
    /**
     * {@inheritdoc}
     */
    public function handle(&$slug, &$suffix, EntityManager $em)
    {
        $similarSlugs = $this->getSlugMapItemRepository($em)->getSimilarSlugs($slug);

        if (empty($similarSlugs) || !in_array($slug, $similarSlugs)) {
            return;
        }

        $originalSlug = $slug;
        $index = 0;

        do {
            $index++;
            $slug = $originalSlug.'-'.$index;
        } while (in_array($slug, $similarSlugs));

        $suffix.='-'.$index;
    }

    /**
     * @param \Doctrine\ORM\EntityManager $em Entity manager
     *
     * @return \Darvin\ContentBundle\Repository\SlugMapItemRepository
     */
    private function getSlugMapItemRepository(EntityManager $em)
    {
        return $em->getRepository(SlugMapItem::SLUG_MAP_ITEM_CLASS);
    }
}

Use constants with "getRepository()" methods.


<?php

function convert_tasks($text) {
	$text = preg_replace('/^\s*
\s*(
)?\s*\[x\]/mi', '
$1<input type="checkbox" checked>', $text);
	$text = preg_replace('/^\s*
\s*\[ \]/mi', '
<input type="checkbox">', $text);
	return $text;

}

kirbytext::$post[] = function($kirbytext, $value) {
	return convert_tasks($value);
};

<?php

function convert_tasks($text) {
	$text = preg_replace('/^\s*
\s*(
)?\s*\[x\]/mi', '
$1<input type="checkbox" disabled checked>', $text);
	$text = preg_replace('/^\s*
\s*\[ \]/mi', '
<input type="checkbox" disabled>', $text);
	return $text;

}

kirbytext::$post[] = function($kirbytext, $value) {
	return convert_tasks($value);
};

Add disabled attribute to checkboxes

Add disabled attribute to checkboxes

because these checkboxes are not meant to be clicked


<?php

namespace Mocka;

class MethodMockCollection {

    /** @var MethodMock[] */
    private $_mockedMethods = array();

    /**
     * @param string $name
     * @return MethodMock
     */
    public function mockMethod($name) {
        $name = (string) $name;
        $this->_mockedMethods[$name] = new MethodMock();
        return $this->_mockedMethods[$name];
    }

    /**
     * @param string $name
     * @throws Exception
     */
    public function unmockMethod($name) {
        $name = (string) $name;
        if (!$this->hasMockedMethod($name)) {
            throw new Exception("Method `{$name}` has not been mocked");
        }
        unset($this->_mockedMethods[$name]);
    }

    /**
     * @param string $name
     * @return bool
     */
    public function hasMockedMethod($name) {
        return array_key_exists($name, $this->_mockedMethods);
    }

    /**
     * @param string $name
     * @param array  $arguments
     * @return mixed
     */
    public function callMockedMethod($name, $arguments) {
        $method = $this->_mockedMethods[$name];
        return $method->invoke($arguments);
    }
}

<?php

namespace Mocka;

class MethodMockCollection {

    /** @var MethodMock[] */
    private $_mockedMethods = array();

    public function __clone() {
        foreach ($this->_mockedMethods as $name => $method) {
            $this->_mockedMethods[$name] = clone $method;
        }
    }

    /**
     * @param string $name
     * @return MethodMock
     */
    public function mockMethod($name) {
        $name = (string) $name;
        if (!isset($this->_mockedMethods[$name])) {
            $this->_mockedMethods[$name] = new MethodMock();
        }
        return $this->_mockedMethods[$name];
    }

    /**
     * @param string $name
     * @throws Exception
     */
    public function unmockMethod($name) {
        $name = (string) $name;
        if (!$this->hasMockedMethod($name)) {
            throw new Exception("Method `{$name}` has not been mocked");
        }
        unset($this->_mockedMethods[$name]);
    }

    /**
     * @param string $name
     * @return bool
     */
    public function hasMockedMethod($name) {
        return array_key_exists($name, $this->_mockedMethods);
    }

    /**
     * @param string $name
     * @param array  $arguments
     * @return mixed
     */
    public function callMockedMethod($name, $arguments) {
        $method = $this->_mockedMethods[$name];
        return $method->invoke($arguments);
    }
}

Allow accesing already mocked methods

Allow accesing already mocked methods


<?php

/*
 * MovieContentFilter (https://www.moviecontentfilter.com/)
 * Copyright (c) delight.im (https://www.delight.im/)
 * Licensed under the GNU AGPL v3 (https://www.gnu.org/licenses/agpl-3.0.txt)
 */

namespace App;

use Delight\Foundation\App;

class Controller {

	protected static function ensureAuthenticated(App $app, $targetPath = null) {
		// if the user is not logged in
		if (!$app->auth()->check()) {
			// if the requested target path has not been provided
			if (empty($targetPath)) {
				// use the current route as the default
				$targetPath = $app->currentRoute();
			}

			// redirect back to the index and tell the user to sign in
			$app->flash()->warning('Please sign in to view the requested page. If you don’t have an account yet, you may sign up for free.');
			$app->redirect('/?continue=' . \urlencode($targetPath));
			exit;
		}
	}

	public static function failNotFound(App $app) {
		// return the appropriate error code
		$app->setStatus(404);
		// return the view for the error page
		echo $app->view('404.html');
	}

}

<?php

/*
 * MovieContentFilter (https://www.moviecontentfilter.com/)
 * Copyright (c) delight.im (https://www.delight.im/)
 * Licensed under the GNU AGPL v3 (https://www.gnu.org/licenses/agpl-3.0.txt)
 */

namespace App;

use Delight\Foundation\App;

class Controller {

	protected static function ensureAuthenticated(App $app, $targetPath = null) {
		// if the user is not logged in
		if (!$app->auth()->check()) {
			// fail with a proper response for non-authenticated users
			self::failNotSignedIn($app, $targetPath);
		}
	}

	public static function failNotSignedIn(App $app, $targetPath = null) {
		// if the requested target path has not been provided
		if (empty($targetPath)) {
			// use the current route as the default
			$targetPath = $app->currentRoute();
		}

		// redirect back to the index and tell the user to sign in
		$app->flash()->warning('Please sign in to view the requested page. If you don’t have an account yet, you may sign up for free.');
		$app->redirect('/?continue=' . \urlencode($targetPath));
		exit;
	}

	public static function failNotFound(App $app) {
		// return the appropriate error code
		$app->setStatus(404);
		// return the view for the error page
		echo $app->view('404.html');
	}

}

Refactor part of 'ensureAuthenticated' into separate 'failNotSignedIn'


<?php
namespace Whm\Opm\Client\Config;

use Symfony\Component\Yaml\Yaml;

class Config
{

  private $config = array();

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

  /**
   * @param string $filename the yaml file name.
   * @return \Whm\Opm\Client\Config\Config
   */
  static public function createFromFile( $filename )
  {
    $yamlString = file_get_contents($filename);
    $yaml = new Yaml();
    return new self($yaml->parse($yamlString));
  }

  public function getPhantomExecutable ()
  {
    return $this->config['phantom']['executable'];
  }

  public function getOpmServer( )
  {
    return $this->config['opm-server']['host'];
  }

  public function getClientId( )
  {
    return $this->config['opm-client']['clientid'];
  }

  public function getMaxParallelRequests()
  {
      return $this->config['opm-client']['max-parallel-requests'];
  }
}

<?php
namespace Whm\Opm\Client\Config;

use Symfony\Component\Yaml\Yaml;

class Config
{

  private $config = array();

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

  /**
   * @param string $filename the yaml file name.
   * @return \Whm\Opm\Client\Config\Config
   */
  public static function createFromFile($filename)
  {
    $yamlString = file_get_contents($filename);
    $yaml = new Yaml();

    return new self($yaml->parse($yamlString));
  }

  public function getPhantomExecutable()
  {
    return $this->config['phantom']['executable'];
  }

  public function getOpmServer()
  {
    return $this->config['opm-server']['host'];
  }

  public function getClientId()
  {
    return $this->config['opm-client']['clientid'];
  }

  public function getMaxParallelRequests()
  {
      return $this->config['opm-client']['max-parallel-requests'];
  }
}

Make config file reader more defensive

Make config file reader more defensive


Mark empty test as incomplete

Mark empty test as incomplete

To make things more explicit.


<?php
$I = new AcceptanceTester($scenario);
$I->wantTo('process tweets looking for beers');
$I->runShellCommand('php artisan nerds:cal test');
$I->seeInShellOutput('Not time to update');

<?php
//$I = new AcceptanceTester($scenario);
//$I->wantTo('process tweets looking for beers');
//$I->runShellCommand('php artisan nerds:cal test');
//$I->seeInShellOutput('Not time to update');

// Need a better way to test since this is time based

Disable calendar command test, need a better way to test time based things


<?

$steps = $_REQUEST['steps'];
$subject = $_REQUEST['subject'];
$error_msg = $_REQUEST['error_msg'];
$description = $_REQUEST['description'];
$new_sub = '[Bug] '.$subject;

$message = 'Login: '.$account->login.EOL.EOL.'-----------'.EOL.EOL.
	 'Account ID: '.$account->account_id.EOL.EOL.'-----------'.EOL.EOL.
	 'Description: '.$description.EOL.EOL.'-----------'.EOL.EOL.
	 'Steps to repeat: '.$steps.EOL.EOL.'-----------'.EOL.EOL.
	 'Error Message: '.$error_msg;

//mail('bugs@smrealms.de',
//	 $new_sub,
//	 $message,
//	 'From: '.$account->email);

$player->sendMessageToBox(BOX_BUGS_REPORTED, nl2br($message));

$container = array();
$container['url'] = 'skeleton.php';
if (SmrSession::$game_id > 0) {

	if ($player->isLandedOnPlanet())
		$container['body'] = 'planet_main.php';
	else
		$container['body'] = 'current_sector.php';

} else
	$container['body'] = 'game_play.php';

forward($container);

?>

<?

$steps = $_REQUEST['steps'];
$subject = $_REQUEST['subject'];
$error_msg = $_REQUEST['error_msg'];
$description = $_REQUEST['description'];
$new_sub = '[Bug] '.$subject;

$message = 'Login: '.$account->login.EOL.EOL.'-----------'.EOL.EOL.
	 'Account ID: '.$account->account_id.EOL.EOL.'-----------'.EOL.EOL.
	 'Description: '.$description.EOL.EOL.'-----------'.EOL.EOL.
	 'Steps to repeat: '.$steps.EOL.EOL.'-----------'.EOL.EOL.
	 'Error Message: '.$error_msg;

//mail('bugs@smrealms.de',
//	 $new_sub,
//	 $message,
//	 'From: '.$account->email);

if(is_object($player))
	$player->sendMessageToBox(BOX_BUGS_REPORTED, nl2br($message));
else
	$account->sendMessageToBox(BOX_BUGS_REPORTED, nl2br($message));

$container = array();
$container['url'] = 'skeleton.php';
if (SmrSession::$game_id > 0) {

	if ($player->isLandedOnPlanet())
		$container['body'] = 'planet_main.php';
	else
		$container['body'] = 'current_sector.php';

} else
	$container['body'] = 'game_play.php';

forward($container);

?>

Fix a bug in bug reporting when not joined to a game.


<?php

namespace Heystack\Ecommerce\Zone\Traits;

use Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface;

/**
 * Class HasZoneServiceTrait
 * @package Heystack\Ecommerce\Zone\Traits
 */
trait HasZoneServiceTrait
{
    /**
     * @var \Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface
     */
    protected $zoneService;

    /**
     * @param \Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface $localService
     */
    public function setZoneService(ZoneServiceInterface $localService)
    {
        $this->zoneService = $localService;
    }

    /**
     * @return \Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface
     */
    public function getZoneService()
    {
        return $this->zoneService;
    }
}

<?php

namespace Heystack\Ecommerce\Locale\Traits;

use Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface;

/**
 * Class HasZoneServiceTrait
 * @package Heystack\Ecommerce\Locale\Traits
 */
trait HasZoneServiceTrait
{
    /**
     * @var \Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface
     */
    protected $zoneService;

    /**
     * @param \Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface $localService
     */
    public function setZoneService(ZoneServiceInterface $localService)
    {
        $this->zoneService = $localService;
    }

    /**
     * @return \Heystack\Ecommerce\Locale\Interfaces\ZoneServiceInterface
     */
    public function getZoneService()
    {
        return $this->zoneService;
    }
}

Correct namespace zone service trait

Correct namespace zone service trait


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

namespace Darvin\AdminBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Tri-state checkbox form type
 */
class TriStateCheckboxType extends AbstractType
{
    const TRI_STATE_CHECKBOX_TYPE_CLASS = __CLASS__;

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'choices' => [
                'boolean.1' => 1,
                'boolean.0' => 0,
            ],
            'choices_as_values' => true,
            'expanded'          => true,
            'empty_value'       => 'boolean.indeterminate',
            'attr'              => [
                'class' => 'tri_state_checkbox',
            ],
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'Symfony\Component\Form\Extension\Core\Type\ChoiceType';
    }
}

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

namespace Darvin\AdminBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Tri-state checkbox form type
 */
class TriStateCheckboxType extends AbstractType
{
    const TRI_STATE_CHECKBOX_TYPE_CLASS = __CLASS__;

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'choices' => [
                'boolean.1' => 1,
                'boolean.0' => 0,
            ],
            'choices_as_values' => true,
            'expanded'          => true,
            'placeholder'       => 'boolean.indeterminate',
            'attr'              => [
                'class' => 'tri_state_checkbox',
            ],
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'Symfony\Component\Form\Extension\Core\Type\ChoiceType';
    }
}

Replace deprecated "empty_value" form option with "placeholder".


<?php namespace Illuminate\Validation;

use Illuminate\Support\ServiceProvider;

class ValidationServiceProvider extends ServiceProvider {

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

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

		$this->app['validator'] = $this->app->share(function($app)
		{
			$validator = new Factory($app['translator'], $app);

			// The validation presence verifier is responsible for determining the existence
			// of values in a given data collection, typically a relational database or
			// other persistent data stores. And it is used to check for uniqueness.
			if (isset($app['validation.presence']))
			{
				$validator->setPresenceVerifier($app['validation.presence']);
			}

			return $validator;
		});
	}

	/**
	 * Register the database presence verifier.
	 *
	 * @return void
	 */
	protected function registerPresenceVerifier()
	{
		$this->app['validation.presence'] = $this->app->share(function($app)
		{
			return new DatabasePresenceVerifier($app['db']);
		});
	}

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

}

<?php namespace Illuminate\Validation;

use Illuminate\Support\ServiceProvider;

class ValidationServiceProvider extends ServiceProvider {

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

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

		$this->app->bindShared('validator', function($app)
		{
			$validator = new Factory($app['translator'], $app);

			// The validation presence verifier is responsible for determining the existence
			// of values in a given data collection, typically a relational database or
			// other persistent data stores. And it is used to check for uniqueness.
			if (isset($app['validation.presence']))
			{
				$validator->setPresenceVerifier($app['validation.presence']);
			}

			return $validator;
		});
	}

	/**
	 * Register the database presence verifier.
	 *
	 * @return void
	 */
	protected function registerPresenceVerifier()
	{
		$this->app->bindShared('validation.presence', function($app)
		{
			return new DatabasePresenceVerifier($app['db']);
		});
	}

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

}

Convert to new bindShared method on container.


Add new string & array methods.

Add new string & array methods.


<?php

global $WEB_UI_ROOT;
require_once($WEB_UI_ROOT . '/app/vendor/Smarty-3.1.18/Smarty.class.php');

/**
 * SmartyEx subclasses Smarty, and does CIRCUS-specific initialization.
 * Requires Smarty 3.1.x
 */
class SmartyEx extends Smarty
{
	/**
	 * Constructor.
	 * Initializes directories.
	 */
	public function __construct()
	{
		global $BASE_DIR, $DIR_SEPARATOR, $WEB_UI_ROOT;
		parent::__construct();
		$rootPath = $WEB_UI_ROOT . $DIR_SEPARATOR . 'app' . $DIR_SEPARATOR . 'smarty' . $DIR_SEPARATOR;
		$this->template_dir  = $rootPath . 'templates';
		$this->compile_dir   = $rootPath . 'templates_c';
		$this->config_dir    = $rootPath . 'configs';
		$this->cache_dir     = $rootPath . 'cache';
		$this->addPluginsDir($rootPath . 'plugins');

		$this->registerPlugin('modifier', 'status_str', array('Job', 'codeToStatusName'));

		$this->assign('currentUser', Auth::currentUser());

		$this->assign('totop', relativeTopDir());
	}
}

<?php

global $WEB_UI_ROOT;
require_once($WEB_UI_ROOT . '/app/vendor/Smarty-3.1.18/Smarty.class.php');

/**
 * SmartyEx subclasses Smarty, and does CIRCUS-specific initialization.
 * Requires Smarty 3.1.x
 */
class SmartyEx extends Smarty
{
	/**
	 * Constructor.
	 * Initializes directories.
	 */
	public function __construct()
	{
		global $BASE_DIR, $DIR_SEPARATOR, $WEB_UI_ROOT;
		parent::__construct();
		$rootPath  = $WEB_UI_ROOT . $DIR_SEPARATOR . 'app' . $DIR_SEPARATOR . 'smarty' . $DIR_SEPARATOR;
		$cachePath = $WEB_UI_ROOT . $DIR_SEPARATOR . 'cache';

		$this->setTemplateDir($rootPath . 'templates')
			->setCompileDir($cachePath)
			->setCacheDir($cachePath)
			->setConfigDir($rootPath . 'configs')
			->addPluginsDir($rootPath . 'plugins');

		$this->registerPlugin('modifier', 'status_str', array('Job', 'codeToStatusName'));

		$this->assign('currentUser', Auth::currentUser());

		$this->assign('totop', relativeTopDir());
	}
}

Change Path of Smarty cache (-> ($WEB_UI_ROOT)/cache)


<?php
namespace Entity;

use \Doctrine\Common\Collections\ArrayCollection;

/**
 * @Table(name="sessions", indexes={
 *   @index(name="cleanup_idx", columns={"expires"})
 * })
 * @Entity
 */
class Session extends \DF\Doctrine\Entity
{
    public function __construct()
    {
        $this->last_modified = time();
        $this->user_agent = $_SERVER['HTTP_USER_AGENT'];
    }

    /**
     * @Column(name="id", type="string", length=128)
     * @Id
     */
    protected $id;

    /** @Column(name="user_agent", type="string", length=255) */
    protected $user_agent;

    /** @Column(name="expires", type="integer") */
    protected $expires;

    public function setLifetime($lifetime)
    {
        $this->expires = time()+$lifetime;
    }

    /** @Column(name="last_modified", type="integer") */
    protected $last_modified;

    /** @Column(name="data", type="text", nullable=true) */
    protected $data;

    /*
     * Validate session.
     * @return boolean
     */
    public function isValid()
    {
        if ($this->expires < time())
            return false;

        $current_ua = $_SERVER['HTTP_USER_AGENT'];
        if (strcmp($this->user_agent, $current_ua) !== 0)
            return false;

        return true;
    }
}

<?php
namespace Entity;

use \Doctrine\Common\Collections\ArrayCollection;

/**
 * @Table(name="sessions", indexes={
 *   @index(name="cleanup_idx", columns={"expires"})
 * })
 * @Entity
 */
class Session extends \DF\Doctrine\Entity
{
    public function __construct()
    {
        $this->last_modified = time();
        $this->user_agent = $_SERVER['HTTP_USER_AGENT'];

        if (empty($this->user_agent))
            $this->user_agent = 'none';
    }

    /**
     * @Column(name="id", type="string", length=128)
     * @Id
     */
    protected $id;

    /** @Column(name="user_agent", type="string", length=255, nullable=true) */
    protected $user_agent;

    /** @Column(name="expires", type="integer") */
    protected $expires;

    public function setLifetime($lifetime)
    {
        $this->expires = time()+$lifetime;
    }

    /** @Column(name="last_modified", type="integer") */
    protected $last_modified;

    /** @Column(name="data", type="text", nullable=true) */
    protected $data;

    /*
     * Validate session.
     * @return boolean
     */
    public function isValid()
    {
        if ($this->expires < time())
            return false;

        $current_ua = $_SERVER['HTTP_USER_AGENT'];
        if (empty($current_ua))
            $current_ua = 'none';

        if (strcmp($this->user_agent, $current_ua) !== 0)
            return false;

        return true;
    }
}

Allow for null user agents in sessions.

Allow for null user agents in sessions.


<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$app = require_once('bootstrap.php');

$app->mount('/', new \DrupalReleaseDate\Controllers\PagesControllerProvider());
$app->mount('/chart', new \DrupalReleaseDate\Controllers\ChartsControllerProvider());
$app->mount('/data', new \DrupalReleaseDate\Controllers\DataControllerProvider());
$app->mount('/cron', new \DrupalReleaseDate\Controllers\CronControllerProvider());

$app->after(function (Request $request, Response $response) {
    $response->headers->set('X-Frame-Options', 'SAMEORIGIN');
    $response->headers->set('X-Xss-Protection', '1; mode=block');
});

// If the Symfony2 Reverse Proxy service was enabled and loaded, use it instead.
if (isset($config['http_cache']) && $config['http_cache'] !== false && !empty($app['http_cache'])) {
    return $app['http_cache'];
} else {
    return $app;
}

<?php

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$app = require_once('bootstrap.php');

$app->mount('/', new \DrupalReleaseDate\Controllers\PagesControllerProvider());
$app->mount('/chart', new \DrupalReleaseDate\Controllers\ChartsControllerProvider());
$app->mount('/data', new \DrupalReleaseDate\Controllers\DataControllerProvider());
$app->mount('/cron', new \DrupalReleaseDate\Controllers\CronControllerProvider());

$app->after(function (Request $request, Response $response) {
    $response->headers->set('X-Frame-Options', 'SAMEORIGIN');
    $response->headers->set('X-Xss-Protection', '1; mode=block');

    if (stripos($response->headers->get('Content-Type'), 'text/html') !== false) {
        $response->headers->set(
            'Content-Security-Policy-Report-Only',
            "default-src 'self'; " .
                "script-src 'self' 'unsafe-inline' code.jquery.com www.google.com www.google-analytics.com; " .
                "style-src 'self' 'unsafe-inline' netdna.bootstrapcdn.com www.google.com ajax.googleapis.com; " .
                "img-src 'self' s3.amazonaws.com www.google-analytics.com stats.g.doubleclick.net; " .
                "connect-src 'self' www.drupal.org www.google-analytics.com;" .
                "report-uri https://gapple.report-uri.io/r/default/csp/reportOnly;"
        );
    }
});

// If the Symfony2 Reverse Proxy service was enabled and loaded, use it instead.
if (isset($config['http_cache']) && $config['http_cache'] !== false && !empty($app['http_cache'])) {
    return $app['http_cache'];
} else {
    return $app;
}

Add Content-Security-Policy-Report-Only header to HTML responses


<?php

namespace AbleCore;

class TaxonomyTerm extends EntityExtension {

	/**
	 * Gets the entity type of the current class.
	 *
	 * @return string The entity type.
	 */
	static function getEntityType()
	{
		return 'taxonomy_term';
	}

	/**
	 * By Vocabulary
	 *
	 * Gets all taxonomy terms by the specified vocabulary.
	 *
	 * @param string $vocabulary_machine_name The machine name of the vocabulary.
	 *
	 * @return array An array of TaxonomyTerm items.
	 */
	public static function byVocabulary($vocabulary_machine_name)
	{
		$query = db_select('taxonomy_term_data', 'td');
		$query->addJoin('inner', 'taxonomy_vocabulary', 'tv', 'tv.vid = td.vid');
		$query->condition('tv.machine_name', $vocabulary_machine_name);
		$query->addField('td', 'tid');
		$query->orderBy('weight');
		return static::mapQuery($query);
	}

}

<?php

namespace AbleCore;

class TaxonomyTerm extends EntityExtension {

	/**
	 * Gets the entity type of the current class.
	 *
	 * @return string The entity type.
	 */
	static function getEntityType()
	{
		return 'taxonomy_term';
	}

	/**
	 * By Vocabulary
	 *
	 * Gets all taxonomy terms by the specified vocabulary.
	 *
	 * @param string $vocabulary_machine_name The machine name of the vocabulary.
	 *
	 * @return array An array of TaxonomyTerm items.
	 */
	public static function byVocabulary($vocabulary_machine_name)
	{
		$query = db_select('taxonomy_term_data', 'td');
		$query->addJoin('inner', 'taxonomy_vocabulary', 'tv', 'tv.vid = td.vid');
		$query->condition('tv.machine_name', $vocabulary_machine_name);
		$query->addField('td', 'tid');
		$query->orderBy('td.weight');
		return static::mapQuery($query);
	}

}

Make sure the weight column is specific.


<?php

/*
 * 이 컨트롤러를 상속받아 구현하는 컨트롤러는 Twig 템플릿 엔진을 기본으로 로드함
 */

class MY_Controller extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('twig');
        $this->load->helper('url');
        // Twig 관련 글로벌 설정은 이곳 또는 application/libraries/Twig.php 에 작성
        $this->twig->addGlobal('session', $_SESSION);

        // 아래 상수들은 constants.php와 동기화 필요
        $this->twig->addGlobal('USER_TYPE_ARTIST', USER_TYPE_ARTIST);
        $this->twig->addGlobal('USER_TYPE_PLACE_OWNER', USER_TYPE_PLACE_OWNER);
        $this->twig->addGlobal('TYPE_ARTWORKS', TYPE_ARTWORKS);
        $this->twig->addGlobal('TYPE_PLACES', TYPE_PLACES);

        if ($this->accountlib->is_login() === false) {
            redirect('/account/login');
        } elseif ($this->accountlib->is_auth() === false) {
            redirect('/account/not_authenticated');
        }
    }
}

if (!class_exists('API_Controller')) {
    require_once APPPATH . 'core/API_Controller.php';
}

<?php

/*
 * 이 컨트롤러를 상속받아 구현하는 컨트롤러는 Twig 템플릿 엔진을 기본으로 로드함
 */

class MY_Controller extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('twig');
        $this->load->helper('url');
        // Twig 관련 글로벌 설정은 이곳 또는 application/libraries/Twig.php 에 작성
        $this->twig->addGlobal('session', $_SESSION);

        // 사용자 정의 상수를 Twig global로 등록
        $defined_constants = get_defined_constants(true)['user'];
        foreach ($defined_constants as $constant => $value) {
            $this->twig->addGlobal($constant, $value);
        }

        if ($this->accountlib->is_login() === false) {
            redirect('/account/login');
        } elseif ($this->accountlib->is_auth() === false) {
            redirect('/account/not_authenticated');
        }
    }
}

if (!class_exists('API_Controller')) {
    require_once APPPATH . 'core/API_Controller.php';
}

Change a way to add constants into twig globals


<?php
  setlocale(LC_ALL, 'it_IT.UTF-8');

  $fname = 'config/config.json';

  $data = @file_get_contents($fname);
  $config = (array)json_decode($data);

  $start_date = strtotime($config['firstDate']);
  $now = strtotime("now");
  $days = 1 + floor(($start_date - $now)/(60*60*24));

  if ($days <= 0) {
    return;
  }

  $header = $config['firstDateFormatted'];
  if ($days == 1) {
    $manca = "E' già domani!";
  } else {
    $manca = "Mancano solo ".$days." giorni!";
  }
?>

<?php echo $header; ?>

La prima lezione del nuovo corso per principianti, intermedi e avanzati.
<?php echo $manca; ?> Ti aspettiamo, contataci!

<?php
  setlocale(LC_ALL, 'it_IT.UTF-8');

  $fname = $_SERVER['DOCUMENT_ROOT'].'/config/config.json';

  $data = @file_get_contents($fname);
  $config = (array)json_decode($data);

  $start_date = strtotime($config['firstDate']);
  $now = strtotime("now");
  $days = 1 + floor(($start_date - $now)/(60*60*24));

  if ($days <= 0) {
    return;
  }

  $header = $config['firstDateFormatted'];
  if ($days == 1) {
    $manca = "E' già domani!";
  } else {
    $manca = "Mancano solo ".$days." giorni!";
  }
?>

<?php echo $header; ?>

La prima lezione del nuovo corso per principianti, intermedi e avanzati.
<?php echo $manca; ?> Ti aspettiamo, contataci!

Fix path to the config file

Fix path to the config file


<?php

class Vocabulary extends Model {
    public function get_set() {
        return $this->belongs_to('Set');
    }

    /**
     * Filters
     */

    public static function active($orm) {
        return $orm->where_gte('category', 1)->order_by_asc('id');
    }

    public static function inactive($orm) {
        return $orm->where_lte('category', 0)->order_by_asc('id');
    }

    public static function due($orm) {
        return $orm->where_lte('due', date('Y-m-d H:i:s'))->order_by_asc('id');
    }

    public static function learned_today($orm) {
        return $orm->where('init_date', date('Y-m-d'));
    }
}

<?php

class Vocabulary extends Model {
    public function get_set() {
        return $this->belongs_to('Set');
    }

    /**
     * Filters
     */

    public static function active($orm) {
        return $orm->where_gte('level', 0)->order_by_asc('id');
    }

    public static function inactive($orm) {
        return $orm->where_lt('level', 0)->order_by_asc('id');
    }

    public static function due($orm) {
        return $orm->where_lte('due', date('Y-m-d H:i:s'))->order_by_asc('id');
    }

    public static function learned_today($orm) {
        return $orm->where('init_date', date('Y-m-d'));
    }
}

Rename 'category' to 'level' and update filters


<?php

declare(strict_types=1);

namespace Doctrine\Tests;

use PHPUnit\Framework\TestCase;

/**
 * Base testcase class for all Doctrine testcases.
 */
abstract class DoctrineTestCase extends TestCase
{
}

<?php

declare(strict_types=1);

namespace Doctrine\Tests;

use PHPUnit\Framework\TestCase;
use PHPUnit\Runner\Version;

/**
 * Base testcase class for all Doctrine testcases.
 */
abstract class DoctrineTestCase extends TestCase
{
    public static function assertDoesNotMatchRegularExpression(
        string $pattern,
        string $string,
        string $message = ''
    ): void {
        // Forward-compatibility wrapper for phpunit 9 : can be removed once phpunit 8 / php 7.2 support is dropped.
        if (self::isPhpunit9()) {
            parent::assertDoesNotMatchRegularExpression($pattern, $string, $message);
        } else {
            self::assertNotRegExp($pattern, $string, $message);
        }
    }

    public static function assertMatchesRegularExpression(string $pattern, string $string, string $message = ''): void
    {
        // Forward-compatibility wrapper for phpunit 9 : can be removed once phpunit 8 / php 7.2 support is dropped.
        if (self::isPhpunit9()) {
            parent::assertMatchesRegularExpression($pattern, $string, $message);
        } else {
            self::assertRegExp($pattern, $string, $message);
        }
    }

    public static function assertFileDoesNotExist(string $filename, string $message = ''): void
    {
        // Forward-compatibility wrapper for phpunit 9 : can be removed once phpunit 8 / php 7.2 support is dropped.
        if (self::isPhpunit9()) {
            parent::assertFileDoesNotExist($filename, $message);
        } else {
            self::assertFileNotExists($filename, $message);
        }
    }

    /**
     * Check if we're running in phpunit >= 9.0
     */
    private static function isPhpunit9(): bool
    {
        return (int) Version::series() >= 9;
    }
}

Add a forward-compatibility wrapper for phpunit8 assertions

While doctrine still supports php7.2 the test cases need to run
under phpunit8 as well. However some assertion methods produce
deprecation warnings in the test output with phpunit >= 9.

This commit adds a thin forward compatiblity wrapper for the
new assertion method names so that they can be used with both
supported phpunit versions.


<?php

declare(strict_types=1);

namespace Tests\Feature;

use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Tests\TestCase;

class PermissionsAndRolesTest extends TestCase
{
    /**
     * Ensure that the admin role has all permissions.
     */
    public function testAdminRoleHasAllPermissions(): void
    {
        $permissions = Role::where('name', 'admin')->first()->permissions;
        $allPermissions = Permission::all();
        $this->assertCount(0, $permissions->diff($allPermissions));
        $this->assertCount(0, $allPermissions->diff($permissions));
    }

    /**
     * Ensure the member and non-member roles have the same permissions.
     */
    public function testMemberAndNonMemberAreSame(): void
    {
        $nonmember = Role::where('name', 'non-member')->first()->permissions;
        $member = Role::where('name', 'member')->first()->permissions;
        $this->assertCount(0, $nonmember->diff($member));
        $this->assertCount(0, $member->diff($nonmember));
    }
}

<?php

declare(strict_types=1);

namespace Tests\Feature;

use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Tests\TestCase;

class PermissionsAndRolesTest extends TestCase
{
    public function testPermissionsLoadedInDatabase(): void
    {
        $allPermissions = Permission::all();
        $this->assertGreaterThan(0, $allPermissions->count(), "The permissions table appears to be " .
            "empty, which means the database configuration for testing is not working. Are you running `composer run " .
            "test`?");
    }

    /**
     * Ensure that the admin role has all permissions.
     */
    public function testAdminRoleHasAllPermissions(): void
    {
        $permissions = Role::where('name', 'admin')->first()->permissions;
        $allPermissions = Permission::all();
        $this->assertCount(0, $permissions->diff($allPermissions));
        $this->assertCount(0, $allPermissions->diff($permissions));
    }

    /**
     * Ensure the member and non-member roles have the same permissions.
     */
    public function testMemberAndNonMemberAreSame(): void
    {
        $nonmember = Role::where('name', 'non-member')->first()->permissions;
        $member = Role::where('name', 'member')->first()->permissions;
        $this->assertCount(0, $nonmember->diff($member));
        $this->assertCount(0, $member->diff($nonmember));
    }
}

Add test to make sure permissions table is populated

Closes #1801


<?php

namespace AdamBrett\ShellWrapper\Tests\Command;

use AdamBrett\ShellWrapper\Command\Argument;

class ArgumentTest extends \PHPUnit_Framework_TestCase
{
    public function testCanCreateInstance()
    {
        $argument = new Argument('test', 'value');
        $this->assertInstanceOf('AdamBrett\ShellWrapper\Command\Argument', $argument);
    }

    public function testToString()
    {
        $argument = new Argument('test', 'value');
        $this->assertEquals("--test 'value'", (string) $argument, 'Argument should cast to a string');
    }

    public function testEscapesArgValue()
    {
        $argument = new Argument('test', '&&');
        $this->assertEquals("--test '&&'", (string) $argument, 'Argument should be escaped');
    }

    public function testGetName()
    {
        $argument = new Argument('test', '&&');
        $this->assertEquals('test', $argument->getName(), 'Argument name should be returned');
    }

    public function testEmptyArgument()
    {
        $argument = new Argument('test');
        $this->assertEquals('--test', (string) $argument, 'Valueless arguments should be allowed');
    }

    public function testMultipleOfSameName()
    {
        $param = new Argument('test', ['value1', 'value2']);
        $this->assertEquals("--test 'value1' --test 'value2'", (string) $param, 'Mutiple params should be allowed');
    }
}

<?php

namespace AdamBrett\ShellWrapper\Tests\Command;

use AdamBrett\ShellWrapper\Command\Argument;

class ArgumentTest extends \PHPUnit_Framework_TestCase
{
    public function testCanCreateInstance()
    {
        $argument = new Argument('test', 'value');
        $this->assertInstanceOf('AdamBrett\ShellWrapper\Command\Argument', $argument);
    }

    public function testToString()
    {
        $argument = new Argument('test', 'value');
        $this->assertEquals("--test 'value'", (string) $argument, 'Argument should cast to a string');
    }

    public function testEscapesArgValue()
    {
        $argument = new Argument('test', '&&');
        $this->assertEquals("--test '&&'", (string) $argument, 'Argument should be escaped');
    }

    public function testGetName()
    {
        $argument = new Argument('test', '&&');
        $this->assertEquals('test', $argument->getName(), 'Argument name should be returned');
    }

    public function testEmptyArgument()
    {
        $argument = new Argument('test');
        $this->assertEquals('--test', (string) $argument, 'Valueless arguments should be allowed');
    }

    public function testMultipleOfSameName()
    {
        $param = new Argument('test', array('value1', 'value2'));
        $this->assertEquals("--test 'value1' --test 'value2'", (string) $param, 'Mutiple params should be allowed');
    }
}

Use 5.3 array syntax in tests

Fix: Use 5.3 array syntax in tests


<!doctype html>

<html <?php language_attributes(); ?> class="no-js" data-logo-width="<?php echo get_theme_mod('logo_width'); ?>";>

		<meta charset="<?php bloginfo('charset'); ?>">
		<title><?php wp_title(''); ?><?php if(wp_title('', false)) { echo ' :'; } ?> <?php bloginfo('name'); ?></title>

		<link href="//www.google-analytics.com" rel="dns-prefetch">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">

		<?php wp_head(); ?>

	<body <?php body_class( ! is_front_page() ? "not-home" : "" ); ?>>

			<?php get_template_part('partials/page_header'); ?>
			<?php // get_template_part('partials/customizer_page_header'); ?>

Rename wrapper to fix woocommerce conflict


<?php

/**
 * @package         Billing
 * @copyright       Copyright (C) 2012-2017 BillRun Technologies Ltd. All rights reserved.
 * @license         GNU Affero General Public License Version 3; see LICENSE.txt
 */

/**
 * EventsNotifier action controller class
 *
 * @author idan
 */
class NotifyAction extends Action_Base {

	public function execute() {
		$possibleOptions = array(
			'type' => true,
		);

		if (($options = $this->_controller->getInstanceOptions($possibleOptions)) === FALSE) {
			return;
		}
		$this->getController()->addOutput("Notify on events");
		CronController::eventsNotifierAction();
		$this->getController()->addOutput("Notifying Done");
	}

}

<?php

/**
 * @package         Billing
 * @copyright       Copyright (C) 2012-2017 BillRun Technologies Ltd. All rights reserved.
 * @license         GNU Affero General Public License Version 3; see LICENSE.txt
 */

/**
 * EventsNotifier action controller class
 *
 * @author idan
 */
class NotifyAction extends Action_Base {

	public function execute() {
		$possibleOptions = array(
			'type' => true,
		);

		if (($options = $this->_controller->getInstanceOptions($possibleOptions)) === FALSE) {
			return;
		}
		$this->getController()->addOutput("Notify on events");
		Billrun_Factory::eventsManager()->notify();
		$this->getController()->addOutput("Notifying Done");
	}

}

Fix PHP notice on notify action

Fix PHP notice on notify action


<?php

	class PostgresDbWrapper extends PostgresDb {
		/**
		 * Execute where method with the specified episode and season numbers
		 *
		 * @param string|int|\DB\Episode $s Season, or array with keys season & episode
		 * @param string|int|null        $e Episode, optional if $s is an array
		 *
		 * @return self
		 */
		public function whereEp($s, $e = null){
			if (!isset($e)){
				parent::where('season', $s->season);
				parent::where('episode', $s->episode);
			}
			else {
				parent::where('season', $s);
				parent::where('episode', $e);
			}
			return $this;
		}

		public $query_count = 0;

		private $_nonexistantClassCache = array();

		/**
		 * @param PDOStatement $stmt Statement to execute
		 *
		 * @return bool|array|object[]
		 */
		protected function _execStatement($stmt){
			$className = $this->tableNameToClassName();
			if (isset($className) && empty($this->_nonexistantClassCache[$className])){
				try {
					if (!class_exists("\\DB\\$className"))
						throw new Exception();

					$this->setClass("\\DB\\$className");
				}
				catch (Exception $e){ $this->_nonexistantClassCache[$className] = true; }
			}

			$this->query_count++;
			return parent::_execStatement($stmt);
		}
	}

<?php

	class PostgresDbWrapper extends PostgresDb {
		/**
		 * Execute where method with the specified episode and season numbers
		 *
		 * @param string|int|\DB\Episode $s Season, or array with keys season & episode
		 * @param string|int|null        $e Episode, optional if $s is an array
		 *
		 * @return self
		 */
		public function whereEp($s, $e = null){
			if (!isset($e)){
				parent::where('season', $s->season);
				parent::where('episode', $s->episode);
			}
			else {
				parent::where('season', $s);
				parent::where('episode', $e);
			}
			return $this;
		}

		public $query_count = 0;

		private $_nonexistantClassCache = array();

		/**
		 * @param PDOStatement $stmt Statement to execute
		 *
		 * @return bool|array|object[]
		 */
		protected function _execStatement($stmt){
			$className = $this->tableNameToClassName();
			if (isset($className) && empty($this->_nonexistantClassCache[$className])){
				if (!class_exists("\\DB\\$className"))
					$this->_nonexistantClassCache[$className] = true;
				else $this->setClass("\\DB\\$className");
			}

			$this->query_count++;
			return parent::_execStatement($stmt);
		}
	}

Speed up non-existent class detection by not using exceptions


<?php

namespace Shopeca\XML\Feed;

use Shopeca\XML\Generators\BaseGenerator;

class FeedGenerator extends BaseGenerator {

	/**
	 * @param $name
	 * @return string
	 */
	protected function getTemplate($name)
	{
		return __DIR__ . '/latte/' . $name . '.latte';
	}

	public function generate () {
		// Here might go some processing before the file is created
	}

}

<?php

namespace Shopeca\XML\Feed;

use Shopeca\XML\Generators\BaseGenerator;

class FeedGenerator extends BaseGenerator {

	/**
	 * @param $name
	 * @return string
	 */
	protected function getTemplate($name)
	{
		$reflectionClass = new \ReflectionClass($this);
		return dirname($reflectionClass->getFileName()) . '/latte/' . $name . '.latte';
	}

	public function generate () {
		// Here might go some processing before the file is created
	}

}

Fix of Latte directory localization

Fix of Latte directory localization


<?php

namespace Perfumer\Contracts;

class TwigExtension extends \Twig_Extension
{
    /**
     * @return array
     */
    public function getFilters()
    {
        return array(
            new \Twig_Filter('ucwords', array($this, 'ucwords')),
        );
    }

    /**
     * @param string $text
     * @return string
     */
    public function ucwords(string $text): string
    {
        return str_replace('_', '', ucwords($text, '_'));
    }
}

<?php

namespace Perfumer\Contracts;

class TwigExtension extends \Twig_Extension
{
    /**
     * @return array
     */
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('ucwords', [$this, 'ucwords']),
        );
    }

    /**
     * @param string $text
     * @return string
     */
    public function ucwords(string $text): string
    {
        return str_replace('_', '', ucwords($text, '_'));
    }
}

Make twig extension compatible with twig 1


<?php

// load Tonic
require_once '../src/Tonic/Autoloader.php';

$config = array(
    'load' => array('../*.php', '../src/Tyrell/*.php'), // load example resources
    #'mount' => array('Tyrell' => '/nexus'), // mount in example resources at URL /nexus
    #'cache' => new Tonic\MetadataCacheFile('/tmp/tonic.cache') // use the metadata cache
    #'cache' => new Tonic\MetadataCacheAPC // use the metadata cache
);

$app = new Tonic\Application($config);

#echo $app;

$request = new Tonic\Request();

#echo $request;

try {

    $resource = $app->getResource($request);

    #echo $resource;

    $response = $resource->exec();

} catch (Tonic\NotFoundException $e) {
    $response = new Tonic\Response(404);

} catch (Tonic\UnauthorizedException $e) {
    $response = new Tonic\Response(401);
    $response->wwwAuthenticate = 'Basic realm="My Realm"';

} catch (Tonic\Exception $e) {
    $response = new Tonic\Response(500);
}

#echo $response;

$response->output();

<?php

// load Tonic
require_once '../src/Tonic/Autoloader.php';

$config = array(
    'load' => array('../*.php', '../src/Tyrell/*.php'), // load example resources
    #'mount' => array('Tyrell' => '/nexus'), // mount in example resources at URL /nexus
    #'cache' => new Tonic\MetadataCacheFile('/tmp/tonic.cache') // use the metadata cache
    #'cache' => new Tonic\MetadataCacheAPC // use the metadata cache
);

$app = new Tonic\Application($config);

#echo $app;

$request = new Tonic\Request();

#echo $request;

try {

    $resource = $app->getResource($request);

    #echo $resource;

    $response = $resource->exec();

} catch (Tonic\NotFoundException $e) {
    $response = new Tonic\Response(404);

} catch (Tonic\UnauthorizedException $e) {
    $response = new Tonic\Response(401);
    $response->wwwAuthenticate = 'Basic realm="My Realm"';

} catch (Tonic\Exception $e) {
    $response = new Tonic\Response(500, $e->getMessage());
}

#echo $response;

$response->output();

Send exception message with 500 error response


<?php
/**
 * Created by mcfedr on 21/03/2014 14:19
 */

namespace mcfedr\Queue\JobManagerBundle\Manager;

use mcfedr\Queue\QueueManagerBundle\Manager\QueueManager;
use mcfedr\Queue\QueueManagerBundle\Queue\Job;

class JobManager
{
    /**
     * @var \mcfedr\Queue\QueueManagerBundle\Manager\QueueManager
     */
    protected $manager;

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

    /**
     * Put a new job on a queue
     *
     * @param string $name The name of the worker
     * @param array $options Options to pass to execute - must be json_encode-able
     * @param string $queue Optional queue name, otherwise the default queue will be used
     * @param int $priority
     * @param \DateTime $when Optionally set a time in the future when this task should happen
     * @return Job
     */
    public function put($name, array $options = null, $queue = null, $priority = null, $when = null)
    {
        return $this->manager->put(json_encode([
            'name' => $name,
            'options' => $options
        ]), $queue, $priority, $when);
    }
}

<?php
/**
 * Created by mcfedr on 21/03/2014 14:19
 */

namespace mcfedr\Queue\JobManagerBundle\Manager;

use mcfedr\Queue\QueueManagerBundle\Exception\WrongJobException;
use mcfedr\Queue\QueueManagerBundle\Manager\QueueManager;
use mcfedr\Queue\QueueManagerBundle\Queue\Job;

class JobManager
{
    /**
     * @var \mcfedr\Queue\QueueManagerBundle\Manager\QueueManager
     */
    protected $manager;

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

    /**
     * Put a new job on a queue
     *
     * @param string $name The name of the worker
     * @param array $options Options to pass to execute - must be json_encode-able
     * @param string $queue Optional queue name, otherwise the default queue will be used
     * @param int $priority
     * @param \DateTime $when Optionally set a time in the future when this task should happen
     * @return Job
     */
    public function put($name, array $options = null, $queue = null, $priority = null, $when = null)
    {
        return $this->manager->put(json_encode([
            'name' => $name,
            'options' => $options
        ]), $queue, $priority, $when);
    }

    /**
     * Remove a job
     *
     * @param $job
     * @throws WrongJobException
     */
    public function delete(Job $job)
    {
        $this->manager->delete($job);
    }
}

Add possibility to delete a job

Add possibility to delete a job


<?php

namespace Aegir\Hostmaster\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ServerType extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder->add('hostname', 'text', array(
      'description' => 'The hostname of the server. Must resolve to the IP addresses.',
    ));

    $builder->add('ip_addresses', 'textarea', array(
      'description' => 'A list of IP addresses this server is publicly available under, one per line. If none is specified, a DNS lookup will be performed based on the server hostname above.
This should point to the public network, if you have such a separation.',
    ));
  }

  public function setDefaultOptions(OptionsResolverInterface $resolver)
  {
    $resolver->setDefaults(array(
      'data_class'         => 'Aegir\Provision\Model\Server',
      'intention'          => 'server',
      'translation_domain' => 'AegirHostmaster'
    ));
  }

  public function getName()
  {
    return 'server';
  }
}

<?php

namespace Aegir\Hostmaster\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ServerType extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder->add('hostname', 'text', array(
      'description' => 'The hostname of the server. Must resolve to the IP addresses.',
    ));

    $builder->add('ip_addresses', 'textarea', array(
      'description' => 'A list of IP addresses this server is publicly available under, one per line. If none is specified, a DNS lookup will be performed based on the server hostname above.
This should point to the public network, if you have such a separation.',
      'required' => FALSE,
    ));
  }

  public function setDefaultOptions(OptionsResolverInterface $resolver)
  {
    $resolver->setDefaults(array(
      'data_class'         => 'Aegir\Provision\Model\Server',
      'intention'          => 'server',
      'translation_domain' => 'AegirHostmaster'
    ));
  }

  public function getName()
  {
    return 'server';
  }
}

Remove requirement for IP addresses

Remove requirement for IP addresses


<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Items extends Model {

    const STATUS_NEW               = 'new';
    const STATUS_BEING_FETCHED     = 'being_fetched';
    const STATUS_FETCHED           = 'fetched';
    const STATUS_BEING_CONVERTED   = 'being_converted';
    const STATUS_CONVERTED         = 'converted';
    const STATUS_CONVERSION_FAILED = 'conversion_failed';
    const STATUS_BEING_UPLOADED    = 'being_uploaded';
    const STATUS_UPLOADED          = 'uploaded';

    public $incrementing = false;
    public $timestamps = false;

    public static $validation = [
        'url' => 'required|url|unique:items|unique:user_items'
    ];
    //

}

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Items extends Model {

    const STATUS_NEW               = 'new';
    const STATUS_BEING_FETCHED     = 'being_fetched';
    const STATUS_FETCHED           = 'fetched';
    const STATUS_BEING_CONVERTED   = 'being_converted';
    const STATUS_CONVERTED         = 'converted';
    const STATUS_BEING_UPLOADED    = 'being_uploaded';
    const STATUS_UPLOADED          = 'uploaded';

    const STATUS_FETCH_FAILED      = 'fetch_failed';
    const STATUS_CONVERSION_FAILED = 'conversion_failed';

    public $incrementing = false;
    public $timestamps = false;

    public static $validation = [
        'url' => 'required|url|unique:items|unique:user_items'
    ];
    //

}

Add new failed status for items that can't be fetched.


<?
defined('C5_EXECUTE') or die("Access Denied.");
$this->inc('elements/header.php', array('enableEditing' => true));
?>

<? $this->inc('elements/header_newsflow.php'); ?>

	<? $a = new Area('Primary'); $a->display($c); ?>

	<? $a = new Area('Secondary 1'); $a->display($c); ?>

	<? $a = new Area('Secondary 2'); $a->display($c); ?>

	<? $a = new Area('Secondary 3'); $a->display($c); ?>
	<? $a = new Area('Secondary 4'); $a->display($c); ?>
	<? $a = new Area('Secondary 5'); $a->display($c); ?>

<? $this->inc('elements/footer.php'); ?>

<?
defined('C5_EXECUTE') or die("Access Denied.");
$this->inc('elements/header.php', array('enableEditing' => true));
?>

<? $this->inc('elements/header_newsflow.php'); ?>

	<? $a = new Area('Primary'); $a->display($c); ?>

	<? $a = new Area('Secondary 1'); $a->display($c); ?>

	<? $a = new Area('Secondary 2'); $a->display($c); ?>

	<? $a = new Area('Secondary 5'); $a->display($c); ?>

<? $this->inc('elements/footer.php'); ?>

Fix broken newsflow on launch

Fix broken newsflow on launch

Former-commit-id: 3edc20d576b57a0e30ed53d61c3ff960cb891853


<?php

/* @var $this yii\web\View */

use yii\helpers\Html;

$this->title = 'Trinket';
?>

<?php echo ""; ?>

Bem vindo a Trinket

Um site feito para trocas de forma rápida, segura e inteligente.

    ola l

            <?= Html::a('Cadastre-se', ['usuario/create'], ['class' => 'btn  btn-lg btn-primary']) ?>

<?php

/* @var $this yii\web\View */

use yii\helpers\Html;

$this->title = 'Trinket';
?>

<?php echo ""; ?>

Bem vindo a Trinket

Um site feito para trocas de forma rápida, segura e inteligente.

        <?php if (Yii::$app->user->isGuest) { ?>

            <?= Html::a('Cadastre-se', ['usuario/create'], ['class' => 'btn  btn-lg btn-primary']) ?>

        <?php } ?>

Update para esconder o botão de cadastrar uma vez que o usuário fizer o logon.


<?php

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

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

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

use Symfony\Component\HttpFoundation\Request;

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

<?php

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

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

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

use Symfony\Component\HttpFoundation\Request;

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

Allow DEV access in De Pinte

Allow DEV access in De Pinte


<?php

use Symfony\Component\HttpFoundation\Request;

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

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

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';

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

<?php

use Symfony\Component\HttpFoundation\Request;

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

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';

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

Remove lockout code to test IP whitelisting from remote places


<?php

$page_title = '';
$page_subtitle = '';

if (is_author()) :
    $page_title = __('Content by:', 'keitaro');

elseif (is_search()):
    global $wp_query;
    $page_title = __('Search results:', 'keitaro') . ' ' . highlight(get_search_query());
    $page_subtitle = __('Found', 'keitaro') . ' ' . highlight($wp_query->found_posts) . ' ' . __('search results', 'keitaro');

elseif (is_archive()) :
    $page_title = single_cat_title(__('Archive:', 'keitaro') . ' ', false);
endif;

if (!empty($page_title)) :

    ?>

                <?php if ($page_title): ?>

<?php echo $page_title; ?>

                <?php endif; ?>
                <?php if ($page_subtitle): ?>

<?php echo $page_subtitle; ?>

                    <?php

                endif;

                keitaro_posted_on();

                if (is_author()) :
                    keitaro_author_box(get_the_author_meta('ID'));
                endif;

                ?>

    <?php

endif;

<?php

$page_title = '';
$page_subtitle = '';

if (is_author()) :
    $page_title = __('Content by:', 'keitaro');

elseif (is_search()):
    global $wp_query;
    $page_title = __('Search results:', 'keitaro') . ' ' . highlight(get_search_query());
    $page_subtitle = __('Found', 'keitaro') . ' ' . highlight($wp_query->found_posts) . ' ' . __('search results', 'keitaro');

elseif (is_archive()) :
    $page_title = get_the_archive_title();

endif;

if (!empty($page_title)) :

    ?>

                <?php if ($page_title): ?>

<?php echo $page_title; ?>

                <?php endif; ?>
                <?php if ($page_subtitle): ?>

<?php echo $page_subtitle; ?>

                    <?php

                endif;

                keitaro_posted_on();

                if (is_author()) :
                    keitaro_author_box(get_the_author_meta('ID'));
                endif;

                ?>

    <?php
endif;

Use get_the_archive_title() for archive pages


<?php

namespace Ampersand;
use Ampersand\Config;
use Ampersand\Http\Session;
use Ampersand\Helpers\URL;

class Render {

  private static $twig;

  public static function getTwig() {
    if(!self::$twig){
      \Twig_Autoloader::register();
      $cache = Config::get('cache') ? Config::get('cache').'/' : false;
      $loader = new \Twig_Loader_Filesystem(Config::get('views').'/');
      $twig = new \Twig_Environment($loader, array(
          'cache' => $cache,
          'debug' => Config::get('debug')
      ));
      // Add globals
      $twig->addGlobal('session', Session::getInstance());
      $twig->addGlobal('url', new URL());
      self::$twig = $twig;
    }
    return self::$twig;
  }

  public static function view($template, $data = []) {
    return self::getTwig()->render(str_replace('.', '/', $template).'.html', $data);
  }

  public static function template($template, $data = []) {
    foreach($data as $key => $value) ${$key} = $value;
    ob_start();
    include(locate_template($template.'.php'));
    return ob_get_clean();
  }

}

<?php

namespace Ampersand;
use Ampersand\Config;
use Ampersand\Http\Session;
use Ampersand\Helpers\URL;
use Ampersand\Helpers\WP;

class Render {

  private static $twig;

  public static function getTwig() {
    if(!self::$twig){
      \Twig_Autoloader::register();
      $cache = Config::get('cache') ? Config::get('cache').'/' : false;
      $loader = new \Twig_Loader_Filesystem(Config::get('views').'/');
      $twig = new \Twig_Environment($loader, array(
          'cache' => $cache,
          'debug' => Config::get('debug')
      ));
      // Add globals
      $twig->addGlobal('session', Session::getInstance());
      $twig->addGlobal('url', new URL());
      $twig->addGlobal('wp', new WP());
      self::$twig = $twig;
    }
    return self::$twig;
  }

  public static function view($template, $data = []) {
    return self::getTwig()->render(str_replace('.', '/', $template).'.html', $data);
  }

  public static function template($template, $data = []) {
    foreach($data as $key => $value) ${$key} = $value;
    ob_start();
    include(locate_template($template.'.php'));
    return ob_get_clean();
  }

}

Allow to call wordpress functions using WP helper


<?php
namespace Netlogix\JsonApiOrg\Schema\Traits;

/*
 * This file is part of the Netlogix.JsonApiOrg package.
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use TYPO3\Flow\Utility\Arrays;

/**
 * Include fields means naming individual relationship paths hand
 * having even nested relationships added to the TopLevel object.
 *
 * @see http://jsonapi.org/format/#fetching-includes
 */
trait IncludeFieldsTrait
{

    /**
     * @var array
     */
    protected $includeFields = array('*');

    /**
     * @param mixed $includeFields
     */
    public function setIncludeFields($includeFields)
    {
        if (is_array($includeFields)) {
            $includeFields = join(',', $includeFields);
        }
        $this->includeFields = array();
        if (is_string($includeFields)) {
            foreach (Arrays::trimExplode(',', $includeFields) as $includeField) {
                if (!$includeField) {
                    continue;
                }
                $this->includeFields[$includeField] = $includeField;
            }
        }
    }

    /**
     * @param string $fieldName
     * @return mixed
     */
    public function isAllowedIncludeField($fieldName)
    {
        if (in_array('*', $this->includeFields)) {
            return true;
        } else {
            return in_array($fieldName, $this->includeFields);
        }
    }

}

<?php
namespace Netlogix\JsonApiOrg\Schema\Traits;

/*
 * This file is part of the Netlogix.JsonApiOrg package.
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use TYPO3\Flow\Utility\Arrays;

/**
 * Include fields means naming individual relationship paths hand
 * having even nested relationships added to the TopLevel object.
 *
 * @see http://jsonapi.org/format/#fetching-includes
 */
trait IncludeFieldsTrait
{

    /**
     * @var array
     */
    protected $includeFields = array();

    /**
     * @param mixed $includeFields
     */
    public function setIncludeFields($includeFields)
    {
        if (is_array($includeFields)) {
            $includeFields = join(',', $includeFields);
        }
        $this->includeFields = array();
        if (is_string($includeFields)) {
            foreach (Arrays::trimExplode(',', $includeFields) as $includeField) {
                if (!$includeField) {
                    continue;
                }
                $this->includeFields[$includeField] = $includeField;
            }
        }
    }

    /**
     * @param string $fieldName
     * @return mixed
     */
    public function isAllowedIncludeField($fieldName)
    {
        if (in_array('*', $this->includeFields)) {
            return true;
        } else {
            return in_array($fieldName, $this->includeFields);
        }
    }

}

[TASK] Include fields should start with no inclusion at all


<?php
class Kwf_Util_Hash
{
    public static function getPrivatePart()
    {
        $salt = Kwf_Cache_SimpleStatic::fetch('hashpp-');
        if (!$salt) {
            if ($salt = Kwf_Config::getValue('hashPrivatePart')) {
                //defined in config, required if multiple webservers should share the same salt
            } else {
                $hashFile = 'cache/hashprivatepart';
                if (!file_exists($hashFile)) {
                    file_put_contents($hashFile, time().rand(100000, 1000000));
                }
                $salt = file_get_contents($hashFile);
                Kwf_Cache_SimpleStatic::add('hashpp-', $salt);
            }
        }
        return $salt;
    }

    public static function hash($str)
    {
        return md5(self::getPrivatePart().$str);
    }
}

<?php
class Kwf_Util_Hash
{
    public static function getPrivatePart()
    {
        $salt = Kwf_Cache_SimpleStatic::fetch('hashpp-');
        if (!$salt) {
            if ($salt = Kwf_Config::getValue('hashPrivatePart')) {
                //defined in config, required if multiple webservers should share the same salt
            } else {
                $hashFile = 'cache/hashprivatepart';
                if (!file_exists($hashFile)) {
                    if (!function_exists('random_bytes')) {
                        require 'vendor/paragonie/random_compat/lib/random.php';
                    }
                    file_put_contents($hashFile, bin2hex(random_bytes(32)));
                }
                $salt = file_get_contents($hashFile);
                Kwf_Cache_SimpleStatic::add('hashpp-', $salt);
            }
        }
        return $salt;
    }

    public static function hash($str)
    {
        return md5(self::getPrivatePart().$str);
    }
}

Improve security by creating a much stronger secret by default

Webs using vkwf are not effected by this as they use hashPrivatePart config setting


<?php
/**
 * Add BBCodes
 */

// BBCode Facebook
function bbcode_facebook() {
    global $post;
	$shares = get_post_meta($post->ID, 'sharecount_facebook', true);

    return empty($shares) ? 0 : $shares;
}
add_shortcode('sharecount_facebook', 'bbcode_facebook');

// BBCode Twitter
function bbcode_twitter() {
    global $post;
	$shares = get_post_meta($post->ID, 'sharecount_twitter', true);

    return empty($shares) ? 0 : $shares;
}
add_shortcode('sharecount_twitter', 'bbcode_twitter');

// BBCode Mail
function bbcode_mail() {
    global $post;
	$shares = get_post_meta($post->ID, 'sharecount_mail', true);

    return empty($shares) ? 0 : $shares;
}
add_shortcode('sharecount_mail', 'bbcode_mail');

// BBCode display buttons
function bbcode_buttons() {
	return sharecount_display();
}
add_shortcode('sharecount_buttons', 'bbcode_buttons');

<?php
/**
 * Add BBCodes
 */

// BBCode Facebook
function sharecount_bbcode_facebook() {
    global $post;
	$shares = get_post_meta($post->ID, 'sharecount_facebook', true);

    return empty($shares) ? 0 : $shares;
}
add_shortcode('sharecount_facebook', 'sharecount_bbcode_facebook');

// BBCode Twitter
function sharecount_bbcode_twitter() {
    global $post;
	$shares = get_post_meta($post->ID, 'sharecount_twitter', true);

    return empty($shares) ? 0 : $shares;
}
add_shortcode('sharecount_twitter', 'sharecount_bbcode_twitter');

// BBCode Mail
function sharecount_bbcode_mail() {
    global $post;
	$shares = get_post_meta($post->ID, 'sharecount_mail', true);

    return empty($shares) ? 0 : $shares;
}
add_shortcode('sharecount_mail', 'sharecount_bbcode_mail');

// BBCode Mail
function sharecount_bbcode_allshares() {
    global $post;
	$shares_facebook = get_post_meta($post->ID, 'sharecount_facebook', true);
	$shares_twitter = get_post_meta($post->ID, 'sharecount_twitter', true);
	$shares_mail = get_post_meta($post->ID, 'sharecount_mail', true);

	$shares = $shares_facebook + $shares_twitter + $shares_mail;

    return empty($shares) ? 0 : $shares;
}
add_shortcode('sharecount_allshares', 'sharecount_bbcode_allshares');

// BBCode display buttons
function sharecount_bbcode_buttons() {
	return sharecount_display();
}
add_shortcode('sharecount_buttons', 'sharecount_bbcode_buttons');

Add bbcode for all shares, rename functions


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

/**
 * @var \Concrete\Core\Search\Pagination\Pagination $pagination
 */
if ($pagination->getTotalResults() > 0) { ?>

            <?=t('ID')?>
            <?=t('Name')?>

        <?php foreach ($pagination->getCurrentPageResults() as $client) { ?>
        <tr data-details-url="<?=$view->action('view_client', $client->getIdentifier())?>">
            <?=$client->getIdentifier()?>
            <?=$client->getName()?>

        <?php } ?>

    <?php if ($pagination->getTotalPages() > 1) { ?>
        <?php echo $pagination->renderView('dashboard'); ?>
    <?php } ?>

<?php } else { ?>

<?=t('No API integrations found.')?>

<?php } ?>

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

/**
 * @var \Concrete\Core\Search\Pagination\Pagination $pagination
 */
if ($pagination->getTotalResults() > 0) { ?>

            <?=t('ID')?>
            <?=t('Name')?>

        <?php foreach ($pagination->getCurrentPageResults() as $client) { ?>
        <tr data-details-url="<?=$view->action('view_client', $client->getIdentifier())?>">
            <?=$client->getIdentifier()?>
            <?=h($client->getName())?>

        <?php } ?>

    <?php if ($pagination->getTotalPages() > 1) { ?>
        <?php echo $pagination->renderView('dashboard'); ?>
    <?php } ?>

<?php } else { ?>

<?=t('No API integrations found.')?>

<?php } ?>

Fix XSS on API Integrations H1 1753684

Fix XSS on API Integrations H1 1753684