<?php namespace JwtAuth;

use Illuminate\Support\ServiceProvider;

class JwtAuthServiceProvider extends ServiceProvider
{

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        // Find path to the package
        $componenentsFileName = with(new ReflectionClass('\JwtAuth\JwtAuthServiceProvider'))->getFileName();
        $componenentsPath = dirname($componenentsFileName);

        $this->loadViewsFrom($componenentsPath . '/../views', 'jwtauth');

        // include $componenentsPath . '/../routes.php';

    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->register(\Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class);

        $loader = AliasLoader::getInstance();
        $loader->alias('JWTAuth', \Tymon\JWTAuth\Facades\JWTAuth::class);
        $loader->alias('JWTFactory', \Tymon\JWTAuth\Facades\JWTFactory::class);
    }

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

}

<?php namespace JwtAuth;

use ReflectionClass;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;

class JwtAuthServiceProvider extends ServiceProvider
{

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        // Find path to the package
        $componenentsFileName = with(new ReflectionClass('\JwtAuth\JwtAuthServiceProvider'))->getFileName();
        $componenentsPath = dirname($componenentsFileName);

        $this->loadViewsFrom($componenentsPath . '/../views', 'jwtauth');

        // include $componenentsPath . '/../routes.php';

    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->register(\Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class);

        $loader = AliasLoader::getInstance();
        $loader->alias('JWTAuth', \Tymon\JWTAuth\Facades\JWTAuth::class);
        $loader->alias('JWTFactory', \Tymon\JWTAuth\Facades\JWTFactory::class);
    }

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

}

Update jwtauth service provider @ fix namespace error.


hI<?php
  print('password hash of "hello-world": ' . password_hash('hello-world!', PASSWORD_ARGON2I));
?>

hI<?php
    $options = [
        'memory_cost' => 1024,
        'time_cost' => 2
    ];
  print('password hash of "hello-world": ' . password_hash('hello-world!', PASSWORD_ARGON2I, $options));
?>

Add input arguments to password_hash function to protect from internal changes

[#167682628]

Co-authored-by: David Freilich <0106e5ee349bb58d7c51800b6acf5b57cf80aef6@pivotal.io>


<?php
namespace Tests\Unit;

use \Dotenv;
/**
 * Dotenv Test
 *
 * @author Leonid Mamchenkov <l.mamchenkov@qobo.biz>
 */
class DotenvTest extends \PHPUnit_Framework_TestCase {

	protected $folder;
	protected $file;

	protected function setUp() {
		$this->folder = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR;
		$this->file = '.env.example';
	}

	/**
	 * Check that the file exists
	 */
	public function testDotenvExampleFileExists() {
		$this->assertTrue(file_exists($this->folder . $this->file), $this->file . " file does not exist in " . $this->folder);
	}

	/**
	* Check that we can parse the file
	*/
	public function testDotenvExampleFileIsParseable() {
		try {
			Dotenv::load($this->folder, $this->file);
		}
		catch (\Exception $e) {
			$this->fail("Failed to parse file " . $this->file . " in " . $this->folder . " : " . $e->getMessage());
		}
	}
}

<?php
namespace Tests\Unit;

use \Dotenv;
/**
 * Dotenv Test
 *
 * @author Leonid Mamchenkov <l.mamchenkov@qobo.biz>
 */
class DotenvTest extends \PHPUnit_Framework_TestCase {

	/**
	 * Provide .env file locations
	 */
	public function dotEnvFilesProvider() {
		return array(
			'.env.example' => array(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR, '.env.example'),
			'.env'         => array(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR, '.env'),
		);
	}

	/**
	 * Check that the file exists
	 *
	 * @dataProvider dotEnvFilesProvider
	 */
	public function testDotenvExampleFileExists($folder, $file) {
		$this->assertTrue(file_exists($folder . $file), $file . " file does not exist in " . $folder);
	}

	/**
	 * Check that we can parse the file
	 *
	 * @dataProvider dotEnvFilesProvider
	 */
	public function testDotenvExampleFileIsParseable($folder, $file) {
		try {
			Dotenv::load($folder, $file);
		}
		catch (\Exception $e) {
			$this->fail("Failed to parse file " . $file . " in " . $folder . " : " . $e->getMessage());
		}
	}
}

Check that .env file was generate as part of install


<?php namespace Craft;

class SmartdownService extends BaseApplicationComponent
{
    protected $parser;

    /**
     * Initialises the parser instance.
     */
    public function __construct()
    {
        $this->parser = smartdown()->parser;
    }

    /**
     * Runs the given string through all of the available parsers.
     *
     * @param $source
     *
     * @return string
     */
    public function parseAll($source)
    {
        return $this->parser->parseAll($source);
    }

    /**
     * Runs the given string through "markup" parser.
     *
     * @param $source
     *
     * @return string
     */
    public function parseMarkup($source)
    {
        return $this->parser->parseMarkup($source);
    }

    /**
     * Runs the given string through "typography" parser.
     *
     * @param string $source
     *
     * @return string
     */
    public function parseTypography($source)
    {
        return $this->parser->parseTypography($source);
    }
}

<?php namespace Craft;

class SmartdownService extends BaseApplicationComponent
{
    /**
     * @var \Experience\Smartdown\App\Utilities\Parser;
     */
    protected $parser;

    /**
     * Initialises the parser instance.
     */
    public function __construct()
    {
        $this->parser = SmartdownPlugin::$container->get('Parser');
    }

    /**
     * Runs the given string through all of the available parsers.
     *
     * @param $source
     *
     * @return string
     */
    public function parseAll($source)
    {
        return $this->parser->parseAll($source);
    }

    /**
     * Runs the given string through "markup" parser.
     *
     * @param $source
     *
     * @return string
     */
    public function parseMarkup($source)
    {
        return $this->parser->parseMarkup($source);
    }

    /**
     * Runs the given string through "typography" parser.
     *
     * @param string $source
     *
     * @return string
     */
    public function parseTypography($source)
    {
        return $this->parser->parseTypography($source);
    }
}

Update service to use new IoC container.


<?php

namespace Laravie\Authen;

use InvalidArgumentException;

class Authen
{
    /**
     * Identifier name.
     *
     * @var string
     */
    public static $identifier = 'identifier';

    /**
     * Get identifier name.
     *
     * @return string
     */
    public static function getIdentifierName(): string
    {
        return static::$identifier;
    }

    /**
     * Set identifier name.
     *
     * @param string $identifier
     *
     * @throws \InvalidArgumentException
     */
    public static function setIdentifierName(string $identifier): void
    {
        if (empty($identifier)) {
            throw new InvalidArgumentException("Identifier shouldn't be empty.");
        } elseif (in_array($identifier, ['password'])) {
            throw new InvalidArgumentException("Identifier [{$identifier}] is not allowed!");
        }

        static::$identifier = $identifier;
    }
}

<?php

namespace Laravie\Authen;

use InvalidArgumentException;

class Authen
{
    /**
     * Identifier name.
     *
     * @var string
     */
    public static $identifier = 'identifier';

    /**
     * Get identifier name.
     *
     * @return string
     */
    public static function getIdentifierName(): string
    {
        return static::$identifier;
    }

    /**
     * Set identifier name.
     *
     * @param string $identifier
     *
     * @throws \InvalidArgumentException
     */
    public static function setIdentifierName(string $identifier): void
    {
        if (empty($identifier)) {
            throw new InvalidArgumentException("Identifier shouldn't be empty.");
        } elseif (\in_array($identifier, ['password'])) {
            throw new InvalidArgumentException("Identifier [{$identifier}] is not allowed!");
        }

        static::$identifier = $identifier;
    }
}

Improve performance by prefixing all global functions calls with \ to
skip the look up and resolve process and go straight to the global
function

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


<?php

namespace WyriHaximus\React\ChildProcess\Pool;

use Evenement\EventEmitterTrait;
use React\Promise\PromiseInterface;
use WyriHaximus\React\ChildProcess\Messenger\Messages\Rpc;
use WyriHaximus\React\ChildProcess\Messenger\Messenger;

class Worker implements WorkerInterface
{
    use EventEmitterTrait;

    /**
     * @var Messenger
     */
    protected $messenger;

    /**
     * @var bool
     */
    protected $busy = false;

    /**
     * @param Messenger $messenger
     */
    public function __construct(Messenger $messenger)
    {
        $this->messenger = $messenger;
    }

    /**
     * @param Rpc $rpc
     * @return PromiseInterface
     */
    public function rpc(Rpc $rpc)
    {
        $this->busy = true;
        return $this->messenger->rpc($rpc)->always(function () {
            $this->busy = false;
            $this->emit('done', [$this]);
        });
    }

    /**
     * @return bool
     */
    public function isBusy()
    {
        return $this->busy;
    }

    /*
     * @return PromiseInterface
     */
    public function terminate()
    {
        $this->emit('terminating', [$this]);
        return $this->messenger->softTerminate();
    }
}

<?php

namespace WyriHaximus\React\ChildProcess\Pool;

use Evenement\EventEmitterTrait;
use React\Promise\PromiseInterface;
use WyriHaximus\React\ChildProcess\Messenger\Messages\Rpc;
use WyriHaximus\React\ChildProcess\Messenger\Messenger;

class Worker implements WorkerInterface
{
    use EventEmitterTrait;

    /**
     * @var Messenger
     */
    protected $messenger;

    /**
     * @var bool
     */
    protected $busy = false;

    /**
     * @param Messenger $messenger
     */
    public function __construct(Messenger $messenger)
    {
        $this->messenger = $messenger;
    }

    /**
     * @param Rpc $rpc
     * @return PromiseInterface
     */
    public function rpc(Rpc $rpc)
    {
        $this->busy = true;
        return $this->messenger->rpc($rpc)->always(function () {
            $this->busy = false;
            $this->emit('done', [$this]);
        });
    }

    /**
     * @return bool
     */
    public function isBusy()
    {
        return $this->busy;
    }

    /*
     * @return PromiseInterface
     */
    public function terminate()
    {
        $this->busy = true;
        $this->emit('terminating', [$this]);
        return $this->messenger->softTerminate();
    }
}

Set to busy when terminating so we don't accidently use it


<?php

namespace Backend\Modules\MediaLibrary\Domain\MediaItem;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class MediaItemType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $label = 'lbl.Title';

        if ($builder->getData()->getMediaItemEntity()->getType()->isMovie()) {
            $label = 'lbl.MediaMovieTitle';
            $this->addField($builder, 'url', 'lbl.MediaMovieId');
        }

        $this->addField($builder, 'title', $label);
    }

    private function addField(FormBuilderInterface $builder, string $name, string $label): void
    {
        $builder->add(
            $name,
            TextType::class,
            [
                'label' => $label,
            ]
        );
    }

    public function getBlockPrefix(): string
    {
        return 'media_item';
    }
}

<?php

namespace Backend\Modules\MediaLibrary\Domain\MediaItem;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\Regex;

class MediaItemType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $label = 'lbl.Title';

        if ($builder->getData()->getMediaItemEntity()->getType()->isMovie()) {
            $label = 'lbl.MediaMovieTitle';
            $builder->add(
                'url',
                TextType::class,
                [
                    'label' => 'lbl.MediaMovieId',
                    'constraints' => [
                        new Regex(['pattern' => '/^[a-zA-Z]+[a-zA-Z0-9._]+$/', 'message' => 'err.InvalidValue']),
                    ],
                ]
            );
        }

        $builder->add(
            'title',
            TextType::class,
            [
                'label' => $label,
            ]
        );
    }

    public function getBlockPrefix(): string
    {
        return 'media_item';
    }
}

Add regex validation for the id when editing movies


<?php

class CaptchaField extends TextField {

	function __construct($name, $title = null, $value = "", $form = null){
		parent::__construct($name, $title, $value, $form);
	}

	function Field($properties = array()) {
		$attributes = array(
			'type' => 'text',
			'class' => 'CaptchaField',
			'id' => $this->id(),
			'name' => $this->getName(),
			'value' => $this->Value(),
			'tabindex' => $this->getAttribute("tabindex"),
			'maxlength' => 4,
			'size' => 30
		);

		// create link to image to display code
		$html =  '<img src="' . _EnquiryPageBase .'/images/captcha.jpg?' . time() . '" class="customcaptcha-image" alt="CAPTCHA security code" />';

		// create input field
		$html .= $this->createTag('input', $attributes);

		return $html;

	}

	// SERVER-SIDE VALIDATION (to ensure a browser with javascript disabled doesn't bypass validation)

	function validate($validator){

		$this->value = trim($this->value);

		$SessionCaptcha = Session::get('customcaptcha');

		if ( md5(trim($this->value).$_SERVER['REMOTE_ADDR']).'a4xn' != $SessionCaptcha ) {
			$validator->validationError(
				$this->name,
				'Codes do not match, please try again',
				'required'
			);
		}

	}
}

<?php

class CaptchaField extends TextField {

	function __construct($name, $title = null, $value = "", $form = null){
		parent::__construct($name, $title, $value, $form);
	}

	function Field($properties = array()) {
		$attributes = array(
			'type' => 'text',
			'class' => 'CaptchaField',
			'id' => $this->id(),
			'name' => $this->getName(),
			'value' => $this->Value(),
			'tabindex' => $this->getAttribute("tabindex"),
			'maxlength' => 4,
			'size' => 30
		);

		// create link to image to display code
		$html =  '<img src="' . _EnquiryPageBase .'/images/captcha.jpg?' . time() . '" class="customcaptcha-image" alt="CAPTCHA security code" width="60" height="24" />';

		// create input field
		$html .= $this->createTag('input', $attributes);

		return $html;

	}

	// SERVER-SIDE VALIDATION (to ensure a browser with javascript disabled doesn't bypass validation)

	function validate($validator){

		$this->value = trim($this->value);

		$SessionCaptcha = Session::get('customcaptcha');

		if ( md5(trim($this->value).$_SERVER['REMOTE_ADDR']).'a4xn' != $SessionCaptcha ) {
			$validator->validationError(
				$this->name,
				'Codes do not match, please try again',
				'required'
			);
		}

	}
}

Set verification image height and width in html


<?php
namespace Tzander\PageFactory;

/*
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Torsten Zander <info@tzander.de>
 * @author    Torsten Zander <info@tzander.de>
 *
 */

use Tzander\FindBy;

class ReflectionProperty
{
    /**
     * @var \ReflectionProperty
     */
    private $property;

    public function __construct(\ReflectionProperty $property)
    {
        $this->property = $property;
    }

    /**
     * @return null|\Tzander\FindBy
     */
    public function getFindAnnotation()
    {
        $comment = $this->property->getDocComment();
        if (preg_match($this->getRegExForFindAnnotation(), $comment, $matches)) {
            return new FindBy($matches[1]);
        }
        return null;
    }

    /**
     * @return string
     */
    private function getRegExForFindAnnotation()
    {
        return '/@find\s+([a-zA-Z0-9._()=@"\':-\\\\x7f-\xff\[\]]+)/';
    }

    /**
     * @return string
     */
    public function getPropertyName()
    {
        return $this->property->getName();
    }
}

<?php
namespace Tzander\PageFactory;

/*
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Torsten Zander <info@tzander.de>
 * @author    Torsten Zander <info@tzander.de>
 *
 */

use Tzander\FindBy;

class ReflectionProperty
{
    /**
     * @var \ReflectionProperty
     */
    private $property;

    public function __construct(\ReflectionProperty $property)
    {
        $this->property = $property;
    }

    /**
     * @return null|\Tzander\FindBy
     */
    public function getFindAnnotation()
    {
        $comment = $this->property->getDocComment();
        if (preg_match($this->getRegExForFindAnnotation(), $comment, $matches)) {
            return new FindBy($matches[1]);
        }
        return null;
    }

    /**
     * @return string
     */
    private function getRegExForFindAnnotation()
    {
        return '/@find\s+([a-zA-Z0-9._()=@"\':-\\\\x7f-\xff\[\]\-]+)/';
    }

    /**
     * @return string
     */
    public function getPropertyName()
    {
        return $this->property->getName();
    }
}

Add support for "-" in find expressions.


<?php

use Slim\Http\Uri;
use Slim\Views\Twig;

$container['view'] = function ($container) {
	$view = new Twig(__DIR__ . '/../resources/views', [
		'cache' => $container->settings['views']['cache']
	]);

	// Instantiate and add Slim specific extension
	$router = $container->get('router');
	$uri = Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER));
	$view->addExtension(new \Slim\Views\TwigExtension($router, $uri));

	$view->getEnvironment()->addGlobal('auth', [
		'check' => $container->auth->check(),
		'user' => $container->auth->user(),
	]);

	$view->getEnvironment()->addGlobal('flash', $container->flash);

	return $view;
};

<?php

use Slim\Http\Uri;
use Slim\Views\Twig;

$container['view'] = function ($container) {
	$view = new Twig(__DIR__ . '/../resources/views', [
		'cache' => $container->settings['views']['cache']
	]);

	// Instantiate and add Slim specific extension
	$router = $container->get('router');
	$uri = Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER));
	$view->addExtension(new \Slim\Views\TwigExtension($router, $uri));
	$view->getEnvironment()->addGlobal('siteUrl', getenv('SITE_URL'));
	$view->getEnvironment()->addGlobal('auth', [
		'check' => $container->auth->check(),
		'user' => $container->auth->user(),
	]);
	$view->getEnvironment()->addGlobal('flash', $container->flash);
	return $view;
};

Add siteUrl Twig global var

Add siteUrl Twig global var


<?php
	class Config{
		// Config database
		public static $host='localhost';
		public static $db_user='root';
		public static $db_password='';
		public static $db_name='project_mvc';

	}

?>

<?php
	class Config{
		// Config database
		public static $host='localhost';
		public static $db_user='root';
		public static $db_password='';
		public static $db_name='education_web';

	}

?>

Edit file config to connect database

Edit file config to connect database


<?php

namespace BryanCrowe\Growl;

class Growl
{
    protected $builder;

    protected $args = array();

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

    public function execute()
    {
        $command = $this->builder->build($args);
        return exec($command);
    }

    public function __call($name, $args)
    {
        $this->args[$name] = $args[0];
    }
}

<?php

namespace BryanCrowe\Growl;

class Growl
{
    protected $builder;

    protected $args = array();

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

    public function execute()
    {
        $command = $this->builder->build($this->args);
        return exec($command);
    }

    public function __call($name, $args)
    {
        $this->args[$name] = $args[0];
    }
}

Fix reference to class property

Fix reference to class property


<?php

/**
 * Get short url from a post.
 *
 * @param int $post_id
 * @param bool $only_short_url Default false
 *
 * @return string|null
 */
function get_short_url( $post_id, $only_short_url ) {
	return short_url()->get_short_url( $post_id, $only_short_url );
}

<?php

/**
 * Get short url from a post.
 *
 * @param int $post_id
 * @param bool $only_short_url Default false
 *
 * @return string|null
 */
function get_short_url( $post_id, $only_short_url = false ) {
	return short_url()->get_short_url( $post_id, $only_short_url );
}

Fix default value for `get_short_url`

Fix default value for `get_short_url`


<?php
/**
 * Copyright (c) 2013 Thomas Tanghus (thomas@tanghus.net)
 * @author Thomas Tanghus
 * @author Robin Appelman
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace OCP;

interface ISession {
	/**
	 * @param string $key
	 * @param mixed $value
	 */
	public function set($key, $value);

	/**
	 * @param string $key
	 * @return mixed should return null if $key does not exist
	 */
	public function get($key);

	/**
	 * @param string $key
	 * @return bool
	 */
	public function exists($key);

	/**
	 * should not throw any errors if $key does not exist
	 *
	 * @param string $key
	 */
	public function remove($key);

	/**
	 * removes all entries within the cache namespace
	 */
	public function clear();

}

<?php
/**
 * Copyright (c) 2013 Thomas Tanghus (thomas@tanghus.net)
 * @author Thomas Tanghus
 * @author Robin Appelman
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace OCP;

/**
 * Interface ISession
 *
 * wrap PHP's internal session handling into the ISession interface
 */
interface ISession {

	/**
	 * Set a value in the session
	 *
	 * @param string $key
	 * @param mixed $value
	 */
	public function set($key, $value);

	/**
	 * Get a value from the session
	 *
	 * @param string $key
	 * @return mixed should return null if $key does not exist
	 */
	public function get($key);

	/**
	 * Check if a named key exists in the session
	 *
	 * @param string $key
	 * @return bool
	 */
	public function exists($key);

	/**
	 * Remove a $key/$value pair from the session
	 *
	 * @param string $key
	 */
	public function remove($key);

	/**
	 * Reset and recreate the session
	 */
	public function clear();

}

Add some docs to the sessions interface.


<?php
/**
 * @package plugins.metadata
 * @subpackage model
 */
class MetadataEntryPeer extends entryPeer implements IMetadataPeer
{
    public static function validateMetadataObjects($profileField, $objectIds, &$errorMessage)
    {
        /** @var MetadataProfileField $profileField */
        $dbObjects = entryPeer::retrieveByPKs($objectIds);

        if(count($dbObjects) != count($objectIds))
        {
            $errorMessage = 'One of the following objects: '.implode(', ', $objectIds).' was not found';
            return false;
        }

        return true;
    }
}

<?php
/**
 * @package plugins.metadata
 * @subpackage model
 */
class MetadataEntryPeer extends entryPeer implements IMetadataPeer
{
    public static function validateMetadataObjects($profileField, $objectIds, &$errorMessage)
    {
    	//commenting out until a larger solution will be applied.
    	//Need to allow eache filed should validate configuration flag to disable or enable the execution of the metadata validation method execution
        /** @var MetadataProfileField $profileField */
    	/*
        $dbObjects = entryPeer::retrieveByPKs($objectIds);

        if(count($dbObjects) != count($objectIds))
        {
            $errorMessage = 'One of the following objects: '.implode(', ', $objectIds).' was not found';
            return false;
        }
        */

        return true;
    }
}

Remove (for now) metadat validation of objectType fields (metadataEntry)


<?php

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

<?php

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

Set release version to 0.8.2

Set release version to 0.8.2


<?php

/*
|--------------------------------------------------------------------------
| Shop Factory
|--------------------------------------------------------------------------
|
| Create models with stub data for all data coming from the Shop
| Data Service.
|
*/

if (!function_exists('shopIdsAndTitle')) {
    function shopIdsAndTitle($faker, $title = '')
    {
        return [
            'shop_id' => $faker->unique()->randomNumber(3) + 999 * pow(10, 3),
            'title' => $title ? $title : ucfirst($faker->words(5, true)),
        ];
    }

    function shopDates($faker)
    {
        return [
            'source_created_at' => $faker->dateTimeThisYear,
            'source_modified_at' => $faker->dateTimeThisYear,
        ];
    }
}

$factory->define(App\Models\Shop\Product::class, function (Faker\Generator $faker) {
    $part1 = ucwords($faker->words(2, true));
    $part2 = ucwords($faker->words(2, true));
    $part3 = ucwords($faker->words(2, true));
    $title = $part1 . ' ' . $part2 . ' ' . $part3;

    return array_merge(
        shopIdsAndTitle($faker, $title),
        [
            'sku' => $faker->ean8,
            'external_sku' => $faker->ean8,
            'image_url' => $faker->imageUrl,
            'description' => $faker->paragraph(3),
            'priority' => $faker->randomDigit,
            'price' => $faker->randomFloat(2, 5, 300),
            'aic_collection' => $faker->boolean,
            'gift_box' => $faker->boolean,
            'holiday' => $faker->boolean,
            'architecture' => $faker->boolean,
            'glass' => $faker->boolean,
            'active' => true,
        ],
        shopDates($faker)
    );
});

<?php

/*
|--------------------------------------------------------------------------
| Shop Factory
|--------------------------------------------------------------------------
|
| Create models with stub data for all data coming from the Shop
| Data Service.
|
*/

if (!function_exists('shopIdsAndTitle')) {
    function shopIdsAndTitle($faker, $title = '')
    {
        return [
            'shop_id' => $faker->unique()->randomNumber(3) + 999 * pow(10, 3),
            'title' => $title ? $title : ucfirst($faker->words(5, true)),
        ];
    }

    function shopDates($faker)
    {
        return [
            'source_modified_at' => $faker->dateTimeThisYear,
        ];
    }
}

$factory->define(App\Models\Shop\Product::class, function (Faker\Generator $faker) {
    $part1 = ucwords($faker->words(2, true));
    $part2 = ucwords($faker->words(2, true));
    $part3 = ucwords($faker->words(2, true));
    $title = $part1 . ' ' . $part2 . ' ' . $part3;

    return array_merge(
        shopIdsAndTitle($faker, $title),
        [
            'external_sku' => $faker->ean8,
            'description' => $faker->paragraph(3),
        ],
        shopDates($faker)
    );
});

Update shop factory to reflect new schema [WEB-2002]


<?php
namespace RetryHandler;

use \RetryHandler\Proc;

use \Exception;

class InvocationCounter
{
    protected $_count = 0;

    protected $_proc;

    public function __construct($proc = NULL)
    {
        if ($proc) {
            $this->_proc = $proc;
        }
    }

    public function __invoke()
    {
        $this->_count++;
        if ($this->_proc) {
            return call_user_func_array($this->_proc, func_get_args());
        }
    }

    public function getCount()
    {
        return $this->_count;
    }
}

class ProcTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function retry_should_call_its_callable_once_if_no_exception_is_thrown()
    {
        $counter = new InvocationCounter;
        $proc = new Proc($counter);
        $proc->retry(3);
        $this->assertEquals(1, $counter->getCount());
    }

    /**
     * @test
     */
    public function retry_should_call_its_callable_repeatedly_until_its_max_count_if_exception_is_thrown()
    {
        $counter = new InvocationCounter(function () {
            throw new Exception;
        });
        $proc = new Proc($counter);
        $proc->retry(3);
        $this->assertEquals(3, $counter->getCount());
    }
}

<?php
namespace RetryHandler;

use \RetryHandler\Proc;

use \Exception;

class ProcTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function retry_should_call_its_callable_once_if_no_exception_is_thrown()
    {
        $count = 0;
        $counter = function () use (&$count) {
            $count++;
        };
        $proc = new Proc($counter);
        $proc->retry(3);
        $this->assertEquals(1, $count);
    }

    /**
     * @test
     */
    public function retry_should_call_its_callable_repeatedly_until_its_max_count_if_exception_is_thrown()
    {
        $count = 0;
        $counter = function () use (&$count) {
            $count++;
            throw new Exception;
        };
        $proc = new Proc($counter);
        $proc->retry(3);
        $this->assertEquals(3, $count);
    }
}

Replace InvocationCounter class with basic Closure.


<?php  defined('C5_EXECUTE') or die("Access Denied.");
$dh = Loader::helper('concrete/dashboard');
$im = Loader::helper('image');
$this->inc('elements/header.php');
$headImage = $c->getAttribute("main_image");
?>

<body class="blog <?php echo ($dh->canRead()) ? "logged_in" : ""; ?>">
<?php $this->inc('elements/navbar.php'); ?>

    <header <?php echo isset($headImage) ? 'style="background-image:url('.$headImage->getURL() .')"' : "" ?>>
      <?php  $ai = new Area('Blog Post Header'); $ai->display($c); ?>

<?php  echo $c->getCollectionName(); ?>

<?php echo $c->getCollectionDescription(); ?>

<?php
        echo t('%s on %s',
          $c->getVersionObject()->getVersionAuthorUserName(),
          $c->getCollectionDatePublic(DATE_APP_GENERIC_MDY_FULL));
      ?>

				<?php  $as = new Area('Main'); $as->display($c); ?>

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

<?php  defined('C5_EXECUTE') or die("Access Denied.");
$dh = Loader::helper('concrete/dashboard');
$im = Loader::helper('image');
$this->inc('elements/header.php');
$headImage = $c->getAttribute("main_image");
?>

<body class="blog <?php echo ($dh->canRead()) ? "logged_in" : ""; ?>">
<?php $this->inc('elements/navbar.php'); ?>

    <header <?php echo is_object($headImage) ? 'style="background-image:url('.$headImage->getURL() .')"' : "" ?>>
      <?php  $ai = new Area('Blog Post Header'); $ai->display($c); ?>

<?php  echo $c->getCollectionName(); ?>

<?php echo $c->getCollectionDescription(); ?>

<?php
        echo t('%s on %s',
          $c->getVersionObject()->getVersionAuthorUserName(),
          $c->getCollectionDatePublic(DATE_APP_GENERIC_MDY_FULL));
      ?>

				<?php  $as = new Area('Main'); $as->display($c); ?>

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

Fix blog page when no image is set

Fix blog page when no image is set


<?php

namespace Hodor\MessageQueue\Adapter;

interface ConfigInterface
{
    /**
     * @return string
     */
    public function getAdapterFactoryConfig();

    /**
     * @param string $queue_key
     * @return array
     */
    public function getQueueConfig($queue_key);
}

<?php

namespace Hodor\MessageQueue\Adapter;

interface ConfigInterface
{
    /**
     * @return array
     */
    public function getAdapterFactoryConfig();

    /**
     * @param string $queue_key
     * @return array
     */
    public function getQueueConfig($queue_key);
}

Fix PHPdoc that was causing PhpStorm warnings in AdapterFactory


<?php

final class PhutilJSONParserException extends Exception {

  private $sourceLine;
  private $sourceChar;
  private $sourceToken;
  private $expected;

  public function __construct(
    $message,
    $line = null,
    $char = null,
    $token = null,
    $expected = null) {

    $this->sourceLine = $line;
    $this->sourceChar = $char;
    $this->sourceToken = $token;
    $this->expected = $expected;

    parent::__construct($message);
  }

  public function getSourceLine() {
    return $this->sourceLine;
  }

  public function getSourceChar() {
    return $this->sourceChar;
  }

  public function getSourceToken() {
    return $this->sourceToken;
  }

  public function getExpectedTokens() {
    return $this->expected;
  }

}

<?php

final class PhutilJSONParserException extends Exception {

  private $sourceLine;
  private $sourceChar;
  private $sourceToken;
  private $expected;

  public function __construct(
    $message,
    $line = null,
    $char = null,
    $token = null,
    $expected = null) {

    $this->sourceLine = $line;
    $this->sourceChar = $char;
    $this->sourceToken = $token;
    $this->expected = $expected;

    parent::__construct(
      pht('Parse error on line %d at column %d: %s', $line, $char, $message));
  }

  public function getSourceLine() {
    return $this->sourceLine;
  }

  public function getSourceChar() {
    return $this->sourceChar;
  }

  public function getSourceToken() {
    return $this->sourceToken;
  }

  public function getExpectedTokens() {
    return $this->expected;
  }

}

Improve the exception message for JSON parsing exceptions.

Summary: Provide contextual information relating to JSON parser exceptions.

Test Plan: See D9679.

Reviewers: epriestley, #blessed_reviewers

Reviewed By: epriestley, #blessed_reviewers

Subscribers: epriestley, Korvin

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


<?php namespace App\Http\Controllers;

class DashboardController extends BaseController {

	public function __construct()
	{
		$this->middleware('auth');

        parent::__construct();
	}

	/**
	 * Show the application dashboard to the user.
	 *
	 * @return Response
	 */
	public function index()
	{
        $items = $this->auth->getUser()->userItems;

		return view('dashboard', array(
			'user' => $this->auth->getUser(),
            'items' => $items
		));
	}

}

<?php namespace App\Http\Controllers;

class DashboardController extends BaseController {

	public function __construct()
	{
		$this->middleware('auth');

        parent::__construct();
	}

	/**
	 * Show the application dashboard to the user.
	 *
	 * @return Response
	 */
	public function index()
	{
        $items = $this->auth->getUser()->userItems->sortByDesc('updated_at');

		return view('dashboard', array(
			'user' => $this->auth->getUser(),
            'items' => $items
		));
	}

}

Order articles by recently updated.

Order articles by recently updated.


<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\UserInfo */

$this->title = 'Create User Info';
$this->params['breadcrumbs'][] = ['label' => 'User Infos', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

        <?php $form = ActiveForm::begin(); ?>

        <?= $form->field($user_model, 'username')->textInput(['maxlength' => true])->label('User ID') ?>

        <?= $form->field($user_model, 'password')->passwordInput() ?>

        <?= $form->field($model, 'full_name')->textInput(['maxlength' => true]) ?>

        <?= $form->field($model, 'school')->textInput(['maxlength' => true]) ?>

        <?= $form->field($user_model, 'email') ?>

        <?= $form->field($model, 'etc')->textInput(['maxlength' => true]) ?>

            <?= Html::submitButton('Create', ['class' => 'btn btn-success']) ?>

        <?php ActiveForm::end(); ?>

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\UserInfo */

$this->title = 'Create User Info';
$this->params['breadcrumbs'][] = ['label' => 'User Infos', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

        <?php $form = ActiveForm::begin(); ?>

        <?= $form->field($user_model, 'username')->textInput(['maxlength' => true])->label('User ID') ?>

        <?= $form->field($user_model, 'password')->passwordInput() ?>

        <?= $form->field($model, 'full_name')->textInput(['maxlength' => true]) ?>

        <?= $form->field($model, 'school')->textInput(['maxlength' => true]) ?>

        <?= $form->field($user_model, 'email') ?>

        <?= $form->field($model, 'etc')->textInput(['maxlength' => true]) ?>

            <?= Html::submitButton('Create', ['class' => 'btn btn-success']) ?>
            <?= Html::a('Go Back', Yii::$app->request->referrer, ['class' => 'btn btn-default']) ?>

        <?php ActiveForm::end(); ?>

Add Go Back in User Creation From

Add Go Back in User Creation From


<!doctype html>

        <link rel="stylesheet" href="<?php echo $my_url; ?>/static/pure-min.css">
        <link rel="stylesheet" href="<?php echo $my_url; ?>/static/grids-responsive-min.css">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title><?php echo $title; ?></title>

<?php echo $title; ?>

            <img class="pure-img" scc="<?php echo $my_url; ?>/logo.png"/>

<!doctype html>

        <link rel="stylesheet" href="<?php echo $my_url; ?>/static/pure-min.css">
        <link rel="stylesheet" href="<?php echo $my_url; ?>/static/grids-responsive-min.css">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title><?php echo $title; ?></title>

<?php echo $title; ?>

            <img class="pure-img" src="<?php echo $my_url; ?>static/logo.png"/>

Fix logo path and markup

Fix logo path and markup


<?php

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

function getConfig(): array
{
    return require __DIR__ . '/config/db.config.php';
}

Enable functional tests to retrieve config


<?php

global $RUNTIME_NOAPPS;
$RUNTIME_NOAPPS = false;

define('PHPUNIT_RUN', 1);

require_once __DIR__.'/../lib/base.php';

if(!class_exists('PHPUnit_Framework_TestCase')) {
	require_once('PHPUnit/Autoload.php');
}

OC_Hook::clear();
OC_Log::$enabled = false;

<?php

define('PHPUNIT_RUN', 1);

require_once __DIR__.'/../lib/base.php';

if(!class_exists('PHPUnit_Framework_TestCase')) {
	require_once('PHPUnit/Autoload.php');
}

OC_Hook::clear();
OC_Log::$enabled = false;

Remove $RUNTIME_NOAPPS - setting to false was not enough


<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
if (!defined('TEST_FILES_PATH')) {
    define('TEST_FILES_PATH', __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR);
}

ini_set('precision', '14');
ini_set('serialize_precision', '14');

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

<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
if (!defined('PHPUNIT_COMPOSER_INSTALL')) {
    define('PHPUNIT_COMPOSER_INSTALL', dirname(__DIR__) . '/vendor/autoload.php');
}

if (!defined('TEST_FILES_PATH')) {
    define('TEST_FILES_PATH', __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR);
}

ini_set('precision', '14');
ini_set('serialize_precision', '14');

require_once PHPUNIT_COMPOSER_INSTALL;

Make sure that PHPUNIT_COMPOSER_INSTALL is always defined, even in tests that are run in isolation from a PHPT test


<?php
$vxml_library = dirname(__DIR__) . '/library';
$vxml_tests = __DIR__;
set_include_path(get_include_path() . PATH_SEPARATOR . $vxml_library . PATH_SEPARATOR . $vxml_library);

require_once 'VXML/Loader.php';
VXML\Loader::registerAutoload();

require_once 'PHPUnit/Framework/TestCase.php';

<?php
$vxml_library = dirname(__DIR__) . '/library';
$vxml_tests = __DIR__;
set_include_path(get_include_path() . PATH_SEPARATOR . $vxml_library . PATH_SEPARATOR . $vxml_tests);

require_once 'VXML/Loader.php';
VXML\Loader::registerAutoload();

require_once 'PHPUnit/Framework/TestCase.php';

Fix double library in include path instead of tests folder


<?php
namespace CodeDay\Clear\Http\Controllers\Manage\Batch;

use \CodeDay\Clear\Models;
use \CodeDay\Clear\Services;

class CsvController extends \CodeDay\Clear\Http\Controller {

    public function getIndex()
    {
        return Services\Registration::GetCsvMultiple(Models\Batch::Managed()->events);
    }
}

<?php
namespace CodeDay\Clear\Http\Controllers\Manage\Batch;

use \CodeDay\Clear\Models;
use \CodeDay\Clear\Services;

class CsvController extends \CodeDay\Clear\Http\Controller {

    public function getIndex()
    {
        $content = Services\Registration::GetCsvMultiple(Models\Batch::Managed()->events);

        return (new \Illuminate\Http\Response($content, 200))
            ->header('Content-type', 'text/csv')
            ->header('Content-disposition', 'attachment;filename=all-attendees-'.time().'.csv');
    }
}

Fix header for CSV downloads

Fix header for CSV downloads


<?php
class Kwc_Basic_LinkTag_Intern_ApiContent implements Kwf_Component_ApiContent_Interface
{
    public function getContent(Kwf_Component_Data $data)
    {
        $targetData = $data->getLinkedData();
        $ret = array(
            'rel' => $data->rel,
            'class' => $data->getLinkClass(),
            'dataAttributes' => $data->getLinkDataAttributes(),
        );
        return array_merge($ret, $this->getTargetLinkContent($targetData));
    }

    public function getTargetLinkContent($targetData)
    {
        $targetContentType = Kwc_Abstract::getSetting($targetData->componentClass, 'apiContentType');
        if (is_instance_of (Kwc_Abstract::getSetting($targetData->componentClass, 'contentSender'), 'Kwf_Component_Abstract_ContentSender_Lightbox')) {
            $targetContentType = 'lightbox';
        }
        return array(
            "href" => $targetData->url,
            "targetId" => $targetData->componentId,
            "targetContentType" => $targetContentType
        );
    }
}

<?php
class Kwc_Basic_LinkTag_Intern_ApiContent implements Kwf_Component_ApiContent_Interface
{
    public function getContent(Kwf_Component_Data $data)
    {
        $targetData = $data->getLinkedData();
        $ret = array(
            'rel' => $data->rel,
            'class' => $data->getLinkClass(),
            'dataAttributes' => $data->getLinkDataAttributes(),
        );
        return array_merge($ret, $this->getTargetLinkContent($targetData));
    }

    public function getTargetLinkContent($targetData)
    {
        if (!$targetData) return array();
        $targetContentType = Kwc_Abstract::getSetting($targetData->componentClass, 'apiContentType');
        if (is_instance_of (Kwc_Abstract::getSetting($targetData->componentClass, 'contentSender'), 'Kwf_Component_Abstract_ContentSender_Lightbox')) {
            $targetContentType = 'lightbox';
        }
        return array(
            "href" => $targetData->url,
            "targetId" => $targetData->componentId,
            "targetContentType" => $targetContentType
        );
    }
}

Fix link-intern on invisible page

MenuApi: Fix link-intern on invisible page


<?php

if ( !defined( 'WP_CLI' ) ) return;

global $argv;

$env = $argv[1];

$config = array();

$config_path = getenv( 'HOME' ) . '/.wp-cli/config.yml';

if ( is_readable( $config_path ) ){

    $configurator = \WP_CLI::get_configurator();

    $configurator->merge_yml( $config_path );
    list( $config, $extra_config ) = $configurator->to_array();
}

if ( isset($config['color']) && $config['color'] === 'auto' ) {
    $colorize = !\cli\Shell::isPiped();
} else {
    $colorize = true;
}

if ( isset($config['quiet']) && $config['quiet'] )
    $logger = new \WP_CLI\Loggers\Quiet;
else
    $logger = new \WP_CLI\Loggers\Regular( $colorize );

\WP_CLI::set_logger( $logger );

try {
    $environment = new \ViewOne\Environment();
    $environment->run($env);
} catch (Exception $e) {
    \WP_CLI::error( $e->getMessage() );
}

<?php

if ( !defined( 'WP_CLI' ) ) return;

require_once 'src/ViewOne/Environment.php';

global $argv;

$env = $argv[1];

$config = array();

$config_path = getenv( 'HOME' ) . '/.wp-cli/config.yml';

if ( is_readable( $config_path ) ){

    $configurator = \WP_CLI::get_configurator();

    $configurator->merge_yml( $config_path );
    list( $config, $extra_config ) = $configurator->to_array();
}

if ( isset($config['color']) && $config['color'] === 'auto' ) {
    $colorize = !\cli\Shell::isPiped();
} else {
    $colorize = true;
}

if ( isset($config['quiet']) && $config['quiet'] )
    $logger = new \WP_CLI\Loggers\Quiet;
else
    $logger = new \WP_CLI\Loggers\Regular( $colorize );

\WP_CLI::set_logger( $logger );

try {
    $environment = new \ViewOne\Environment();
    $environment->run($env);
} catch (Exception $e) {
    \WP_CLI::error( $e->getMessage() );
}

Add require for global installation

Add require for global installation


<?php

return [
    'Load more items' => 'Weitere eintrge laden',
    'You reached the end' => 'Sie sind am Ende angekommen'
];

<?php

return [
    'Load more items' => 'Weitere Einträge laden',
    'You reached the end' => 'Keine weiteren Einträge vorhanden'
];

Improve wording of german translation file


<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;

class Managedinstalls extends Migration
{
    public function up()
    {
        $capsule = new Capsule();
        $capsule::schema()->create('managedinstalls', function (Blueprint $table) {
            $table->increments('id');

            $table->string('serial_number');
            $table->string('name');
            $table->string('display_name');
            $table->string('version')->nullable();
            $table->integer('size')->nullable();
            $table->integer('installed');
            $table->string('status');
            $table->string('type');

            $table->index('display_name', 'managedinstalls_display_name');
            $table->index('name', 'managedinstalls_name');
            $table->index(['name', 'version'], 'managedinstalls_name_version');
            $table->index('serial_number', 'managedinstalls_serial_number');
            $table->index('status', 'managedinstalls_status');
            $table->index('type', 'managedinstalls_type');
            $table->index('version', 'managedinstalls_version');
//            $table->timestamps();
        });
    }

    public function down()
    {
        $capsule = new Capsule();
        $capsule::schema()->dropIfExists('managedinstalls');
    }
}

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;

class Managedinstalls extends Migration
{
    public function up()
    {
        $capsule = new Capsule();
        $capsule::schema()->create('managedinstalls', function (Blueprint $table) {
            $table->increments('id');

            $table->string('serial_number');
            $table->string('name');
            $table->string('display_name');
            $table->string('version')->nullable();
            $table->integer('size')->nullable();
            $table->integer('installed');
            $table->string('status');
            $table->string('type');

            $table->index('display_name');
            $table->index('name');
            $table->index(['name', 'version']);
            $table->index('serial_number');
            $table->index('status');
            $table->index('type');
            $table->index('version');
//            $table->timestamps();
        });
    }

    public function down()
    {
        $capsule = new Capsule();
        $capsule::schema()->dropIfExists('managedinstalls');
    }
}

Simplify indexes for managed installs

Simplify indexes for managed installs


<?php

require 'vendor/autoload.php';

$loop = new React\EventLoop\StreamSelectLoop();
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket);

$context = new React\ZMQ\Context($loop);
$dealer = $context->getSocket(ZMQ::SOCKET_DEALER);
$dealer->bind('tcp://127.0.0.1:4444');

$conns = new ArrayObject();

$dealer->on('message', function ($msg) use ($conns) {
    list($hash, $blank, $data) = $msg;

    $response = $conns[$hash];
    $response->writeHead();
    $response->end($data);
});

$http->on('request', function ($request, $response) use ($dealer, $conns) {
    $hash = spl_object_hash($request);
    $conns[$hash] = $response;

    $request->on('end', function () use ($conns, $hash) {
        unset($conns[$hash]);
    });

    $dealer->send(array(
        $hash,
        '',
        $request->getPath()
    ));
});

$socket->listen(8080);
$loop->run();

<?php

require 'vendor/autoload.php';

$loop = new React\EventLoop\StreamSelectLoop();
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket);

$context = new React\ZMQ\Context($loop);
$dealer = $context->getSocket(ZMQ::SOCKET_DEALER);
$dealer->bind('tcp://127.0.0.1:4444');

$conns = new ArrayObject();

$dealer->on('message', function ($msg) use ($conns) {
    list($hash, $blank, $data) = $msg;

    if (!isset($conns[$hash])) {
        return;
    }

    $response = $conns[$hash];
    $response->writeHead();
    $response->end($data);
});

$http->on('request', function ($request, $response) use ($dealer, $conns) {
    $hash = spl_object_hash($request);
    $conns[$hash] = $response;

    $request->on('end', function () use ($conns, $hash) {
        unset($conns[$hash]);
    });

    $dealer->send(array(
        $hash,
        '',
        $request->getPath()
    ));
});

$socket->listen(8080);
$loop->run();

Handle case of client closing conn before worker replies


<?php
function resolve_external_url($url) {
	if (substr($url, 0, 10) == "jamendo://") {
		return process_jamendo_url($url);
	}

	return $url;
}

function process_jamendo_url($url) {
	if (substr($url, 10, 13) == "track/stream/") {
		$id = substr($url, 23);
		return "http://api.jamendo.com/get2/stream/track/redirect/?id=" . $id . "&streamencoding=ogg2";
	}

	if (substr($url, 10, 15) == "album/download/") {
		$id = substr($url, 25);
		return "http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=" . $id . "&type=archive&class=ogg3";
	}

	if (substr($url, 10, 10) == "album/art/") {
		$id = substr($url, 20);
		return "http://api.jamendo.com/get2/image/album/redirect/?id=" . $id . "&imagesize=400";
	}

	// We don't know what this is
	return $url;
}

?>

<?php
function resolve_external_url($url) {
	if (substr($url, 0, 10) == "jamendo://") {
		return process_jamendo_url($url);
	}

	return $url;
}

function process_jamendo_url($url) {
	if (substr($url, 10, 13) == "track/stream/") {
		$id = substr($url, 23);
		return "http://api.jamendo.com/get2/stream/track/redirect/?id=" . $id . "&streamencoding=ogg2";
	}

	if (substr($url, 10, 15) == "album/download/") {
		$id = substr($url, 25);
		return "http://api.jamendo.com/get2/bittorrent/file/plain/?album_id=" . $id . "&type=archive&class=ogg3";
	}

	if (substr($url, 10, 10) == "album/art/") {
		$id = substr($url, 20);
		return "http://api.jamendo.com/get2/image/album/redirect/?id=" . $id . "&imagesize=200";
	}

	// We don't know what this is
	return $url;
}

?>

Reduce the size of the jamendo album cover images requested since we don't use them for anything larger than 160x160 at the moment


@servers(['web' =>  'root@162.243.246.75'])

@task('deploy', ['on' => 'web'])
    cd /var/www/nestor-qa/public_html
    git fetch --all
    git reset --hard origin/master
    git pull origin master
    composer dump-autoload
    composer update --no-dev --prefer-dist --profile -vvv --no-scripts
    php artisan migrate --force
@endtask

@servers(['web' =>  'root@162.243.246.75'])

@task('deploy', ['on' => 'web'])
    cd /var/www/nestor-qa/public_html
    git fetch --all
    git reset --hard origin/master
    git pull origin master
    cp .env.docker .env
    sed -i 's/=local/=prod/' .env
    touch database/database.sqlite
    composer dump-autoload
    composer update --no-dev --prefer-dist --profile -vvv --no-scripts
    php artisan migrate:refresh --force
    php artisan db:seed
@endtask

Use prod env in prod, and .env.docker as base. Also call migrations and seed


Map Demo

Powered by LeafletJS and Google API

PHP

$map = app()->createMap()->set('lon', 0)->set('lat', 0)->set('zoom', 2);
$marker = $map->model->createMarker(0, 0, 'Hello Architect!', true);
$map->model->addMarker($marker);
c($map);

Default Template

theme/default/map.php

Map Demo

Powered by LeafletJS, Google API and Map Icons Collection

PHP

$map = app()->createMap()->set('lon', 0)->set('lat', 0)->set('zoom', 2);
$marker = $map->model->createMarker(0, 0, 'Hello Architect!', true);
$map->model->addMarker($marker);
c($map);

Default Template

theme/default/map.php

Add credit for Map Icons Collection

Add credit for Map Icons Collection


<?php
add_action('init', 'register_post_types');
function register_post_types() {
/**** NEWSLETTER POST TYPE ****/
	$labels = array(
		'name' => _x('Newsletters', 'post type general name'),
		'singular_name' => _x('Newsletter', 'post type singular name'),
		'add_new' => _x('Add New Newsletter', 'portfolio item'),
		'add_new_item' => __('Add New Newsletter'),
		'edit_item' => __('Edit Newsletter'),
		'new_item' => __('New Newsletter'),
		'view_item' => __('View Newsletter'),
		'search_items' => __('Search Newsletters'),
		'not_found' =>  __('Nothing found'),
		'not_found_in_trash' => __('Nothing found in Trash'),
		'parent_item_colon' => ''
	);

	$args = array(
		'labels' => $labels,
		'public' => true,
		'publicly_queryable' => true,
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => true,
		'capability_type' => 'post',
		'hierarchical' => false,
		'menu_position' => null,
		'supports' => array('title','editor'),
		//"menu_position" => 21
	  );

	register_post_type( 'newsletter' , $args );
	flush_rewrite_rules();
}
?>

<?php
add_action('init', 'register_post_types');
function register_post_types() {
/**** NEWSLETTER POST TYPE ****/
	$labels = array(
		'name' => _x('Newsletters', 'post type general name'),
		'singular_name' => _x('Newsletter', 'post type singular name'),
		'add_new' => _x('Add New Newsletter', 'portfolio item'),
		'add_new_item' => __('Add New Newsletter'),
		'edit_item' => __('Edit Newsletter'),
		'new_item' => __('New Newsletter'),
		'view_item' => __('View Newsletter'),
		'search_items' => __('Search Newsletters'),
		'not_found' =>  __('Nothing found'),
		'not_found_in_trash' => __('Nothing found in Trash'),
		'parent_item_colon' => ''
	);

	$args = array(
		'labels' => $labels,
		'public' => true,
		'publicly_queryable' => true,
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => true,
		'capability_type' => 'post',
		'hierarchical' => false,
		'menu_position' => null,
		'supports' => array('title','editor'),
		//"menu_position" => 21
	  );

	register_post_type( 'anw_newsletter' , $args );
	flush_rewrite_rules();
}
?>

Change name of post type

Change name of post type


<?php

namespace Stampie\Extra\EventListener;

use Psr\Log\LoggerInterface;
use Stampie\Extra\Event\MessageEvent;
use Stampie\Extra\StampieEvents;
use Stampie\Util\IdentityUtils;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Listener responsible to log the sent emails.
 */
class LoggerListener implements EventSubscriberInterface
{
    private $logger;

    public function __construct(LoggerInterface $logger = null)
    {
        $this->logger = $logger;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            StampieEvents::PRE_SEND => 'preSend',
        ];
    }

    public function preSend(MessageEvent $event)
    {
        if (null === $this->logger) {
            return;
        }

        $message = $event->getMessage();

        $this->logger->debug(
            sprintf('Sending an email from "%s" to "%s"', IdentityUtils::buildIdentityString($message->getFrom()), IdentityUtils::buildIdentityString($message->getTo())),
            ['subject' => $message->getSubject(), 'headers' => $message->getHeaders()]
        );
    }
}

<?php

namespace Stampie\Extra\EventListener;

use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Stampie\Extra\Event\MessageEvent;
use Stampie\Extra\StampieEvents;
use Stampie\Util\IdentityUtils;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Listener responsible to log the sent emails.
 */
class LoggerListener implements EventSubscriberInterface
{
    private $logger;

    private $logLevel;

    public function __construct(LoggerInterface $logger = null, $logLevel = LogLevel::DEBUG)
    {
        $this->logger = $logger;
        $this->logLevel = $logLevel;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            StampieEvents::PRE_SEND => 'preSend',
        ];
    }

    public function preSend(MessageEvent $event)
    {
        if (null === $this->logger) {
            return;
        }

        $message = $event->getMessage();

        $this->logger->log(
            $this->logLevel,
            sprintf('Sending an email from "%s" to "%s"', IdentityUtils::buildIdentityString($message->getFrom()), IdentityUtils::buildIdentityString($message->getTo())),
            ['subject' => $message->getSubject(), 'headers' => $message->getHeaders()]
        );
    }
}

Allow caller to define log level for listener

The current implementation always uses debug as log level. This makes
the logger less flexible as it requires the caller to use debug log
level for all logging to see the output.

This change allows the caller to set the desired log level in the
constructor. The default is still debug to retain current behavior.


<?php namespace Orchestra\Memory\Console;

use Illuminate\Console\Command;

class MemoryCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'memory:migrate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run migration for orchestra/memory package.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $this->call('migrate', array('--package' => 'orchestra/memory'));
    }
}

<?php namespace Orchestra\Memory\Console;

use Illuminate\Console\Command;

class MemoryCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'memory:migrate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run migration for orchestra/memory package.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $path = $this->laravel['path.base'].'/vendor/orchestra/memory/src/migrations';

        $this->call('migrate', ['--path' => $path]);
    }
}

Use --path instead of deprecated --package.

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


<?php

namespace FluxBB\CommonMark\Parser\Block;

use FluxBB\CommonMark\Common\Text;
use FluxBB\CommonMark\Node\CodeBlock;
use FluxBB\CommonMark\Node\Container;
use FluxBB\CommonMark\Parser\AbstractBlockParser;

class CodeBlockParser extends AbstractBlockParser
{

    /**
     * Parse the given content.
     *
     * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser
     * in the chain.
     *
     * @param Text $content
     * @param Container $target
     * @return void
     */
    public function parseBlock(Text $content, Container $target)
    {
        $content->handle(
            '{
                (?:\n\n|\A)
                (                      # $1 = the code block -- one or more lines, starting with at least four spaces
                  (?:
                    (?:[ ]{4})         # Lines must start with four spaces
                    .*\n+
                  )+
                )
                (?:(?=^[ ]{0,4}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
            }mx',
            function (Text $whole, Text $code) use ($target) {
                // TODO: Prepare contents

                // Remove indent
                $code->replace('/^(\t|[ ]{1,4})/m', '');

                $target->acceptCodeBlock(new CodeBlock($code));
            },
            function(Text $part) use ($target) {
                $this->next->parseBlock($part, $target);
            }
        );
    }

}

<?php

namespace FluxBB\CommonMark\Parser\Block;

use FluxBB\CommonMark\Common\Text;
use FluxBB\CommonMark\Node\CodeBlock;
use FluxBB\CommonMark\Node\Container;
use FluxBB\CommonMark\Parser\AbstractBlockParser;

class CodeBlockParser extends AbstractBlockParser
{

    /**
     * Parse the given content.
     *
     * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser
     * in the chain.
     *
     * @param Text $content
     * @param Container $target
     * @return void
     */
    public function parseBlock(Text $content, Container $target)
    {
        $content->handle(
            '{
                ^
                (?:(?<=\n\n)|\A)    # Ensure blank line before (or beginning of subject)
                [ ]{4}              # four leading spaces
                .+
                (?:                 # optionally more spaces
                    (?:             # blank lines in between are okay
                        \n[ ]*
                    )*
                    \n
                    [ ]{4}
                    .+
                )*
                $
            }mx',
            function (Text $code) use ($target) {
                // Remove indent
                $code->replace('/^[ ]{1,4}/m', '');
                $code->append("\n");

                $target->acceptCodeBlock(new CodeBlock($code));
            },
            function(Text $part) use ($target) {
                $this->next->parseBlock($part, $target);
            }
        );
    }

}

Improve indented code block parsing.

Improve indented code block parsing.


<?php

namespace Bolt\Storage;

use Bolt\Storage\Mapping\ContentType;
use Silex\Application;

/**
 * Legacy bridge for Content object backward compatibility.
 *
 * @author Ross Riley <riley.ross@gmail.com>
 */
class ContentLegacyService
{
    use Entity\ContentRelationTrait;
    use Entity\ContentRouteTrait;
    use Entity\ContentSearchTrait;
    use Entity\ContentTaxonomyTrait;
    use Entity\ContentValuesTrait;

    protected $app;

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

    /**
     * Initialise.
     *
     * @param Entity\Entity $entity
     */
    public function initialize(Entity\Entity $entity)
    {
        $this->setupContenttype($entity);
        $this->setupContainer($entity);
    }

    /**
     * Set the legacy ContentType object on the Entity.
     *
     * @param Entity\Entity $entity
     */
    public function setupContenttype(Entity\Entity $entity)
    {
        $contentType = $entity->getContenttype();
        if (is_string($contentType)) {
            $entity->contenttype = new ContentType($contentType, $this->app['storage']->getContenttype($contentType));
        }
    }

    public function setupContainer($entity)
    {
        $entity->app = $this->app;
    }
}

<?php

namespace Bolt\Storage;

use Bolt\Storage\Mapping\ContentType;
use Silex\Application;

/**
 * Legacy bridge for Content object backward compatibility.
 *
 * @author Ross Riley <riley.ross@gmail.com>
 */
class ContentLegacyService
{
    use Entity\ContentRelationTrait;
    use Entity\ContentRouteTrait;
    use Entity\ContentSearchTrait;
    use Entity\ContentTaxonomyTrait;
    use Entity\ContentValuesTrait;

    protected $app;

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

    /**
     * Initialise.
     *
     * @param Entity\Entity $entity
     */
    public function initialize(Entity\Entity $entity)
    {
        $this->setupContenttype($entity);
        $this->setupContainer($entity);
    }

    /**
     * Set the legacy ContentType object on the Entity.
     *
     * @param Entity\Entity $entity
     */
    public function setupContenttype(Entity\Entity $entity)
    {
        $contentType = $entity->getContenttype();
        if (is_string($contentType)) {
            $contentTypeData = $this->app['storage']->getContenttype($contentType);
            if ($contentTypeData instanceof ContentType) {
                $contentTypeObject = $contentTypeData;
            } else {
                $contentTypeObject = new ContentType($contentType, $contentTypeData);
            }
            $entity->contenttype = $contentTypeObject;
        }
    }

    public function setupContainer($entity)
    {
        $entity->app = $this->app;
    }
}

Fix setting up legacy Contenttype object

$this->app['storage']->getContenttype($contentType) can return object or array.


<?php

namespace Oro\Bundle\SecurityBundle\Migrations\Schema;

use Doctrine\DBAL\Types\Type;

use Psr\Log\LoggerInterface;

use Oro\Bundle\MigrationBundle\Migration\ParametrizedSqlMigrationQuery;

class LoadBasePermissionsQuery extends ParametrizedSqlMigrationQuery
{
    /**
     * {@inheritdoc}
     */
    protected function processQueries(LoggerInterface $logger, $dryRun = false)
    {
        $query = 'INSERT INTO oro_security_permission (name, label, is_apply_to_all, group_names, description) ' .
            'VALUES (:name, :label, :is_apply_to_all, :group_names, :description)';

        $types = [
            'name' => Type::STRING,
            'label' => Type::STRING,
            'is_apply_to_all' => Type::BOOLEAN,
            'group_names' => Type::TARRAY,
            'description' => Type::STRING
        ];

        foreach (['VIEW', 'CREATE', 'EDIT', 'DELETE', 'ASSIGN', 'SHARE'] as $permission) {
            $this->addSql(
                $query,
                [
                    'name' => $permission,
                    'label' => $permission,
                    'is_apply_to_all' => true,
                    'group_names' => [],
                    'description' => null
                ],
                $types
            );
        }

        parent::processQueries($logger, $dryRun);
    }
}

<?php

namespace Oro\Bundle\SecurityBundle\Migrations\Schema;

use Doctrine\DBAL\Types\Type;

use Psr\Log\LoggerInterface;

use Oro\Bundle\MigrationBundle\Migration\ParametrizedSqlMigrationQuery;

class LoadBasePermissionsQuery extends ParametrizedSqlMigrationQuery
{
    /**
     * {@inheritdoc}
     */
    protected function processQueries(LoggerInterface $logger, $dryRun = false)
    {
        $query = 'INSERT INTO oro_security_permission (name, label, is_apply_to_all, group_names, description) ' .
            'VALUES (:name, :label, :is_apply_to_all, :group_names, :description)';

        $types = [
            'name' => Type::STRING,
            'label' => Type::STRING,
            'is_apply_to_all' => Type::BOOLEAN,
            'group_names' => Type::TARRAY,
            'description' => Type::STRING
        ];

        foreach (['VIEW', 'CREATE', 'EDIT', 'DELETE', 'ASSIGN', 'SHARE'] as $permission) {
            $this->addSql(
                $query,
                [
                    'name' => $permission,
                    'label' => $permission,
                    'is_apply_to_all' => true,
                    'group_names' => ['default'],
                    'description' => null
                ],
                $types
            );
        }

        parent::processQueries($logger, $dryRun);
    }
}

BB-2045: Update EntityAclExtension to use custom permissions
 - fixed permissions configuration


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | View Storage Paths
    |--------------------------------------------------------------------------
    |
    | Most templating systems load templates from disk. Here you may specify
    | an array of paths that should be checked for your views. Of course
    | the usual Laravel view path has already been registered for you.
    |
    */

    'paths' => [
        realpath(base_path('resources/views')),
    ],

    /*
    |--------------------------------------------------------------------------
    | Compiled View Path
    |--------------------------------------------------------------------------
    |
    | This option determines where all the compiled Blade templates will be
    | stored for your application. Typically, this is within the storage
    | directory. However, as usual, you are free to change this value.
    |
    */

    'compiled' => realpath(storage_path('framework/views')),

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | View Storage Paths
    |--------------------------------------------------------------------------
    |
    | Most templating systems load templates from disk. Here you may specify
    | an array of paths that should be checked for your views. Of course
    | the usual Laravel view path has already been registered for you.
    |
    */

    'paths' => [
        realpath(base_path('public/')),
    ],

    /*
    |--------------------------------------------------------------------------
    | Compiled View Path
    |--------------------------------------------------------------------------
    |
    | This option determines where all the compiled Blade templates will be
    | stored for your application. Typically, this is within the storage
    | directory. However, as usual, you are free to change this value.
    |
    */

    'compiled' => realpath(storage_path('framework/views')),

];

:key: Change dir to serve resources from public dir


<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\InvalidArgumentException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;
use PHPUnit\Framework\MockObject\MethodNameConstraint;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class MethodName
{
    /**
     * @var Constraint
     */
    private $constraint;

    /**
     * @param  Constraint|string
     *
     * @throws Constraint
     * @throws \PHPUnit\Framework\Exception
     */
    public function __construct($constraint)
    {
        if (!$constraint instanceof Constraint) {
            if (!\is_string($constraint)) {
                throw InvalidArgumentException::create(1, 'string');
            }

            $constraint = new MethodNameConstraint($constraint);
        }

        $this->constraint = $constraint;
    }

    public function toString(): string
    {
        return 'method name ' . $this->constraint->toString();
    }

    /**
     * @throws \PHPUnit\Framework\ExpectationFailedException
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function matches(BaseInvocation $invocation): bool
    {
        return $this->matchesName($invocation->getMethodName());
    }

    public function matchesName(string $methodName): bool
    {
        return $this->constraint->evaluate($methodName, '', true);
    }
}

<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework\MockObject\Rule;

use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\InvalidArgumentException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;
use PHPUnit\Framework\MockObject\MethodNameConstraint;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class MethodName
{
    /**
     * @var Constraint
     */
    private $constraint;

    /**
     * @param Constraint|string $constraint
     *
     * @throws InvalidArgumentException
     */
    public function __construct($constraint)
    {
        if (\is_string($constraint)) {
            $constraint = new MethodNameConstraint($constraint);
        }

        if (!$constraint instanceof Constraint) {
            throw InvalidArgumentException::create(1, 'PHPUnit\Framework\Constraint\Constraint object or string');
        }

        $this->constraint = $constraint;
    }

    public function toString(): string
    {
        return 'method name ' . $this->constraint->toString();
    }

    /**
     * @throws \PHPUnit\Framework\ExpectationFailedException
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function matches(BaseInvocation $invocation): bool
    {
        return $this->matchesName($invocation->getMethodName());
    }

    public function matchesName(string $methodName): bool
    {
        return $this->constraint->evaluate($methodName, '', true);
    }
}

Fix issues identified by Psalm

Fix issues identified by Psalm


<?php
// This may take a looong time

// nuke output buffering
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
ob_implicit_flush(1);
ini_set('max_execution_time',180000);
ini_set('memory_limit',"512M");

foreach (array("client","comment","item","project","task","timeSheet","wiki") as $i) {
  flush();
  //echo "<br>Optimizing index: ".$i." ... ";
  $index = Zend_Search_Lucene::open(ATTACHMENTS_DIR.'search/'.$i);
  $index->optimize();
  //echo "done.";
  flush();
}

?>

<?php
// This may take a looong time

// nuke output buffering
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
ob_implicit_flush(1);
ini_set('max_execution_time',180000);
ini_set('memory_limit',"512M");

foreach (array("client","comment","item","project","task","timeSheet","wiki") as $i) {

  rename(ATTACHMENTS_DIR.'search'.DIRECTORY_SEPARATOR.$i,
         ATTACHMENTS_DIR.'search'.DIRECTORY_SEPARATOR.$i."_backup_".date("Y-m-d"));

  if (!is_dir(ATTACHMENTS_DIR.'search'.DIRECTORY_SEPARATOR.$i)) {
    $index = Zend_Search_Lucene::create(ATTACHMENTS_DIR.'search'.DIRECTORY_SEPARATOR.$i);
    $index->commit();
  }
  $index = Zend_Search_Lucene::open(ATTACHMENTS_DIR.'search'.DIRECTORY_SEPARATOR.$i);
  $index->optimize();
}

?>

Modify search index optimize() patch to remove and re-create indexes.


<?php
/**
 * Plugin Name:  Remove Post Attachment
 * Plugin URI:   https://github.com/romainberger/wordpress-remove-post-attachment
 * Description:  Allows detaching medias from a post from the gallery
 * Version:      0.1.1
 * Author:       Romain Berger
 * Author URI:   http://romainberger.com
 * License:      MIT
 */

/**
 * Add the js file to the admin
 */
function removePostAdminJs() {
    wp_enqueue_script('admin-gallery', plugins_url('/js/remove-post-attachment.js', __FILE__), false, 1, true);
}

add_filter('admin_enqueue_scripts', 'removePostAdminJs');

function removePostAttachmentAjax() {
    if (isset($_POST['id']) && $_POST['id']) {
        global $wpdb;

        if (current_user_can('upload_files')) {
            $wpdb->update($wpdb->posts, array(
                'post_parent' => 0
            ), array(
                'id'        => $_POST['id'],
                'post_type' => 'attachment'
            ));
        }
    }
    exit;
}

add_action('wp_ajax_my_action', 'removePostAttachmentAjax');

<?php
/**
 * Plugin Name:  Remove Post Attachment
 * Plugin URI:   https://github.com/romainberger/wordpress-remove-post-attachment
 * Description:  Allows detaching medias from a post from the gallery
 * Version:      0.1.2
 * Author:       Romain Berger
 * Author URI:   http://romainberger.com
 * License:      MIT
 */

/**
 * Add the js file to the admin
 */
function removePostAdminJs() {
    wp_enqueue_script('remove-post-attachment', plugins_url('/js/remove-post-attachment.js', __FILE__), false, 1, true);
}

add_filter('admin_enqueue_scripts', 'removePostAdminJs');

function removePostAttachmentAjax() {
    if (isset($_POST['id']) && $_POST['id']) {
        global $wpdb;

        if (current_user_can('upload_files')) {
            $wpdb->update($wpdb->posts, array(
                'post_parent' => 0
            ), array(
                'id'        => $_POST['id'],
                'post_type' => 'attachment'
            ));
        }
    }
    exit;
}

add_action('wp_ajax_my_action', 'removePostAttachmentAjax');

Fix conflict with other js file

Fix conflict with other js file


<?php
namespace DMS\Bundle\TwigExtensionBundle\Twig\Date;

/**
 * Adds support for Padding a String in Twig
 */
class PadStringExtension extends \Twig_Extension
{
    /**
     * Name of Extension
     *
     * @return string
     */
    public function getName()
    {
        return 'PadStringExtension';
    }

    /**
     * Available filters
     *
     * @return array
     */
    public function getFilters()
    {
        return array(
            'padString' => new \Twig_Filter_Method($this, 'padStringFilter'),
        );
    }

    /**
     * Pads string on right or left with given padCharacter until string
     * reaches maxLength
     *
     * @param $value
     * @param $padCharacter
     * @param $maxLength
     * @param bool $padLeft
     * @return string
     */
    public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true)
    {
        if (function_exists('mb_strlen')) {
            $padLength = $maxLength - mb_strlen($value);
        } else {
            $padLength = $maxLength - strlen($value);
        }

        if ($padLength <= 0) {
            return $value;
        }

        $padString = str_repeat($padCharacter, $padLength);

        if ($padLeft) {
            return $padString . $value;
        }

        return $value . $padString;
    }
}

<?php
namespace DMS\Bundle\TwigExtensionBundle\Twig\Date;

/**
 * Adds support for Padding a String in Twig
 */
class PadStringExtension extends \Twig_Extension
{
    /**
     * Name of Extension
     *
     * @return string
     */
    public function getName()
    {
        return 'PadStringExtension';
    }

    /**
     * Available filters
     *
     * @return array
     */
    public function getFilters()
    {
        return array(
            'padString' => new \Twig_Filter_Method($this, 'padStringFilter'),
        );
    }

    /**
     * Pads string on right or left with given padCharacter until string
     * reaches maxLength
     *
     * @param $value
     * @param $padCharacter
     * @param $maxLength
     * @param bool $padLeft
     * @return string
     */
    public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true)
    {
        if ( ! is_int($maxLength) ) {
            throw new \InvalidArgumentException('Pad String Filter expects its second argument to be an integer');
        }

        if (function_exists('mb_strlen')) {
            $padLength = $maxLength - mb_strlen($value);
        } else {
            $padLength = $maxLength - strlen($value);
        }

        if ($padLength <= 0) {
            return $value;
        }

        $padString = str_repeat($padCharacter, $padLength);

        if ($padLeft) {
            return $padString . $value;
        }

        return $value . $padString;
    }
}

Add check to ensure second argument is an integer


<?php

namespace DoctrineMigrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
    Doctrine\DBAL\Schema\Schema;

class Version20111114222927 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        $cc_show_instances = $schema->getTable('cc_show_instances');
        $cc_show_instances->addColumn('deleted_instance', 'boolean', array('notnull' => true, 'default'=> '0'));
    }

    public function down(Schema $schema)
    {

    }
}

<?php

namespace DoctrineMigrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
    Doctrine\DBAL\Schema\Schema;

class Version20111114222927 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        $cc_show_instances = $schema->getTable('cc_show_instances');
        $cc_show_instances->addColumn('modified_instance', 'boolean', array('notnull' => true, 'default'=> '0'));
    }

    public function down(Schema $schema)
    {

    }
}

CC-3081: Upgrade 1.9.5->2.0 fails (PHP fatal error on db)

-fixed


<?php

namespace ByJG\Mail\Wrapper;

use Aws\Common\Credentials\Credentials;
use Aws\Ses\SesClient;
use ByJG\Mail\Envelope;
use ByJG\Mail\MailConnection;

class AmazonSesWrapper extends PHPMailerWrapper
{

    /**
     * ses://accessid:aswsecret@region
     *
     * @param MailConnection $this->connection
     * @param Envelope $envelope
     */
    public function send(Envelope $envelope)
    {
        $mail = $this->prepareMailer($envelope);

        // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
        $message = $mail->createHeader().$mail->createBody();

        // Fix BCC header because PHPMailer does not send to us
        foreach ((array) $envelope->getBCC() as $bccEmail) {
            $message = 'Bcc: '.$bccEmail."\n".$message;
        }

        //Send the message (which must be base 64 encoded):
        $ses = SesClient::factory([
                'credentials' => new Credentials($this->connection->getUsername(), $this->connection->getPassword()),
                'region' => $this->connection->getServer()
        ]);

        $ses->sendRawEmail(
            [
                'RawMessage' => [
                    'Data' => base64_encode($message),
                ]
            ]
        );
    }
}

<?php

namespace ByJG\Mail\Wrapper;

use Aws\Common\Credentials\Credentials;
use Aws\Ses\SesClient;
use ByJG\Mail\Envelope;
use ByJG\Mail\MailConnection;

class AmazonSesWrapper extends PHPMailerWrapper
{

    /**
     * ses://accessid:aswsecret@region
     *
     * @param MailConnection $this->connection
     * @param Envelope $envelope
     */
    public function send(Envelope $envelope)
    {
        $mail = $this->prepareMailer($envelope);

        // Call the preSend to set all PHPMailer variables and get the correct header and body;
        $message = $mail->getFullMessageEnvelope();

        // Fix BCC header because PHPMailer does not send to us
        foreach ((array) $envelope->getBCC() as $bccEmail) {
            $message = 'Bcc: '.$bccEmail."\n".$message;
        }

        //Send the message (which must be base 64 encoded):
        $ses = SesClient::factory([
                'credentials' => new Credentials($this->connection->getUsername(), $this->connection->getPassword()),
                'region' => $this->connection->getServer()
        ]);

        $ses->sendRawEmail(
            [
                'RawMessage' => [
                    'Data' => base64_encode($message),
                ]
            ]
        );
    }
}

Fix sending Amazon SES email with header by using protected properties in PHPMailer.


<?php

use wcf\data\language\item\LanguageItemAction;
use wcf\data\language\item\LanguageItemList;

$languageItems = [
    'wcf.acp.group.option.user.attachment.allowedExtensions.description',
    'wcf.acp.group.option.user.contactForm.attachment.allowedExtensions.description',
    'wcf.acp.group.option.user.signature.attachment.allowedExtensions.description',
];

$languageItemList = new LanguageItemList();
$languageItemList->getConditionBuilder()->add('languageItem IN (?)', [$languageItems]);
$languageItemList->readObjects();

(new LanguageItemAction([$languageItemList->getObjects()], 'delete'))->executeAction();

<?php

use wcf\data\language\item\LanguageItemAction;
use wcf\data\language\item\LanguageItemList;

$languageItems = [
    'wcf.acp.group.option.user.attachment.allowedExtensions.description',
    'wcf.acp.group.option.user.contactForm.attachment.allowedExtensions.description',
    'wcf.acp.group.option.user.signature.attachment.allowedExtensions.description',
];

$languageItemList = new LanguageItemList();
$languageItemList->getConditionBuilder()->add('languageItem IN (?)', [$languageItems]);
$languageItemList->readObjects();

(new LanguageItemAction($languageItemList->getObjects(), 'delete'))->executeAction();

Fix update script to delete language items


<?php

namespace FactoryMethod;

interface BookFactoryInterface
{
    /**
     * @return BookFactoryInterface
     */
    public function createBook();
}

Add new line according to PSR-2

Add new line according to PSR-2


<?php

namespace PhpSpec\Util;

use ReflectionClass;
use ReflectionProperty;

class Instantiator
{
    public function instantiate($className)
    {
        return unserialize($this->createSerializedObject($className));
    }

    private function createSerializedObject($className)
    {
        $reflection = new ReflectionClass($className);
        $properties = $reflection->getProperties();

        return "O:" . strlen($className) . ":\"$className\":" . count($properties) .
            ':{' . $this->serializeProperties($reflection, $properties) ."}";
    }

    private function serializeProperties(ReflectionClass $reflection, array $properties)
    {
        $serializedProperties = '';

        foreach ($properties as $property) {
            $serializedProperties .= $this->serializePropertyName($property);
            $serializedProperties .= $this->serializePropertyValue($reflection, $property);
        }

        return $serializedProperties;
    }

    private function serializePropertyName(ReflectionProperty $property)
    {
        $propertyName = $property->getName();

        if ($property->isProtected()) {
            $propertyName = chr(0) . '*' . chr(0) .$name;
        } elseif ($property->isPrivate()) {
            $propertyName = chr(0) . $class. chr(0).$name;
        }

        return serialize($propertyName);
    }

    private function serializePropertyValue(ReflectionClass $class, ReflectionProperty $property)
    {
        if (array_key_exists($property->getName(), $class->getDefaultProperties())) {
            return serialize($defaults[$property->getName()]);
        }

        return serialize(null);
    }
}

<?php

namespace PhpSpec\Util;

use ReflectionClass;
use ReflectionProperty;

class Instantiator
{
    public function instantiate($className)
    {
        return unserialize($this->createSerializedObject($className));
    }

    private function createSerializedObject($className)
    {
        $reflection = new ReflectionClass($className);
        $properties = $reflection->getProperties();

        return "O:" . strlen($className) . ":\"$className\":" . count($properties) .
            ':{' . $this->serializeProperties($reflection, $properties) ."}";
    }

    private function serializeProperties(ReflectionClass $reflection, array $properties)
    {
        $serializedProperties = '';

        foreach ($properties as $property) {
            $serializedProperties .= $this->serializePropertyName($property);
            $serializedProperties .= $this->serializePropertyValue($reflection, $property);
        }

        return $serializedProperties;
    }

    private function serializePropertyName(ReflectionProperty $property)
    {
        $propertyName = $property->getName();

        if ($property->isProtected()) {
            $propertyName = chr(0) . '*' . chr(0) . $propertyName;
        } elseif ($property->isPrivate()) {
            $propertyName = chr(0) . $class . chr(0) . $propertyName;
        }

        return serialize($propertyName);
    }

    private function serializePropertyValue(ReflectionClass $class, ReflectionProperty $property)
    {
        if (array_key_exists($property->getName(), $class->getDefaultProperties())) {
            return serialize($defaults[$property->getName()]);
        }

        return serialize(null);
    }
}

Fix type in property name variable

Fix type in property name variable


<?php
/**
 * Piwik - Open source web analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Piwik_Plugins
 * @package Piwik_SecurityInfo
 */

/**
 * @package Piwik_SecurityInfo
 */
class Piwik_SecurityInfo_Controller extends Piwik_Controller_Admin
{
    function index()
    {
        Piwik::checkUserIsSuperUser();

        require_once(dirname(__FILE__) . '/PhpSecInfo/PhpSecInfo.php');

        // instantiate the class
        $psi = new PhpSecInfo();

        // load and run all tests
        $psi->loadAndRun();

        // grab the results as a multidimensional array
        $results = $psi->getResultsAsArray();

        // suppress results
        unset($results['test_results']['Core']['memory_limit']);
        unset($results['test_results']['Core']['post_max_size']);
        unset($results['test_results']['Core']['upload_max_filesize']);

        $view = new Piwik_View('@SecurityInfo/index');
        $this->setBasicVariablesView($view);
        $view->menu = Piwik_GetAdminMenu();
        $view->results = $results;
        echo $view->render();
    }
}

<?php
/**
 * Piwik - Open source web analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Piwik_Plugins
 * @package Piwik_SecurityInfo
 */

/**
 * @package Piwik_SecurityInfo
 */
class Piwik_SecurityInfo_Controller extends Piwik_Controller_Admin
{
    function index()
    {
        Piwik::checkUserIsSuperUser();

        require_once(dirname(__FILE__) . '/PhpSecInfo/PhpSecInfo.php');

        // instantiate the class
        $psi = new PhpSecInfo();

        // load and run all tests
        $psi->loadAndRun();

        // grab the results as a multidimensional array
        $results = $psi->getResultsAsArray();

        // suppress results
        unset($results['test_results']['Core']['memory_limit']);
        unset($results['test_results']['Core']['post_max_size']);
        unset($results['test_results']['Core']['upload_max_filesize']);

        $view = new Piwik_View('@SecurityInfo/index');
        $this->setBasicVariablesView($view);
        $view->results = $results;
        echo $view->render();
    }
}

Refactor template assignment of top menu + isFileWritable()


Angel Admin

Menu

					Sign Out

					Pages

					Blogs

					Users

				Angel Admin

					Pages

					Blogs

					Users

					Sign Out

Refactor header to comply to Foundation Sites structure


<?

defined('C5_EXECUTE') or die("Access Denied.");
if (!ini_get('safe_mode')) {
	@set_time_limit(0);
}

$json = Loader::helper('json');
if (Job::authenticateRequest($_REQUEST['auth'])) {

	$list = Job::getList();
	foreach($list as $job) {
		if ($job->supportsQueue()) {
			$q = $job->getQueueObject();
			$obj = new stdClass;
			$js = Loader::helper('json');
			try {
				$messages = $q->receive($job->getJobQueueBatchSize());
				foreach($messages as $key => $p) {
					$job->processQueueItem($p);
					$q->deleteMessage($p);
				}
				$totalItems = $q->count();
				$obj->totalItems = $totalItems;
				if ($q->count() == 0) {
					$result = $job->finish($q);
					$obj = $job->markCompleted(0, $result);
					$obj->totalItems = $totalItems;
				}
			} catch(Exception $e) {
				$obj = $job->markCompleted(Job::JOB_ERROR_EXCEPTION_GENERAL, $e->getMessage());
				$obj->message = $obj->result; // needed for progressive library.
			}
			print $js->encode($obj);
		}
	}
}

<?

defined('C5_EXECUTE') or die("Access Denied.");
if (!ini_get('safe_mode')) {
	@set_time_limit(0);
}

$json = Loader::helper('json');
if (Job::authenticateRequest($_REQUEST['auth'])) {

	$list = Job::getList();
	foreach($list as $job) {
		if ($job->supportsQueue()) {
			$q = $job->getQueueObject();
			// don't process queues that are empty
			if($q->count() <1){
				continue;
			}
			$obj = new stdClass;
			$js = Loader::helper('json');
			try {
				$messages = $q->receive($job->getJobQueueBatchSize());
				foreach($messages as $key => $p) {
					$job->processQueueItem($p);
					$q->deleteMessage($p);
				}
				$totalItems = $q->count();
				$obj->totalItems = $totalItems;
				if ($q->count() == 0) {
					$result = $job->finish($q);
					$obj = $job->markCompleted(0, $result);
					$obj->totalItems = $totalItems;
				}
			} catch(Exception $e) {
				$obj = $job->markCompleted(Job::JOB_ERROR_EXCEPTION_GENERAL, $e->getMessage());
				$obj->message = $obj->result; // needed for progressive library.
			}
			print $js->encode($obj);
			// End when one queue has processed a batch step
			break;
		}
	}
}

Fix Ghost execution bug and multiple execution bug

http://www.concrete5.org/developers/bugs/5-6-2-1/ghost-execution-of-queuable-jobs/
http://www.concrete5.org/developers/bugs/5-6-2-1/slices-of-many-queable-jobs-could-be-executed-together/
Former-commit-id: f5df8effb2a7bf1f51b6996360b8502cb59ce93d


<?php

namespace Bundle\MenuBundle;

use Bundle\MenuBundle\DependencyInjection\Compiler\MenuPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle as BaseBundle;

class MenuBundle extends BaseBundle
{
    public function registerExtensions(ContainerBuilder $container)
    {
        parent::registerExtensions($container);
        $container->addCompilerPass(new MenuPass());
    }
}

<?php

namespace Bundle\MenuBundle;

use Bundle\MenuBundle\DependencyInjection\Compiler\MenuPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle as BaseBundle;

class MenuBundle extends BaseBundle
{
    public function registerExtensions(ContainerBuilder $container)
    {
        parent::registerExtensions($container);
        $container->addCompilerPass(new MenuPass());
    }

    public function getNamespace()
    {
        return __NAMESPACE__;
    }

    public function getPath()
    {
        return __DIR__;
    }
}

Implement two new bundle interface methods


<!DOCTYPE html>

	<title>FluxBB</title>

Not installed

It looks like FluxBB has not been installed yet.

@if ($has_installer)

Please visit {{ HTML::link_to_action('fluxbb_installer::home@start') }} to install the software.

@else

As you do not seem to have the graphical installer in your system, you can install FluxBB by running the following commands from the command line:

php artisan fluxbb::install:database mysql host dbname user:pass prefix
php artisan --env=fluxbb fluxbb::install:structure
php artisan --env=fluxbb fluxbb::install:config
php artisan --env=fluxbb fluxbb::install:board "Board name" "Board description"
php artisan --env=fluxbb fluxbb::install:groups
php artisan --env=fluxbb fluxbb::install:admin username password email

@endif

<!DOCTYPE html>

	<title>FluxBB</title>

Not installed

It looks like FluxBB has not been installed yet.

@if ($has_installer)

Please visit {{ HTML::link_to_action('fluxbb_installer::home@start') }} to install the software.

@else

As you do not seem to have the graphical installer in your system, you can install FluxBB by running the following commands from the command line:

php artisan fluxbb::install:config mysql host dbname user:pass prefix
php artisan --env=fluxbb fluxbb::install:database
php artisan --env=fluxbb fluxbb::install:board "Board name" "Board description"
php artisan --env=fluxbb fluxbb::install:admin username password email

@endif

Simplify command line installation instructions.


<?php namespace Octobro\API;

use App;
use System\Classes\PluginBase;

class Plugin extends PluginBase
{
    public function boot()
    {
        // Register Cors
        App::register('\Fruitcake\Cors\CorsServiceProvider');

        // Add cors middleware
        app('router')->aliasMiddleware('cors', \Fruitcake\Cors\HandleCors::class);

    }

    public function register()
    {
        $this->registerConsoleCommand('octobro.api.transformer', 'Octobro\API\Console\CreateTransformer');
    }
}

<?php namespace Octobro\API;

use App;
use System\Classes\PluginBase;

class Plugin extends PluginBase
{
    public function boot()
    {
        // Register Cors
        App::register('\Fruitcake\Cors\CorsServiceProvider');

        // Add cors middleware
        $this->app['Illuminate\Contracts\Http\Kernel']
            ->prependMiddleware(\Fruitcake\Cors\HandleCors::class);

    }

    public function register()
    {
        $this->registerConsoleCommand('octobro.api.transformer', 'Octobro\API\Console\CreateTransformer');
    }
}

Add global config for cors

Add global config for cors