<?php

namespace DTR\DTRBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ShopType
 *
 * @ORM\Table(name="shoptype")
 * @ORM\Entity
 */
class ShopType
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return ShopType
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

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

//Table created

Create table in the database via console.


<?php
$quotes = [
    "Les serveurs se frisent les moustaches",
    "Faut pas pousser mémé dans les orties",
    "On avait un peu de gras sur France Loisirs, mais on va jongler",
    "C'est à la fin de la foire qu'on compte les bouses",
    "Je tente même pas le plan B, je passe au plan Z",
    "De toute façon c'est pas la taille qui compte, c'est le coefficient de dilatation",
    "Si vous avez le coeur sur la main, vous devez avoir les fesses à une drôle de place",
    "Faut pas se mettre la rate au court-bouillon !",
    "Ce n'est pas aux vieux singes qu'on apprend à faire la grimace",
    "C'est une orthodoxie à géométrie variable ce machin.",
    "On a en tout autour du bide des serveurs.",
    "C'est la foire d'empoigne !",
    "Ils savent faire de l'informatique comme moi je parle serbo-croate du nord.",
    "Faudrait pas qu'il se gratte tout seul la biscotte dans son coin.",
    "Airbrake marche pas, il a l'air brake.",
    "Ici, Dieu c'est moi.",
    "Je men tape le coquillard.",
];

<?php
$quotes = [
    "Les serveurs se frisent les moustaches",
    "Faut pas pousser mémé dans les orties",
    "On avait un peu de gras sur France Loisirs, mais on va jongler",
    "C'est à la fin de la foire qu'on compte les bouses",
    "Je tente même pas le plan B, je passe au plan Z",
    "De toute façon c'est pas la taille qui compte, c'est le coefficient de dilatation",
    "Si vous avez le coeur sur la main, vous devez avoir les fesses à une drôle de place",
    "Faut pas se mettre la rate au court-bouillon !",
    "Ce n'est pas aux vieux singes qu'on apprend à faire la grimace",
    "C'est une orthodoxie à géométrie variable ce machin.",
    "On a en tout autour du bide des serveurs.",
    "C'est la foire d'empoigne !",
    "Ils savent faire de l'informatique comme moi je parle serbo-croate du nord.",
    "Faudrait pas qu'il se gratte tout seul la biscotte dans son coin.",
    "Airbrake marche pas, il a l'air brake.",
    "Ici, Dieu c'est moi.",
    "Je men tape le coquillard.",
    "C'est pas ceinture-bretelles, c'est ceinture-bretelles-parachute",
];

Add new quote for botzac

Add new quote for botzac


<?php

namespace Demontpx\UtilBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * @copyright 2014 Bert Hekman
 */
class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('demontpx_util');
        $rootNode = $treeBuilder->getRootNode();

        $rootNode->children()
            ->booleanNode('testing')->defaultFalse()->end()
        ->end();

        return $treeBuilder;
    }
}

<?php

namespace Demontpx\UtilBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * @copyright 2014 Bert Hekman
 */
class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('demontpx_util');
        /** @var ArrayNodeDefinition $rootNode */
        $rootNode = $treeBuilder->getRootNode();

        $rootNode->children()
            ->booleanNode('testing')->defaultFalse()->end()
        ->end();

        return $treeBuilder;
    }
}

Add type hint to $rootNode

Add type hint to $rootNode


<?php

namespace Omnipay\WechatPay\Message;

use Omnipay\Common\Message\AbstractResponse;

/**
 * Class CompletePurchaseResponse
 * @package Omnipay\WechatPay\Message
 * @link    https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=9_1
 *
 */
class CompletePurchaseResponse extends AbstractResponse
{

    /**
     * Is the response successful?
     *
     * @return boolean
     */
    public function isSuccessful()
    {
        return $this->isPaid();
    }

    public function isSignMatch()
    {
        $data = $this->getData();

        return $data['sign_match'];
    }

    public function isPaid()
    {
        $data = $this->getData();

        return $data['paid'];
    }

    public function getData()
    {
        return $this->request->getData();
    }
}

<?php

namespace Omnipay\WechatPay\Message;

use Omnipay\Common\Message\AbstractResponse;

/**
 * Class CompletePurchaseResponse
 * @package Omnipay\WechatPay\Message
 * @link    https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=9_1
 *
 */
class CompletePurchaseResponse extends AbstractResponse
{

    /**
     * Is the response successful?
     *
     * @return boolean
     */
    public function isSuccessful()
    {
        return $this->isPaid();
    }

    public function isSignMatch()
    {
        $data = $this->getData();

        return $data['sign_match'];
    }

    public function isPaid()
    {
        $data = $this->getData();

        return $data['paid'];
    }

    public function getRequestData()
    {
        return $this->request->getData();
    }
}

Add getData method to get notify data

Add getData method to get notify data


<?php

class SiteController extends Controller
{
	public $layout = 'column1';

	/**
	 * Displays the front page.
	 */
	public function actionIndex()
	{
		$this->redirect(array('/auth/assignment/index'));
	}

	/**
	 * Resets the database for the demo application.
	 */
	public function actionReset()
	{
		/* @var $db CDbConnection */
		$db = Yii::app()->getComponent('db');
		$filename = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'schema.sql';
		if (file_exists($filename))
		{
			$schema = file_get_contents($filename);
			$schema = preg_split("/;\s+/", trim($schema, ';'));
			foreach ($schema as $sql)
				$db->createCommand($sql)->execute();
		}
		Yii::app()->user->setFlash('success', 'Demo reset.');
		$this->redirect(array('index'));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if ($error = Yii::app()->errorHandler->error)
		{
			if (Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}
}

<?php

class SiteController extends Controller
{
	public $layout = 'column1';

	/**
	 * Displays the front page.
	 */
	public function actionIndex()
	{
		$this->redirect(array('/auth/assignment/index'));
	}

	/**
	 * Resets the database for the demo application.
	 */
	public function actionReset()
	{
		/* @var $db CDbConnection */
		$db = Yii::app()->getComponent('db');
		$filename = dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'schema.sql';
		if (file_exists($filename))
		{
			$schema = file_get_contents($filename);
			$schema = preg_split("/;\s+/", trim($schema, ';'));
			foreach ($schema as $sql)
				$db->createCommand($sql)->execute();
		}
		Yii::app()->user->setFlash('success', 'Demo reset.');
		$this->redirect(array('index'));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if ($error = Yii::app()->errorHandler->error)
		{
			if (Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}
}

Change to use dirname instead of __DIR__


<?php
/**
 * Created by PhpStorm.
 * User: andela
 * Date: 8/6/15
 * Time: 1:55 PM
 */

use Illuminate\Database\Seeder;
use ChopBox\User;
use Faker\Factory;

class UserTableSeeder extends Seeder {

    public function run() {
        $faker = Factory::create();
        //User::truncate();
        foreach(range(1,50) as $index) {
            User::create([
                'username' => $faker->userName,
                'password' => $faker->password(8, 20),
                'email' => $faker->email,
                'profile_state' => $faker->boolean(),
            ]);
        }
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: andela
 * Date: 8/6/15
 * Time: 1:55 PM
 */

use Illuminate\Database\Seeder;
use ChopBox\User;
use Faker\Factory;

class UserTableSeeder extends Seeder {

    public function run() {
        $faker = Factory::create();
        //User::truncate();
        foreach(range(1,50) as $index) {
            User::create([
                'username' => $faker->userName,
                'password' => $faker->password(8, 20),
                'email' => $faker->email,
                'profile_state' => $faker->boolean(),
                'image_uri' => $faker->imageUrl()
            ]);
        }
    }
}

Add seeder for image_uri column of Users table


<?php namespace Dakshhmehta\LaravelValidation;

use Exception;
use Illuminate\Validation\Validator;

class ValidationException extends Exception {
	protected $validation;
	protected $input;

	public function __construct(Validator $validation, array $data = array(), string $message = null){
		$this->code = 400;
		$this->validation = $validation;
		$this->input = $data;

		if($message == null && count($data) > 0){
			foreach($this->validation->getData() as $key => $value){
				if($this->getErrors()->first($key) != null){
					$this->message = 'Input:'.$this->input[$key].'|'.$this->getErrors()->first($key);
					break;
				}
			}
		}
		else {
			$this->message = $this->getErrors()->first();
		}
	}

	public function getErrors(){
		return $this->validation->errors();
	}
}

<?php namespace Dakshhmehta\LaravelValidation\Exceptions;

use Exception;
use Illuminate\Validation\Validator;

class ValidationException extends Exception {
	protected $validation;
	protected $input;

	public function __construct(Validator $validation, array $data = array(), string $message = null){
		$this->code = 400;
		$this->validation = $validation;
		$this->input = $data;

		if($message == null && count($data) > 0){
			foreach($this->validation->getData() as $key => $value){
				if($this->getErrors()->first($key) != null){
					$this->message = 'Input:'.$this->input[$key].'|'.$this->getErrors()->first($key);
					break;
				}
			}
		}
		else {
			$this->message = $this->getErrors()->first();
		}
	}

	public function getErrors(){
		return $this->validation->errors();
	}
}

Fix the validation exception namespace

Fix the validation exception namespace


<?php
namespace wcf\util\exception;
use wcf\system\exception\IExtraInformationException;
use wcf\system\exception\SystemException;
use wcf\util\HTTPRequest;
use wcf\util\StringUtil;

/**
 * Denotes failure to perform a HTTP request.
 *
 * @author	Tim Duesterhus
 * @copyright	2001-2017 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Util\Exception
 * @since	3.0
 */
class HTTPException extends SystemException implements IExtraInformationException {
	/**
	 * The HTTP request that lead to this Exception.
	 *
	 * @param	HTTPRequest
	 */
	protected $http = null;

	/**
	 * @inheritDoc
	 */
	public function __construct(HTTPRequest $http, $message, $code = 0, $previous = null) {
		parent::__construct($message, $code, '', $previous);

		$this->http = $http;
	}

	/**
	 * @inheritDoc
	 */
	public function getExtraInformation() {
		$reply = $this->http->getReply();
		$body = StringUtil::truncate(preg_replace('/[\x00-\x1F\x80-\xFF]/', '.', $reply['body']), 80, StringUtil::HELLIP, true);

		return [
			['Body', $body],
			['Status Code', $reply['statusCode']]
		];
	}
}

<?php
namespace wcf\util\exception;
use wcf\system\exception\IExtraInformationException;
use wcf\system\exception\SystemException;
use wcf\util\HTTPRequest;
use wcf\util\StringUtil;

/**
 * Denotes failure to perform a HTTP request.
 *
 * @author	Tim Duesterhus
 * @copyright	2001-2017 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Util\Exception
 * @since	3.0
 */
class HTTPException extends SystemException implements IExtraInformationException {
	/**
	 * The HTTP request that lead to this Exception.
	 *
	 * @param	HTTPRequest
	 */
	protected $http = null;

	/**
	 * @inheritDoc
	 */
	public function __construct(HTTPRequest $http, $message, $code = 0, $previous = null) {
		parent::__construct($message, $code, '', $previous);

		$this->http = $http;
	}

	/**
	 * @inheritDoc
	 */
	public function getExtraInformation() {
		$reply = $this->http->getReply();
		$body = StringUtil::truncate(preg_replace('/[\x00-\x1F\x80-\xFF]/', '.', $reply['body']), 512, StringUtil::HELLIP, true);

		return [
			['Body', $body],
			['Status Code', $reply['statusCode']]
		];
	}
}

Increase length of logged request responses in `HTTPException`


<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Filename
    |--------------------------------------------------------------------------
    |
    | The default path to the helper file
    |
    */

    'filename' => '_ide_helper.php',

    /*
    |--------------------------------------------------------------------------
    | Helper files to include
    |--------------------------------------------------------------------------
    |
    | Include helper files. By default not included, but can be toggled with the
    | -- helpers (-H) option. Extra helper files can be included.
    |
    */

    'include_helpers' => false,

    'helper_files' => array(
        base_path().'/vendor/laravel/framework/src/Illuminate/Support/helpers.php',
    ),

    /*
    |--------------------------------------------------------------------------
    | Extra classes
    |--------------------------------------------------------------------------
    |
    | These implementations are not really extended, but called with magic functions
    |
    */

    'extra' => array(
        'Eloquent'  => array('Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'),
    ),

    'magic' => array(
        'Log' => array(
            'debug'     => 'Monolog\Logger::addDebug',
            'info'      => 'Monolog\Logger::addInfo',
            'notice'    => 'Monolog\Logger::addNotice',
            'warning'   => 'Monolog\Logger::addWarning',
            'error'     => 'Monolog\Logger::addError',
            'critical'  => 'Monolog\Logger::addCritical',
            'alert'     => 'Monolog\Logger::addAlert',
            'emergency' => 'Monolog\Logger::addEmergency',
        )
    )

);

<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Filename
    |--------------------------------------------------------------------------
    |
    | The default path to the helper file
    |
    */

    'filename' => '_ide_helper.php',

    /*
    |--------------------------------------------------------------------------
    | Helper files to include
    |--------------------------------------------------------------------------
    |
    | Include helper files. By default not included, but can be toggled with the
    | -- helpers (-H) option. Extra helper files can be included.
    |
    */

    'include_helpers' => false,

    'helper_files' => array(
        base_path().'/vendor/laravel/framework/src/Illuminate/Support/helpers.php',
    ),

    /*
    |--------------------------------------------------------------------------
    | Extra classes
    |--------------------------------------------------------------------------
    |
    | These implementations are not really extended, but called with magic functions
    |
    */

    'extra' => array(
        'Eloquent'  => array('Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'),
        'Session' => array('Illuminate\Session\Store'),
    ),

    'magic' => array(
        'Log' => array(
            'debug'     => 'Monolog\Logger::addDebug',
            'info'      => 'Monolog\Logger::addInfo',
            'notice'    => 'Monolog\Logger::addNotice',
            'warning'   => 'Monolog\Logger::addWarning',
            'error'     => 'Monolog\Logger::addError',
            'critical'  => 'Monolog\Logger::addCritical',
            'alert'     => 'Monolog\Logger::addAlert',
            'emergency' => 'Monolog\Logger::addEmergency',
        )
    )

);

Add SessionStore to Session Facade

Add SessionStore to Session Facade

Because of changes to the session facade. Fixes #37


<?php
/**
 * Quafzi_CustomerPaymentFilter_Model_Observer
 *
 * @category    Payment
 * @package     Quafzi_CustomerPaymentFilter
 * @author      Thomas Birke <tbirke@netextreme.de>
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
class Quafzi_CustomerPaymentFilter_Model_Observer
{
    public function paymentMethodIsAllowed($observer)
    {
        $checkResult = $observer->getEvent()->getResult();
        $method      = $observer->getEvent()->getMethodInstance();
        $quote       = $observer->getEvent()->getQuote();

        if ($checkResult->isAvailable
            && $quote->getCustomer()
            && $quote->getCustomer()->getId() // customer exists
        ) {
            // if there is no method allowed explicitly, we expect all methods to be allowed
            $allowedMethods = $quote->getCustomer()->getAllowedPaymentMethods();
            if ($allowedMethods) {
                $allowedMethods = explode(',', $allowedMethods);
                if (false === in_array($method->getCode(), $allowedMethods)) {
                    $checkResult->isAvailable = false;
                }
            }
        }
    }
}

<?php
/**
 * Quafzi_CustomerPaymentFilter_Model_Observer
 *
 * @category    Payment
 * @package     Quafzi_CustomerPaymentFilter
 * @author      Thomas Birke <tbirke@netextreme.de>
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
class Quafzi_CustomerPaymentFilter_Model_Observer
{
    public function paymentMethodIsAllowed($observer)
    {
        $checkResult = $observer->getEvent()->getResult();
        $method      = $observer->getEvent()->getMethodInstance();
        $quote       = $observer->getEvent()->getQuote();
        $customer    = Mage::getSingleton('customer/session')->getCustomer();
        if (is_null($customer) || is_null($customer->getId())) {
            if ($quote && $quote->getCustomer() && $quote->getCustomer()->getId()) {
                $customer = $quote->getCustomer();
            }
        }

        if ($checkResult->isAvailable
            && $customer
            && $customer->getId() // customer exists
        ) {
            // if there is no method allowed explicitly, we expect all methods to be allowed
            $allowedMethods = $customer->getAllowedPaymentMethods();
            if ($allowedMethods) {
                $allowedMethods = explode(',', $allowedMethods);
                if (false === in_array($method->getCode(), $allowedMethods)) {
                    $checkResult->isAvailable = false;
                }
            }
        }
    }
}

Allow determining allowed payment methods without having a current quote


<?php
namespace Concrete\Core\Updater\Migrations\Migrations;

use Concrete\Core\Updater\Migrations\AbstractMigration;
use Concrete\Core\Updater\Migrations\RepeatableMigrationInterface;

class Version20190826000000 extends AbstractMigration implements RepeatableMigrationInterface
{
    public function upgradeDatabase()
    {
        /* Refresh youtube block */
        $this->refreshBlockType('youtube');
    }
}

<?php
namespace Concrete\Core\Updater\Migrations\Migrations;

use Concrete\Core\Updater\Migrations\AbstractMigration;
use Concrete\Core\Updater\Migrations\RepeatableMigrationInterface;

class Version20191002000000 extends AbstractMigration implements RepeatableMigrationInterface
{
    public function upgradeDatabase()
    {
        /* Refresh youtube block */
        $this->refreshBlockType('youtube');
    }
}

Add migration version file for youtube block


<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Non-acceptable request</title>

The resource you are looking cannot be provided in any of the formats you accept.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Non-acceptable request</title>

The resource you are looking for cannot be provided in any of the formats you accept.

{{ $exception->getMessage() }}

Update HTTP 406 view to display exception message

The exception message will contain the list of content types that are accepted/supported by the back-end.

This commit also fixes a typo.


@include('core::admin._buttons-form')

@include('contacts::_fields')

{!! BootForm::hidden('my_time')->value(Crypt::encrypt(time()-60)) !!}

@component('core::admin._buttons-form', ['model' => $model])
@endcomponent

@include('contacts::_fields')

{!! BootForm::hidden('my_time')->value(Crypt::encrypt(time()-60)) !!}

Use of @component for buttons in form

Use of @component for buttons in form


@include('core::admin._buttons-form')

{!! BootForm::hidden('id') !!}
{!! BootForm::hidden('group')->value('db') !!}

{!! BootForm::text(__('Key'), 'key') !!}

{{ __('Translations') }}

@foreach ($locales as $lang)

has('translation.'.$lang))has-error @endif">

            {{ strtoupper($lang) }}
            {!! Form::text('translation['.$lang.']')->addClass('form-control') !!}

        {!! $errors->first('translation.'.$lang, '
:message
') !!}

@endforeach

@component('core::admin._buttons-form', ['model' => $model])
@endcomponent

{!! BootForm::hidden('id') !!}
{!! BootForm::hidden('group')->value('db') !!}

{!! BootForm::text(__('Key'), 'key') !!}

{{ __('Translations') }}

@foreach ($locales as $lang)

has('translation.'.$lang))has-error @endif">

            {{ strtoupper($lang) }}
            {!! Form::text('translation['.$lang.']')->addClass('form-control') !!}

        {!! $errors->first('translation.'.$lang, '
:message
') !!}

@endforeach

Use of @component for buttons in form

Use of @component for buttons in form


<?php

namespace App\Providers;

use EGALL\Transformer\Contracts\Transformer as TransformerContract;
use EGALL\Transformer\Transformer;
use Illuminate\Support\ServiceProvider;

class TransformerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(TransformerContract::class, Transformer::class);
    }
}

<?php

namespace EGALL\Transformer;

use Illuminate\Support\ServiceProvider;
use EGALL\Transformer\Contracts\Transformer as TransformerContract;

/**
 * Transformer service provider.
 *
 * @package EGALL\Transformer
 * @author Erik Galloway <erik@mybarnapp.com>
 */
class TransformerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(TransformerContract::class, Transformer::class);
    }
}

Update the transformer service provider to use the correct namespace


<?php

namespace Isotop\Cargo\Content;

class Post extends Abstract_Content {

	/**
	 * Post constructor.
	 *
	 * @param mixed $post
	 */
	public function __construct( $post ) {
		// Bail if empty.
		if ( empty( $post ) ) {
			return;
		}

		// Bail if a revision post.
		if ( wp_is_post_revision( $post ) ) {
			return;
		}

		// Bail if `nav_menu_item` post type.
		if ( get_post_type( $post ) === 'nav_menu_item' ) {
			return;
		}

		$post = get_post( $post );

		// Bail if empty.
		if ( empty( $post ) ) {
			return;
		}

		// Create post object.
		$this->create( 'post', $post );

		// Add meta data.
		$this->add( 'meta', $this->prepare_meta( $post->ID, get_post_meta( $post->ID ) ) );

		// Add extra data.
		$this->add( 'extra', [
			'permalink' => get_permalink( $post ),
			'site_id'   => get_current_blog_id()
		] );
	}
}

<?php

namespace Isotop\Cargo\Content;

class Post extends Abstract_Content {

	/**
	 * Post constructor.
	 *
	 * @param mixed $post
	 */
	public function __construct( $post ) {
		// Bail if empty.
		if ( empty( $post ) ) {
			return;
		}

		// Bail if a revision post.
		if ( wp_is_post_revision( $post ) ) {
			return;
		}

		// Bail if `nav_menu_item` post type.
		if ( get_post_type( $post ) === 'nav_menu_item' ) {
			return;
		}

		$post = get_post( $post );

		// Bail if empty.
		if ( empty( $post ) ) {
			return;
		}

		// Apply the content filter before creating post object.
		$post->post_content = apply_filters( 'the_content', $post->post_content );

		// Create post object.
		$this->create( 'post', $post );

		// Add meta data.
		$this->add( 'meta', $this->prepare_meta( $post->ID, get_post_meta( $post->ID ) ) );

		// Add extra data.
		$this->add( 'extra', [
			'permalink' => get_permalink( $post ),
			'site_id'   => get_current_blog_id()
		] );
	}
}

Apply the content before creating post object


<?php namespace xp;

if (version_compare(PHP_VERSION, '5.4.0', '<')) {
  trigger_error('This version of the XP Framework requires PHP 5.4.0+, have PHP '.PHP_VERSION, E_USER_ERROR);
  exit(0x3d);
}

$p= max(strrpos(__FILE__, DIRECTORY_SEPARATOR), strrpos(__FILE__, '?'));
require substr(__FILE__, 0, $p + 1).'lang.base.php';

\lang\ClassLoader::getDefault();

<?php namespace xp;

if (version_compare(PHP_VERSION, '5.4.0', '<')) {
  trigger_error('This version of the XP Framework requires PHP 5.4.0+, have PHP '.PHP_VERSION, E_USER_ERROR);
  exit(0x3d);
}

$p= max(strrpos(__FILE__, DIRECTORY_SEPARATOR), strrpos(__FILE__, '?'));
require_once substr(__FILE__, 0, $p + 1).'lang.base.php';

\lang\ClassLoader::getDefault();

Use require_once for lang.base.php - easing Composer integration

# composer.pth
  vendor/autoload.php

# xp.ini
  use=vendor/xp-framework/core

  [runtime]
  date.timezone=Europe/Berlin

This way, we ensure bootstrapping occurs from the correct source
and that we can use XP runners as well as standalone PHP with a
`require("vendor/autoload.php") statement inside


<?php

namespace Bolt\Provider;

use Bolt\Menu\AdminMenuBuilder;
use Bolt\Menu\MenuBuilder;
use Bolt\Menu\MenuEntry;
use Silex\Application;
use Silex\ServiceProviderInterface;

class MenuServiceProvider implements ServiceProviderInterface
{
    /**
     * {@inheritdoc}
     */
    public function register(Application $app)
    {
        $app['menu'] = $app->share(
            function ($app) {
                $builder = new MenuBuilder($app);

                return $builder;
            }
        );

        /**
         * @internal Backwards compatibility not guaranteed on this provider presently.
         */
        $app['menu.admin'] = $app->share(
            function ($app) {
                // This service should not be invoked until request cycle since it depends
                // on url generation. Probably should be refactored somehow.
                $baseUrl = $app['url_generator']->generate('dashboard');
                $adminMenu = new AdminMenuBuilder(new MenuEntry('root', $baseUrl));
                $rootEntry = $adminMenu->build($app);

                return $rootEntry;
            }
        );
    }

    /**
     * {@inheritdoc}
     */
    public function boot(Application $app)
    {
    }
}

<?php

namespace Bolt\Provider;

use Bolt\Menu\AdminMenuBuilder;
use Bolt\Menu\MenuBuilder;
use Bolt\Menu\MenuEntry;
use Silex\Application;
use Silex\ServiceProviderInterface;

class MenuServiceProvider implements ServiceProviderInterface
{
    /**
     * {@inheritdoc}
     */
    public function register(Application $app)
    {
        $app['menu'] = $app->share(
            function ($app) {
                $builder = new MenuBuilder($app);

                return $builder;
            }
        );

        /**
         * @internal Backwards compatibility not guaranteed on this provider presently.
         */
        $app['menu.admin'] = $app->share(
            function ($app) {
                // This service should not be invoked until request cycle since it depends
                // on url generation and request base path. Probably should be refactored somehow.
                $baseUrl = '';
                if (($request = $app['request_stack']->getCurrentRequest()) !== null) {
                    $baseUrl = $request->getBasePath();
                }
                $baseUrl .= '/' . trim($app['controller.backend.mount_prefix'], '/');

                $adminMenu = new AdminMenuBuilder(new MenuEntry('root', $baseUrl));
                $rootEntry = $adminMenu->build($app);

                return $rootEntry;
            }
        );
    }

    /**
     * {@inheritdoc}
     */
    public function boot(Application $app)
    {
    }
}

Determine menu base path from request base path and backend mount prefix instead of generating url.

Fixes #6139 The base url generated could have query params or fragment which breaks urls that are concatenated to it.


<?php namespace Modules\Page\Database\Seeders;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Modules\Page\Repositories\PageRepository;

class PageDatabaseSeeder extends Seeder
{
    /**
     * @var PageRepository
     */
    private $page;

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

    public function run()
    {
        Model::unguard();

        $data = [
            'template' => 'home',
            'is_home' => 1,
            'en' => [
                'title' => 'Home page',
                'slug' => 'home',
                'body' => '
You made it!

You've installed AsgardCMS and are ready to proceed to the administration area.

What's next ?

Learn how you can develop modules for AsgardCMS by reading our documentation.

',
                'meta_title' => 'Home page',
            ],
        ];
        $this->page->create($data);
    }
}

Make the backend link relative

Make the backend link relative


<?php

namespace HeyDoc\Console\Command;

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

class SetupCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('setup')
            ->setDescription('Setup project')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->createEmptyDir('docs');
        $this->copyFile('docs/settings.yml');
        $this->copyFile('docs/index.md');

        $this->createEmptyDir('web');
        $this->copyFile('web/.htaccess');
        $this->copyFile('web/index.php');
    }

    private function copyFile($fileName)
    {
        $fileToCopy = $this->currentDir . DIRECTORY_SEPARATOR . $fileName;

        if ($this->fs->exists($fileToCopy)) {
            $this->output->writeln(sprintf('>> file already exists <fg=blue>%s</>', $fileName));
            return;
        }

        $sourceDir = realpath(__DIR__.'/../../../HeyDoc/Resources/templates/');

        $this->fs->copy($sourceDir . DIRECTORY_SEPARATOR . $fileName, $fileToCopy, false);
        $this->output->writeln(sprintf('>> copy file <fg=green>%s</>', $fileName));
    }
}

<?php

namespace HeyDoc\Console\Command;

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

class SetupCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('setup')
            ->setDescription('Setup project')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->createEmptyDir('docs');
        $this->copyFile('docs/settings.yml');
        $this->copyFile('docs/index.md');

        $this->createEmptyDir('web');
        $this->copyFile('web/.htaccess');
        $this->copyFile('web/index.php');

        $this->createEmptyDir('cache', 0777);
    }

    private function copyFile($fileName)
    {
        $fileToCopy = $this->currentDir . DIRECTORY_SEPARATOR . $fileName;

        if ($this->fs->exists($fileToCopy)) {
            $this->output->writeln(sprintf('>> file already exists <fg=blue>%s</>', $fileName));
            return;
        }

        $sourceDir = realpath(__DIR__.'/../../../HeyDoc/Resources/templates/');

        $this->fs->copy($sourceDir . DIRECTORY_SEPARATOR . $fileName, $fileToCopy, false);
        $this->output->writeln(sprintf('>> copy file <fg=green>%s</>', $fileName));
    }
}

Update Setup command to create the cache dir


<?php
/* Adds more compatibility to application

   $this->api->add('Controller_Compat_Frame');

 */
class Controller_Compat extends AbstractController {
    function init(){
        parent::init();
        $this->api->addGlobalMethod('frame',array($this,'frame'));
        $this->api->addGlobalMethod('ajax',array($this,'ajax'));
    }
	function frame($obj,$spot=null,$title=null,$p=null,$opt=''){
		/*
		 * This function is just a shortcut in creating a frame
		 */
		if(!$p)$p=$obj;
		if(!isset($title)){
			$title=$spot;
			$spot='Content';
		}
		$f=$p->add('View','frame_'.(++$this->frame),$spot,array('frames','MsgBox'));
		$f->template->set('title',$title);
		$f->template->trySet('opt',$opt);
		return $f;
	}
    function ajax($obj,$instance=null){
        if(!is_null($instance)&&isset($obj->js['never'][$instance]))return $obj->js['never'][$instance];
        return $obj->js(null,null,$instance)->univ();
    }
}

<?php
/* Adds more compatibility to application

   $this->api->add('Controller_Compat_Frame');

 */
class Controller_Compat extends AbstractController {
    function init(){
        parent::init();
        $this->api->addGlobalMethod('frame',array($this,'frame'));
        $this->api->addGlobalMethod('ajax',array($this,'ajax'));
        $this->api->addHook('compat-addModelSave',array($this,'addModelSave'));
    }
    function addModelSave($obj,$other=null){
        $obj->addSubmit('Save');
    }
	function frame($obj,$spot=null,$title=null,$p=null,$opt=''){
		/*
		 * This function is just a shortcut in creating a frame
		 */
		if(!$p)$p=$obj;
		if(!isset($title)){
			$title=$spot;
			$spot='Content';
		}
		$f=$p->add('View','frame_'.(++$this->frame),$spot,array('frames','MsgBox'));
		$f->template->set('title',$title);
		$f->template->trySet('opt',$opt);
		return $f;
	}
    function ajax($obj,$instance=null){
        if(!is_null($instance)&&isset($obj->js['never'][$instance]))return $obj->js['never'][$instance];
        return $obj->js(null,null,$instance)->univ();
    }
}

Add backwards compatibility for MVCform

Add backwards compatibility for MVCform


<?php

abstract class PhabricatorXHProfController extends PhabricatorController {

  public function buildStandardPageResponse($view, array $data) {
    $page = $this->buildStandardPageView();

    $page->setApplicationName('XHProf');
    $page->setBaseURI('/xhprof/');
    $page->setTitle(idx($data, 'title'));
    $page->setGlyph("\xE2\x98\x84");
    $page->appendChild($view);

    $response = new AphrontWebpageResponse();

    if (isset($data['frame'])) {
      $response->setFrameable(true);
      $page->setFrameable(true);
      $page->setShowChrome(false);
      $page->setDisableConsole(true);
    }

    return $response->setContent($page->render());
  }

}

<?php

abstract class PhabricatorXHProfController extends PhabricatorController {

  public function buildStandardPageResponse($view, array $data) {
    $page = $this->buildStandardPageView();

    $page->setApplicationName('XHProf');
    $page->setBaseURI('/xhprof/');
    $page->setTitle(idx($data, 'title'));
    $page->setGlyph("\xE2\x98\x84");
    $page->appendChild($view);
    $page->setDeviceReady(true);

    $response = new AphrontWebpageResponse();

    if (isset($data['frame'])) {
      $response->setFrameable(true);
      $page->setFrameable(true);
      $page->setShowChrome(false);
      $page->setDisableConsole(true);
    }

    return $response->setContent($page->render());
  }

}

Set device true on all XHProf pages

Set device true on all XHProf pages

Summary: Pass this as true when building XHProf pages

Test Plan: Verify setDeviceReady exists in class PhabricatorBarePageView

Reviewers: epriestley

Reviewed By: epriestley

Subscribers: Korvin, epriestley

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


<?php
declare(strict_types = 1);

namespace Soliant\SimpleFM\Client\ResultSet\Transformer;

use Litipk\BigNumbers\Decimal;

final class NumberTransformer
{
    public function __invoke(string $value)
    {
        $cleanedValue = preg_replace_callback(
            '(^[^\d-.]*(-?)([^.]*)(.?)(.*)$)',
            function (array $match) : string {
                return
                    $match[1]
                    . preg_replace('([^\d]+)', '', $match[2])
                    . $match[3]
                    . preg_replace('([^\d]+)', '', $match[4]);
            },
            $value
        );

        if ('' === $cleanedValue) {
            return null;
        }

        if ('-' === $cleanedValue) {
            $cleanedValue = '0';
        }

        if (0 === strpos($cleanedValue, '.')) {
            $cleanedValue = '0' . $cleanedValue;
        }

        return Decimal::fromString($cleanedValue);
    }
}

<?php
declare(strict_types = 1);

namespace Soliant\SimpleFM\Client\ResultSet\Transformer;

use Litipk\BigNumbers\Decimal;

final class NumberTransformer
{
    public function __invoke(string $value)
    {
        $cleanedValue = preg_replace_callback(
            '(^[^\d-\.]*(-?)([^.]*)(.?)(.*)$)',
            function (array $match) : string {
                return
                    $match[1]
                    . preg_replace('([^\d]+)', '', $match[2])
                    . $match[3]
                    . preg_replace('([^\d]+)', '', $match[4]);
            },
            $value
        );

        if ('' === $cleanedValue) {
            return null;
        }

        if ('-' === $cleanedValue) {
            $cleanedValue = '0';
        }

        if (0 === strpos($cleanedValue, '.')) {
            $cleanedValue = '0' . $cleanedValue;
        }

        return Decimal::fromString($cleanedValue);
    }
}

Fix escaping for stricter php7.3.

Fix escaping for stricter php7.3.


<?php
/**
 * Created by Pierre-Henry Soria
 */

namespace PFBC\Validation;

use PH7\Framework\Date\CDateTime;
use PH7\Framework\Mvc\Model\DbConfig;

class BirthDate extends \PFBC\Validation
{
    /** @var int */
    protected $iMin;

    /** @var int */
    protected $iMax;

    public function __construct()
    {
        parent::__construct();

        $this->iMin = DbConfig::getSetting('minAgeRegistration');
        $this->iMax = DbConfig::getSetting('maxAgeRegistration');
        $this->message = t('You must be from %0% to %1% years old to join the service.', $this->iMin, $this->iMax);
    }

    /**
     * @return bool
     */
    public function isValid($sValue)
    {
        if ($this->isNotApplicable($sValue)) {
            return true;
        }

        $sValue = (new CDateTime)->get($sValue)->date('m/d/Y');

        return $this->oValidate->birthDate($sValue, $this->iMin, $this->iMax);
    }
}

<?php
/**
 * Created by Pierre-Henry Soria
 */

namespace PFBC\Validation;

use PH7\Framework\Date\CDateTime;
use PH7\Framework\Mvc\Model\DbConfig;

class BirthDate extends \PFBC\Validation
{
    /** @var int */
    protected $iMin;

    /** @var int */
    protected $iMax;

    public function __construct()
    {
        parent::__construct();

        $this->iMin = DbConfig::getSetting('minAgeRegistration');
        $this->iMax = DbConfig::getSetting('maxAgeRegistration');
        $this->message = t('You must be from %0% to %1% years old to join the service.', $this->iMin, $this->iMax);
    }

    /**
     * @param string $sDate
     *
     * @return bool
     */
    public function isValid($sDate)
    {
        if ($this->isNotApplicable($sDate)) {
            return true;
        }

        $sDate = (new CDateTime)->get($sDate)->date('m/d/Y');

        return $this->oValidate->birthDate($sDate, $this->iMin, $this->iMax);
    }
}

Change variable name to a better desciptive one..


<?php

/*
	WildPHP - a modular and easily extendable IRC bot written in PHP
	Copyright (C) 2015 WildPHP

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
namespace WildPHP\IRC;

/**
 * Represents an incoming PRIVMSG command.
 */
template ICommandPRIVMSG {

	/**
	 * Returns the complete IRC message as it was received from the server.
	 * @return string Full IRC message.
	 */
	public function getIRCMessage();

	/**
	 * Returns the sender name.
	 * @return string Username of sender
	 */
	public function getSenderName();

	/**
	 * Returns the target user/channel name.
	 * @return string Name of the target user/channel of this message.
	 */
	public function getTargetName();

	/**
	 * Returns the sender hostname.
	 * @return string Hostname of sender.
	 */
	public function getSenderHostname();

	/**
	 * Returns the sent message.
	 * @return string The message which was sent.
	 */
	public function getMessage();
}

<?php

/*
	WildPHP - a modular and easily extendable IRC bot written in PHP
	Copyright (C) 2015 WildPHP

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
namespace WildPHP\IRC;

/**
 * Represents an incoming PRIVMSG command.
 */
template ICommandPRIVMSG extends IServerMessage {

	/**
	 * Returns the sender name.
	 * @return string Username of sender
	 */
	public function getSenderName();

	/**
	 * Returns the target user/channel name.
	 * @return string Name of the target user/channel of this message.
	 */
	public function getTargetName();

	/**
	 * Returns the sender hostname.
	 * @return string Hostname of sender.
	 */
	public function getSenderHostname();

	/**
	 * Returns the sent message.
	 * @return string The message which was sent.
	 */
	public function getUserMessage();
}

Extend the IServerMessage thing instead

Extend the IServerMessage thing instead


<?

defined('C5_EXECUTE') or die("Access Denied.");
class ConcreteUpgradeVersion562Helper {

	public $dbRefreshTables = array(
		'Queues',
		'QueueMessages',
		'QueuePageDuplicationRelations',
		'Jobs',
		'JobSets',
		'JobSetJobs',
		'Blocks'
	);

	public function run() {
		$j = Job::getByHandle('index_search_all');
		if (!is_object($j)) {
			Job::installByHandle('index_search_all');
		}

		$js = JobSet::getByName('Default');
		if (!is_object($js)) {
			$js = JobSet::add('Default');
		}
		$js->clearJobs();
		$jobs = Job::getList();
		foreach($jobs as $j) {
			if (!$j->supportsQueue()) {
				$js->addJob($j);
			}
		}
	}

}

<?

defined('C5_EXECUTE') or die("Access Denied.");
class ConcreteUpgradeVersion562Helper {

	public $dbRefreshTables = array(
		'Queues',
		'QueueMessages',
		'QueuePageDuplicationRelations',
		'Jobs',
		'JobSets',
		'JobSetJobs',
		'Blocks',
		'Pages'
	);

	public function run() {
		$j = Job::getByHandle('index_search_all');
		if (!is_object($j)) {
			Job::installByHandle('index_search_all');
		}

		$js = JobSet::getByName('Default');
		if (!is_object($js)) {
			$js = JobSet::add('Default');
		}
		$js->clearJobs();
		$jobs = Job::getList();
		foreach($jobs as $j) {
			if (!$j->supportsQueue()) {
				$js->addJob($j);
			}
		}
	}

}

Add Pages to Refresh Tables for Upgrade

Add Pages to Refresh Tables for Upgrade

Add Pages to Refresh Tables for Upgrade

Former-commit-id: a99355a7060e9f344b41707420f70905280bc61a


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

/**
 * Users Toolbar Class
 *
 * @author      Gergo Erdosi <http://nooku.assembla.com/profile/gergoerdosi>
 * @category	Nooku
 * @package		Nooku_Server
 * @subpackage	Users
 */
class ComUsersControllerToolbarUsers extends ComDefaultControllerToolbarDefault
{
    public function __construct(KConfig $config)
    {
        parent::__construct($config);

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

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

/**
 * Users Toolbar Class
 *
 * @author      Gergo Erdosi <http://nooku.assembla.com/profile/gergoerdosi>
 * @category	Nooku
 * @package		Nooku_Server
 * @subpackage	Users
 */
class ComUsersControllerToolbarUsers extends ComDefaultControllerToolbarDefault
{
    public function getCommands()
    {
        $this->addSeperator()
			 ->addEnable()
			 ->addDisable();

	    return parent::getCommands();
    }
}

Insert custom commands through the getCommands() function.


@extends('layouts/default')

{{-- Page title --}}
@section('title')
{{ trans('admin/manufacturers/table.asset_manufacturers') }}
@parent
@stop

{{-- Page title --}}
@section('header_right')

  {{ trans('general.create') }}
@stop

{{-- Page content --}}
@section('content')

@stop

@section('moar_scripts')
  @include ('partials.bootstrap-table',
      ['exportFile' => 'manufacturers-export',
      'search' => true,
      'columns' => \App\Presenters\ManufacturerPresenter::dataTableLayout()
  ])
@stop

@extends('layouts/default')

{{-- Page title --}}
@section('title')
{{ trans('admin/manufacturers/table.asset_manufacturers') }}
@parent
@stop

{{-- Page title --}}
@section('header_right')
  @can('create', \App\Models\Manufacturer::class)

    {{ trans('general.create') }}
  @endcan
@stop

{{-- Page content --}}
@section('content')

@stop

@section('moar_scripts')
  @include ('partials.bootstrap-table',
      ['exportFile' => 'manufacturers-export',
      'search' => true,
      'columns' => \App\Presenters\ManufacturerPresenter::dataTableLayout()
  ])
@stop

Hide mfg button if no permissions to create


<article <?php post_class(); ?>>

  	<?php if (($posts[0]->post_type != 'faq') && ($posts[0]->post_type != 'service')) : ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

   	<?php else: ?>
   	<?php $content_class = "large_text_display"; ?>

<?php the_title(); ?>

   	<?php endif ?>
    <?php if ($posts[0]->post_type == 'post')
      		get_template_part('templates/entry-meta'); ?>

  <div class="entry-summary <?php echo $content_class ? $content_class : '' ?> ">
    	<?php the_content(); ?>

<article <?php post_class(); ?>>

  	<?php if (($posts[0]->post_type != 'faq') && ($posts[0]->post_type != 'service')) : ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

   	<?php else: ?>
   	<?php $content_class = "large_text_display"; ?>
   	 <a class="archive_title" href="<?=the_permalink()?>">
<?php the_title(); ?>

   	<?php endif ?>
    <?php if ($posts[0]->post_type == 'post')
      		get_template_part('templates/entry-meta'); ?>

  <div class="entry-summary <?php echo $content_class ? $content_class : '' ?> ">
    <?php the_content(); ?>

Make title in archive page link to article.


<?php

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

$loop = React\EventLoop\Factory::create();

$factory = new Datagram\Factory($loop);

$factory->createServer(1234)->then(function (Datagram\Server $server) {
    $server->on('message', function($message, $client) {
        $client->send('hello '.$client->getAddress().'! echo: '.$message);

        // $server->send() is not available here
    });
});

$loop->run();

<?php

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

$loop = React\EventLoop\Factory::create();

$factory = new Datagram\Factory($loop);

$factory->createServer(1234)->then(function (Datagram\Server $server) {
    $server->on('message', function($message, $client) {
        $client->send('hello '.$client->getAddress().'! echo: '.$message);

        echo 'client ' . $client->getAddress() . ': ' . $message . PHP_EOL;
    });
});

$loop->run();

Extend example to echo received client messages


    id }}"> User Profile

     Projects

     Support Tickets

     Invoices

Use sentry to get the user instead of expecting the variable to exist


<fieldset <?php if (!empty($attr)) print drupal_attributes($attr) ?>>
  <?php if (!empty($title)): ?>
    <legend><h2 class='<?php print $hook ?>-title'><?php print $title ?>
</legend>
  <?php endif; ?>
  <?php if (!empty($content)): ?>
    <div class='<?php print $hook ?>-content clear-block <?php if (!empty($is_prose)) print 'prose' ?>'>
      <?php print $content ?>

  <?php endif; ?>
</fieldset>

<fieldset <?php if (!empty($attr)) print drupal_attributes($attr) ?>>
  <?php if (!empty($title)): ?>
    <legend><span class='<?php print $hook ?>-title'><?php print $title ?></legend>
  <?php endif; ?>
  <?php if (!empty($content)): ?>
    <div class='<?php print $hook ?>-content clear-block <?php if (!empty($is_prose)) print 'prose' ?>'>
      <?php print $content ?>

  <?php endif; ?>
</fieldset>

Fix for Firefox JS/DOM error.

Fix for Firefox JS/DOM error.


Change Access

<form class="form-horizontal">

    Select Access Type

      <select id="access-type" name="access-type" class="form-control">
        <option disabled>Select Access Type</option>
        <?php
        $types = $dal->getAccessTypes();
        $selected_user = $_GET['for'];
        $curr = $dal->getUserAccessLevel($selected_user);
        $level_options = '';
        foreach ($types as $row) {
          return '';
          //$level_options .= "<option value=".$row['id'].">".$row['type']."</option>";
        }
        echo $level_options;
        /*
        if ($types) {
          foreach ($types as $row) {
            $option = "<option value='".$row['type']."' ";
            if ($row['type'] == $curr) {
              $option .= "selected>$row['type']</option>";
            } else {
              $option .= ">$row['type']</option>";
            }
            echo $option;
          }
        }
        */
        ?>
      </select>

      <button id="submit" name="submit" class="btn btn-primary">Update</button>

</form>

Change Access

<form class="form-horizontal">

    Select Access Type

      <?php
      $types = $dal->getAccessTypes();
      $selected_user = $_GET['for'];
      $curr = $dal->getUserAccessLevel($selected_user);
      $level_options = '';
      ?>
      <select id="access-type" name="access-type" class="form-control">
        <option disabled>Select Access Type</option>
        <?php
        foreach ($types as $row) {
          return '';
          //$level_options .= "<option value=".$row['id'].">".$row['type']."</option>";
        }
        echo $level_options;
        /*
        if ($types) {
          foreach ($types as $row) {
            $option = "<option value='".$row['type']."' ";
            if ($row['type'] == $curr) {
              $option .= "selected>$row['type']</option>";
            } else {
              $option .= ">$row['type']</option>";
            }
            echo $option;
          }
        }
        */
        ?>
      </select>

      <button id="submit" name="submit" class="btn btn-primary">Update</button>

</form>

Move that block to see if that is what is causing the issue


<?php

$namespace = 'site';
require_once __DIR__ . '/../index.php';

// route
$container['console']->logMemory(null, 'Bootstrapping is done');
Loader::loadInstance('router', 'Router');
$container['console']->logMemory(null, 'Routing is done');

<?php

$namespace = 'site';
require_once __DIR__ . '/../index.php';

// route
$container['console']->logMemory(null, 'Bootstrapping is done');

$dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) {
    $r->addRoute('GET', '/', 'HomeController');
    $r->addRoute('GET', '/terms/', 'TermsController');
    $r->addRoute('GET', '/change-log/', 'ChangelogController');
    $r->addRoute(['GET', 'POST'], '/contact/', 'ContactController');
});

$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = rawurldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
$status = reset($routeInfo);

switch ($status) {
    case FastRoute\Dispatcher::NOT_FOUND:
        $container['logger']->debug('Route not found - 404');
        Loader::loadNew('controller', '/Error404Controller')->activate();
        break;
    case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
        // todo - return allowed routes in header
        $container['logger']->debug('Unallowed method - 405');
        Loader::loadNew('controller', '/Error404Controller')->activate();
        break;
    case FastRoute\Dispatcher::FOUND:
        $container['logger']->debug('found!');
        Loader::loadNew('controller', "{$namespace}/{$routeInfo[1]}")->activate();
        break;
}

$container['console']->logMemory(null, 'Routing is done');

Use inline-routing to kick off controller


<?php

namespace Anam\Captcha\Tests;

use Anam\Captcha\Captcha;
use Illuminate\Http\Request;

class CaptchaTest extends TestCase
{
    /**
     * @expectedException \Anam\Captcha\SecretNotFoundException
     */
    public function testExceptionThrownOnInvalidSecret()
    {
        $captcha = new Captcha();
    }

    public function testVerifyReturnsErrorOnMissingInputResponse()
    {
        $captcha = new Captcha('secret');

        $response = $captcha->check(new Request);

        $this->assertFalse($response->isVerified());

        $this->assertEquals('missing-input-response', $response->errors()->first());
    }
}

<?php

namespace Anam\Captcha\Tests;

use Mockery;
use ReCaptcha\ReCaptcha;
use ReCaptcha\Response;
use Anam\Captcha\Captcha;
use Illuminate\Http\Request;

class CaptchaTest extends TestCase
{
    /**
     * @expectedException \Anam\Captcha\SecretNotFoundException
     */
    public function testExceptionThrownOnInvalidSecret()
    {
        $captcha = new Captcha();
    }

    public function testVerifyReturnsErrorOnMissingInputResponse()
    {
        $captcha = new Captcha('secret');

        $response = $captcha->check(new Request);

        $this->assertFalse($response->isVerified());

        $this->assertEquals('missing-input-response', $response->errors()->first());
    }

    public function testSuccessfulResponseRequest()
    {
        $request = Mockery::mock(Request::class);
        $request->allows()->input('g-recaptcha-response')->andReturn('xyz');

        $request->allows()->ip()->andReturn('127.0.0.1');

        $captcha = Mockery::mock(Captcha::class)->makePartial();
        $captcha->allows()->verify($request->input('g-recaptcha-response'), $request->ip())
            ->andReturn(new Response(true));

        $captcha->check($request);

        $this->assertTrue($captcha->isVerified());

    }

    public function testUnsuccessfulResponseRequest()
    {
        $request = Mockery::mock(Request::class);
        $request->allows()->input('g-recaptcha-response')->andReturn('xyz');

        $request->allows()->ip()->andReturn('127.0.0.1');

        $captcha = Mockery::mock(Captcha::class)->makePartial();
        $captcha->allows()->verify($request->input('g-recaptcha-response'), $request->ip())
            ->andReturn(new Response(false));

        $captcha->check($request);

        $this->assertFalse($captcha->isVerified());

    }

    public function testHostname()
    {
        $request = Mockery::mock(Request::class);
        $request->allows()->input('g-recaptcha-response')->andReturn('xyz');

        $request->allows()->ip()->andReturn('127.0.0.1');

        $captcha = Mockery::mock(Captcha::class)->makePartial();
        $captcha->allows()->verify($request->input('g-recaptcha-response'), $request->ip())
            ->andReturn(new Response(true, [], $request->ip()));

        $captcha->check($request);

        $this->assertEquals('127.0.0.1', $captcha->hostname());

    }
}

Add tests to verify the Captcha request

Add tests to verify the Captcha request


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Mvc\Service;

use ArrayAccess;
use Zend\ServiceManager\FactoryInterface;
use Zend\Mvc\View\Http\InjectTemplateListener;
use Zend\ServiceManager\ServiceLocatorInterface;

class InjectTemplateListenerFactory implements FactoryInterface
{
    /**
     * Create and return an InjectTemplateListener instance.
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return InjectTemplateListener
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $listener = new InjectTemplateListener();

        $config = $serviceLocator->get('Config');
        if (isset($config['view_manager'])
            && (is_array($config['view_manager']) || $config['view_manager'] instanceof ArrayAccess)
            && isset($config['view_manager']['controller_map'])
            && (is_array($config['view_manager']['controller_map']))
        ) {
            $listener->setControllerMap($config['view_manager']['controller_map']);
        }

        return $listener;
    }
}

<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Mvc\Service;

use ArrayAccess;
use Zend\ServiceManager\FactoryInterface;
use Zend\Mvc\View\Http\InjectTemplateListener;
use Zend\ServiceManager\ServiceLocatorInterface;

class InjectTemplateListenerFactory implements FactoryInterface
{
    /**
     * Create and return an InjectTemplateListener instance.
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return InjectTemplateListener
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $listener = new InjectTemplateListener();

        $config = $serviceLocator->get('Config');
        if (isset($config['view_manager']['controller_map'])
            && (is_array($config['view_manager']['controller_map']))
        ) {
            $listener->setControllerMap($config['view_manager']['controller_map']);
        }

        return $listener;
    }
}

Simplify test for controller_map key within $config['view_manager'].


<?php
function Assets_NFTseries_response_newItem ($params) {
	$req = array_merge($_REQUEST, $params);
	$stream = Assets_NFT_Series::getComposerStream($req["chainId"], Q::ifset($req, "userId", null));
	return array("publisherId" => $stream->publisherId, "streamName" => $stream->name);
}

<?php
function Assets_NFTseries_response_newItem ($params) {
	$req = array_merge($_REQUEST, $params);
	$userId = Q::ifset($req, "userId", null);
	$stream = Assets_NFT_Series::getComposerStream($req["chainId"], $userId);
	$data = Q::event("Users/external/response/data", array("userId"));

	return array("publisherId" => $stream->publisherId, "streamName" => $stream->name, "wallet" => $data["wallet"]);
}

Use handler Users/external/response/data to get users wallet address to use it in setSeriesInfo method as author.


<?php

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

class AddProfileToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->text('intro');
            $table->string('avatar')->default('https://loverecorder-1251779005.picsh.myqcloud.com/user/avatar/avatar-default.png');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('intro');
            $table->dropColumn('avatar');
        });
    }
}

<?php

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

class AddProfileToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->text('intro')->default('');
            $table->string('avatar')->default('https://loverecorder-1251779005.picsh.myqcloud.com/user/avatar/avatar-default.png');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('intro');
            $table->dropColumn('avatar');
        });
    }
}

Add default value to intro

Add default value to intro


<?php

$app->get('users/login', ['as' => 'users.login', 'uses' => 'UserController@login']);
resource('users', 'UserController');
resource('devices', 'DeviceController');
resource('templates', 'TemplateController');
$app->put('attributes/reorder', ['as' => 'attributes.reorder', 'uses' => 'AttributeController@reorder']);
resource('attributes', 'AttributeController');

<?php

$app->options('{route:.*}', function () {
	return response()->json();
});
$app->get('users/login', ['as' => 'users.login', 'uses' => 'UserController@login']);
resource('users', 'UserController');
resource('devices', 'DeviceController');
resource('templates', 'TemplateController');
$app->put('attributes/reorder', ['as' => 'attributes.reorder', 'uses' => 'AttributeController@reorder']);
resource('attributes', 'AttributeController');

Add response for OPTIONS requests.

Add response for OPTIONS requests.


<?php

/* Access db of homer */
define(HOST, "localhost");
define(USER, "root");
define(PW, "root");
define(DB, "homer_users");

/* Homer connection
*  this user must have the same password for all Homer nodes
*  please define all your nodes in homer_nodes table
*/
define(HOMER_HOST, "localhost");
define(HOMER_USER, "homer_user");
define(HOMER_PW, "homer_password");
define(HOMER_DB, "homer_db");
define(HOMER_TABLE, "sip_capture");

/* Settings
*  Be shure, that you have the last version of text2pcap
*  text2pcap shall support -4 -6 IP headers
*
*  Text2pcap: https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=5650
*  Callflow: http://sourceforge.net/projects/callflow/
*
*/

define(PCAPDIR,"/var/www/html/webhomer/tmp/");
define(WEBPCAPLOC,"/webhomer/tmp/");
define(TEXT2PCAP,"/usr/sbin/text2pcap");
define(MERGECAP,"/usr/sbin/mergecap");
define(COLORTAG, 0); /* color based on callid, fromtag */
define(MODULES, 0); /* display modules in homepage flag */
define(CFLOW_CLEANUP, 1); /* Automatic Cleanup of old Cflow images */

?>

<?php

/* Access db of homer */
define(HOST, "localhost");
define(USER, "root");
define(PW, "root");
define(DB, "homer_users");

/* Homer connection
*  this user must have the same password for all Homer nodes
*  please define all your nodes in homer_nodes table
*/
define(HOMER_HOST, "localhost");
define(HOMER_USER, "homer_user");
define(HOMER_PW, "homer_password");
define(HOMER_DB, "homer_db");
define(HOMER_TABLE, "sip_capture");

/* Settings
*  Be shure, that you have the last version of text2pcap
*  text2pcap shall support -4 -6 IP headers
*
*  Text2pcap: https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=5650
*  Callflow: http://sourceforge.net/projects/callflow/
*
*/

define(PCAPDIR,"/var/www/html/webhomer/tmp/");
define(WEBPCAPLOC,"/webhomer/tmp/");
define(TEXT2PCAP,"/usr/sbin/text2pcap");
define(MERGECAP,"/usr/sbin/mergecap");
define(COLORTAG, 0); /* color based on callid, fromtag */
define(MODULES, 0); /* display modules in homepage flag */
define(CFLOW_CLEANUP, 1); /* Automatic Cleanup of old Cflow images */
define(CFLOW_TIMEZONE, "America/Los_Angeles"); /* Timezone that will display in Call Flow Ladder Diagram */

?>

Define Timezone for Call Flow

Define Timezone for Call Flow


<!DOCTYPE html>

        <title>Budget</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito:300,300i" />
        <link rel="stylesheet" href="/style.css" />

        @if (Auth::check())

                        Dashboard

                        Reports

                        Budgets

                        Tags

                        Settings

                        Log out

        @endif

            @yield('body')

<!DOCTYPE html>

        <title>Budget</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito+Sans:400,400i" />
        <link rel="stylesheet" href="/style.css" />

        @if (Auth::check())

                        Dashboard

                        Reports

                        Budgets

                        Tags

                        Settings

                        Log out

        @endif

            @yield('body')

Fix link to font in layout view

Fix link to font in layout view


<?php

require_once(dm::getDir().'/dmFrontPlugin/lib/config/dmFrontApplicationConfiguration.php');

class frontConfiguration extends dmFrontApplicationConfiguration
{

  public function configure()
  {
    $this->getEventDispatcher()->connect('dm.search.filter_boost_values', array($this, 'listenToSearchFilterBoostValues'));

    $this->getEventDispatcher()->connect('dm.page_cache.enable', array($this, 'listenToPageCacheEnable'));
  }

  public function listenToPageCacheEnable(sfEvent $event, $enable)
  {
    if($enable)
    {
      $uri = $_SERVER['REQUEST_URI'];

      if(0 === strncmp($uri, '/security', 9))
      {
        $enable = false;
      }
    }

    return $enable;
  }

  public function listenToSearchFilterBoostValues(sfEvent $event, array $boostValues)
  {
    $page = $event['page'];

    if($page->isModuleAction('version', 'show'))
    {
      $boostValues['body'] = 0;
    }
    elseif($page->isModuleAction('docPage', 'show'))
    {
      $boostValues['body'] = 3;
    }

    if($page->isModuleAction('doc', 'show') || $page->isModuleAction('docPage', 'show'))
    {
      if($page->getRecord()->getAncesTorRecord('Branch')->get('number') != sfConfig::get('app_branches_current'))
      {
        throw new dmSearchPageNotIndexableException();
      }
    }

    return $boostValues;
  }
}

<?php

require_once(dm::getDir().'/dmFrontPlugin/lib/config/dmFrontApplicationConfiguration.php');

class frontConfiguration extends dmFrontApplicationConfiguration
{

  public function configure()
  {
    $this->getEventDispatcher()->connect('dm.search.filter_boost_values', array($this, 'listenToSearchFilterBoostValues'));

    $this->getEventDispatcher()->connect('dm.page_cache.enable', array($this, 'listenToPageCacheEnable'));
  }

  public function listenToPageCacheEnable(sfEvent $event, $enable)
  {
    if($enable)
    {
      $uri = $_SERVER['REQUEST_URI'];

      if(0 === strncmp($uri, '/security', 9))
      {
        $enable = false;
      }
      if(0 === strncmp($uri, '/contact', 8))
      {
        $enable = false;
      }
    }

    return $enable;
  }

  public function listenToSearchFilterBoostValues(sfEvent $event, array $boostValues)
  {
    $page = $event['page'];

    if($page->isModuleAction('version', 'show'))
    {
      $boostValues['body'] = 0;
    }
    elseif($page->isModuleAction('docPage', 'show'))
    {
      $boostValues['body'] = 3;
    }

    if($page->isModuleAction('doc', 'show') || $page->isModuleAction('docPage', 'show'))
    {
      if($page->getRecord()->getAncesTorRecord('Branch')->get('number') != sfConfig::get('app_branches_current'))
      {
        throw new dmSearchPageNotIndexableException();
      }
    }

    return $boostValues;
  }
}

Disable cache on contact page to avoid CSRF issues


<?php if ($milestone instanceof TBGMilestone): ?>
    <?php echo $milestone->getName(); ?>

    <?php foreach ($status_details['details'] as $status): ?>
        <div class="statusblock" style="background-color: <?php echo (isset($statuses[$status['id']])) ? $statuses[$status['id']]->getColor() : '#FFF'; ?>; width: <?php echo $status['percent']; ?>%;" title="<?php echo (isset($statuses[$status['id']])) ? $statuses[$status['id']]->getName() : __('Unknown status'); ?> - <?php echo $status['percent']; ?>%">

    <?php endforeach; ?>

        <div class="filler" id="milestone_<?php echo $milestone->getID(); ?>_percentage_filler" style="width: <?php echo $milestone->getPercentComplete(); ?>%;">

<?php else: ?>
    <?php echo __('No milestones exists'); ?>
<?php endif; ?>

<?php if ($milestone instanceof TBGMilestone): ?>
    <?php echo $milestone->getName(); ?>

    <?php foreach ($status_details['details'] as $status): ?>
        <div class="statusblock" style="background-color: <?php echo (isset($statuses[$status['id']])) ? $statuses[$status['id']]->getColor() : '#FFF'; ?>; width: <?php echo $status['percent']; ?>%;" title="<?php echo __('%status_name - %percentage (%count of %total)', array('%status_name' => (isset($statuses[$status['id']])) ? $statuses[$status['id']]->getName() : __('Unknown status'), '%percentage' => $status['percent'].'%', '%count' => $status['count'], '%total' => $status_details['total'])); ?>">

    <?php endforeach; ?>

        <div class="filler" id="milestone_<?php echo $milestone->getID(); ?>_percentage_filler" style="width: <?php echo $milestone->getPercentComplete(); ?>%;" title="<?php echo __('%percentage completed', array('%percentage' => $milestone->getPercentComplete().'%')); ?>">

<?php else: ?>
    <?php echo __('No milestones exists'); ?>
<?php endif; ?>

Improve hover text for milestone status display


<?php

namespace Maghead\TableParser;

class TypeInfo
{
    public $type;

    public $length;

    public $precision;

    public $isa;

    public $fullQualifiedTypeName;

    public $unsigned;

    public $enum = array();

    public $set = array();

    public function __construct($typeName = null, $length = null)
    {
        $this->type = $typeName;
        $this->length = $length;
    }

    public function getType()
    {
        return $this->type;
    }

    public function getLength()
    {
        return $this->length;
    }

    public function getPrecision()
    {
        return $this->precision;
    }
}

<?php

namespace Maghead\TableParser;

/**
 * Plain old object for column type info
 */
class TypeInfo
{
    public $type;

    public $length;

    public $precision;

    public $isa;

    public $fullQualifiedTypeName;

    public $unsigned;

    public $enum = array();

    public $set = array();

    public function __construct($typeName = null, $length = null)
    {
        $this->type = $typeName;
        $this->length = $length;
    }
}

Clean up type info interfaces

Clean up type info interfaces


<?php

namespace Phive\TaskQueue;

use Phive\Queue\Exception\ExceptionInterface;

abstract class AbstractExecutor
{
    protected $context;

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

    /**
     * @return bool True if a task was processed, false otherwise.
     */
    public function execute()
    {
        try {
            $task = $this->context->getQueue()->pop();
        } catch (ExceptionInterface $e) {
            $this->context->getLogger()->error($e->getMessage());
            return false;
        }

        if (!$task instanceof TaskInterface) {
            $task = new Task($task);
        }

        $logger = $this->context->getLogger();
        $logger->debug(sprintf('Dequeued "%s".', $task));

        try {
            $this->doExecute($task);
            $logger->info(sprintf('Task "%s" was successfully executed.', $task));
        } catch (TaskFailedException $e) {
            $logger->error(sprintf('Task "%s" failed: %s', $task, $e->getMessage()));
        } catch (\Exception $e) {
            if ($eta = $task->reschedule()) {
                $logger->error(sprintf('An error occurred while executing task "%s": %s', $task, $e->getMessage()));
                $this->context->getQueue()->push($task, $eta);
            } else {
                $logger->error(sprintf('Task "%s" failed: %s.', $task, $e->getMessage()));
            }
        }

        return true;
    }

    abstract protected function doExecute(TaskInterface $task);
}

<?php

namespace Phive\TaskQueue;

use Phive\Queue\Exception\ExceptionInterface;
use Phive\Queue\Exception\NoItemException;

abstract class AbstractExecutor
{
    protected $context;

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

    /**
     * @return bool True if a task was processed, false otherwise.
     */
    public function execute()
    {
        $logger = $this->context->getLogger();

        try {
            $task = $this->context->getQueue()->pop();
        } catch (ExceptionInterface $e) {
            $e instanceof NoItemException
                ? $logger->debug('Nothing to execute.')
                : $logger->error($e->getMessage());

            return false;
        }

        if (!$task instanceof TaskInterface) {
            $task = new Task($task);
        }

        $logger->debug(sprintf('Dequeued "%s".', $task));

        try {
            $this->doExecute($task);
            $logger->info(sprintf('Task "%s" was successfully executed.', $task));
        } catch (TaskFailedException $e) {
            $logger->error(sprintf('Task "%s" failed: %s', $task, $e->getMessage()));
        } catch (\Exception $e) {
            if ($eta = $task->reschedule()) {
                $logger->error(sprintf('An error occurred while executing task "%s": %s', $task, $e->getMessage()));
                $this->context->getQueue()->push($task, $eta);
            } else {
                $logger->error(sprintf('Task "%s" failed: %s.', $task, $e->getMessage()));
            }
        }

        return true;
    }

    abstract protected function doExecute(TaskInterface $task);
}

Change log priority to 'debug' when no items are available in a queue


            {{ trans('cachet.incidents.scheduled') }}

            @foreach($scheduled_maintenance as $schedule)

                {{ $schedule->name }} scheduled_at_formatted }}" data-timeago="{{ $schedule->scheduled_at_iso }}">

                    {!! $schedule->formatted_message !!}

                @if($schedule->components->count() > 0)

                @foreach($schedule->components as $affected_component)
                {{ $affected_component->component->name }}
                @endforeach
                @endif

            @endforeach

            {{ trans('cachet.incidents.scheduled') }}

            @foreach($scheduled_maintenance as $schedule)

id }}">
                {{ $schedule->name }} scheduled_at_formatted }}" data-timeago="{{ $schedule->scheduled_at_iso }}">

                    {!! $schedule->formatted_message !!}

                @if($schedule->components->count() > 0)

                @foreach($schedule->components as $affected_component)
                {{ $affected_component->component->name }}
                @endforeach
                @endif

            @endforeach

Add ID of scheduled maintenance to list group item

This allows us to use a static URL to a scheduled maintenance.


<div class='note-form-wrapper'>
    <textarea class="flight-note" name="flight[flight_note]"><?php echo $flight->getFlightNote() ? $flight->getFlightNote() : '' ?></textarea>
    <button type="submit" class="submit btn btn-green"><?php echo $flight->getFlightNote() ? 'Update Note' : 'Add Note' ?></button>
</div>
<script type='text/javascript'>
    jQuery('.submit').bind('click', function(event){
        event.preventDefault();
        var btn = jQuery(this);
        var note = jQuery('.flight-note').val();
        jQuery.ajax({
            url: '<?php echo url_for("@flight_note_process?id={$flight->getId()}") ?>',
            dataType: 'json',
            data: {note: note},
            type: 'post',
            success: function(data) {
                if(data.result == 'OK'){
                    var root_li = btn.closest('li');
                    var form = jQuery('.note-form', root_li);
                    var open_link = jQuery('.flight-note-link', root_li);
                    if(note){
                        open_link.text('Update Note');
                    } else {
                        open_link.text('Add Note');
                    }
                    form.removeClass('open').hide(500);
                    jQuery('.note-form-wrapper', form).remove();
                }
            }

        });

    });
</script>

<div class='note-form-wrapper'>
    <textarea class="flight-note" name="flight[flight_note]"><?php echo $flight->getFlightNote() ? $flight->getFlightNote() : '' ?></textarea>
    <button class="submit btn btn-green">Submit</button>
    <button class="cancel btn btn-gray">Cancel</button>
</div>
<script type='text/javascript'>
    jQuery('.submit').bind('click', submitNote);
    jQuery('.cancel').bind('click', cancelNote);

    function submitNote(event){
        event.preventDefault();
        var btn = jQuery(this);
        var note = jQuery('.flight-note').val();
        var root_li = btn.closest('li');
        var form = jQuery('.note-form', root_li);
        var open_link = jQuery('.flight-note-link', root_li);
        jQuery.ajax({
            url: '<?php echo url_for("@flight_note_process?id={$flight->getId()}") ?>',
            dataType: 'json',
            data: {note: note},
            type: 'post',
            success: function(data) {
                if(data.result == 'OK'){
                    if(note){
                        open_link.text('Update Note');
                    } else {
                        open_link.text('Add Note');
                    }
                    form.removeClass('open').hide(500);
                    jQuery('.note-form-wrapper', form).remove();
                }
            }

        });

    }

    function cancelNote(event){
        event.preventDefault();
        var btn = jQuery(this);
        var root_li = btn.closest('li');
        var form = jQuery('.note-form', root_li);
        form.removeClass('open').hide(500);
        jQuery('.note-form-wrapper', form).remove();
    }

</script>

Add cancel button to note

Add cancel button to note


<?php
/**
 * @author: Patsura Dmitry http://github.com/ovr <talk@dmtry.me>
 */

namespace Lynx;

use Doctrine\DBAL\Connection;

class EntityManager
{
    /**
     * @var Connection
     */
    protected $connection;

    /**
     * @var Repository[]
     */
    protected $repositories;

    public function __construct(\Doctrine\DBAL\Connection $connection)
    {
        $this->connection = $connection;
    }

    /**
     * @return \Doctrine\DBAL\Query\QueryBuilder
     */
    public function createQueryBuilder()
    {
        return $this->connection->createQueryBuilder();
    }

    /**
     * @param $className
     * @param $id
     * @return null|object
     */
    public function find($className, $id)
    {
        return $this->getRepository($className)->getOne($id);
    }

    /**
     * @param $name
     * @return Repository
     */
    public function getRepository($name)
    {
        if (isset($this->repositories[$name])) {
            return $this->repositories[$name];
        }

        return $this->repositories[$name] = new Repository($this, $name);
    }

    /**
     * @param $className
     * @return object
     */
    public function getObject($className)
    {
        $instantiator = new \Doctrine\Instantiator\Instantiator();
        return $instantiator->instantiate($className);
    }
}

<?php
/**
 * @author: Patsura Dmitry http://github.com/ovr <talk@dmtry.me>
 */

namespace Lynx;

use Doctrine\DBAL\Connection;

class EntityManager
{
    /**
     * @var Connection
     */
    protected $connection;

    /**
     * @var Repository[]
     */
    protected $repositories;

    public function __construct(\Doctrine\DBAL\Connection $connection)
    {
        $this->connection = $connection;
    }

    /**
     * @return \Doctrine\DBAL\Query\QueryBuilder
     */
    public function createQueryBuilder()
    {
        return $this->connection->createQueryBuilder();
    }

    /**
     * @param $className
     * @param $id
     * @return null|object
     */
    public function find($className, $id)
    {
        return $this->getRepository($className)->getOne($id);
    }

    /**
     * @param $className
     * @return Repository
     */
    public function getRepository($className)
    {
        if (isset($this->repositories[$className])) {
            return $this->repositories[$className];
        }

        if (class_exists($className . 'Repository', true)) {
            $class = $className . 'Repository';
            return $this->repositories[$className] = new $class($this, $className);
        }

        return $this->repositories[$className] = new Repository($this, $className);
    }

    /**
     * @param $className
     * @return object
     */
    public function getObject($className)
    {
        $instantiator = new \Doctrine\Instantiator\Instantiator();
        return $instantiator->instantiate($className);
    }
}

Allow to use own Repositories like UserRepository


<?php

/**
 * This file is part of the Minty templating library.
 * (c) Dániel Buga <daniel@bugadani.hu>
 *
 * For licensing information see the LICENSE file.
 */

namespace Minty\Compiler\Tags;

use Minty\Compiler\Parser;
use Minty\Compiler\Stream;
use Minty\Compiler\Tag;

class ExtendsTag extends Tag
{

    public function getTag()
    {
        return 'extends';
    }

    public function parse(Parser $parser, Stream $stream)
    {
        $parser->getCurrentClassNode()->setParentTemplate(
            $parser->parseExpression($stream)
        );
    }
}

<?php

/**
 * This file is part of the Minty templating library.
 * (c) Dániel Buga <daniel@bugadani.hu>
 *
 * For licensing information see the LICENSE file.
 */

namespace Minty\Compiler\Tags;

use Minty\Compiler\Exceptions\ParseException;
use Minty\Compiler\Parser;
use Minty\Compiler\Stream;
use Minty\Compiler\Tag;

class ExtendsTag extends Tag
{

    public function getTag()
    {
        return 'extends';
    }

    public function parse(Parser $parser, Stream $stream)
    {
        if(!$parser->inMainScope()) {
            throw new ParseException(
                "Extends tags must be placed in the main scope. Unexpected extends tag",
                $stream->current()->getLine()
            );
        }
        $parser->getCurrentClassNode()->setParentTemplate(
            $parser->parseExpression($stream)
        );
    }
}

Throw an exception when extends tag is not in the main scope.


<?php namespace Flarum\Events;

use Flarum\Api\Actions\SerializeAction;

class BuildApiAction
{
    protected $action;

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

    public function serializer($serializer)
    {
        $this->action->serializer = $serializer;
    }

    public function addInclude($relation, $default = true)
    {
        $this->action->include[$relation] = $default;
    }

    public function removeInclude($relation)
    {
        unset($this->action->include[$relation]);
    }

    public function addLink($relation)
    {
        $this->action->link[] = $relation;
    }

    public function removeLink($relation)
    {
        if (($k = array_search($relation, $this->action->link)) !== false) {
            unset($this->action->link[$k]);
        }
    }

    public function limitMax($limitMax)
    {
        $this->action->limitMax = $limitMax;
    }

    public function limit($limit)
    {
        $this->action->limit = $limit;
    }

    public function addSortField($field)
    {
        $this->action->sortFields[] = $field;
    }

    public function removeSortField($field)
    {
        if (($k = array_search($field, $this->action->sortFields)) !== false) {
            unset($this->action->sortFields[$k]);
        }
    }

    public function sort($sort)
    {
        $this->action->sort = $sort;
    }
}

<?php namespace Flarum\Events;

use Flarum\Api\Actions\SerializeAction;

class BuildApiAction
{
    public $action;

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

    public function serializer($serializer)
    {
        $this->action->serializer = $serializer;
    }

    public function addInclude($relation, $default = true)
    {
        $this->action->include[$relation] = $default;
    }

    public function removeInclude($relation)
    {
        unset($this->action->include[$relation]);
    }

    public function addLink($relation)
    {
        $this->action->link[] = $relation;
    }

    public function removeLink($relation)
    {
        if (($k = array_search($relation, $this->action->link)) !== false) {
            unset($this->action->link[$k]);
        }
    }

    public function limitMax($limitMax)
    {
        $this->action->limitMax = $limitMax;
    }

    public function limit($limit)
    {
        $this->action->limit = $limit;
    }

    public function addSortField($field)
    {
        $this->action->sortFields[] = $field;
    }

    public function removeSortField($field)
    {
        if (($k = array_search($field, $this->action->sortFields)) !== false) {
            unset($this->action->sortFields[$k]);
        }
    }

    public function sort($sort)
    {
        $this->action->sort = $sort;
    }
}

Fix incorrect member visibility on event


<?php

namespace Lily\Test\Usage;

use Symfony\Component\DomCrawler\Crawler;

use Lily\Application\MiddlewareApplication;
use Lily\Application\RoutedApplication;

use Lily\Util\Request;
use Lily\Util\Response;

class DescribeTestingTest extends \PHPUnit_Framework_TestCase
{
    private function applicationToTest()
    {
        $html = file_get_contents(dirname(__FILE__).'/example.html');
        return
            new MiddlewareApplication(
                array(
                    new RoutedApplication(
                        array(
                            array('POST', '/form', $html)))));
    }

    private function applicationResponse($request)
    {
        $application = $this->applicationToTest();
        return $application($request);
    }

    private function filterNotEmpty($html, $filter)
    {
        $crawler = new Crawler($html);
        return $crawler->filter($filter)->count() > 0;
    }

    private function responseBodyHasClass($response, $class)
    {
        return $this->filterNotEmpty($response['body'], $class);
    }

    public function testFormErrorShouldBeShown()
    {
        $response = $this->applicationResponse(Request::post('/form'));
        $this->assertTrue($this->responseBodyHasClass($response, '.error'));
    }

    public function testFormShouldSuccessfullySubmit()
    {
        $response = $this->applicationResponse(Request::post('/form'));
        $this->assertTrue($this->responseBodyHasClass($response, 'h1.success'));
    }
}

<?php

namespace Lily\Test\Usage;

use Symfony\Component\DomCrawler\Crawler;

use Lily\Application\MiddlewareApplication;
use Lily\Application\RoutedApplication;

use Lily\Util\Request;
use Lily\Util\Response;

class DescribeTestingTest extends \PHPUnit_Framework_TestCase
{
    private function applicationToTest()
    {
        $html = file_get_contents(dirname(__FILE__).'/example.html');
        return
            new MiddlewareApplication(
                array(
                    new RoutedApplication(
                        array(
                            array('POST', '/form', $html)))));
    }

    private function applicationResponse($request)
    {
        $application = $this->applicationToTest();
        return $application($request);
    }

    private function htmlHasClass($html, $class)
    {
        $crawler = new Crawler($html);
        return $crawler->filter($class)->count() > 0;
    }

    private function responseBodyHasClass($response, $class)
    {
        return $this->htmlHasClass($response['body'], $class);
    }

    public function testFormErrorShouldBeShown()
    {
        $response = $this->applicationResponse(Request::post('/form'));
        $this->assertTrue($this->responseBodyHasClass($response, '.error'));
    }

    public function testFormShouldSuccessfullySubmit()
    {
        $response = $this->applicationResponse(Request::post('/form'));
        $this->assertTrue($this->responseBodyHasClass($response, 'h1.success'));
    }
}

Rename method and param to better describe what is happening


<?php
/**
 * Configuration
 *
 */
Configure::write('Translate.models', array(
	'Node' => array(
		'fields' => array(
			'title' => 'titleTranslation',
			'excerpt' => 'excerptTranslation',
			'body' => 'bodyTranslation',
		),
		'translateModel' => 'Nodes.Node',
	),
	'Block' => array(
		'fields' => array(
			'title' => 'titleTranslation',
			'body' => 'bodyTranslation',
		),
		'translateModel' => 'Blocks.Block',
	),
	'Link' => array(
		'fields' => array(
			'title' => 'titleTranslation',
			'description' => 'descriptionTranslation',
		),
		'translateModel' => 'Menus.Link',
	),
));

/**
 * Do not edit below this line unless you know what you are doing.
 *
 */
foreach (Configure::read('Translate.models') as $translateModel => $config) {
	Croogo::hookBehavior($translateModel, 'Translate.CroogoTranslate', $config);
	Croogo::hookAdminRowAction(Inflector::pluralize($translateModel) . '/admin_index', 'Translate', 'admin:true/plugin:translate/controller:translate/action:index/:id/' . $translateModel);
}

<?php
/**
 * Configuration
 *
 */
Configure::write('Translate.models', array(
	'Node' => array(
		'fields' => array(
			'title' => 'titleTranslation',
			'excerpt' => 'excerptTranslation',
			'body' => 'bodyTranslation',
		),
		'translateModel' => 'Nodes.Node',
	),
	'Block' => array(
		'fields' => array(
			'title' => 'titleTranslation',
			'body' => 'bodyTranslation',
		),
		'translateModel' => 'Blocks.Block',
	),
	'Contact' => array(
		'fields' => array(
			'title' => 'titleTranslation',
			'body' => 'bodyTranslation',
		),
		'translateModel' => 'Contacts.Contact',
	),
	'Link' => array(
		'fields' => array(
			'title' => 'titleTranslation',
			'description' => 'descriptionTranslation',
		),
		'translateModel' => 'Menus.Link',
	),
));

/**
 * Do not edit below this line unless you know what you are doing.
 *
 */
foreach (Configure::read('Translate.models') as $translateModel => $config) {
	Croogo::hookBehavior($translateModel, 'Translate.CroogoTranslate', $config);
	Croogo::hookAdminRowAction(Inflector::pluralize($translateModel) . '/admin_index', 'Translate', 'admin:true/plugin:translate/controller:translate/action:index/:id/' . $translateModel);
}

Enable translations for Contact fields

Enable translations for Contact fields

Closes #387


<?php

namespace Friendica\Module;

use Friendica\Core\L10n;
use Friendica\Core\Renderer;
use Friendica\Model;

/**
 * @author Hypolite Petovan <mrpetovan@gmail.com>
 */
class Itemsource extends \Friendica\BaseModule
{
	public static function content()
	{
		if (!is_site_admin()) {
			return;
		}

		$source = '';
		$item_uri = '';
		if (!empty($_REQUEST['guid'])) {
			$item = Model\Item::selectFirst([], ['guid' => $_REQUEST['guid']]);

			$conversation = Model\Conversation::getByItemUri($item['uri']);

			$item_uri = $item['uri'];
			$source = $conversation['source'];
		}

		$tpl = Renderer::getMarkupTemplate('debug/itemsource.tpl');
		$o = Renderer::replaceMacros($tpl, [
			'$guid'          => ['guid', L10n::t('Item Guid'), defaults($_REQUEST, 'guid', ''), ''],
			'$source'        => $source,
			'$item_uri'      => $item_uri
		]);

		return $o;
	}
}

<?php

namespace Friendica\Module;

use Friendica\Core\L10n;
use Friendica\Core\Renderer;
use Friendica\Model;

/**
 * @author Hypolite Petovan <mrpetovan@gmail.com>
 */
class Itemsource extends \Friendica\BaseModule
{
	public static function content()
	{
		if (!is_site_admin()) {
			return;
		}

		$a = self::getApp();

		if (!empty($a->argv[1])) {
			$guid = $a->argv[1];
		}

		$guid = defaults($_REQUEST['guid'], $guid);

		$source = '';
		$item_uri = '';
		if (!empty($guid)) {
			$item = Model\Item::selectFirst([], ['guid' => $guid]);

			$conversation = Model\Conversation::getByItemUri($item['uri']);

			$item_uri = $item['uri'];
			$source = $conversation['source'];
		}

		$tpl = Renderer::getMarkupTemplate('debug/itemsource.tpl');
		$o = Renderer::replaceMacros($tpl, [
			'$guid'          => ['guid', L10n::t('Item Guid'), defaults($_REQUEST, 'guid', ''), ''],
			'$source'        => $source,
			'$item_uri'      => $item_uri
		]);

		return $o;
	}
}

Add query path capabilities to /itemsource


<?php

namespace Happyr\TranslationBundle\Service;

use Happyr\TranslationBundle\Model\Message;

class Blackhole implements TranslationServiceInterface
{
    /**
     * @inheritDoc
     */
    public function fetchTranslation(Message $message, $updateFs = false)
    {
    }

    /**
     * @inheritDoc
     */
    public function updateTranslation(Message $message)
    {
    }

    /**
     * @inheritDoc
     */
    public function flagTranslation(Message $message, $type = 0)
    {
    }

    /**
     * @inheritDoc
     */
    public function createAsset(Message $message)
    {
    }

    /**
     * @inheritDoc
     */
    public function downloadAllTranslations()
    {
    }

    /**
     * @inheritDoc
     */
    public function importAllTranslations()
    {
    }

    /**
     * @inheritDoc
     */
    public function synchronizeAllTranslations()
    {
    }

}

<?php

namespace Happyr\TranslationBundle\Service;

use Happyr\TranslationBundle\Model\Message;

class Blackhole implements TranslationServiceInterface
{
    /**
     * @inheritDoc
     */
    public function fetchTranslation(Message $message, $updateFs = false)
    {
    }

    /**
     * @inheritDoc
     */
    public function updateTranslation(Message $message)
    {
    }

    /**
     * @inheritDoc
     */
    public function flagTranslation(Message $message, $type = 0)
    {
    }

    /**
     * @inheritDoc
     */
    public function createAsset(Message $message)
    {
    }

    /**
     * @inheritDoc
     */
    public function downloadAllTranslations()
    {
    }

    /**
     * @inheritDoc
     */
    public function importAllTranslations()
    {
    }

    /**
     * @inheritDoc
     */
    public function synchronizeAllTranslations()
    {
    }

    /**
     * @inheritDoc
     */
    public function uploadAllTranslations()
    {
    }
}

Make sure blackhole implmenents its interface


<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Bus\DispatchesCommands;

abstract class Controller extends BaseController
{
    use DispatchesCommands, ValidatesRequests;
}

<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Bus\DispatchesCommands;

abstract class Controller extends BaseController
{
    use DispatchesCommands, ValidatesRequests;

    protected $log;

    public function __construct()
    {
        $this->log = app('log');
    }
}

Add protected $log access to logger

Add protected $log access to logger

Allows to: Avoid using static access to class '\Log' in method '...'