<?php
/**
 * Laravel 4 Repository classes
 *
 * @author   Andreas Lutro <anlutro@gmail.com>
 * @license  http://opensource.org/licenses/MIT
 * @package  l4-repository
 */

namespace anlutro\LaravelRepository;

use Illuminate\Database\Eloquent\Model;

class SoftDeletingEloquentRepository extends EloquentRepository
{

    /**
     * @var boolean
     */
    protected $onlyTrashed = false;

    /**
     * @var boolean
     */
    protected $withTrashed = false;

    /**
     * @param \Illuminate\Database\Eloquent\Model $model
     */
    public function restore($model)
    {
        $model->restore();
    }

    /**
     * Limit to trashed entities.
     */
    public function onlyTrashed()
    {
        $this->onlyTrashed = true;
        $this->withTrashed = false;
    }

    /**
     * Return trashed entites aswell.
     */
    public function withTrashed()
    {
        $this->onlyTrashed = false;
        $this->withTrashed = true;
    }

    /**
     * {@inheritdoc}
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    protected function newQuery()
    {
        if ($this->onlyTrashed === true) {
            return call_user_func([$this->model, 'onlyTrashed']);
        }

        if ($this->withTrashed === true) {
            return call_user_func([$this->model, 'withTrashed']);
        }

        return $this->model->newQuery();
    }

}

<?php
/**
 * Laravel 4 Repository classes
 *
 * @author   Andreas Lutro <anlutro@gmail.com>
 * @license  http://opensource.org/licenses/MIT
 * @package  l4-repository
 */

namespace anlutro\LaravelRepository;

use Illuminate\Database\Eloquent\Model;

class SoftDeletingEloquentRepository extends EloquentRepository
{

    /**
     * @var boolean
     */
    protected $onlyTrashed = false;

    /**
     * @var boolean
     */
    protected $withTrashed = false;

    /**
     * @param \Illuminate\Database\Eloquent\Model $model
     */
    public function restore($model)
    {
        $model->restore();
    }

    /**
     * Limit to trashed entities.
     */
    public function onlyTrashed()
    {
        $this->onlyTrashed = true;
        $this->withTrashed = false;
    }

    /**
     * Return trashed entites aswell.
     */
    public function withTrashed()
    {
        $this->onlyTrashed = false;
        $this->withTrashed = true;
    }

    /**
     * {@inheritdoc}
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    protected function newQuery()
    {
        if ($this->onlyTrashed === true) {
            return call_user_func([$this->model, 'onlyTrashed']);
        }

        if ($this->withTrashed === true) {
            return call_user_func([$this->model, 'withTrashed']);
        }

        return parent::newQuery();
    }

}

Return `parent::newQuery();` is not using `withTrashed` or `onlyTrashed`


<?php

// Upload types
define('MX_UPLOAD_TYPE_IMAGE', 'image');
define('MX_UPLOAD_TYPE_DOCUMENT', 'document');
define('MX_UPLOAD_TYPE_AUDIO', 'audio');
define('MX_UPLOAD_TYPE_VIDEO', 'video');

// modules
define('MODULESEARCH', 'Mconsole');
define('BOOTSTRAPFILE', 'bootstrap.php');

<?php

$defines = [
    // Upload types
    'MX_UPLOAD_TYPE_IMAGE' => 'image',
    'MX_UPLOAD_TYPE_DOCUMENT' => 'document',
    'MX_UPLOAD_TYPE_AUDIO' => 'audio',
    'MX_UPLOAD_TYPE_VIDEO' => 'video',

    // modules
    'MODULESEARCH' => 'Mconsole',
    'BOOTSTRAPFILE' => 'bootstrap.php',
];

foreach ($defines as $key => $value) {
    if (!defined($key)) {
        define($key, $value);
    }
}

Check if defined for unit tests

Check if defined for unit tests


<?php

namespace ZephirTestCase;

use Zephir\Commands\CommandBuild;
use Zephir\Config;
use Zephir\Logger as ZephirLogger;
use Zephir\Commands\CommandFullClean;
use Zephir\BaseBackend;

class ZephirRunner
{
    /**
     * @var ZephirExtensionBuilder
     */
    private $zephirExtensionBuilder;
    /**
     * @var \PHPUnit_Util_PHP
     */
    private $phpRunner;

    /**
     * @param ZephirExtensionBuilder $zephirExtensionBuilder
     * @param \PHPUnit_Util_PHP $phpRunner
     */
    public function __construct(ZephirExtensionBuilder $zephirExtensionBuilder, \PHPUnit_Util_PHP $phpRunner)
    {
        $this->zephirExtensionBuilder = $zephirExtensionBuilder;
        $this->phpRunner = $phpRunner;
    }

    /**
     * @param string $zephirCode
     *
     * @throws \Exception
     */
    public function run($zephir, $phpcode, $silent)
    {
        return $this->phpRunner->runJob(
            $phpcode,
            array('extension=' . $this->zephirExtensionBuilder->build($zephir, $silent))
        );
    }
}

<?php

namespace ZephirTestCase;

use Zephir\Commands\CommandBuild;
use Zephir\Config;
use Zephir\Logger as ZephirLogger;
use Zephir\Commands\CommandFullClean;
use Zephir\BaseBackend;

class ZephirRunner
{
    /**
     * @var ZephirExtensionBuilder
     */
    private $zephirExtensionBuilder;
    /**
     * @var \PHPUnit_Util_PHP
     */
    private $phpRunner;

    /**
     * @param ZephirExtensionBuilder $zephirExtensionBuilder
     * @param \PHPUnit_Util_PHP $phpRunner
     */
    public function __construct(ZephirExtensionBuilder $zephirExtensionBuilder, \PHPUnit_Util_PHP $phpRunner)
    {
        $this->zephirExtensionBuilder = $zephirExtensionBuilder;
        $this->phpRunner = $phpRunner;
    }

    /**
     * @param string $zephirCode
     *
     * @throws \Exception
     */
    public function run($zephir, $phpcode, $silent)
    {
        $extensionPath = $this->zephirExtensionBuilder->build($zephir, $silent);

        if (is_file($extensionPath) === false) {
            throw new \InvalidArgumentException(sprintf('Extension should be in "%s" but the file does not exist', $extensionPath));
        }

        return $this->phpRunner->runJob(
            $phpcode,
            array('extension=' . $extensionPath)
        );
    }
}

Add exception if the extension does not exist


<?php

namespace Oro\Bundle\OrganizationBundle\Form\Transformer;

use Doctrine\Common\Collections\Collection;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager;
use Symfony\Component\Form\DataTransformerInterface;

class BusinessUnitTreeTransformer implements DataTransformerInterface
{
    /** @var BusinessUnitManager */
    protected $manager;

    /** @var BusinessUnit */
    protected $entity;

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

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (null == $value) {
            return 0;
        } elseif (is_array($value)) {
            foreach($value as &$val) {
                if ($val === "") {
                    $val =0;
                }
            }

            return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]);
        }

        return $this->manager->getBusinessUnitRepo()->find($value);
    }

    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (null == $value) {
            return 0;
        }

        if (is_array($value) || (is_object($value) && ($value instanceof Collection))) {
            $result = [];
            foreach ($value as $object) {
                $result[] = $object->getId();
            }
        } elseif (is_object($value)) {
            $result = $value->getId();
        } else {
            $result = $value;
        }

        return $result;
    }
}

<?php

namespace Oro\Bundle\OrganizationBundle\Form\Transformer;

use Doctrine\Common\Collections\Collection;
use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
use Oro\Bundle\OrganizationBundle\Entity\Manager\BusinessUnitManager;
use Symfony\Component\Form\DataTransformerInterface;

class BusinessUnitTreeTransformer implements DataTransformerInterface
{
    /** @var BusinessUnitManager */
    protected $manager;

    /** @var BusinessUnit */
    protected $entity;

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

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (null == $value) {
            return 0;
        } elseif (is_array($value)) {
            foreach($value as &$val) {
                if ($val === "") {
                    $val = 0;
                }
            }

            return $this->manager->getBusinessUnitRepo()->findBy(['id' => $value]);
        }

        return $this->manager->getBusinessUnitRepo()->find($value);
    }

    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (null == $value) {
            return 0;
        }

        if (is_array($value) || (is_object($value) && ($value instanceof Collection))) {
            $result = [];
            foreach ($value as $object) {
                $result[] = $object->getId();
            }
        } elseif (is_object($value)) {
            $result = $value->getId();
        } else {
            $result = $value;
        }

        return $result;
    }
}

BAP-10985: Update the rules displaying autocomplete result for business unit owner field


<?php

    global $wp_query;

    $slider_or_image       = '';
    $page_parent_image     = function_exists('get_field') ? get_field('header_image', $wp_query->post->post_parent) : '';
    $page_parent_animation = function_exists('get_field') ? get_field('show_vobe_animation', $wp_query->post->post_parent) : '';
    $page_google_map       = function_exists('get_field') ? get_field('show_google_map', $wp_query->post->post_parent) : '';

    if ( $page_parent_image ) {

        $slider_or_image =  wp_get_attachment_image( $page_parent_image, 'full' );

    } else if ( is_front_page() ) {

        $slider_or_image = do_shortcode( '[responsive_slider]' );

    } else if ( $page_parent_animation ) {

        $slider_or_image = get_template_part('templates/animation');

    } else if ( $page_google_map ) {

        $slider_or_image = get_option('plugin_options')['vobe_google_map_code'];

    }

    echo $slider_or_image;

?>

<?php

    global $wp_query;

    $slider_or_image       = '';
    $page_parent_image     = function_exists('get_field') ? get_field('header_image', $wp_query->post->post_parent) : '';
    $page_parent_animation = function_exists('get_field') ? get_field('show_vobe_animation', $wp_query->post->post_parent) : '';
    $page_google_map       = function_exists('get_field') ? get_field('show_google_map', $wp_query->post->post_parent) : '';

    if ( $page_parent_image ) {

        $slider_or_image =  wp_get_attachment_image( $page_parent_image, 'full' );

    } else if ( is_front_page() ) {

        $slider_or_image = do_shortcode( '[responsive_slider]' );

    } else if ( $page_parent_animation ) {

        $slider_or_image = get_template_part('templates/animation');

    } else if ( $page_google_map ) {

        $options = $get_option('plugin_options');
        $slider_or_image = $options['vobe_google_map_code'];

    }

    echo $slider_or_image;

?>

Fix teaser image for maps.

Fix teaser image for maps.


<?php
/**
 * This file is part of the TelegramBot package.
 *
 * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Longman\TelegramBot\Commands\SystemCommands;

use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Request;

/**
 * Callback query command
 */
class CallbackqueryCommand extends SystemCommand
{
    /**
     * @var string
     */
    protected $name = 'callbackquery';

    /**
     * @var string
     */
    protected $description = 'Reply to callback query';

    /**
     * @var string
     */
    protected $version = '1.1.0';

    /**
     * Command execute method
     *
     * @return mixed
     * @throws \Longman\TelegramBot\Exception\TelegramException
     */
    public function execute()
    {
        $update            = $this->getUpdate();
        $callback_query    = $update->getCallbackQuery();
        $callback_query_id = $callback_query->getId();
        $callback_data     = $callback_query->getData();

        $data = [
            'callback_query_id' => $callback_query_id,
            'text'              => 'Hello World!',
            'show_alert'        => $callback_data === 'thumb up',
        ];

        return Request::answerCallbackQuery($data);
    }
}

<?php
/**
 * This file is part of the TelegramBot package.
 *
 * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Longman\TelegramBot\Commands\SystemCommands;

use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Request;

/**
 * Callback query command
 */
class CallbackqueryCommand extends SystemCommand
{
    /**
     * @var string
     */
    protected $name = 'callbackquery';

    /**
     * @var string
     */
    protected $description = 'Reply to callback query';

    /**
     * @var string
     */
    protected $version = '1.1.0';

    /**
     * Command execute method
     *
     * @return mixed
     * @throws \Longman\TelegramBot\Exception\TelegramException
     */
    public function execute()
    {
        $update            = $this->getUpdate();
        $callback_query    = $update->getCallbackQuery();
        $callback_query_id = $callback_query->getId();
        $callback_data     = $callback_query->getData();

        $data = [
            'callback_query_id' => $callback_query_id,
            'text'              => 'Hello World!',
            'show_alert'        => $callback_data === 'thumb up',
            'cache_time'        => 5,
        ];

        return Request::answerCallbackQuery($data);
    }
}

Add example of new cache_time field for callback queries.


<?php

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

class CleanWebArtists extends Migration
{
    public function up()
    {
        Schema::table('web_artists', function (Blueprint $table) {
            $table->dropColumn('title');
        });

        Schema::table('web_artists', function (Blueprint $table) {
            $table->renameColumn('datahub_id', 'agent_id');
            $table->index('agent_id');
        });
    }

    public function down()
    {
        Schema::table('web_artists', function (Blueprint $table) {
            $table->text('title')->after('id');
        });

        Schema::table('web_artists', function (Blueprint $table) {
            $table->dropIndex(['agent_id']);
            $table->renameColumn('agent_id', 'datahub_id');
        });
    }
}

<?php

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

class CleanWebArtists extends Migration
{
    public function up()
    {
        Schema::table('web_artists', function (Blueprint $table) {
            $table->dropColumn('title');
        });

        Schema::table('web_artists', function (Blueprint $table) {
            $table->renameColumn('datahub_id', 'agent_id');
            $table->index('agent_id');
        });

        Schema::table('web_artists', function (Blueprint $table) {
            $table->integer('agent_id')->after('id')->change();
        });
    }

    public function down()
    {
        Schema::table('web_artists', function (Blueprint $table) {
            // API-337: Not nullable as an oversight!
            $table->text('title')->after('id');
        });

        Schema::table('web_artists', function (Blueprint $table) {
            $table->integer('agent_id')->after('intro_copy')->change();
        });

        Schema::table('web_artists', function (Blueprint $table) {
            $table->dropIndex(['agent_id']);
            $table->renameColumn('agent_id', 'datahub_id');
        });
    }
}

Move `agent_id` after `id` in `web_artists` [API-341, API-338]


<?php

namespace Lexik\Bundle\TranslationBundle\Util\Profiler;

use Symfony\Component\HttpKernel\Profiler\Profiler;

/**
 * @author Cédric Girard <c.girard@lexik.fr>
 */
class TokenFinder
{
    /**
     * @var Profiler
     */
    private $profiler;

    /**
     * @var int
     */
    private $defaultLimit;

    /**
     * @param Profiler $profiler
     * @param int      $defaultLimit
     */
    public function __construct(?Profiler $profiler, $defaultLimit)
    {
        $this->profiler = $profiler;
        $this->defaultLimit = $defaultLimit;
    }

    /**
     * @param string $ip
     * @param string $url
     * @param int    $limit
     * @param string $method
     * @param string $start
     * @param string $end
     * @return array
     */
    public function find($ip = null, $url = null, $limit = null, $method = null, $start = null, $end = null)
    {
        if ($this->profiler === null) {
            return [];
        }

        $limit = $limit ?: $this->defaultLimit;

        return $this->profiler->find($ip, $url, $limit, $method, $start, $end);
    }
}

<?php

namespace Lexik\Bundle\TranslationBundle\Util\Profiler;

use Symfony\Component\HttpKernel\Profiler\Profiler;

/**
 * @author Cédric Girard <c.girard@lexik.fr>
 */
class TokenFinder
{
    /**
     * @var Profiler
     */
    private $profiler;

    /**
     * @var int
     */
    private $defaultLimit;

    /**
     * @param Profiler $profiler
     * @param int      $defaultLimit
     */
    public function __construct(Profiler $profiler, $defaultLimit)
    {
        $this->profiler = $profiler;
        $this->defaultLimit = $defaultLimit;
    }

    /**
     * @param string $ip
     * @param string $url
     * @param int    $limit
     * @param string $method
     * @param string $start
     * @param string $end
     * @return array
     */
    public function find($ip = null, $url = null, $limit = null, $method = null, $start = null, $end = null)
    {
        $limit = $limit ?: $this->defaultLimit;

        return $this->profiler->find($ip, $url, $limit, $method, $start, $end);
    }
}

Revert Profiler as optional dependency

Revert Profiler as optional dependency


<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\User;

class StatusTest extends TestCase
{
    /**
     * Test the home page returns a 200 status code (OK)
     *
     * @return void
     */
    public function testHomePage()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }

    /**
     * Test the login page redirects to GitHub
     *
     * @return void
     */
    public function testLoginPage()
    {
        $response = $this->get('login');
        parse_str(parse_url($response->headers->get('location'))['query'], $query);

        $response->assertRedirect('https://github.com/login/oauth/authorize?client_id='.env('GITHUB_ID').'&scope=user%3Aemail%2Cadmin%3Aorg&redirect_uri='.env('GITHUB_CALLBACK').'&response_type=code&state='.$query['state']);
    }

    /**
     * Test the dashboard page redirects to login
     *
     * @return void
     */
    public function testDashboardAuth()
    {
        $response = $this->get('dashboard');

        $response->assertRedirect('login');
    }

    /**
     * Test the dashboard returns a 200 status code when logged in (OK)
     *
     * @return void
     */
    public function testDashboard()
    {
        $user = factory(User::class)->create();
        $response = $this->actingAs($user)
                         ->get('dashboard');

        $response->assertStatus(200);
    }
}

<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\User;

class StatusTest extends TestCase
{
    /**
     * Test the home page returns a 200 status code (OK)
     *
     * @return void
     */
    public function testHomePage()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }

    /**
     * Test the login page redirects to GitHub
     *
     * @return void
     */
    public function testLoginPage()
    {
        $response = $this->get('login');
        parse_str(parse_url($response->headers->get('location'))['query'], $query);

        $response->assertRedirect('https://github.com/login/oauth/authorize?client_id='.env('GITHUB_ID').'&scope=user%3Aemail%2Cadmin%3Aorg&redirect_uri='.env('GITHUB_CALLBACK').'&response_type=code&state='.$query['state']);
    }

    /**
     * Test the dashboard page redirects to login
     *
     * @return void
     */
    public function testDashboardAuth()
    {
        $response = $this->get('dashboard');

        $response->assertRedirect('login');
    }

    /**
     * Test the dashboard returns a 200 status code when logged in (OK)
     *
     * @return void
     */
    public function testDashboard()
    {
        $user = factory(User::class)->create();
        $response = $this->actingAs($user)
                         ->get('dashboard');

        $response->assertStatus(200);
        $user->delete();
    }
}

Delete user after dashboard test

:white_check_mark: Delete user after dashboard test


<?php

namespace fieldwork\components;

class TextField extends Field
{

    const ON_ENTER_NEXT   = 'next';
    const ON_ENTER_SUBMIT = 'submit';

    private $onEnter = '',
        $mask = null;

    public function getAttributes ()
    {
        $att = array();
        if (!empty($this->onEnter))
            $att['data-input-action-on-enter'] = $this->onEnter;
        if ($this->mask !== null)
            $att['data-input-mask'] = $this->mask;
        return array_merge(parent::getAttributes(), $att);
    }

    public function onEnter ($action = '')
    {
        $this->onEnter = $action;
        return $this;
    }

    /**
     * Sets input mask for this field
     *
     * @param string $mask
     *
     * @return static
     */
    public function setMask ($mask)
    {
        $this->mask = $mask;
        return $this;
    }

    public function getClasses ()
    {
        return array_merge(
            parent::getClasses(), array('textfield', 'fieldwork-inputfield')
        );
    }

    public function getHTML ($showLabel = true)
    {
        if ($showLabel)
            return sprintf("
<input type='text' %s>%s
",
                $this->getAttributesString(),
                $this->getId(),
                $this->label);
        else
            return sprintf("
<input type='text' %s>
",
                $this->getAttributesString(),
                $this->getId());
    }

}

<?php

namespace fieldwork\components;

class TextField extends Field
{

    const ON_ENTER_NEXT   = 'next';
    const ON_ENTER_SUBMIT = 'submit';

    private $onEnter = '',
        $mask = null;

    public function getAttributes ()
    {
        $att = array();
        if (!empty($this->onEnter))
            $att['data-input-action-on-enter'] = $this->onEnter;
        if ($this->mask !== null)
            $att['data-input-mask'] = $this->mask;
        return array_merge(parent::getAttributes(), $att);
    }

    public function onEnter ($action = '')
    {
        $this->onEnter = $action;
        return $this;
    }

    /**
     * Sets input mask for this field
     *
     * @param string $mask
     *
     * @return static
     */
    public function setMask ($mask)
    {
        $this->mask = $mask;
        return $this;
    }

    public function getClasses ()
    {
        return array_merge(
            parent::getClasses(), array('textfield', 'fieldwork-inputfield')
        );
    }

    public function getHTML ($showLabel = true)
    {
        if ($showLabel)
            return sprintf("
<input type='text' %s>%s
",
                $this->getAttributesString(),
                $this->getId(),
                $this->label);
        else
            return sprintf("
<input placeholder='%s' type='text' %s>
",
                $this->label,
                $this->getAttributesString());
    }

}

Disable the placeholder if the label is hidden


<?php
    namespace DB\Driver;

    /**
     * Database driver for MYSQL using MYSQLI rather than default and deprecated
     * MYSQL which is recommended by most PHP developer.
     *
     * @package DB\Driver
     */
    class MYSQLI implements IDriver
    {
        private $mysqli;

        public function connect($host, $user, $password)
        {
            $this->mysqli = new \mysqli($host, $user, $password);
        }

        public function database($name)
        {
            $this->mysqli->select_db($name);
        }

        public function query($sql)
        {
            $result = $this->mysqli->query($sql);
            return $result->mysqli_fetch_all();
        }

        public function bind($sql, $data=[])
        {
            $length = count($data);
            for ($i=0;$i<$length;$i++)
            {
                $data[$i] = mysqli_escape_string($data[$i]);
            }

            $subs = 0;
            while (($pos = strpos($sql, '?')) !== false)
            {
                $sql = substr_replace($sql, $data[$subs], $pos);
                $subs++;
            }

            return $sql;
        }
    }

?>

<?php
    namespace DB\Driver;

    /**
     * Database driver for MYSQL using MYSQLI rather than default and deprecated
     * MYSQL which is recommended by most PHP developer.
     *
     * @package DB\Driver
     */
    class MYSQLI implements IDriver
    {
        private $mysqli;

        public function connect($host, $user, $password)
        {
            $this->mysqli = new \mysqli($host, $user, $password);
        }

        public function database($name)
        {
            $this->mysqli->select_db($name);
        }

        public function query($sql)
        {
            $result = $this->mysqli->query($sql);
            return $result->mysqli_fetch_all();
        }

        public function bind($sql, $data=[])
        {
            $length = count($data);
            for ($i=0;$i<$length;$i++)
            {
                $data[$i] = mysqli_escape_string($data[$i]);
            }

            $subs = 0;
            while (($pos = strpos($sql, '?')) !== false)
            {
                $sql = substr_replace($sql, $data[$subs], $pos);
                $subs++;
            }

            return $this->query($sql);
        }
    }

?>

Use query result rather than simply syntax binding


<?php

namespace kato\behaviors;

use yii\base\Behavior;
use yii\db\ActiveRecord;

class DefaultTitle extends Behavior {

    /**
     * @var string attribute
     */
    public $attribute = "title";
    public $defaultPrefix = 'New';

    /**
     * @inheritdoc
     */
    public function events()
    {
        return [ActiveRecord::EVENT_BEFORE_INSERT => 'setDefaultValue'];
    }

    public function setDefaultValue()
    {
        $id = $this->getLastRow()->id + 1;
        $this->owner->{$this->attribute} = $this->defaultPrefix . '-' . $id;
    }

    /**
     * Return last row inserted
     * @return mixed
     */
    public function getLastRow()
    {
        return $this->owner->find()
            ->orderBy('id DESC')
            ->one();
    }
}

<?php

namespace kato\behaviors;

use yii\base\Behavior;
use yii\db\ActiveRecord;

class DefaultTitle extends Behavior {

    /**
     * @var string attribute
     */
    public $attribute = "title";
    public $defaultPrefix = 'New';

    /**
     * @inheritdoc
     */
    public function events()
    {
        return [ActiveRecord::EVENT_BEFORE_INSERT => 'setDefaultValue'];
    }

    public function setDefaultValue()
    {
        if (!empty($this->owner->{$this->attribute})) {
            return true;
        }

        $id = $this->getLastRow()->id + 1;
        $this->owner->{$this->attribute} = $this->defaultPrefix . '-' . $id;
    }

    /**
     * Return last row inserted
     * @return mixed
     */
    public function getLastRow()
    {
        return $this->owner->find()
            ->orderBy('id DESC')
            ->one();
    }
}

Set title only if data is empty

Set title only if data is empty


    <?php
    /* translators: %s: Name of current post */
    printf(apply_filters('the_content', $post->post_content));
//                    the_content(sprintf(
//                                    __('Continue reading "%s"', 'twentyseventeen'), get_the_title()
//                    ));

    wp_link_pages(array(
        'before' => '
' . __('Pages:', 'twentyseventeen'),
        'after' => '
',
        'link_before' => '',
        'link_after' => '',
    ));
    ?>

    <?php
    /* translators: %s: Name of current post */
    echo apply_filters('the_content', $post->post_content);
//                    the_content(sprintf(
//                                    __('Continue reading "%s"', 'twentyseventeen'), get_the_title()
//                    ));

    wp_link_pages(array(
        'before' => '
' . sprintf('
%s
', __('Page', 'twentyseventeen')),
        'after' => '
',
        'link_before' => '',
        'link_after' => '',
    ));
    ?>

Add Pages title and code clean

Add Pages title and code clean


<?php

class AuthController extends BaseController {

    public function login()
    {
        $remember = Input::get('remember') == 'true' ? true : false;

        if (Auth::attempt(['shadow_name' => Str::lower(Input::get('username')),
            'password' => Input::get('password'), 'is_activated' => true], $remember))
        {
            if (Auth::user()->removed_at || Auth::user()->blocked_at)
            {
                Auth::logout();
                return Response::json(['error' => 'Account blocked or removed'], 400);
            }

            $folders = Auth::user()->folders->toArray();

            foreach ($folders as &$folder)
            {
                $folder['groups'] = Group::whereIn('_id', $folder['groups'])->get()->toArray();
            }

            $data['user'] = array_merge(Auth::user()->toArray(), [
                'subscribed_groups' => Group::whereIn('_id', Auth::user()->subscribedGroups())->get()->toArray(),
                'blocked_groups' => Group::whereIn('_id', Auth::user()->blockedGroups())->get()->toArray(),
                'moderated_groups' => Group::whereIn('_id', Auth::user()->moderatedGroups())->get()->toArray(),
                'folders' => $folders,
            ]);

            return Response::json($data);
        }

        return Response::json(['error' => 'Invalid login or password'], 400);
    }

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

}

<?php

class AuthController extends BaseController {

    public function login()
    {
        $remember = Input::get('remember') == 'true' ? true : false;

        if (Auth::attempt(['shadow_name' => Str::lower(Input::get('username')),
            'password' => Input::get('password'), 'is_activated' => true], $remember))
        {
            if (Auth::user()->removed_at || Auth::user()->blocked_at)
            {
                Auth::logout();
                return Response::json(['error' => 'Account blocked or removed'], 400);
            }

            $folders = Auth::user()->folders->toArray();

            foreach ($folders as &$folder)
            {
                $folder['groups'] = Group::whereIn('_id', $folder['groups'])->get()->toArray();
            }

            $notifications = Notification::with(['sourceUser' => function($q) { $q->select('avatar')->remember(3); }])
                ->target(['user_id' => Auth::id()])
                ->orderBy('created_at', 'desc')
                ->take(15)->get();

            $data['user'] = array_merge(Auth::user()->toArray(), [
                'subscribed_groups' => Group::whereIn('_id', Auth::user()->subscribedGroups())->get()->toArray(),
                'blocked_groups' => Group::whereIn('_id', Auth::user()->blockedGroups())->get()->toArray(),
                'moderated_groups' => Group::whereIn('_id', Auth::user()->moderatedGroups())->get()->toArray(),
                'folders' => $folders,
                'notifications' => $notifications,
            ]);

            return Response::json($data);
        }

        return Response::json(['error' => 'Invalid login or password'], 400);
    }

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

}

Add notifications to retsult of api /login method


#!/usr/bin/env php
<?php
/**
 * Protokollen - create services and add hostnames from entity definitions
 */

require_once('../php/Protokollen.class.php');

$p = new Protokollen();

$m = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$m->set_charset(DB_CHARSET) or die("$m->error\n");

$q = 'SELECT domain FROM entities WHERE domain IS NOT NULL ORDER BY id';
$r = $m->query($q) or die("$m->error, SQL: $q\n");
while($row = $r->fetch_object()) {
	/* Load entity */
	$e = $p->getEntityByDomain($row->domain);

	/* Add HTTP service */
	$s = $p->addService($e->id, Protokollen::SERVICE_TYPE_HTTP, $e->domain, 'Webbsajt '. $e->org);
	$p->addServiceHostname($s->id, $e->domain);
	$p->addServiceHostname($s->id, 'www.'. $e->domain);

	/* Add SMTP service */
	if($e->domain_email === NULL)
		continue;

	$s = $p->addService($e->id, Protokollen::SERVICE_TYPE_SMTP, $e->domain_email, 'E-postdomän '. $e->org);
	/* Not yet implemented - should this be MX pointers instead? */
	$p->addServiceHostname($s->id, $e->domain_email);
}

$r->close();

#!/usr/bin/env php
<?php
/**
 * Protokollen - create services and add hostnames from entity definitions
 */

require_once('../php/Protokollen.class.php');

$p = new Protokollen();

foreach($p->listEntityDomains() as $domain) {
	/* Load entity */
	$e = $p->getEntityByDomain($domain);

	/* Add HTTP service */
	$s = $p->addService($e->id, Protokollen::SERVICE_TYPE_HTTP, $e->domain, 'Webbsajt '. $e->org);
	$p->addServiceHostname($s->id, $e->domain);
	$p->addServiceHostname($s->id, 'www.'. $e->domain);

	/* Add SMTP service */
	if($e->domain_email === NULL)
		continue;

	$s = $p->addService($e->id, Protokollen::SERVICE_TYPE_SMTP, $e->domain_email, 'E-postdomän '. $e->org);
	/* Not yet implemented - should this be MX pointers instead? */
	$p->addServiceHostname($s->id, $e->domain_email);
}

Use Protokollen class instead of raw MySQL queries


Auditions

Auditions for Partial Credit are held once per semester. Come check
      us out at the activities fair to sign up for an audition time or look
      for fliers posted around campus for information about audition
      opportunities!

During auditions, we'll ask you to:

Go up and down scales to warm up and test your range

Do a volume exercise (crescendo and decrescendo on a single
          pitch)

Match patterns of notes played on a piano

Perform one to two minutes of a song of your choice (usually a
          verse and a chorus)

Do some impromptu vocal percussion if you can

Just remember to relax, do your best, and have fun!
      Contact us if you have any questions and to sign
      up for an audition time slot.

Auditions

Auditions for Partial Credit are held once per semester. Come check
      us out at the activities fair to sign up for an audition time or look
      for fliers posted around campus for information about audition
      opportunities!

During auditions, we'll ask you to:

Go up and down scales to warm up and test your range

Do a volume exercise (crescendo and decrescendo on a single
          pitch)

Match patterns of notes played on a piano

Perform about one minute of a song of your choice (usually a verse
          and a chorus)

Do some impromptu vocal percussion if you can

Just remember to relax, do your best, and have fun!
      Contact us if you have any questions and to sign
      up for an audition time slot.

Change audition recommendations on auditions page


<!DOCTYPE html>

        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">

        @yield('head')

            @yield('content')

        @include('analytics')

<!DOCTYPE html>

        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">

        <title>ekosme.me</title>
        @yield('head')

            @yield('content')

        @include('analytics')

Add title to the site

Add title to the site


<?php

class IndexHandler {
    function get() {
        if (!isset($_SESSION['id'])) {
            global $BASE_URL;
            header("Location: " . $BASE_URL . "promotional.html");
        } else {
            global $smarty;
            global $BASE_DIR;
            include($BASE_DIR . 'pages/common/header.php');
            include($BASE_DIR . 'pages/catalogs/whats-hot.php');
            include($BASE_DIR . 'pages/common/footer.php');
        }
    }

    function get_xhr() {
        if (!isset($_SESSION['id'])) {
            global $BASE_URL;
            header("Location: " . $BASE_URL . "promotional.html");
        } else {
            global $smarty;
            global $BASE_DIR;
            include($BASE_DIR . 'pages/catalogs/whats-hot.php');
        }
    }
}

<?php

class IndexHandler
{
    function get()
    {
        global $smarty;
        global $BASE_DIR;
        include($BASE_DIR . 'pages/common/header.php');
        include($BASE_DIR . 'pages/catalogs/whats-hot.php');
        include($BASE_DIR . 'pages/common/footer.php');
    }

    function get_xhr()
    {
        global $smarty;
        global $BASE_DIR;
        include($BASE_DIR . 'pages/catalogs/whats-hot.php');
    }
}

Stop redirecting to promotinal.html in index.


<?php
/* (c) Anton Medvedev <anton@medv.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Deployer;

desc('Lock deploy');
task('deploy:lock', function () {
    $locked = run("if [ -f {{deploy_path}}/.dep/deploy.lock ]; then echo 'true'; fi")->toBool();

    if ($locked) {
        throw new \RuntimeException(
            "Deploy locked.\n" .
            "Run deploy:unlock command to unlock."
        );
    } else {
        run("touch {{deploy_path}}/.dep/deploy.lock");
    }
});

desc('Unlock deploy');
task('deploy:unlock', function () {
    try {
        run("rm {{deploy_path}}/.dep/deploy.lock");//always success
    } catch (\Exception $e) {
    }
});

<?php
/* (c) Anton Medvedev <anton@medv.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Deployer;

desc('Lock deploy');
task('deploy:lock', function () {
    $locked = run("if [ -f {{deploy_path}}/.dep/deploy.lock ]; then echo 'true'; fi")->toBool();

    if ($locked) {
        throw new \RuntimeException(
            "Deploy locked.\n" .
            "Run deploy:unlock command to unlock."
        );
    } else {
        run("touch {{deploy_path}}/.dep/deploy.lock");
    }
});

desc('Unlock deploy');
task('deploy:unlock', function () {
    run("rm -f {{deploy_path}}/.dep/deploy.lock");//always success
});

Use -f to avoid error when file is not exist

Use -f to avoid error when file is not exist


<?php

namespace App\Libs;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Libs\ViewResolver;
use Illuminate\Http\Request;

abstract class Controller extends BaseController{

    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct(Request $request,ViewResolver $viewResolver){
    	$this->request = $request;

        $this->view = $viewResolver;

       if(app()->isInstalled()){
            foreach(app()->plugins as $plugin){

                    foreach($plugin->getRegister('injectJs',[]) as $js){
                           $this->view->data['jsplugins'][] = str_contains($js,"http")? $js : $plugin->getPath().'/'.$js;
                    }

            }
        }

    }

    public function redirect($location){
    	return redirect($location);
    }

    public function redirectToSelf(){
        return redirect()->back();
    }

    public function insideLink($location){
    	return redirect(\Config::get('horizontcms.backend_prefix')."/".$location);
    }

}

<?php

namespace App\Libs;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Libs\ViewResolver;
use Illuminate\Http\Request;

abstract class Controller extends BaseController{

    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct(Request $request,ViewResolver $viewResolver){
    	$this->request = $request;

        $this->view = $viewResolver;

       if(app()->isInstalled()){
            foreach(app()->plugins as $plugin){

                    foreach($plugin->getRegister('injectJs',[]) as $js){
                           $this->view->data['jsplugins'][] = $plugin->getPath().'/'.$js;
                    }

            }
        }
    }

    public function redirect($location){
    	return redirect($location);
    }

    public function redirectToSelf(){
        return redirect()->back();
    }

    public function insideLink($location){
    	return redirect(\Config::get('horizontcms.backend_prefix')."/".$location);
    }

}

Revert last commit, to avoid vulnerabilities


<?php

namespace Bundle\MenuBundle;

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

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

<?php

namespace Bundle\MenuBundle;

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

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

    public function getNamespace()
    {
        return __NAMESPACE__;
    }

    public function getPath()
    {
        return __DIR__;
    }
}

Implement two new bundle interface methods


<?php namespace Nwidart\Breezometer;

use GuzzleHttp\Client;

class Breezometer
{
    /**
     * @var string
     */
    private $apiKey;

    private $endpoint = 'http://api-beta.breezometer.com';

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

    /**
     * Get BreezoMeter Air Quality Index (BAQI) by Latitude & Longitude
     * @param string $lat
     * @param string $lon
     * @return array
     */
    public function baqi($lat, $lon)
    {
        $baqi = $this->getClient()->get("{$this->endpoint}/baqi/?lat={$lat}&lon={$lon}&key={$this->apiKey}");

        return $baqi->json();
    }

    /**
     * Get BreezoMeter Air Quality Index (BAQI) by Address or Location
     * @param string $location
     * @return array
     */
    public function baqiFromLocation($location)
    {
        $baqi = $this->getClient()->get("{$this->endpoint}/baqi/?location={$location}&key={$this->apiKey}");

        return $baqi->json();
    }

    /**
     * @return Client
     */
    private function getClient()
    {
        return new Client();
    }
}

<?php namespace Nwidart\Breezometer;

use GuzzleHttp\Client;

class Breezometer
{
    /**
     * @var string
     */
    private $apiKey;

    private $endpoint = 'http://api-beta.breezometer.com';

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

    /**
     * Get BreezoMeter Air Quality Index (BAQI) by Latitude & Longitude
     * @param string $lat
     * @param string $lon
     * @return array
     */
    public function baqi($lat, $lon)
    {
        $this->guardAgainstEmptyArguement($lat);
        $this->guardAgainstEmptyArguement($lon);

        $baqi = $this->getClient()->get("{$this->endpoint}/baqi/?lat={$lat}&lon={$lon}&key={$this->apiKey}");

        return $baqi->json();
    }

    /**
     * Get BreezoMeter Air Quality Index (BAQI) by Address or Location
     * @param string $location
     * @return array
     */
    public function baqiFromLocation($location)
    {
        $this->guardAgainstEmptyArguement($location);

        $baqi = $this->getClient()->get("{$this->endpoint}/baqi/?location={$location}&key={$this->apiKey}");

        return $baqi->json();
    }

    /**
     * @return Client
     */
    private function getClient()
    {
        return new Client();
    }

    /**
     * Guard against empty arguments
     * @param string $arg
     * @throws \InvalidArgumentException
     */
    private function guardAgainstEmptyArguement($arg)
    {
        if (empty($arg)) {
            throw new \InvalidArgumentException;
        }
    }
}

Add a guard against empty arguments

Add a guard against empty arguments


<?hh

namespace HackPack\HackMini\Message;

<<Provides('ServerRequest')>>
function buildRequestFromGlobals(
  \FactoryContainer $c,
): \HackPack\HackMini\Message\Request {
  $server = new Map($_SERVER);

  // Determine the http protocol version
  $protocol = HttpProtocolVersion::coerce($server->get('SERVER_PROTOCOL'));
  $protocol = $protocol === null ? HttpProtocolVersion::v10 : $protocol;

  $method =
    $server->containsKey('REQUEST_METHOD')
      ? $server->at('REQUEST_METHOD')
      : '';
  $method = RestMethod::coerce($method);
  if ($method === null) {
    $method = RestMethod::Unknown;
  }

  $uri = $server->containsKey('SCRIPT_URI') ? $server->at('SCRIPT_URI') : '/';

  return new Request(
    $protocol,
    $method,
    Uri::fromString($uri),
    new Map(getallheaders()),
    $c->getServerBody(),
  );
}

<<Provides('ServerBody')>>
function buildServerBodyFromGlobals(
  \FactoryContainer $c,
): \HackPack\HackMini\Message\StreamBody {
  return new StreamBody(fopen('php://input', 'r'));
}

<?hh

namespace HackPack\HackMini\Message;

<<Provides('ServerRequest')>>
function buildRequestFromGlobals(
  \FactoryContainer $c,
): \HackPack\HackMini\Message\Request {
  $server = new Map($_SERVER);

  // Determine the http protocol version
  $protocol = HttpProtocolVersion::coerce($server->get('SERVER_PROTOCOL'));
  $protocol = $protocol === null ? HttpProtocolVersion::v10 : $protocol;

  $method =
    $server->containsKey('REQUEST_METHOD')
      ? $server->at('REQUEST_METHOD')
      : '';
  $method = RestMethod::coerce($method);
  if ($method === null) {
    $method = RestMethod::Unknown;
  }

  $uri = $server->containsKey('REQUEST_URI') ? $server->at('REQUEST_URI') : '/';

  return new Request(
    $protocol,
    $method,
    Uri::fromString($uri),
    new Map(getallheaders()),
    $c->getServerBody(),
  );
}

<<Provides('ServerBody')>>
function buildServerBodyFromGlobals(
  \FactoryContainer $c,
): \HackPack\HackMini\Message\StreamBody {
  return new StreamBody(fopen('php://input', 'r'));
}

Use the request uri, not the script uri.


<?php

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

//$kernel = new AppCache(new AppKernel('prod', false));
$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();

// if you want to use the SonataPageBundle with multisite
// using different relative paths, you must change the request
// object to use the SiteRequest
use Sonata\PageBundle\Request\SiteRequest as Request;

//use Symfony\Component\HttpFoundation\Request;

$kernel->handle(Request::createFromGlobals())->send();

<?php

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

//$kernel = new AppCache(new AppKernel('prod', false));
$kernel = new AppKernel('prod', false);
//$kernel->loadClassCache();

// if you want to use the SonataPageBundle with multisite
// using different relative paths, you must change the request
// object to use the SiteRequest
use Sonata\PageBundle\Request\SiteRequest as Request;

//use Symfony\Component\HttpFoundation\Request;

$kernel->handle(Request::createFromGlobals())->send();

Fix 'Cannot redeclare class Sonata\PageBundle\Request\SiteRequestInterface'


<?php

namespace League\CLImate\Util;

class Cursor
{
    /**
     * Move the cursor up in the terminal x number of lines.
     *
     * @param int $lines
     *
     * @return string
     */
    public function up($lines = 1)
    {
        return "\e[{$lines}A";
    }

    /**
     * Move the cursor left in the terminal x number of columns.
     *
     * @param int $cols
     *
     * @return string
     */
    public function left($cols = 1)
    {
        return "\e[{$cols}D";
    }

    /**
     * Move cursor to the beginning of the current line.
     *
     * @return string
     */
    public function startOfCurrentLine()
    {
        return "\r";
    }

    /**
     * Delete the current line to the end.
     *
     * @return string
     */
    public function deleteCurrentLine()
    {
        return "\e[K";
    }

    /**
     * Get the style for hiding the cursor
     *
     * @return string
     */
    public function hide()
    {
        return "\e[?25l";
    }

    /**
     * Get the style for returning the cursor to its default
     *
     * @return string
     */
    public function defaultStyle()
    {
        return "\e[?25h";
    }
}

<?php

namespace League\CLImate\Util;

class Cursor
{
    /**
     * Move the cursor up in the terminal x number of lines.
     *
     * @param int $lines
     *
     * @return string
     */
    public function up($lines = 1)
    {
        return "\e[{$lines}A";
    }

    /**
     * Move the cursor down in the terminal x number of lines.
     *
     * @param int $lines
     *
     * @return string
     */
    public function down($lines = 1)
    {
        return "\e[{$lines}B";
    }

    /**
     * Move the cursor right in the terminal x number of columns.
     *
     * @param int $cols
     *
     * @return string
     */
    public function right($columns = 1)
    {
        return "\e[{$columns}C";
    }

    /**
     * Move the cursor left in the terminal x number of columns.
     *
     * @param int $cols
     *
     * @return string
     */
    public function left($cols = 1)
    {
        return "\e[{$cols}D";
    }

    /**
     * Move cursor to the beginning of the current line.
     *
     * @return string
     */
    public function startOfCurrentLine()
    {
        return "\r";
    }

    /**
     * Delete the current line to the end.
     *
     * @return string
     */
    public function deleteCurrentLine()
    {
        return "\e[K";
    }

    /**
     * Get the style for hiding the cursor
     *
     * @return string
     */
    public function hide()
    {
        return "\e[?25l";
    }

    /**
     * Get the style for returning the cursor to its default
     *
     * @return string
     */
    public function defaultStyle()
    {
        return "\e[?25h";
    }
}

Add a couple more cursor helpers

Add a couple more cursor helpers


<?php

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Acme\DemoBundle\Form\ContactType;

// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DemoController extends Controller
{
    /**
     * @Route("/", name="_demo")
     * @Template()
     */
    public function indexAction()
    {
        return array();
    }

    /**
     * @Route("/hello/{name}", name="_demo_hello")
     * @Template()
     */
    public function helloAction($name)
    {
        return array('name' => $name);
    }

    /**
     * @Route("/contact", name="_demo_contact")
     * @Template()
     */
    public function contactAction()
    {
        $form = $this->get('form.factory')->create(new ContactType());

        $request = $this->get('request');
        if ('POST' == $request->getMethod()) {
            $form->bindRequest($request);
            if ($form->isValid()) {
                $mailer = $this->get('mailer');
                // .. setup a message and send it
                // http://symfony.com/doc/current/cookbook/email.html

                $this->get('session')->setFlash('notice', 'Message sent!');

                return new RedirectResponse($this->generateUrl('_demo'));
            }
        }

        return array('form' => $form->createView());
    }
}

<?php

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Acme\DemoBundle\Form\ContactType;

// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DemoController extends Controller
{
    /**
     * @Route("/", name="_demo")
     * @Template()
     */
    public function indexAction()
    {
        return array();
    }

    /**
     * @Route("/hello/{name}", name="_demo_hello")
     * @Template()
     */
    public function helloAction($name)
    {
        return array('name' => $name);
    }

    /**
     * @Route("/contact", name="_demo_contact")
     * @Template()
     */
    public function contactAction()
    {
        $form = $this->get('form.factory')->create(new ContactType());

        $request = $this->get('request');
        if ('POST' == $request->getMethod()) {
            $form->bind($request);
            if ($form->isValid()) {
                $mailer = $this->get('mailer');
                // .. setup a message and send it
                // http://symfony.com/doc/current/cookbook/email.html

                $this->get('session')->setFlash('notice', 'Message sent!');

                return new RedirectResponse($this->generateUrl('_demo'));
            }
        }

        return array('form' => $form->createView());
    }
}

Remove a deprecated call to bindRequest()


<?php

namespace CdliTwoStageSignup\Form;

use Zend\Form\Form,
    Zend\Form\Element\Csrf,
    ZfcUser\Mapper\UserInterface as UserMapper,
    ZfcBase\Form\ProvidesEventsForm;

class EmailVerification extends ProvidesEventsForm
{
    public function __construct()
    {
        parent::__construct();

        $this->add(array(
            'name' => 'email',
            'attributes' => array(
                'label' => 'Email Address',
                'type' => 'text',
            ),
        ));

        $this->add(array(
            'name' => 'submit',
            'attributes' => array(
                'label' => 'Verify Email Address',
                'type' => 'submit',
            ),
        ));

        $this->add(new Csrf('csrf'));

        $this->events()->trigger('init', $this);
    }
}

<?php

namespace CdliTwoStageSignup\Form;

use Zend\Form\Form,
    Zend\Form\Element\Csrf,
    ZfcUser\Mapper\UserInterface as UserMapper,
    ZfcBase\Form\ProvidesEventsForm;

class EmailVerification extends ProvidesEventsForm
{
    public function __construct()
    {
        parent::__construct();

        $this->add(array(
            'name' => 'email',
            'attributes' => array(
                'label' => 'Email Address',
                'type' => 'text',
            ),
        ));

        $this->add(array(
            'name' => 'submit',
            'attributes' => array(
                'value' => 'Verify Email Address',
                'type' => 'submit',
            ),
        ));

        $this->add(new Csrf('csrf'));

        $this->events()->trigger('init', $this);
    }
}

Fix typo in form (Submit button, label -> value)


<?php

return [

	/*
	|--------------------------------------------------------------------------
	| Third Party Services
	|--------------------------------------------------------------------------
	|
	| This file is for storing the credentials for third party services such
	| as Stripe, Mailgun, Mandrill, and others. This file provides a sane
	| default location for this type of information, allowing packages
	| to have a conventional place to find your various credentials.
	|
	*/

	'mailgun' => [
		'domain' => '',
		'secret' => '',
	],

	'mandrill' => [
		'secret' => '',
	],

	'ses' => [
		'key' => '',
		'secret' => '',
		'region' => 'us-east-1',
	],

	'stripe' => [
		'model'  => 'App\User',
		'secret' => '',
	],

];

<?php

return [

	/*
	|--------------------------------------------------------------------------
	| Third Party Services
	|--------------------------------------------------------------------------
	|
	| This file is for storing the credentials for third party services such
	| as Stripe, Mailgun, Mandrill, and others. This file provides a sane
	| default location for this type of information, allowing packages
	| to have a conventional place to find your various credentials.
	|
	*/

	'mailgun' => [
		'domain' => getenv('MAILGUN_DOMAIN'),
		'secret' => getenv('MAILGUN_SECRET'),
	],

	'mandrill' => [
		'secret' => '',
	],

	'ses' => [
		'key' => '',
		'secret' => '',
		'region' => 'us-east-1',
	],

	'stripe' => [
		'model'  => 'App\User',
		'secret' => '',
	],

];

Load mailgun settings from env

Config: Load mailgun settings from env


      <?php echo __('Link');?>
      <?php echo __('Comment');?>

  <?php foreach($links as $link):?>

      <?php echo link_to($link->getUrl(),'extlinks/extLinks?table='.$table.'&cid='.$link->getId().'&id='.$eid,array('class' => 'link_catalogue','title' => __('Edit Url') )) ; ?>
      <a href="<?php echo $link->getUrl();?>" target="_pop" class='complete_widget'>
      <?php echo image_tag('next.png',array('title'=>__('Go to this link'))) ; ?>

      <?php echo $link->getComment();?>

      <a class="widget_row_delete" href="<?php echo url_for('catalogue/deleteRelated?table=ext_links&id='.$link->getId());?>" title="<?php echo __('Delete Link') ?>"><?php echo image_tag('remove.png'); ?>

  <?php endforeach;?>

<?php echo image_tag('add_green.png');?><a title="<?php echo __('Add Link');?>" class="link_catalogue" href="<?php echo url_for('extlinks/extLinks?table='.$table.'&id='.$eid);?>"><?php echo __('Add');?>

      <?php echo __('Link');?>
      <?php echo __('Comment');?>

  <?php foreach($links as $link):?>

      <?php echo link_to(image_tag('edit.png'),'extlinks/extLinks?table='.$table.'&cid='.$link->getId().'&id='.$eid,array('class' => 'link_catalogue','title' => __('Edit Url') )) ; ?>

      <a href="<?php echo $link->getUrl();?>" target="_pop" class='complete_widget'>
        <?php echo $link->getUrl();?>

      <?php echo $link->getComment();?>

      <a class="widget_row_delete" href="<?php echo url_for('catalogue/deleteRelated?table=ext_links&id='.$link->getId());?>" title="<?php echo __('Delete Link') ?>"><?php echo image_tag('remove.png'); ?>

  <?php endforeach;?>

<?php echo image_tag('add_green.png');?><a title="<?php echo __('Add Link');?>" class="link_catalogue" href="<?php echo url_for('extlinks/extLinks?table='.$table.'&id='.$eid);?>"><?php echo __('Add');?>

Rework external link style in catalogues


<?php

/*
 * This file is part of the Active Collab Payments project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

declare(strict_types=1);

namespace ActiveCollab\Payments\Subscription;

use ActiveCollab\DateValue\DateTimeValueInterface;
use ActiveCollab\Payments\Common\GatewayedObjectInterface;
use ActiveCollab\Payments\Product\ProductInterface;

interface SubscriptionInterface extends GatewayedObjectInterface, ProductInterface
{
    const MONTHLY = 'monthly';
    const YEARLY = 'yearly';

    const BILLING_PERIODS = [self::MONTHLY, self::YEARLY];

    public function getBillingPeriod(): string;

    public function getNextBillingTimestamp(): DateTimeValueInterface;

    public function &setNextBillingTimestamp(DateTimeValueInterface $value): SubscriptionInterface;

    public function calculateNextBillingTimestamp(DateTimeValueInterface $reference): DateTimeValueInterface;
}

<?php

/*
 * This file is part of the Active Collab Payments project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

declare(strict_types=1);

namespace ActiveCollab\Payments\Subscription;

use ActiveCollab\DateValue\DateTimeValueInterface;
use ActiveCollab\Payments\Common\GatewayedObjectInterface;
use ActiveCollab\Payments\Common\InternallyIdentifiedObjectInterface;
use ActiveCollab\Payments\Common\ReferencedObjectInterface;
use ActiveCollab\Payments\Common\TimestampedObjectInterface;
use ActiveCollab\Payments\Product\ProductInterface;

interface SubscriptionInterface extends
    GatewayedObjectInterface,
    InternallyIdentifiedObjectInterface,
    ProductInterface,
    ReferencedObjectInterface,
    TimestampedObjectInterface
{
    const MONTHLY = 'monthly';
    const YEARLY = 'yearly';

    const BILLING_PERIODS = [self::MONTHLY, self::YEARLY];

    public function getBillingPeriod(): string;

    public function getNextBillingTimestamp(): DateTimeValueInterface;

    public function &setNextBillingTimestamp(DateTimeValueInterface $value): SubscriptionInterface;

    public function calculateNextBillingTimestamp(DateTimeValueInterface $reference): DateTimeValueInterface;
}

Add common interfeces to the subscription interface


<?php
/**
 *
 * @package     OpenFlame Web Framework
 * @copyright   (c) 2010 OpenFlameCMS.com
 * @license     http://opensource.org/licenses/mit-license.php The MIT License
 * @link        https://github.com/OpenFlame/OpenFlame-Framework
 *
 * Minimum Requirement: PHP 5.3.0
 */

namespace OpenFlame\Framework\Header\Submodule;
use OpenFlame\Framework\Core;

if(!defined('OpenFlame\\ROOT_PATH')) exit;

/**
 * OpenFlame Web Framework - Header management submodule interface,
 * 	     Makes sure that we have the methods necessary to manipulate the header management submodule object.
 *
 *
 * @license     http://opensource.org/licenses/mit-license.php The MIT License
 * @link        https://github.com/OpenFlame/OpenFlame-Framework
 */
interface SubmoduleInterface
{
	public static function newInstance();
	public function setManager(\OpenFlame\Framework\Header\Manager $manager);
}

<?php
/**
 *
 * @package     OpenFlame Web Framework
 * @copyright   (c) 2010 OpenFlameCMS.com
 * @license     http://opensource.org/licenses/mit-license.php The MIT License
 * @link        https://github.com/OpenFlame/OpenFlame-Framework
 *
 * Minimum Requirement: PHP 5.3.0
 */

namespace OpenFlame\Framework\Header\Submodule;
use OpenFlame\Framework\Core;

if(!defined('OpenFlame\\ROOT_PATH')) exit;

/**
 * OpenFlame Web Framework - Header management submodule interface,
 * 	     Makes sure that we have the methods necessary to manipulate the header management submodule object.
 *
 *
 * @license     http://opensource.org/licenses/mit-license.php The MIT License
 * @link        https://github.com/OpenFlame/OpenFlame-Framework
 */
interface SubmoduleInterface
{
	public static function newInstance();
	public function setManager(\OpenFlame\Framework\Header\Manager $manager);
	public function injectHeaders();
}

Add another method to the submodule interface


<?php

namespace HostBox\Components;

use Nette;

/**
 * Class SocialPluginComponent
 * @package HostBox\Components
 */
abstract class ComponentFactory extends Nette\Object {

    /** @var mixed */
    protected $config;

    /** @var array */
    protected $plugins;

    public function __call($name, $args) {
        if (substr($name, 0, 6) == 'create' && strlen($name) > 6) {
            if ($this->config === NULL)
                throw new Nette\MemberAccessException('Config is not set');

            $name = substr($name, -(strlen($name) - 6));

            /** @var Nette\Reflection\ClassType $calledClass */
            $calledClass = get_called_class();
            $reflection = $calledClass::getReflection();
            $namespace = $reflection->getNamespaceName();
            $componentName = $namespace . '\\' . $name;

            /** @var ISocialPluginComponent $component */
            $component = new $componentName($this->config);
            if (!empty($args) && is_array($settings = $args[0])) {
                $component->assign($settings);
            }

            return $component;
        } else {
            throw new Nette\MemberAccessException(sprintf('%s is not create method', $name));
        }
    }

}

<?php

namespace HostBox\Components;

use Nette;

/**
 * Class ComponentFactory
 * @package HostBox\Components
 */
abstract class ComponentFactory extends Nette\Object {

    /** @var mixed */
    protected $config;

    /** @var array */
    protected $plugins;

    public function __call($name, $args) {
        if (substr($name, 0, 6) == 'create' && strlen($name) > 6) {
            if ($this->config === NULL)
                throw new Nette\MemberAccessException('Config is not set');

            $name = substr($name, -(strlen($name) - 6));

            /** @var Nette\Reflection\ClassType $calledClass */
            $calledClass = get_called_class();
            $reflection = $calledClass::getReflection();
            $namespace = $reflection->getNamespaceName();
            $componentName = $namespace . '\\' . $name;

            /** @var ISocialPluginComponent $component */
            $component = new $componentName($this->config);
            if (!empty($args) && is_array($settings = $args[0])) {
                $component->assign($settings);
            }

            return $component;
        } else {
            throw new Nette\MemberAccessException(sprintf('%s is not create method', $name));
        }
    }

}

Fix class name in annotation

Fix class name in annotation


<?php
/**
 * Byte values validator
 * @file    Byte.php
 *
 * PHP version 5.3.9+
 *
 * @author  Alexander Yancharuk <alex@itvault.info>
 * @date    Вск Фев 17 10:48:43 2013
 * @copyright The BSD 3-Clause License.
 */

namespace Veles\Validators;

/**
 * Class Byte
 * @author  Alexander Yancharuk <alex@itvault.info>
 */
class Byte implements iValidator
{

	/**
	 * Check byte values
	 * @param mixed $size Size in bytes
	 * @return bool
	 */
	final public function check($size)
	{
		return is_numeric($size);
	}

	/**
	 * Convert byte values to human readable format
	 * @param int $size Size in bytes
	 * @param int $precision Precision of returned values
	 * @return string
	 */
	final public static function format($size, $precision = 2)
	{
		$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');

		$size = max($size, 0);
		$pow = floor(($size ? log($size) : 0) / log(1024));
		$pow = min($pow, count($units) - 1);

		$size /= (1 << (10 * $pow));

		return round($size, $precision) . ' ' . $units[$pow];
	}
}

<?php
/**
 * Byte values validator
 * @file    Byte.php
 *
 * PHP version 5.3.9+
 *
 * @author  Alexander Yancharuk <alex@itvault.info>
 * @date    Вск Фев 17 10:48:43 2013
 * @copyright The BSD 3-Clause License.
 */

namespace Veles\Validators;

/**
 * Class Byte
 * @author  Alexander Yancharuk <alex@itvault.info>
 */
class Byte implements iValidator
{

	/**
	 * Check byte values
	 * @param mixed $size Size in bytes
	 * @return bool
	 */
	final public function check($size)
	{
		return is_numeric($size);
	}

	/**
	 * Convert byte values to human readable format
	 * @param int $size Size in bytes
	 * @param int $precision Precision of returned values
	 * @return string
	 */
	final public static function format($size, $precision = 2)
	{
		$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');

		$size = max($size, 0);
		$pow = floor(($size ? log($size) : 0) / log(1024));
		$pow = min($pow, count($units) - 1);

		$size /= (1 << (10 * $pow));

		return number_format($size, $precision) . ' ' . $units[$pow];
	}
}

Fix formatting in byte validator

Fix formatting in byte validator


<?php

// For basic auth, we want to use the username, not the email address
Route::filter('auth.basic', function()
{
    Config::set('auth.model', 'User');
    return Auth::basic('username');
});

// get the "index" page if we hit the main site
Route::get('/', function()
{
    $page = Page::where('slug', 'index')->first();
    return View::make('page')->with($page->getContent());
});

/**
 * Admin routes - handled by resource controllers in admin/
 */
Route::group(['prefix' => 'sysop', 'before' => 'auth.basic'], function()
{
    Route::get('/', function()
    {
        return Redirect::route('sysop.pages.index');
    });
    Route::resource('pages', 'Admin_PagesController');
    Route::resource('pitches', 'Admin_PitchesController');
});

/**
 * Static page controller
 */
Route::get('/page/{slug}', function($slug)
{
    $page = Page::where('slug', $slug)->first();
    if (empty($page) || !$page->is_visible) {
        return Response::make('Page not found', 404);
    }
    return View::make('page')->with($page->getContent());
});

/**
 * Pitch form
 */
Route::controller('pitch', 'PitchController');

<?php

// For basic auth, we want to use the username, not the email address
Route::filter('auth.basic', function()
{
    Config::set('auth.model', 'User');
    return Auth::basic('username');
});

// get the "index" page if we hit the main site
Route::get('/', function()
{
    $page = Page::where('slug', 'index')->first();
    return View::make('page')->with($page->getContent());
});

/**
 * Admin routes - handled by resource controllers in admin/
 */
Route::group(['prefix' => 'sysop', 'before' => 'auth.basic'], function()
{
    Route::get('/', function()
    {
        return Redirect::route('sysop.pages.index');
    });
    Route::resource('pages', 'Admin_PagesController');
    Route::resource('pitches', 'Admin_PitchesController');

    Route::get('/do', function() {
    	for ($i=1; $i < 50; $i++) {
    		$p = new Pitch();
    		$p->name = "Author $i";
    		$p->email = "author$i@gmail.com";
    		$p->blurb = "Lorem ipsum $i et cetera herein forthwith and blah blah blah to the maximum something something furry.";
    		$p->save();
    	}
    	return "Done.";
    });
});

/**
 * Static page controller
 */
Route::get('/page/{slug}', function($slug)
{
    $page = Page::where('slug', $slug)->first();
    if (empty($page) || !$page->is_visible) {
        return Response::make('Page not found', 404);
    }
    return View::make('page')->with($page->getContent());
});

/**
 * Pitch form
 */
Route::controller('pitch', 'PitchController');

Add an arbitrary "do" route for testing purposes


<?php namespace CodeIgniter\Config;

use Config\Email;

class ConfigTest extends \CIUnitTestCase
{

	public function testCreateSingleInstance()
	{
		$Config          = Config::get('Format', false);
		$NamespaceConfig = Config::get('Config\\Format', false);

		$this->assertInstanceOf(Format::class, $Config);
		$this->assertInstanceOf(Format::class, $NamespaceConfig);
	}

	public function testCreateInvalidInstance()
	{
		$Config = Config::get('gfnusvjai', false);

		$this->assertNull($Config);
	}

	public function testCreateSharedInstance()
	{
		$Config  = Config::get('Format' );
		$Config2 = Config::get('Config\\Format');

		$this->assertTrue($Config === $Config2);
	}

	public function testCreateNonConfig()
	{
		$Config = Config::get('Constants', false);

		$this->assertNull($Config);
	}
}

<?php namespace CodeIgniter\Config;

use Config\Format;

class ConfigTest extends \CIUnitTestCase
{

	public function testCreateSingleInstance()
	{
		$Config          = Config::get('Format', false);
		$NamespaceConfig = Config::get('Config\\Format', false);

		$this->assertInstanceOf(Format::class, $Config);
		$this->assertInstanceOf(Format::class, $NamespaceConfig);
	}

	public function testCreateInvalidInstance()
	{
		$Config = Config::get('gfnusvjai', false);

		$this->assertNull($Config);
	}

	public function testCreateSharedInstance()
	{
		$Config  = Config::get('Format' );
		$Config2 = Config::get('Config\\Format');

		$this->assertTrue($Config === $Config2);
	}

	public function testCreateNonConfig()
	{
		$Config = Config::get('Constants', false);

		$this->assertNull($Config);
	}
}

Remove Email module - missed tests

Remove Email module - missed tests


<?php

namespace Zf1Module\Controller;

use Zend\Mvc\Controller\AbstractController;
use Zend\Mvc\MvcEvent;

class DispatchController extends AbstractController
{
    /**
     * Execute the request
     *
     * @param \Zend\Mvc\MvcEvent $event
     * @return \Zend_Controller_Response_Abstract|null
     */
    public function onDispatch(MvcEvent $event)
    {
        /** @var $bootstrap \Zend_Application_Bootstrap_Bootstrap */
        $bootstrap = $this->getServiceLocator()->get('Zf1Module\Application')->getBootstrap();
        $bootstrap->bootstrap();

        /** @var $front \Zend_Controller_Front */
        $front = $bootstrap->getResource('FrontController');
        $front->returnResponse(true);

        /** @var $response \Zend_Controller_Response_Abstract */
        $response = $bootstrap->run();
        if (!$response instanceof \Zend_Controller_Response_Abstract) {
            // looks like ZF1 already sent response, so there is nothing more to do
            $event->stopPropagation();
            return;
        }

        $event->setResult($response);
    }
}

<?php

namespace Zf1Module\Controller;

use Zend\Mvc\Controller\AbstractController;
use Zend\Mvc\MvcEvent;

class DispatchController extends AbstractController
{
    /**
     * Execute the request
     *
     * @param \Zend\Mvc\MvcEvent $event
     * @return \Zend_Controller_Response_Abstract|null
     */
    public function onDispatch(MvcEvent $event)
    {
        /** @var $bootstrap \Zend_Application_Bootstrap_Bootstrap */
        $bootstrap = $event->getApplication()->getServiceManager()->get('Zf1Module\Application')->getBootstrap();
        $bootstrap->bootstrap();

        /** @var $front \Zend_Controller_Front */
        $front = $bootstrap->getResource('FrontController');
        $front->returnResponse(true);

        /** @var $response \Zend_Controller_Response_Abstract */
        $response = $bootstrap->run();
        if (!$response instanceof \Zend_Controller_Response_Abstract) {
            // looks like ZF1 already sent response, so there is nothing more to do
            $event->stopPropagation();
            return;
        }

        $event->setResult($response);
    }
}

Fix deprecation message from zend-mvc 2.7


<?php

namespace EricMakesStuff\ServerMonitor\Monitors;

use EricMakesStuff\ServerMonitor\Exceptions\InvalidConfiguration;

class ServerMonitorFactory
{
    /**
     * @param array $monitorConfiguration
     * @param array $filter
     * @return mixed
     */
    public static function createForMonitorConfig(array $monitorConfiguration, array $filter = [])
    {
        $monitors = collect($monitorConfiguration);

        if (count($filter) && !empty($filter[0])) {
            $monitors = $monitors->only($filter);
        }

        $configured_monitors = collect();

        $monitors->map(function($monitorConfigs, $monitorName) {
            if (file_exists(__DIR__.'/'.ucfirst($monitorName).'Monitor.php')) {
                $className = '\\EricMakesStuff\\ServerMonitor\\Monitors\\'.ucfirst($monitorName).'Monitor';
                return collect($monitorConfigs)->map(function($monitorConfig) use ($className) {
                    return app($className, [$monitorConfig]);
                });
            }

            throw InvalidConfiguration::cannotFindMonitor($monitorName);
        })->each(function($monitor_group) use ($configured_monitors) {
            $monitor_group->each(function($monitor) use ($configured_monitors) {
                $configured_monitors->push($monitor);
            });
        });

        return $configured_monitors;
    }
}

<?php

namespace EricMakesStuff\ServerMonitor\Monitors;

use EricMakesStuff\ServerMonitor\Exceptions\InvalidConfiguration;

class ServerMonitorFactory
{
    /**
     * @param array $monitorConfiguration
     * @param array $filter
     * @return mixed
     */
    public static function createForMonitorConfig(array $monitorConfiguration, array $filter = [])
    {
        $monitors = collect($monitorConfiguration);

        if (count($filter) && !empty($filter[0])) {
            $monitors = $monitors->only($filter);
        }

        $configured_monitors = collect();

        $monitors->map(function($monitorConfigs, $monitorName) {
            if (file_exists(__DIR__.'/'.ucfirst($monitorName).'Monitor.php')) {
                $className = '\\EricMakesStuff\\ServerMonitor\\Monitors\\'.ucfirst($monitorName).'Monitor';
                return collect($monitorConfigs)->map(function($monitorConfig) use ($className) {
                    return new $className($monitorConfig);
                });
            }

            throw InvalidConfiguration::cannotFindMonitor($monitorName);
        })->each(function($monitor_group) use ($configured_monitors) {
            $monitor_group->each(function($monitor) use ($configured_monitors) {
                $configured_monitors->push($monitor);
            });
        });

        return $configured_monitors;
    }
}

Update to handle Laravel 5.4

Update to handle Laravel 5.4

(Should still work with 5.1+)


<?php

class m131226_162226_create_user_table extends CDbMigration
{
    public function up()
    {
        $this->createTable('tbl_user', array(
            'id' => 'pk',
            'email' => 'varchar(128) NOT NULL',
            'password' => 'varchar(128) NOT NULL',
            'create_time' => 'int NOT NULL',
            'update_time' => 'int NOT NULL',
            'last_login_time' => 'int',
        ));
        $this->createIndex('tbl_user_email_unique', 'tbl_user', 'email', true);
    }

    public function down()
    {
        $this->dropTable('tbl_user');
    }

    /*
    // Use safeUp/safeDown to do migration with transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}

<?php

class m131226_162226_create_user_table extends CDbMigration
{
    public function up()
    {
        date_default_timezone_set('Europe/Berlin');
        $this->createTable('tbl_user', array(
            'id' => 'pk',
            'email' => 'varchar(128) NOT NULL',
            'password' => 'varchar(128) NOT NULL',
            'create_time' => 'int NOT NULL',
            'update_time' => 'int NOT NULL',
            'last_login_time' => 'int',
        ));
        $this->createIndex('tbl_user_email_unique', 'tbl_user', 'email', true);
        $this->insert('tbl_user', array(
            "email" => "admin@einsle.de",
            "password" => sha1("ni.xd.ol"),
            "create_time" => strtotime('now'),
            "update_time" => strtotime('now'),
        ));
    }

    public function down()
    {
        $this->dropTable('tbl_user');
    }

    /*
    // Use safeUp/safeDown to do migration with transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}

Add sample date into migration script

Add sample date into migration script


<?

  function is_edit_mode() {
    global $c;
    if ($c->isEditMode()) {
      echo "edit-mode";
    }
  }

  function image_tag($t, $img) {
    $imgPath = ($t->getThemePath()) . "/images/";
    echo "<img src='" . $imgPath . $img . "' />";
  }

  function has_blocks($area) {
    global $c;
    return $area->getTotalBlocksInArea($c) > 0;
  }

?>

<?

  function is_edit_mode() {
    global $c;
    if ($c->isEditMode()) {
      echo "edit-mode";
    }
  }

  function is_logged_in() {
    global $u;
    if ($u -> isLoggedIn ()) {
      echo "logged-in";
    }
  }

  function has_blocks($area) {
    global $c;
    return $area->getTotalBlocksInArea($c) > 0;
  }

  function image_tag($t, $img, $html_options = false) {
    $imgPath = ($t->getThemePath()) . "/images/";
    if ($html_options) {
      $options = " alt='" . explode(".", $img, 2)[0] . "'";
      foreach ($html_options as $k => $v) {
        $options .= " " . $k . "='" . $v . "'";
      }
    } else {
      $options = " alt='" . explode(".", $img, 2)[0] . "'";
    };
    echo "<img src='" . $imgPath . $img . "'" . $options . " />";
  }
?>

Add optional html options argument to image tag and add is_logged_in view helper


<?php

namespace josegonzalez\Queuesadilla;

class Job
{
    protected $item;

    protected $backend;

    public function __construct($item, $backend)
    {
        $this->item = $item;
        $this->backend = $backend;
    }

    public function attempts()
    {
        if (array_key_exists('attempts', $this->item)) {
            return $this->item['attempts'];
        }

        return $this->item['attempts'] = 0;
    }

    public function data($key, $default = null)
    {
        if (array_key_exists($key, $this->item['vars'])) {
            return $this->item['vars'][$key];
        }

        return $default;
    }

    public function delete()
    {
        return $this->backend->delete($this->item);
    }

    public function release($delay = 0)
    {
        if (!isset($this->item['attempts'])) {
            $this->item['attempts'] = 0;
        }

        $this->item['attempts'] += 1;
        $this->item['delay'] = $delay;
        return $this->backend->release($this->item);
    }
}

<?php

namespace josegonzalez\Queuesadilla;

class Job
{
    protected $item;

    protected $backend;

    public function __construct($item, $backend)
    {
        $this->item = $item;
        $this->backend = $backend;
    }

    public function attempts()
    {
        if (array_key_exists('attempts', $this->item)) {
            return $this->item['attempts'];
        }

        return $this->item['attempts'] = 0;
    }

    public function data($key = null, $default = null)
    {
        if ($key === null) {
            return $this->item['vars'];
        }

        if (array_key_exists($key, $this->item['vars'])) {
            return $this->item['vars'][$key];
        }

        return $default;
    }

    public function delete()
    {
        return $this->backend->delete($this->item);
    }

    public function release($delay = 0)
    {
        if (!isset($this->item['attempts'])) {
            $this->item['attempts'] = 0;
        }

        $this->item['attempts'] += 1;
        $this->item['delay'] = $delay;
        return $this->backend->release($this->item);
    }
}

Add ability to retrieve the entire item

Add ability to retrieve the entire item


<?php

function mfh_get_mail_headers_for_dropdown($user_id, $hesk_settings, $hesklang) {
    $deleted_user_text = hesk_dbEscape($hesklang['deleted_user_title_case']);
    $sql = "SELECT `mail`.`id` AS `id`, `mail`.`subject` AS `subject`,
              COALESCE(`users`.`name`, '{$deleted_user_text}') AS `from`, `mail`.`dt` AS `date`
        FROM `" . hesk_dbEscape($hesk_settings['db_pfix']) . "mail` AS `mail`
        LEFT JOIN `" . hesk_dbEscape($hesk_settings['db_pfix']) . "users` AS `users`
            ON `mail`.`from` = `users`.`id`
        WHERE `to` = " . hesk_dbEscape($user_id) . "
            AND `read` = '0'
        ORDER BY `mail`.`dt` DESC";

    $rs = hesk_dbQuery($sql);

    $mails = array();
    while ($row = hesk_dbFetchAssoc($rs)) {
        $mails[] = $row;
    }

    return $mails;
}

<?php

function mfh_get_mail_headers_for_dropdown($user_id, $hesk_settings, $hesklang) {
    $deleted_user_text = hesk_dbEscape($hesklang['deleted_user_title_case']);
    $sql = "SELECT `mail`.`id` AS `id`, `mail`.`subject` AS `subject`,
              `users`.`name` AS `from`, `mail`.`dt` AS `date`, `mail`.`from` AS `from_id`
        FROM `" . hesk_dbEscape($hesk_settings['db_pfix']) . "mail` AS `mail`
        LEFT JOIN `" . hesk_dbEscape($hesk_settings['db_pfix']) . "users` AS `users`
            ON `mail`.`from` = `users`.`id`
        WHERE `to` = " . hesk_dbEscape($user_id) . "
            AND `read` = '0'
        ORDER BY `mail`.`dt` DESC";

    $rs = hesk_dbQuery($sql);

    $mails = array();
    while ($row = hesk_dbFetchAssoc($rs)) {
        if ($row['from'] == null) {
            if ($row['from_id'] == 9999) {
                $row['from'] = 'HESK.com';
            } else {
                $row['from'] = $deleted_user_text;
            }
        }

        $mails[] = $row;
    }

    return $mails;
}

Fix 'from' on email header

Fix 'from' on email header


<?php

    /**
     * Vendor Class
     *
     * Manage vendor and can automatically detect vendor.
     *
     * @package Core
     */
    class Vendor
    {
        public function __construct()
        {
            if (ENVIRONMENT == 'testing' || ENVIRONMENT == 'development')
            {
                $dirs = scandir(BASE_PATH);
                $length = count($dirs);
                $arr = array();
                for ($i = 0 ; $i < count($dirs) ; $i++)
                {
                    if ($dirs[$i] != '.' && $dirs[$i] != '..' && $dirs[$i] != '.git' &&
                        is_dir($dirs[$i]))
                    {
                        $arr[] = $dirs[$i];
                    }
                }

                $config =& loadClass('Config', 'Core');
                $config->save('Vendor', $arr);
            }
        }
    }

?>

<?php

    /**
     * Vendor Class
     *
     * Manage vendor and can automatically detect vendor.
     *
     * @package Core
     */
    class Vendor
    {
        private $vendors = array();

        public function __construct()
        {
            if (ENVIRONMENT == 'testing' || ENVIRONMENT == 'development')
            {
                $dirs = scandir(BASE_PATH);
                $length = count($dirs);
                $arr = array();
                for ($i = 0 ; $i < count($dirs) ; $i++)
                {
                    if ($dirs[$i] != '.' && $dirs[$i] != '..' && $dirs[$i] != '.git' &&
                        is_dir($dirs[$i]))
                    {
                        $arr[] = $dirs[$i];
                    }
                }

                $config =& loadClass('Config', 'Core');
                $config->save('Vendor', $arr);
                $this->vendors = $arr;
            }
        }

        public function lists()
        {
            return $this->vendors;
        }
    }

?>

Add method to get lists vendors

Add method to get lists vendors


<?php
/**
 * Created by IntelliJ IDEA.
 * User: luzifer
 * Date: 26.04.14
 * Time: 14:16
 */

class HerokuConfigStore implements IConfigReader {

  /**
   * @var IConfigReader
   */
  private $origin_reader = null;

  /**
   * @param IConfigReader $config_reader Filesystem config reader
   */
  public function __construct($config_reader) {
    $this->origin_reader = $config_reader;
  }

  public function get($config_key, $default = null) {
    if(array_key_exists($config_key, $_ENV)) {
      return $_ENV[$config_key];
    } else {
      return $this->origin_reader->get($config_key, $default);
    }
  }

  public function getSection($config_section_name) {
    $this->origin_reader->getSection($config_section_name);
  }

  public function set($config_key, $config_value) {
    if(array_key_exists($config_key, $_ENV)) {
      throw new HerokuConfigStoreException($config_key . ' is a variable from the read-only-storage at Heroku');
    } else {
      $this->origin_reader->set($config_key, $config_value);
    }
  }
}

class HerokuConfigStoreException extends Exception {}

<?php
/**
 * Created by IntelliJ IDEA.
 * User: luzifer
 * Date: 26.04.14
 * Time: 14:16
 */

class HerokuConfigStore implements IConfigReader {

  /**
   * @var IConfigReader
   */
  private $origin_reader = null;

  /**
   * @param IConfigReader $config_reader Filesystem config reader
   */
  public function __construct($config_reader) {
    $this->origin_reader = $config_reader;
  }

  public function get($config_key, $default = null) {
    $secure_key = str_replace('.', '_', $config_key);
    if(array_key_exists($secure_key, $_ENV)) {
      return $_ENV[$secure_key];
    } else {
      return $this->origin_reader->get($config_key, $default);
    }
  }

  public function getSection($config_section_name) {
    $this->origin_reader->getSection($config_section_name);
  }

  public function set($config_key, $config_value) {
    if(array_key_exists($config_key, $_ENV)) {
      throw new HerokuConfigStoreException($config_key . ' is a variable from the read-only-storage at Heroku');
    } else {
      $this->origin_reader->set($config_key, $config_value);
    }
  }
}

class HerokuConfigStoreException extends Exception {}

Enable Heroku wrapper to read config vars using '.'


<?php /** @var $l \OCP\IL10N */ ?>
<?php
script('core', 'dist/login');
?>

<?php if (!empty($_['alt_login'])) { ?>

        <?php foreach($_['alt_login'] as $login): ?>
            <a class="button <?php p(isset($login['style']) ? $login['style'] : ''); ?>" aria-label="<?php p($login['label']); ?>" href="<?php print_unescaped($login['href']); ?>" >
                <?php p($login['name']); ?>

        <?php endforeach; ?>

<?php } ?>

<?php /** @var $l \OCP\IL10N */ ?>
<?php
script('core', 'dist/login');
?>

<?php if (!empty($_['alt_login'])) { ?>

        <?php foreach($_['alt_login'] as $login): ?>
            <a class="button <?php p($login['style'] ?? ''); ?>" aria-label="<?php p($login['label'] ?? ''); ?>" href="<?php print_unescaped($login['href']); ?>" >
                <?php p($login['name']); ?>

        <?php endforeach; ?>

<?php } ?>

Add null coalesce for label and style attribute

https://github.com/nextcloud/server/pull/16832#discussion_r322380822

Signed-off-by: Jochen <2adebb9ae67263bdef3d87f7c2531201909e0388@gmail.com>


<?php

namespace ParaunitTestCase\Client;

use Doctrine\Common\Persistence\AbstractManagerRegistry;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Client;

/**
 * Class ParaunitTestClient
 * @package Facile\Cbr\CoreBundle\Tests
 */
class ParaunitTestClient extends Client
{
    /**
     * This method checks that the EM is still valid and avoids rebooting the kernel.
     * The EM is cleared every time to avoid inconsistencies.
     * If something broke the EntityManager, the connection is closed, to avoid further usage.
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param bool $rebootKernel If true, reboots the kernel anyway: needed when the container has stale services
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function doRequest($request, $rebootKernel = false)
    {
        if ($rebootKernel) {
            return parent::doRequest($request);
        }

        /** @var AbstractManagerRegistry $doctrine */
        $doctrine = $this->getContainer()->get('doctrine');
        /** @var EntityManagerInterface $manager */
        foreach ($doctrine->getManagers() as $manager) {
            $this->handleManager($manager);
        }

        return $this->kernel->handle($request);
    }

    /**
     * @param EntityManagerInterface $manager
     */
    private function handleManager(EntityManagerInterface $manager)
    {
        $manager->clear();

        if ( ! $manager->isOpen()) {
            $manager->getConnection()->close();
        }
    }
}

<?php

namespace ParaunitTestCase\Client;

use Doctrine\Common\Persistence\AbstractManagerRegistry;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Client;

/**
 * Class ParaunitTestClient
 * @package Facile\Cbr\CoreBundle\Tests
 */
class ParaunitTestClient extends Client
{
    public function rebootKernel()
    {
        $this->kernel->shutdown();
        $this->kernel->boot();
    }

    /**
     * This method checks that the EM is still valid and avoids rebooting the kernel.
     * The EM is cleared every time to avoid inconsistencies.
     * If something broke the EntityManager, the connection is closed, to avoid further usage.
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function doRequest($request)
    {
        /** @var AbstractManagerRegistry $doctrine */
        $doctrine = $this->getContainer()->get('doctrine');
        /** @var EntityManagerInterface $manager */
        foreach ($doctrine->getManagers() as $manager) {
            $this->handleManager($manager);
        }

        return $this->kernel->handle($request);
    }

    /**
     * @param EntityManagerInterface $manager
     */
    private function handleManager(EntityManagerInterface $manager)
    {
        $manager->clear();

        if ( ! $manager->isOpen()) {
            $manager->getConnection()->close();
        }
    }
}

Change of plans: let's have a separate method


<h2>{tr:admin_guests_section}</h2>

<?php Template::display('guests_table', array(
    'status' => 'available',
    'mode' => 'admin',
    'guests' => Guest::all(Guest::AVAILABLE)
)) ?>

Add content to admin guest section

Add content to admin guest section

git-svn-id: 28fe03dfd74dd77dcc8ecfe99fabcec8eed81bba@3374 8555b757-d854-4b86-925a-82fd84c90ff4


<?php

namespace App\Helpers\BBCode\Tags;

class CodeTag extends Tag {

    function __construct()
    {
        $this->token = 'code';
        $this->element = 'code';
    }

    public function FormatResult($result, $parser, $state, $scope, $options, $text)
    {
        $text = $parser->CleanString($text);
        return '<code>' . $text . '</code>';
    }
}

<?php

namespace App\Helpers\BBCode\Tags;

class CodeTag extends Tag {

    function __construct()
    {
        $this->token = 'code';
        $this->element = 'code';
    }

    public function FormatResult($result, $parser, $state, $scope, $options, $text)
    {
        // The text is already html escaped at this point (the default element cleans all strings)
        return '<code>' . $text . '</code>';
    }
}

Fix double escape in the code tag

Fix double escape in the code tag


<?php

namespace JDecool\Bundle\TwigConstantAccessorBundle\DataCollector;

use JDecool\Bundle\TwigConstantAccessorBundle\Accessor\ConstantCollection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;

class ConstantCollector extends DataCollector
{
    /** @var ConstantCollection */
    private $accessors;

    /**
     * Constructor
     *
     * @param ConstantCollection $accessors
     */
    public function __construct(ConstantCollection $accessors)
    {
        $this->accessors = $accessors;
    }

    /**
     * {@inheritdoc}
     */
    public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        $this->data = [
            'accessors' => $this->accessors->toArray(),
        ];
    }

    /**
     * Get all constants accessors declared
     *
     * @return ConstantCollection
     */
    public function getAccessors()
    {
        return $this->data['accessors'];
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'constant_accessor.constant_collector';
    }
}

<?php

namespace JDecool\Bundle\TwigConstantAccessorBundle\DataCollector;

use JDecool\Bundle\TwigConstantAccessorBundle\Accessor\ConstantCollection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;

class ConstantCollector extends DataCollector
{
    /** @var ConstantCollection */
    private $accessors;

    /**
     * Constructor
     *
     * @param ConstantCollection $accessors
     */
    public function __construct(ConstantCollection $accessors)
    {
        $this->accessors = $accessors;
    }

    /**
     * {@inheritdoc}
     */
    public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        $this->data = [
            'accessors' => $this->accessors->toArray(),
        ];
    }

    /**
     * Get all constants accessors declared
     *
     * @return ConstantCollection
     */
    public function getAccessors()
    {
        return $this->data['accessors'];
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'constant_accessor.constant_collector';
    }

    /**
     * {@inheritdoc}
     */
    public function reset()
    {
    }
}

Fix data collector function unimplemented


<?php
namespace Modules\Frontend\Controllers;

use \Entity\Song;

class UtilController extends BaseController
{
    public function testAction()
    {
        $this->doNotRender();

        set_time_limit(0);

        \PVL\Debug::setEchoMode();

        // Sync the BronyTunes library.
        \PVL\Service\BronyTunes::load(true);

        // Sync the Pony.fm library.
        \PVL\Service\PonyFm::load(true);

        // Sync the EqBeats library.
        \PVL\Service\EqBeats::load(true);

        \PVL\Debug::log('Donezo!');
    }
}

<?php
namespace Modules\Frontend\Controllers;

use \Entity\Song;

class UtilController extends BaseController
{
    public function permissions()
    {
        return $this->acl->isAllowed('administer all');
    }

    public function testAction()
    {
        $this->doNotRender();

        set_time_limit(0);

        \PVL\Debug::setEchoMode();

        // Sync the BronyTunes library.
        \PVL\Service\BronyTunes::load(true);

        // Sync the Pony.fm library.
        \PVL\Service\PonyFm::load(true);

        // Sync the EqBeats library.
        \PVL\Service\EqBeats::load(true);

        \PVL\Debug::log('Donezo!');
    }
}

Access control on util script.

Access control on util script.