<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\CacheWarmer;

/**
 * Abstract cache warmer that knows how to write a file to the cache.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
abstract class CacheWarmer implements CacheWarmerInterface
{
    protected function writeCacheFile($file, $content)
    {
        $tmpFile = tempnam(dirname($file), basename($file));
        if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $file)) {
            @chmod($file, 0666 & ~umask());

            return;
        }

        throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $file));
    }
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\CacheWarmer;

/**
 * Abstract cache warmer that knows how to write a file to the cache.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
abstract class CacheWarmer implements CacheWarmerInterface
{
    protected function writeCacheFile($file, $content)
    {
        $tmpFile = @tempnam(dirname($file), basename($file));
        if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $file)) {
            @chmod($file, 0666 & ~umask());

            return;
        }

        throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $file));
    }
}

Fix PHP 7.1 related failures

Fix PHP 7.1 related failures


<?php
class CyclicRotation
{
    private $array;
    private $rotation;

    public function __construct($array, $rotation) {
        $this->array = $array;
        $this->rotation = $rotation;
    }

    /**
     * @param mixed $rotation
     */
    public function setRotation($rotation) {
        $this->rotation = $rotation;
    }

    /**
     * @param mixed $array
     */
    public function setArray($array) {
        $this->array = $array;
    }

    /**
     * @return mixed
     */
    public function getArray() {
        return $this->array;
    }

    /**
     * @return mixed
     */
    public function getRotation() {
        return $this->rotation;
    }

    public function rotateArray() {
        $arrayToRotate = $this->getArray();
        $rotation = $this->getRotation();
        $arrayCount = count($arrayToRotate);
        //var_dump($arrayCount);exit;
        $outputArray = array();
        foreach($arrayToRotate as $key => $value) {
            $rotationTimes = $key + $rotation;
            if($rotationTimes >= $arrayCount) {
                $modulusKey = $rotationTimes % $rotation;
                $outputArray[$modulusKey] = $value;
            }
            else {

                $outputArray[$rotationTimes] = $value;
            }

        }
    }

}

$cyclicRotation = new CyclicRotation([3, 8, 9, 7, 6], 3);
$cyclicRotation->rotateArray();

<?php
class CyclicRotation
{
    private $array;
    private $rotation;

    public function __construct($array, $rotation) {
        $this->array = $array;
        $this->rotation = $rotation;
    }

    /**
     * @param mixed $rotation
     */
    public function setRotation($rotation) {
        $this->rotation = $rotation;
    }

    /**
     * @param mixed $array
     */
    public function setArray($array) {
        $this->array = $array;
    }

    /**
     * @return mixed
     */
    public function getArray() {
        return $this->array;
    }

    /**
     * @return mixed
     */
    public function getRotation() {
        return $this->rotation;
    }

    public function rotateArray() {
        $arrayToRotate = $this->getArray();
        $rotation = $this->getRotation();
        $arrayCount = count($arrayToRotate);
        //var_dump($arrayCount);exit;
        $outputArray = array();
        foreach($arrayToRotate as $key => $value) {
            $rotationTimes = $key + $rotation + 1;
            if($rotationTimes > $arrayCount) {
                $modulusKey = $rotationTimes % $rotation;
                $outputArray[$modulusKey] = $value;
            }
            else {
                $outputArray[$rotationTimes - 1] = $value;
            }

        }
        return $outputArray;
    }

}
$cyclicRotation = new CyclicRotation([3, 8, 9, 7, 6], 3);
var_dump($cyclicRotation->rotateArray());

Complete cyclic rotation on a given array.


<?php

namespace Noback\PHPUnitTestServiceContainer\PHPUnit;

use Noback\PHPUnitTestServiceContainer\ServiceContainer;
use Noback\PHPUnitTestServiceContainer\ServiceContainerInterface;
use Noback\PHPUnitTestServiceContainer\ServiceProviderInterface;

/**
 * Extend from this test case to make use of a service container in your tests
 */
abstract class AbstractTestCaseWithServiceContainer extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ServiceContainerInterface
     */
    protected $container;

    /**
     * Return an array of ServiceProviderInterface instances you want to use in this test case
     *
     * @return ServiceProviderInterface[]
     */
    abstract protected function getServiceProviders();

    /**
     * When overriding this method, make sure you call parent::setUp()
     */
    protected function setUp()
    {
        $this->container = new ServiceContainer();

        foreach ($this->getServiceProviders() as $serviceProvider) {
            $this->container->register($serviceProvider);
        }
    }

    /**
     * When overriding this method, make sure you call parent::tearDown()
     */
    protected function tearDown()
    {
        $this->container->tearDown();
    }
}

<?php

namespace Noback\PHPUnitTestServiceContainer\PHPUnit;

use Noback\PHPUnitTestServiceContainer\ServiceContainer;
use Noback\PHPUnitTestServiceContainer\ServiceContainerInterface;
use Noback\PHPUnitTestServiceContainer\ServiceProviderInterface;

/**
 * Extend from this test case to make use of a service container in your tests
 */
abstract class AbstractTestCaseWithServiceContainer extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ServiceContainerInterface
     */
    protected $container;

    /**
     * Return an array of ServiceProviderInterface instances you want to use in this test case
     *
     * @return ServiceProviderInterface[]
     */
    abstract protected function getServiceProviders();

    /**
     * When overriding this method, make sure you call parent::setUp()
     */
    protected function setUp()
    {
        $this->container = new ServiceContainer();

        foreach ($this->getServiceProviders() as $serviceProvider) {
            $this->container->register($serviceProvider);
        }
    }

    /**
     * When overriding this method, make sure you call parent::tearDown()
     */
    protected function tearDown()
    {
        $this->container->tearDown();
        $this->container = null;
    }
}

Remove reference to container variable

Remove reference to container variable


<?php
$UserId = $_SESSION["MangoPayDemo"]["UserLegal"];
$BankAccount = new \MangoPay\BankAccount();
$BankAccount->Type = "IBAN";
$BankAccount->Details = new MangoPay\BankAccountDetailsIBAN();
$BankAccount->Details->IBAN = "FR7618829754160173622224154";
$BankAccount->Details->BIC = "CMBRFR2BCME";
$BankAccount->OwnerName = "Joe Bloggs";
$BankAccount->OwnerAddress = "1 Mangopay Street";
$result = $mangoPayApi->Users->CreateBankAccount($UserId, $BankAccount);

//Display result
pre_dump($result);

$_SESSION["MangoPayDemo"]["BankAccount"] = $result->Id;

<?php
$UserId = $_SESSION["MangoPayDemo"]["UserLegal"];
$BankAccount = new \MangoPay\BankAccount();
$BankAccount->Type = "IBAN";
$BankAccount->Details = new MangoPay\BankAccountDetailsIBAN();
$BankAccount->Details->IBAN = "FR7618829754160173622224154";
$BankAccount->Details->BIC = "CMBRFR2BCME";
$BankAccount->OwnerName = "Joe Bloggs";
$BankAccount->OwnerAddress = new \MangoPay\Address();
$BankAccount->OwnerAddress->AddressLine1 = 'Address line 1';
$BankAccount->OwnerAddress->AddressLine2 = 'Address line 2';
$BankAccount->OwnerAddress->City = 'City';
$BankAccount->OwnerAddress->Country = 'FR';
$BankAccount->OwnerAddress->PostalCode = '11222';
$BankAccount->OwnerAddress->Region = 'Region';
$result = $mangoPayApi->Users->CreateBankAccount($UserId, $BankAccount);

//Display result
pre_dump($result);

$_SESSION["MangoPayDemo"]["BankAccount"] = $result->Id;

Update Address for API v2.01

Update Address for API v2.01


<?php

use App\Models\Season;
use Illuminate\Database\Seeder;

class SeasonsTableSeeder extends Seeder
{
    public function run(): void
    {
        factory(Season::class)->times(2)->create();
    }
}

<?php

use App\Models\Season;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;

class SeasonsTableSeeder extends Seeder
{
    public function run(): void
    {
        factory(Season::class)->times(2)->create();

        $this->createRoles();
    }

    private function createRoles(): void
    {
        Season::all()->each(function (Season $season) {
            Role::create(['name' => "Season {$season->getName()} Admin"]);
        });
    }
}

Create Season Admin roles for each season seeded


<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title> Template </title>
        <link rel="shortcut icon" href="/includes/img/kp.ico">
        <link href="/includes/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
        <link href="/includes/css/flat-ui-pro.min.css" rel="stylesheet">
        <link href="/includes/css/style.css" rel="stylesheet">
        <link href="/includes/js/konami.js">

        <?php include 'includes/php/header.php'; ?>

 Page content

 This be your page content...

        <?php include 'includes/php/footer.php'; ?>

<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title> Template </title>
        <link rel="shortcut icon" href="/includes/img/kp.ico">
        <link href="/includes/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
        <link href="/includes/css/flat-ui-pro.min.css" rel="stylesheet">
        <link href="/includes/css/style.css" rel="stylesheet">

        <?php include 'includes/php/header.php'; ?>

 Page content

 This be your page content...

        <?php include 'includes/php/footer.php'; ?>

Move along, nothing to see here.

Move along, nothing to see here.


<?php
namespace Tev\TevMailchimp\Command;

use Exception;
use TYPO3\CMS\Extbase\Mvc\Controller\CommandController;
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
use Tev\TevMailchimp\Services\Mailchimp;

/**
 * Command controller for Mailchimp.
 */
class MailchimpCommandController extends CommandController
{
    /**
     * Mailchimp service.
     *
     * @var \Tev\TevMailchimp\Services\MailchimpService
     * @inject
     */
    protected $mailchimpService;

    /**
     * Download all lists from Mailchimp.
     *
     * @return void
     */
    public function listsCommand()
    {
        $this->outputLine('<info>Downloading lists...</info>');

        try {
            $lists = $this->mailchimpService->downloadLists();

            foreach ($lists as $l) {
                $this->outputLine("<comment>- {$l->getMcListId()} downloaded</comment>");
            }

            $this->outputLine('<info>complete</info>');
        } catch (Exception $e) {
            $this->outputLine("<error>Error: {$e->getMessage()}</error>");
        }
    }
}

<?php
namespace Tev\TevMailchimp\Command;

use Exception;
use TYPO3\CMS\Core\Log\LogManager;
use TYPO3\CMS\Extbase\Mvc\Controller\CommandController;
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
use Tev\TevMailchimp\Services\Mailchimp;

/**
 * Command controller for Mailchimp.
 */
class MailchimpCommandController extends CommandController
{
    /**
     * Mailchimp service.
     *
     * @var \Tev\TevMailchimp\Services\MailchimpService
     * @inject
     */
    protected $mailchimpService;

    /**
     * Logger instance.
     *
     * @var \TYPO3\CMS\Core\Log\Logger
     */
    protected $logger;

    /**
     * @param  \TYPO3\CMS\Core\Log\LogManager $logManager
     * @return void
     */
    public function injectLogManager(LogManager $logManager)
    {
        $this->logger = $logManager->getLogger(__CLASS__);
    }

    /**
     * Download all lists from Mailchimp.
     *
     * @return void
     */
    public function listsCommand()
    {
        $this->outputLine('<info>Downloading lists...</info>');

        try {
            $lists = $this->mailchimpService->downloadLists();

            foreach ($lists as $l) {
                $this->outputLine("<comment>- {$l->getMcListId()} downloaded</comment>");
            }

            $this->outputLine('<info>complete</info>');

            $this->logger->info('Lists downloaded successfully via CLI');
        } catch (Exception $e) {
            $this->outputLine("<error>Error: {$e->getMessage()}</error>");

            $this->logger->error('Lists failed to download via CLI', [
                'message' => $e->getMessage()
            ]);
        }
    }
}

Add logging to CLI controller

Add logging to CLI controller


<?php
/*
 * This file is part of the AlphaLemonThemeEngineBundle and it is distributed
 * under the MIT License. To use this bundle you must leave
 * intact this copyright notice.
 *
 * Copyright (c) AlphaLemon <webmaster@alphalemon.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://alphalemon.com
 *
 * @license    MIT License
 */

namespace AlphaLemon\ElFinderBundle\Core\Connector;

/**
 * Configures the connector
 *
 * @author AlphaLemon
 */
class AlphaLemonElFinderConnector extends AlphaLemonElFinderBaseConnector
{
    protected function configure()
    {
        $request = $this->container->get('request');

        $options = array(
            'roots' => array(
                array(
                    'driver'        => 'LocalFileSystem',   // driver for accessing file system (REQUIRED)
                    'path'          => 'bundles/alphalemonelfinder/files/',         // path to files (REQUIRED)
                    'URL'           => $request->getScheme().'://'.$request->getHttpHost() . '/bundles/alphalemonelfinder/files/', // URL to files (REQUIRED)
                    'accessControl' => 'access'             // disable and hide dot starting files (OPTIONAL)
                )
            )
        );

        return $options;
    }
}

<?php
/*
 * This file is part of the AlphaLemonThemeEngineBundle and it is distributed
 * under the MIT License. To use this bundle you must leave
 * intact this copyright notice.
 *
 * Copyright (c) AlphaLemon <webmaster@alphalemon.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://alphalemon.com
 *
 * @license    MIT License
 */

namespace AlphaLemon\ElFinderBundle\Core\Connector;

/**
 * Configures the connector
 *
 * @author AlphaLemon
 */
class AlphaLemonElFinderConnector extends AlphaLemonElFinderBaseConnector
{
    protected function configure()
    {
        $request = $this->container->get('request');

        $options = array(
            'roots' => array(
                array(
                    'driver'        => 'LocalFileSystem',   // driver for accessing file system (REQUIRED)
                    'path'          => 'bundles/alphalemonelfinder/vendor/ElFinder/files/',         // path to files (REQUIRED)
                    'URL'           => $request->getScheme().'://'.$request->getHttpHost() . '/bundles/alphalemonelfinder/vendor/ElFinder/files/', // URL to files (REQUIRED)
                    'accessControl' => 'access'             // disable and hide dot starting files (OPTIONAL)
                )
            )
        );

        return $options;
    }
}

Update the path and the url

Update the path and the url


<?php

namespace AshleyDawson\SimplePaginationBundle\DependencyInjection;

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

/**
 * Class Configuration
 *
 * @package AshleyDawson\SimplePaginationBundle\DependencyInjection
 * @author Ashley Dawson <ashley@ashleydawson.co.uk>
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('ashley_dawson_simple_pagination');
        $rootNode = $treeBuilder->getRootNode();

        $rootNode
            ->children()
                ->arrayNode('defaults')
                ->addDefaultsIfNotSet()
                ->children()
                    ->integerNode('items_per_page')->defaultValue(10)->min(1)->isRequired()->end()
                    ->integerNode('pages_in_range')->defaultValue(5)->min(1)->isRequired()->end()
                    ->scalarNode('template')->defaultValue('AshleyDawsonSimplePaginationBundle:Pagination:default.html.twig')->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

<?php

namespace AshleyDawson\SimplePaginationBundle\DependencyInjection;

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

/**
 * Class Configuration
 *
 * @package AshleyDawson\SimplePaginationBundle\DependencyInjection
 * @author Ashley Dawson <ashley@ashleydawson.co.uk>
 */
class Configuration implements ConfigurationInterface
{
    const ROOT_NODE_NAME = '';

    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('ashley_dawson_simple_pagination');
        $rootNode = \method_exists($treeBuilder, 'getRootNode')
            ? $treeBuilder->getRootNode()
            : $treeBuilder->root('ashley_dawson_simple_pagination');

        $rootNode
            ->children()
                ->arrayNode('defaults')
                ->addDefaultsIfNotSet()
                ->children()
                    ->integerNode('items_per_page')->defaultValue(10)->min(1)->isRequired()->end()
                    ->integerNode('pages_in_range')->defaultValue(5)->min(1)->isRequired()->end()
                    ->scalarNode('template')->defaultValue('AshleyDawsonSimplePaginationBundle:Pagination:default.html.twig')->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

Check getRootNode method exists for older Symfony versions


<?php

namespace Symfony\Bundle\DoctrineMigrationsBundle\DependencyInjection;

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

/**
 * DoctrineMigrationsExtension configuration structure.
 *
 * @author Lukas Kahwe Smith <smith@pooteeweet.org>
 */
class Configuration
{
    /**
     * Generates the configuration tree.
     *
     * @return NodeInterface
     */
    public function getConfigTree()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('doctrine_migrations', 'array');

        $rootNode
            ->children()
                ->scalarNode('dir_name')->defaultValue('%kernel.root_dir%/DoctrineMigrations')->cannotBeEmpty()->end()
                ->scalarNode('namespace')->defaultValue('Application\Migrations')->cannotBeEmpty()->end()
                ->scalarNode('table_name')->defaultValue('migration_versions')->cannotBeEmpty()->end()
                ->scalarNode('name')->defaultValue('Application Migrations')->end()
            ->end()
        ;

        return $treeBuilder->buildTree();
    }
}

<?php

namespace Symfony\Bundle\DoctrineMigrationsBundle\DependencyInjection;

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

/**
 * DoctrineMigrationsExtension configuration structure.
 *
 * @author Lukas Kahwe Smith <smith@pooteeweet.org>
 */
class Configuration
{
    /**
     * Generates the configuration tree.
     *
     * @return \Symfony\Component\Config\Definition\ArrayNode The config tree
     */
    public function getConfigTree()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('doctrine_migrations', 'array');

        $rootNode
            ->children()
                ->scalarNode('dir_name')->defaultValue('%kernel.root_dir%/DoctrineMigrations')->cannotBeEmpty()->end()
                ->scalarNode('namespace')->defaultValue('Application\Migrations')->cannotBeEmpty()->end()
                ->scalarNode('table_name')->defaultValue('migration_versions')->cannotBeEmpty()->end()
                ->scalarNode('name')->defaultValue('Application Migrations')->end()
            ->end()
        ;

        return $treeBuilder->buildTree();
    }
}

Tweak PHPDocs in the extension configuration files


<?php

namespace zaporylie\Vipps\Tests\Unit;

use Eloquent\Enumeration\Exception\UndefinedMemberException;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\UriInterface;
use zaporylie\Vipps\Endpoint;
use zaporylie\Vipps\EndpointInterface;

class EndpointTest extends TestCase
{

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        parent::setUp();
    }

    /**
     * @covers \zaporylie\Vipps\Endpoint::__construct()
     * @covers \zaporylie\Vipps\Endpoint::initializeMembers()
     */
    public function testAllowedEndpoints()
    {
        $this->assertInstanceOf(EndpointInterface::class, Endpoint::test());
        $this->assertInstanceOf(EndpointInterface::class, Endpoint::live());
        $this->expectException(UndefinedMemberException::class);
        Endpoint::foo();
    }

    /**
     * @covers \zaporylie\Vipps\Endpoint::getScheme()
     * @covers \zaporylie\Vipps\Endpoint::getHost()
     * @covers \zaporylie\Vipps\Endpoint::getPort()
     * @covers \zaporylie\Vipps\Endpoint::getPath()
     * @covers \zaporylie\Vipps\Endpoint::getUri()
     */
    public function testGetters()
    {
        $endpoint = Endpoint::test();
        $this->assertNotEmpty($endpoint->getScheme());
        $this->assertNotEmpty($endpoint->getHost());
        $this->assertNotEmpty($endpoint->getPort());
        $this->assertNotNull($endpoint->getPath());
        $this->assertInstanceOf(UriInterface::class, $endpoint->getUri());
    }
}

<?php

namespace zaporylie\Vipps\Tests\Unit;

use Eloquent\Enumeration\Exception\UndefinedMemberException;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\UriInterface;
use zaporylie\Vipps\Endpoint;
use zaporylie\Vipps\EndpointInterface;

/**
 * @coversDefaultClass \zaporylie\Vipps\Endpoint
 */
class EndpointTest extends TestCase
{

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        parent::setUp();
    }

    public function testAllowedEndpoints()
    {
        $this->assertInstanceOf(EndpointInterface::class, Endpoint::test());
        $this->assertInstanceOf(EndpointInterface::class, Endpoint::live());
        $this->expectException(UndefinedMemberException::class);
        Endpoint::foo();
    }

    public function testGetters()
    {
        $endpoint = Endpoint::test();
        $this->assertNotEmpty($endpoint->getScheme());
        $this->assertNotEmpty($endpoint->getHost());
        $this->assertNotEmpty($endpoint->getPort());
        $this->assertNotNull($endpoint->getPath());
        $this->assertInstanceOf(UriInterface::class, $endpoint->getUri());
    }
}

Clean up coverage in Endpoint

Clean up coverage in Endpoint


                        ©
                        <?php
                            $copyYear = 2015;
                            $currentYear = date('Y');
                            echo $copyYear . (($copyYear != $currentYear) ? ' - ' . $currentYear : '');
                        ?>
                        Kosta Rashev

Add current year to footer copyright

Add current year to footer copyright


<?php

namespace Coosos\UserRoleTypeBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $treeBuilder->root('coosos_user_role_type');

        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}

<?php

namespace Coosos\UserRoleTypeBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('coosos_user_role_type');
        $rootNode = (method_exists($treeBuilder, 'getRootNode'))
            ? $treeBuilder->getRootNode()
            : $treeBuilder->root("coosos_user_role_type");

        return $treeBuilder;
    }
}

Fix deprecated symfony > 4.2

Fix deprecated symfony > 4.2


<?php

return [
    'class' => 'yii\db\Connection',
    // 'dsn' => 'oci:host=103.13.28.239;dbname=103.13.28.239/XE;charset=UTF8',
    'dsn' => 'mysql:host=103.253.75.56;dbname=unitedla_aci;charset=UTF8',
    'username' => 'unitedla_aci',
    'password' => 'aci_2015',
    'charset' => 'utf8',
];

<?php

return [
    'class' => 'yii\db\Connection',
    // 'dsn' => 'oci:host=103.13.28.239;dbname=103.13.28.239/XE;charset=UTF8',
    'dsn' => 'mysql:host=103.13.28.239;dbname=aci_dev;charset=UTF8',
    'username' => 'aci_dev',
    'password' => 'aci_2015',
    'charset' => 'utf8',
];

Change DB Pointer for use Mysql 5.6.11

Change DB Pointer for use Mysql 5.6.11


<?php

namespace Concrete\Core\Site;

use Concrete\Core\Foundation\Service\Provider;

class ServiceProvider extends Provider
{
    public function register()
    {
        $this->app->singleton('Concrete\Core\Site\Service');
        $this->app->alias('Concrete\Core\Site\Service', 'site');

        $this->app->singleton('Concrete\Core\Site\Type\Service');
        $this->app->alias('Concrete\Core\Site\Type\Service', 'site/type');

        $this->app->singleton('Concrete\Core\Site\Resolver\DriverInterface', function ($app) {
            return $app->make('Concrete\Core\Site\Resolver\StandardDriver');
        });
    }
}

<?php

namespace Concrete\Core\Site;

use Concrete\Core\Application\Application;
use Concrete\Core\Foundation\Service\Provider as BaseServiceProvider;
use Concrete\Core\Site\Resolver\DriverInterface;
use Concrete\Core\Site\Resolver\StandardDriver;
use Concrete\Core\Site\Service as SiteService;
use Concrete\Core\Site\Type\Service as SiteTypeService;

class ServiceProvider extends BaseServiceProvider
{
    public function register()
    {
        $this->app->singleton(SiteService::class);
        $this->app->alias(SiteService::class, 'site');

        $this->app->singleton(SiteTypeService::class);
        $this->app->alias(SiteTypeService::class, 'site/type');

        $this->app->singleton(DriverInterface::class, function (Application $app) {
            return $this->app->make(StandardDriver::class);
        });
    }
}

Use ::class instead of strings

Use ::class instead of strings


<?php

class DevCheckController extends Controller {

	public static $allowed_actions = array(
		'index'
	);

	function index($request) {
		$suiteName = $request->param('Suite') ? $request->param('Suite') : 'check';
		$e = new EnvironmentChecker($suiteName, 'Environment status');
		$e->init('ADMIN');  //check for admin permissions before running this check
		return $e;
	}
}

<?php

class DevCheckController extends Controller {

	public static $allowed_actions = array(
		'index'
	);

	/**
	 * @var string Permission code to check for access to this controller.
	 */
	private static $permission = 'ADMIN';

	function index($request) {
		$suiteName = $request->param('Suite') ? $request->param('Suite') : 'check';
		$e = new EnvironmentChecker($suiteName, 'Environment status');
		$e->init($this->config()->permission);  //check for admin permissions before running this check
		return $e;
	}
}

Allow specifying the permission for dev/check


<?php

/*
 * Copyright 2012 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @group search
 */
final class PhabricatorSearchUserIndexer
  extends PhabricatorSearchDocumentIndexer {

  public static function indexUser(PhabricatorUser $user) {
    $doc = new PhabricatorSearchAbstractDocument();
    $doc->setPHID($user->getPHID());
    $doc->setDocumentType(PhabricatorPHIDConstants::PHID_TYPE_USER);
    $doc->setDocumentTitle($user->getUserName().' ('.$user->getRealName().')');
    $doc->setDocumentCreated($user->getDateCreated());
    $doc->setDocumentModified($user->getDateModified());

    // TODO: Index the blurbs from their profile or something? Probably not
    // actually useful...

    self::reindexAbstractDocument($doc);
  }
}

<?php

/*
 * Copyright 2012 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @group search
 */
final class PhabricatorSearchUserIndexer
  extends PhabricatorSearchDocumentIndexer {

  public static function indexUser(PhabricatorUser $user) {
    $doc = new PhabricatorSearchAbstractDocument();
    $doc->setPHID($user->getPHID());
    $doc->setDocumentType(PhabricatorPHIDConstants::PHID_TYPE_USER);
    $doc->setDocumentTitle($user->getUserName().' ('.$user->getRealName().')');
    $doc->setDocumentCreated($user->getDateCreated());
    $doc->setDocumentModified($user->getDateModified());

    // TODO: Index the blurbs from their profile or something? Probably not
    // actually useful...

    if (!$user->getIsDisabled()) {
      $doc->addRelationship(
        PhabricatorSearchRelationship::RELATIONSHIP_OPEN,
        $user->getPHID(),
        PhabricatorPHIDConstants::PHID_TYPE_USER,
        time());
    }

    self::reindexAbstractDocument($doc);
  }
}

Mark disabled users as "closed documents" in search

Test Plan:
  $ ./reindex_all_users.php

Search for me in open documents.
Search for @epriestley in open documents.

Reviewers: epriestley

Reviewed By: epriestley

CC: aran, Korvin

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


<?php

use Collective\Html\HtmlBuilder;
use Illuminate\Http\Request;
use Illuminate\Routing\RouteCollection;
use Illuminate\Routing\UrlGenerator;

use Noylecorp\Recaptcha\RecaptchaBuilder;

class RecaptchaBuilderTest extends PHPUnit_Framework_TestCase
{
    /**
     * Setup the test environment.
     */
    public function setUp()
    {
        $this->urlGenerator = new UrlGenerator(new RouteCollection(), Request::create('/foo', 'GET'));
        $this->htmlBuilder = new HtmlBuilder($this->urlGenerator);
        $this->recaptchaBuilder = new RecaptchaBuilder($this->htmlBuilder);
    }

    public function testWidget()
    {
        $r1 = $this->recaptchaBuilder->widget('my-site-key');

        $this->assertEquals('

'.PHP_EOL, $r1);
    }

    public function testScript()
    {
        $script = $this->recaptchaBuilder->script();
        $this->assertEquals(''.PHP_EOL, $script);
    }
}

<?php

use Collective\Html\HtmlBuilder;
use Illuminate\Http\Request;
use Illuminate\Routing\RouteCollection;
use Illuminate\Routing\UrlGenerator;

use Noylecorp\Recaptcha\RecaptchaBuilder;

class RecaptchaBuilderTest extends PHPUnit_Framework_TestCase
{
    /**
     * Setup the test environment.
     */
    public function setUp()
    {
        $this->urlGenerator = new UrlGenerator(new RouteCollection(), Request::create('/foo', 'GET'));
        $this->htmlBuilder = new HtmlBuilder($this->urlGenerator);
        $this->siteKey = 'my-site-key';
        $this->recaptchaBuilder = new RecaptchaBuilder($this->siteKey, $this->htmlBuilder);
    }

    public function testWidget()
    {
        $r1 = $this->recaptchaBuilder->widget();
        $r2 = $this->recaptchaBuilder->widget(['theme' => 'dark']);
        $r3 = $this->recaptchaBuilder->widget(['type' => 'audio']);

        $this->assertEquals('

'.PHP_EOL, $r1);
        $this->assertEquals('

'.PHP_EOL, $r2);
        $this->assertEquals('

'.PHP_EOL, $r3);
    }

    public function testScript()
    {
        $script = $this->recaptchaBuilder->script();
        $this->assertEquals(''.PHP_EOL, $script);
    }
}

Update testing and add a couple more

Update testing and add a couple more


<?php

namespace iFixit\Matryoshka;

use iFixit\Matryoshka;

/**
 * Ensures that a delete is issued before trying to update an existing key.
 *
 * This layer is useful for working with mcrouter. mcrouter provides a reliable
 * delete stream, but can't guarantee updates are recorded.
 */
class DeleteBeforeUpdate extends BackendWrap {
   public function set($key, $value, $expiration = 0) {
      if ($this->backend->add($key, $value) === false) {
         $this->backend->delete($key);
         $this->backend->add($key, $valaue);
      }
   }

   public function setMultiple(array $values, $expiration = 0) {
      foreach ($values as $key => $value) {
         $this->set($key, $value, $expiration);
      }
   }
}

<?php

namespace iFixit\Matryoshka;

use iFixit\Matryoshka;

/**
 * Ensures that a delete is issued before trying to update an existing key.
 *
 * This layer is useful for working with mcrouter. mcrouter provides a reliable
 * delete stream, but can't guarantee updates are recorded.
 */
class DeleteBeforeUpdate extends BackendWrap {
   public function set($key, $value, $expiration = 0) {
      if ($this->backend->add($key, $value) === false) {
         $this->backend->delete($key);
         $this->backend->set($key, $valaue);
      }
   }

   public function setMultiple(array $values, $expiration = 0) {
      foreach ($values as $key => $value) {
         $this->set($key, $value, $expiration);
      }
   }
}

Use `set` not `add` after the delete

Use `set` not `add` after the delete

We want the `add` action to be _synchronous_. That means that if the
action fails anywhere we consider it a failure.

Afterwards, we want to do an _asynchronous_ `set` action. It is okay if
some hosts do not recieve the set, they will consistently get the prior
delete.


<?php

class CM_InputStream_Readline extends CM_InputStream_Abstract {

	public function __construct() {
		$this->_outputStream = new CM_OutputStream_Stream_StandardError();
	}

	protected function _read($hint = null) {
		$value = readline($hint);
		readline_add_history($value);
		return (string) $value;
	}
}

<?php

class CM_InputStream_Readline extends CM_InputStream_Abstract {

	public function __construct() {
		if (!extension_loaded('readline')) {
			throw new CM_Exception('`readline` extension is not loaded.');
		}
		$this->_outputStream = new CM_OutputStream_Stream_StandardError();
	}

	protected function _read($hint = null) {
		$value = readline($hint);
		readline_add_history($value);
		return (string) $value;
	}
}

Throw exception if readline extension is not loaded


<?php
    /*
        The MIT License (MIT)

        Copyright (c) 2014 Julian Xhokaxhiu

        Permission is hereby granted, free of charge, to any person obtaining a copy of
        this software and associated documentation files (the "Software"), to deal in
        the Software without restriction, including without limitation the rights to
        use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
        the Software, and to permit persons to whom the Software is furnished to do so,
        subject to the following conditions:

        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.

        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
        FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
        COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
        IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
        CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    */

    require 'vendor/autoload.php';

    use \JX\CmOta\CmOta;

    $app = new CmOta();
    $app->run();

<?php
    /*
        The MIT License (MIT)

        Copyright (c) 2014 Julian Xhokaxhiu

        Permission is hereby granted, free of charge, to any person obtaining a copy of
        this software and associated documentation files (the "Software"), to deal in
        the Software without restriction, including without limitation the rights to
        use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
        the Software, and to permit persons to whom the Software is furnished to do so,
        subject to the following conditions:

        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.

        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
        FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
        COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
        IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
        CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    */

    require 'vendor/autoload.php';

    use \JX\CmOta\CmOta;

    $app = new CmOta();
    $app
    ->setConfig( 'basePath', '/CyanogenModOTA' )
    ->setConfig( 'memcached.host', 'localhost' )
    ->setConfig( 'memcached.port', 11211 )
    ->enableMemcached()
    ->run();

Use the new API system to set some basic configurations.


<?php include('plugin/page_declaration.php');?>
	<title>PAT Locker</title>

PAT Locker:

A resource for Portable Appliance Test personnel and appliance owners:

		Login / Join

		<?php include'plugin/footer.php'?>

<?php include('plugin/page_declaration.php');?>
	<title>PAT Locker</title>

PAT Locker:

An open source implementation  resource for Portable Appliance Test personnel and appliance owners:

		Login / Join

		<?php include'plugin/footer.php'?>

Test commit from pauls Atom

Test commit from pauls Atom


<?php

require_once 'config.inc.php';
require_once 'MailManagerWebService.php';

$ws = new MailManagerWebService($db_config, $smtp_config, $mail_config);

Create instance of web service

Create instance of web service


<?php

namespace PerFi\PerFiBundle\Repository;

use Doctrine\ORM\EntityRepository;
use PerFi\Domain\Transaction\Transaction;
use PerFi\Domain\Transaction\TransactionRepository as TransactionRepositoryInterface;
use PerFi\PerFiBundle\Entity\Transaction as DtoTransaction;

/**
 * TransactionRepository
 */
class TransactionRepository extends EntityRepository
    implements TransactionRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function add(Transaction $transaction)
    {
        $entity = new DtoTransaction();
        $entity->setTransactionId((string) $transaction->id());
        $entity->setType((string) $transaction->type());
        $entity->setSourceAccount((string) $transaction->sourceAccount()->id());
        $entity->setDestinationAccount((string) $transaction->destinationAccount()->id());
        $entity->setDate($transaction->date());
        $entity->setDescription($transaction->description());

        $amount = $transaction->amount();
        $entity->setAmount($amount->getAmount());
        $entity->setCurrency((string) $amount->getCurrency());

        $em = $this->getEntityManager();
        $em->persist($entity);
        $em->flush();
    }

    /**
     * {@inheritdoc}
     */
    public function getAll() : array
    {
        return [];
    }
}

<?php

namespace PerFi\PerFiBundle\Repository;

use Doctrine\ORM\EntityRepository;
use PerFi\Domain\Transaction\Transaction;
use PerFi\Domain\Transaction\TransactionRepository as TransactionRepositoryInterface;
use PerFi\PerFiBundle\Entity\Transaction as DtoTransaction;

/**
 * TransactionRepository
 */
class TransactionRepository extends EntityRepository
    implements TransactionRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function add(Transaction $transaction)
    {
        $entity = new DtoTransaction();
        $entity->setTransactionId((string) $transaction->id());
        $entity->setType((string) $transaction->type());
        $entity->setSourceAccount((string) $transaction->sourceAccount()->id());
        $entity->setDestinationAccount((string) $transaction->destinationAccount()->id());
        $entity->setDate($transaction->date());
        $entity->setRecordDate($transaction->recordDate());
        $entity->setDescription($transaction->description());

        $amount = $transaction->amount();
        $entity->setAmount($amount->getAmount());
        $entity->setCurrency((string) $amount->getCurrency());

        $em = $this->getEntityManager();
        $em->persist($entity);
        $em->flush();
    }

    /**
     * {@inheritdoc}
     */
    public function getAll() : array
    {
        return [];
    }
}

Set record date on entity when persisting transaction


<?php
$navItems = $controller->getNavItems(true);
?>

<?php if (count($navItems) > 1): ?>

            <?php foreach ($navItems as $ni): ?>
                <?php if (!$ni->isCurrent): ?>

                        <a href="<?php echo $ni->url; ?>" target="<?php echo $ni->target; ?>" itemprop="url">
                            <?php echo $ni->name; ?>

                <?php else: ?>

                        <?php echo $ni->name; ?>

                <?php endif; ?>
            <?php endforeach; ?>

<?php endif; ?>

<?php
$navItems = $controller->getNavItems(true);
?>

<?php if (count($navItems) > 1): ?>

            <?php foreach ($navItems as $i => $ni): ?>
                <?php if (!$ni->isCurrent): ?>

                        <a href="<?php echo $ni->url; ?>" target="<?php echo $ni->target; ?>" itemprop="item">
                            <?php echo $ni->name; ?>

                        <meta itemprop="position" content="<?php echo $i + 1; ?>">

                <?php else: ?>

                        <?php echo $ni->name; ?>
                        <meta itemprop="position" content="<?php echo $i + 1; ?>">

                <?php endif; ?>
            <?php endforeach; ?>

<?php endif; ?>

Replace breadcrumb data-vocabulary.org microdata with schema.org


<?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'  => 'JamylBot\User',
		'key' => '',
		'secret' => '',
	],

    'github' => [
        'client_id' => env('GITHUB_CLIENT_ID'),
        'client_secret' => env('GITHUB_CLIENT_SECRET'),
        'redirect' => 'http://localhost:8000/callback',
    ],

    'eveonline' => [
        'client_id' => env('EVE_CLIENT_ID'),
        'client_secret' => env('EVE_CLIENT_SECRET'),
        'redirect' => 'http://localhost:8000/callback',
    ],

];

<?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'  => 'JamylBot\User',
		'key' => '',
		'secret' => '',
	],

    'github' => [
        'client_id' => env('GITHUB_CLIENT_ID'),
        'client_secret' => env('GITHUB_CLIENT_SECRET'),
        'redirect' => 'http://localhost:8000/callback',
    ],

    'eveonline' => [
        'client_id' => env('EVE_CLIENT_ID'),
        'client_secret' => env('EVE_CLIENT_SECRET'),
        'redirect' => env('EVE_REDIRECT'),
    ],

];

Move callback URL to .env

Move callback URL to .env


<?php

namespace gries\MControl\Server\Command\ResponseParser;

class TestForBlockParser implements ResponseParserInterface
{

    /**
     * Get the Server response
     *
     * @param $response
     *
     * @return mixed Response could be a string or an array
     */
    public function getResponse($response)
    {
        // block was detected
        if (false !== strpos($response, 'Successfully found')) {
            return true;
        }

        // only meta index is wrong
        if (false !== strpos($response, 'value of')) {
            // find format: ... data value of 4 (expected: 0)
            $regex = "/value of ([a-zA-Z0-9_]*) \(expected/";

            $matches = array();
            preg_match_all($regex, $response, $matches);

            return $matches[1][0];
        }

        if (false !== $tilePos = strpos($response, 'is tile.')) {
            // find format: ... is tile.air.name (expected: somethingelse)
            $regex = "/is tile.([a-zA-Z0-9_]*).name/";

            $matches = array();
            preg_match_all($regex, $response, $matches);

            return 'minecraft:' . $matches[1][0];
        }

        // find format: ... is Wooden Planks (expected: somethingelse)
        $regex   = "/is ([a-zA-Z0-9_\ ]*) \(expected/";
        $matches = array();

        preg_match_all($regex, $response, $matches);

        return $matches[1][0];
    }
}

<?php

namespace gries\MControl\Server\Command\ResponseParser;

class TestForBlockParser implements ResponseParserInterface
{

    /**
     * Get the Server response
     *
     * @param $response
     *
     * @return mixed Response could be a string or an array
     */
    public function getResponse($response)
    {
        // block was detected
        if (false !== strpos($response, 'Successfully found')) {
            return true;
        }

        // only meta index is wrong
        if (false !== strpos($response, 'value of')) {
            // find format: ... data value of 4 (expected: 0)
            $regex = "/value of ([a-zA-Z0-9_]*) \(expected/";

            $matches = array();
            preg_match_all($regex, $response, $matches);

            return $matches[1][0];
        }

        if (false !== $tilePos = strpos($response, 'is tile.')) {
            // find format: ... is tile.air.name (expected: somethingelse)
            $regex = "/is tile.([a-zA-Z0-9_]*).name/";

            $matches = array();
            preg_match_all($regex, $response, $matches);

            return 'minecraft:' . $matches[1][0];
        }

        // find format: ... is Wooden Planks (expected: somethingelse)
        $regex   = "/is ([a-zA-Z0-9_\ ]*) \(expected/";
        $matches = array();

        preg_match_all($regex, $response, $matches);

        if (!isset($matches[1][0])) {
            throw new \LogicException(sprintf('Cant handle response: "%s" while parsing a TestForBlockOutput', $response));
        }

        return $matches[1][0];
    }
}

Add errorhandling for testforblock parser.


<?php

class DatabaseSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Eloquent::unguard();

		$this->call('CategoriesTableSeeder');

        $this->command->info('Categories table seeded!');
	}

}

class CategoriesTableSeeder extends Seeder {

    public function run()
    {
        DB::table('categories')->delete();

        DB::table('categories')->insert([
        	['name' => 'Aide à domicile'],
        	['name' => 'Babysitting'],
        	['name' => 'Cobaye pour expériences'],
        	['name' => 'Informatique'],
        	['name' => 'Job de bureau'],
        	['name' => 'Promotion'],
        	['name' => 'Restauration - Hôtellerie'],
        	['name' => 'Soutien scolaire'],
        	['name' => 'Autre']
        ]);
    }

}

<?php

class DatabaseSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Eloquent::unguard();

		$this->call('CategoriesTableSeeder');

        $this->command->info('Categories table seeded!');

        $this->call('AdsTableSeeder');

        $this->command->info('Ads table seeded!');
	}

}

class CategoriesTableSeeder extends Seeder {

    public function run()
    {
        DB::table('categories')->delete();

        DB::table('categories')->insert([
        	['name' => 'Aide à domicile'],
        	['name' => 'Babysitting'],
        	['name' => 'Cobaye pour expériences'],
        	['name' => 'Informatique'],
        	['name' => 'Job de bureau'],
        	['name' => 'Promotion'],
        	['name' => 'Restauration - Hôtellerie'],
        	['name' => 'Soutien scolaire'],
        	['name' => 'Autre']
        ]);
    }

}

class AdsTableSeeder extends Seeder  {

    public function run()
    {
        DB::table('ads')->delete();

        DB::table('ads')->insert([
            ['category_id' => 1, 'url' => 'ad1', 'title' => 'ad1', 'description' => 'Lorem ipsum génial'],
            ['category_id' => 2, 'url' => 'ad2', 'title' => 'ad2', 'description' => 'Lorem ipsum nul'],
            ['category_id' => 3, 'url' => 'ad3', 'title' => 'ad3', 'description' => 'Lorem ipsum moyen']
        ]);
    }
}

Add simple seeder for Ads

Add simple seeder for Ads


<?php

/**
 * This file is part of the Krystal Framework
 *
 * Copyright (c) No Global State Lab
 *
 * For the full copyright and license information, please view
 * the license file that was distributed with this source code.
 */

namespace Krystal\Profiler;

class Memory
{
    /**
     * Returns memory usage
     *
     * @return string
     */
    public static function getUsage()
    {
        $size = memory_get_usage(true);
        $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');

        // Count the exponent
        $exp = floor(log($size, 1024));
        $pow = pow(1024, $exp);

        return round($size / $pow, 2).' '.strtoupper($unit[$exp]);
    }
}

<?php

/**
 * This file is part of the Krystal Framework
 *
 * Copyright (c) No Global State Lab
 *
 * For the full copyright and license information, please view
 * the license file that was distributed with this source code.
 */

namespace Krystal\Profiler;

use Krystal\Filesystem\FileManager;

class Memory
{
    /**
     * Returns memory usage
     *
     * @return string
     */
    public static function getUsage()
    {
        $size = memory_get_usage(true);
        return FileManager::humanSize($size);
    }
}

Use improved humanSize() method to convert bytes


<?php

namespace DMS\Bundle\TwigExtensionBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('dms_twig_extension');

        $rootNode->children()
            ->arrayNode('fabpot')
                ->addDefaultsIfNotSet()
                ->children()
                    ->booleanNode('i18n')->defaultFalse()->end()
                    ->booleanNode('debug')->defaultFalse()->end()
                    ->booleanNode('text')->defaultTrue()->end()
                    ->booleanNode('intl')->defaultTrue()->end()
                ->end()
            ->end();

        $rootNode->children()
            ->arrayNode('dms')
                ->addDefaultsIfNotSet()
                ->children()
                    ->booleanNode('textual_date')->defaultTrue()->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

<?php

namespace DMS\Bundle\TwigExtensionBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('dms_twig_extension');

        $rootNode->children()
            ->arrayNode('fabpot')
                ->addDefaultsIfNotSet()
                ->children()
                    ->booleanNode('i18n')->defaultFalse()->end()
                    ->booleanNode('debug')->defaultFalse()->end()
                    ->booleanNode('text')->defaultTrue()->end()
                    ->booleanNode('intl')->defaultTrue()->end()
                ->end()
            ->end();

        $rootNode->children()
            ->arrayNode('dms')
                ->addDefaultsIfNotSet()
                ->children()
                    ->booleanNode('textual_date')->defaultTrue()->end()
                    ->booleanNode('pad_string')->defaultTrue()->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

Add extension to DI configuration

Add extension to DI configuration


<?php

namespace Pippin\Transport;

use Psr\Http\Message\RequestInterface;

use RuntimeException;

class cURLTransport implements TransportInterface {

	private $curl;

	public function __construct() {
		if (!extension_loaded('curl')) {
			throw new RuntimeException('The cURL extension must be installed to use the cURLTransport class.');
		}

		$this->curl = curl_init();

		curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, 1);
		curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($this->curl, CURLOPT_FORBID_REUSE, 1);
		curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
	}

	public function request(RequestInterface $request) {
		curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $request->getMethod());
		curl_setopt($this->curl, CURLOPT_HTTPHEADER, $request->getHeaders());
		curl_setopt($this->curl, CURLOPT_URL, (string)$request->getUri());

		$stream = $request->getStream();
		if (!is_null($stream)) {
			curl_setopt($this->curl, CURLOPT_POSTFIELDS, (string)$stream);
		}

		return curl_exec($this->curl);
	}

}

<?php

namespace Pippin\Transport;

use Psr\Http\Message\RequestInterface;

use RuntimeException;

class cURLTransport implements TransportInterface {

	private $curl;

	public function __construct() {
		if (!extension_loaded('curl')) {
			throw new RuntimeException('The cURL extension must be installed to use the cURLTransport class.');
		}

		$this->curl = curl_init();

		curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, 1);
		curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($this->curl, CURLOPT_FORBID_REUSE, 1);
		curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
	}

	public function request(RequestInterface $request) {
		curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $request->getMethod());
		curl_setopt($this->curl, CURLOPT_HTTPHEADER, $request->getHeaders());
		curl_setopt($this->curl, CURLOPT_URL, (string)$request->getUri());

		$body = $request->getBody();
		if (!is_null($body)) {
			curl_setopt($this->curl, CURLOPT_POSTFIELDS, (string)$body);
		}

		return curl_exec($this->curl);
	}

}

Use correct method, and rename variable.


<?php
/**
 * Copyright (c) 2011 Bart Visscher <bartv@thisnet.nl>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

require_once('../../../lib/base.php');
$l10n = new OC_L10N('calendar');
if(!OC_USER::isLoggedIn()) {
	die("<script type=\"text/javascript\">document.location = oc_webroot;</script>");
}
OC_JSON::checkAppEnabled('calendar');
$calendar = array(
	'id' => 'new',
	'displayname' => 'Test',
	'description' => 'Test calendar',
	'calendarcolor' => 'black',
);
$tmpl = new OC_Template('calendar', 'part.editcalendar');
$tmpl->assign('new', true);
$tmpl->assign('calendar', $calendar);
$tmpl->printPage();
?>

<?php
/**
 * Copyright (c) 2011 Bart Visscher <bartv@thisnet.nl>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

require_once('../../../lib/base.php');
$l10n = new OC_L10N('calendar');
if(!OC_USER::isLoggedIn()) {
	die("<script type=\"text/javascript\">document.location = oc_webroot;</script>");
}
OC_JSON::checkAppEnabled('calendar');
$calendar = array(
	'id' => 'new',
	'displayname' => '',
	'description' => '',
	'calendarcolor' => '',
);
$tmpl = new OC_Template('calendar', 'part.editcalendar');
$tmpl->assign('new', true);
$tmpl->assign('calendar', $calendar);
$tmpl->printPage();
?>

Remove test data from calendar creation

Remove test data from calendar creation


<?php

return [
    'page_sleep' => 10,
    'image_sleep' => 3,

    'downloader' => 'normal',  // normal or curl
];

<?php

return [
    'page_sleep' => 10,
    'image_sleep' => 3,

    'downloader' => 'curl',  // normal or curl
];

Change default downloader to cURL

Change default downloader to cURL


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

namespace ZendTest\Form\TestAsset;

use DomainException;
use Zend\Stdlib\ArraySerializableInterface;

/**
 * @category   Zend
 * @package    Zend_Form
 * @subpackage UnitTest
 */
class Model implements ArraySerializableInterface
{
    protected $foo;
    protected $bar;
    protected $foobar;

    public function __set($name, $value)
    {
        throw new DomainException('Overloading to set values is not allowed');
    }

    public function __get($name)
    {
        if (property_exists($this, $name)) {
            return $this->$name;
        }
        throw new DomainException('Unknown attribute');
    }

    public function exchangeArray(array $array)
    {
        foreach ($array as $key => $value) {
            if (!property_exists($this, $key)) {
                continue;
            }
            $this->$key = $value;
        }
    }

    public function getArrayCopy()
    {
        return array(
            'foo'    => $this->foo,
            'bar'    => $this->bar,
            'foobar' => $this->foobar,
        );
    }
}

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

namespace ZendTest\Form\TestAsset;

use DomainException;
use Zend\Stdlib\ArraySerializableInterface;

/**
 * @category   Zend
 * @package    Zend_Form
 * @subpackage UnitTest
 */
class Model implements ArraySerializableInterface
{
    protected $foo;
    protected $bar;
    protected $foobar;

    public function __set($name, $value)
    {
        throw new DomainException('Overloading to set values is not allowed');
    }

    public function __get($name)
    {
        if (property_exists($this, $name)) {
            return $this->$name;
        }
        throw new DomainException('Unknown attribute');
    }

    public function exchangeArray(array $array)
    {
        foreach ($array as $key => $value) {
            if (!property_exists($this, $key)) {
                continue;
            }
            $this->$key = $value;
        }
    }

    public function getArrayCopy()
    {
        return array(
            'foo'    => $this->foo,
            'bar'    => $this->bar,
            'foobar' => $this->foobar,
        );
    }
}

Remove @package & restart travis

Remove @package & restart travis


<?php
/**
 *
 * Spork Zend Framework 2 Library
 *
 * @author Chris Schreiber <chris@sporkcode.com>
 */
return array(
    'service_manager' => array(
        'abstract_factories' => array(),
        'aliases' => array(),
        'factories' => array(
            'cssLess' => 'Spork\CSS\Less',
            'cssSass' => 'Spork\CSS\Sass',
            'cssStylus' => 'Spork\CSS\Stylus',
        ),
        'invokables' => array(),
    ),
    'view_helpers' => array(
        'invokables' => array(
            'date' => 'Spork\View\Helper\Date',
            'headScript' => 'Spork\View\Helper\HeadScript',
            'inlineScript' => 'Spork\View\Helper\InlineScript',
            'cssLess' => 'Spork\View\Helper\CSS\Less',
            'cssSass' => 'Spork\View\Helper\CSS\Sass',
            'cssStylus' => 'Spork\View\Helper\CSS\Stylus',
            'tagTrim' => 'Spork\View\Helper\TagTrim',
            'timeElapsed' => 'Spork\View\Helper\TimeElapsed',
        ),
        'factories' => array(
            'dojo' => 'Spork\View\Helper\Dojo',
            'googleAnalytic' => 'Spork\View\Helper\GoogleAnalytic',
        )
    )
);

<?php
/**
 *
 * Spork Zend Framework 2 Library
 *
 * @author Chris Schreiber <chris@sporkcode.com>
 */
return array(
    'service_manager' => array(
        'abstract_factories' => array(),
        'aliases' => array(),
        'factories' => array(
            'cssLess' => 'Spork\CSS\Less',
            'cssSass' => 'Spork\CSS\Sass',
            'cssStylus' => 'Spork\CSS\Stylus',
        ),
        'invokables' => array(
            'IcalendarViewStrategy' => 'Spork\View\Strategy\Icalendar',
        ),
    ),
    'view_helpers' => array(
        'invokables' => array(
            'date' => 'Spork\View\Helper\Date',
            'headScript' => 'Spork\View\Helper\HeadScript',
            'inlineScript' => 'Spork\View\Helper\InlineScript',
            'cssLess' => 'Spork\View\Helper\CSS\Less',
            'cssSass' => 'Spork\View\Helper\CSS\Sass',
            'cssStylus' => 'Spork\View\Helper\CSS\Stylus',
            'tagTrim' => 'Spork\View\Helper\TagTrim',
            'timeElapsed' => 'Spork\View\Helper\TimeElapsed',
        ),
        'factories' => array(
            'dojo' => 'Spork\View\Helper\Dojo',
            'googleAnalytic' => 'Spork\View\Helper\GoogleAnalytic',
        )
    )
);

Add icalendar stragegy to service manager


Update to the latest issue (36)

Update to the latest issue (36)


<?php

namespace Kanboard\Plugin\Budget;

use Kanboard\Core\Translator;
use Kanboard\Core\Plugin\Base;

class Plugin extends Base
{
    public function initialize()
    {
        $this->acl->extend('project_manager_acl', array('budget' => '*'));

        $this->template->hook->attach('template:project:dropdown', 'budget:project/dropdown');
        $this->template->hook->attach('template:user:sidebar:actions', 'budget:user/sidebar');

        $this->on('session.bootstrap', function($container) {
            Translator::load($container['config']->getCurrentLanguage(), __DIR__.'/Locale');
        });
    }

    public function getClasses()
    {
        return array(
            'Plugin\Budget\Model' => array(
                'HourlyRate',
                'Budget',
            )
        );
    }

    public function getPluginName()
    {
        return 'Budget Planning';
    }

    public function getPluginDescription()
    {
        return t('Add budget section for projects and expense reports based on user hourly rates');
    }

    public function getPluginAuthor()
    {
        return 'Frédéric Guillot';
    }

    public function getPluginVersion()
    {
        return '1.0.0';
    }
}

<?php

namespace Kanboard\Plugin\Budget;

use Kanboard\Core\Translator;
use Kanboard\Core\Plugin\Base;

class Plugin extends Base
{
    public function initialize()
    {
        $this->acl->extend('project_manager_acl', array('budget' => '*'));

        $this->template->hook->attach('template:project:dropdown', 'budget:project/dropdown');
        $this->template->hook->attach('template:user:sidebar:actions', 'budget:user/sidebar');

        $this->on('session.bootstrap', function($container) {
            Translator::load($container['config']->getCurrentLanguage(), __DIR__.'/Locale');
        });
    }

    public function getClasses()
    {
        return array(
            'Plugin\Budget\Model' => array(
                'HourlyRate',
                'Budget',
            )
        );
    }

    public function getPluginName()
    {
        return 'Budget Planning';
    }

    public function getPluginDescription()
    {
        return t('Add budget section for projects and expense reports based on user hourly rates');
    }

    public function getPluginAuthor()
    {
        return 'Frédéric Guillot';
    }

    public function getPluginVersion()
    {
        return '1.0.0';
    }

    public function getPluginHomepage()
    {
        return 'https://github.com/kanboard/plugin-budget';
    }
}

Fix plugin link is not displayed

Fix plugin link is not displayed


<?php
/**
 * Field which gets suggestions from google search
 */
class GoogleSuggestField extends FormField
{

    public function Field($properties = array())
    {
        Requirements::customScript(<<<JS

 			(function($) {

				$.entwine('ss', function($){

					$('.cms-edit-form input#Form_EditForm_{$this->getName()}').entwine({
						// Constructor: onmatch
						onmatch : function() {

							$( "#Form_EditForm_{$this->getName()}" ).autocomplete({
								source: function( request, response ) {
									$.ajax({
									  url: "//suggestqueries.google.com/complete/search",
									  dataType: "jsonp",
									  data: {
										  client: 'firefox',
									    q: request.term
									  },
									  success: function( data ) {
									    response( data[1] );
									  }
									});
								},
								minLength: 3
							});

						},
					});
				});

			})(jQuery);
JS
);

        $this->addExtraClass('text');

        return parent::Field($properties);
    }
}

<?php
/**
 * Field which gets suggestions from google search
 */
class GoogleSuggestField extends FormField
{

    public function Field($properties = array())
    {
        Requirements::customScript(<<<JS

 			(function($) {
				var edit_form_id = "Form_EditForm";
				var alt_edit_form_id = "Form_ItemEditForm";

				$.entwine('ss', function($){

					$('.cms-edit-form input#Form_EditForm_{$this->getName()}').entwine({
						// Constructor: onmatch
						onmatch : function() {
							if (!$("#" + edit_form_id ).length) {
								edit_form_id = alt_edit_form_id;
							}

							console.log("#" + edit_form_id + "_{$this->getName()}");

							$( "#" + edit_form_id + "_{$this->getName()}" ).autocomplete({
								source: function( request, response ) {
									$.ajax({
									  url: "//suggestqueries.google.com/complete/search",
									  dataType: "jsonp",
									  data: {
										  client: 'firefox',
									    q: request.term
									  },
									  success: function( data ) {
									    response( data[1] );
									  }
									});
								},
								minLength: 3
							});

						},
					});
				});

			})(jQuery);
JS
);

        $this->addExtraClass('text');

        return parent::Field($properties);
    }
}

Add form type check to suggestion field

Add form type check to suggestion field


<?php

namespace EdpGithub;

use Zend\Module\Manager,
    Zend\Module\Consumer\AutoloaderProvider,
    Zend\EventManager\StaticEventManager;

class Module implements AutoloaderProvider
{
    protected static $options;

    public function init(Manager $moduleManager)
    {
        $moduleManager->events()->attach('loadModules.post', array($this, 'modulesLoaded'));
        $events = StaticEventManager::getInstance();
        $events->attach('ZfcUser\Authentication\Adapter\AdapterChain', 'authenticate.pre', function($e) {
            $e->getTarget()->attach(new Authentication\Adapter\EdpUserGithub);
        });
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig($env = null)
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function modulesLoaded($e)
    {
        $config = $e->getConfigListener()->getMergedConfig();
        static::$options = $config['edpgithub'];
    }

    public static function getOption($option)
    {
        if (!isset(static::$options[$option])) {
            return null;
        }
        return static::$options[$option];
    }
}

<?php

namespace EdpGithub;

use Zend\Module\Manager,
    Zend\Module\Consumer\AutoloaderProvider,
    Zend\EventManager\StaticEventManager;

class Module implements AutoloaderProvider
{
    protected static $options;

    public function init(Manager $moduleManager)
    {
        $moduleManager->events()->attach('loadModules.post', array($this, 'modulesLoaded'));
        $events = StaticEventManager::getInstance();
        $events->attach('ZfcUser\Authentication\Adapter\AdapterChain', 'authenticate.pre', function($e) {
            $e->getTarget()->attach(new Authentication\Adapter\ZfcUserGithub);
        });
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig($env = null)
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function modulesLoaded($e)
    {
        $config = $e->getConfigListener()->getMergedConfig();
        static::$options = $config['edpgithub'];
    }

    public static function getOption($option)
    {
        if (!isset(static::$options[$option])) {
            return null;
        }
        return static::$options[$option];
    }
}

Change classname in auth adapter listener


<?php

if (Config::item('hooks.enable')) {
    Event::add('system.routing', 'arag_module_hooks');
}

function arag_module_hooks()
{
    // All of the hooks are enabled, so we use list_files
    $hooks = array_unique(Kohana::list_files('modules/'.Router::$module.'/hooks', TRUE));

    // To validate the filename extension
    $ext = -(strlen(EXT));

    foreach($hooks as $hook) {

        if (substr($hook, $ext) === EXT) {
            // Hook was found, include it
            include_once $hook;

        } else {
            // This should never happen
            Log::add('error', 'Hook not found: '.$hook);
        }
    }
}

<?php

if (Config::item('hooks.enable')) {
    Event::add('system.routing', 'arag_module_hooks');
}

function arag_module_hooks()
{
    $hooks   = Array();
    $modules = Config::item('config.hooks');
    $modules = is_array($modules) ? array_merge($modules, Array(Router::$module)) : Array(Router::$module);

    $modules_path = $include_paths = Config::item('core.modules');
    foreach ($modules as $module) {
        $modules_path[] = MODPATH.$module;
    }

    Config::set('core.modules', $modules_path);

    foreach ($modules as $module) {
        $hooks = array_unique(array_merge($hooks, Kohana::list_files('modules/'.$module.'/hooks', TRUE)));
    }

    // To validate the filename extension
    $ext = -(strlen(EXT));

    foreach($hooks as $hook) {

        if (substr($hook, $ext) === EXT) {
            // Hook was found, include it
            include_once $hook;

        } else {
            // This should never happen
            Log::add('error', 'Hook not found: '.$hook);
        }
    }

    Config::set('core.modules', $include_paths);
}

Load module hooks in global scope.

Load module hooks in global scope.


<?php

class FacebookMetadataSiteConfig extends DataExtension {

    static $db = array(
        'SkipToMainContentAccessKey' => 'VarChar(1)'
    );

    static $has_one = array(
        'FacebookLogo' => 'Image'
    );

    public function updateCMSFields(FieldList $fields) {
	    $tf2 = new TextField('SkipToMainContentAccessKey');
	    $tf2->setMaxLength(1);
	    $fields->addFieldToTab('Root.FacebookMetadata', $tf2);
	    $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY'));
        $fields->addFieldToTab("Root.FacebookMetadata", new UploadField("FacebookLogo", _t('Facebook.METADATA_LOGO', 'Image that will show in facebook when linking to this site. The image should be a square')));
	}

}
?>

<?php

class FacebookMetadataSiteConfig extends DataExtension {

    static $db = array(
        'SkipToMainContentAccessKey' => 'VarChar(1)'
    );

    static $has_one = array(
        'FacebookLogo' => 'Image'
    );

    public function updateCMSFields(FieldList $fields) {

	    $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY'));
        $fields->addFieldToTab("Root.FacebookMetadata", new UploadField("FacebookLogo", _t('Facebook.METADATA_LOGO',
            'Image that will show in facebook when linking to this site. The image should be a square of minimum size 200px')));
	}

}
?>

FIX: Remove empty field, hangover from access keys module


<?php

/*
 * This file is a part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\Order;

/**
 * @author Grzegorz Sadowski <grzegorz.sadowski@lakion.com>
 */
final class CartActions
{
    const ADD = 'add';

    private function __construct()
    {
    }
}

<?php

/*
 * This file is a part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\Order;

/**
 * @author Grzegorz Sadowski <grzegorz.sadowski@lakion.com>
 */
final class CartActions
{
    const ADD = 'add';
    const REMOVE = 'remove';

    private function __construct()
    {
    }
}

Change events in order item controller

[Order][Cart] Change events in order item controller


<?php
/**
 * Studioforty9 Gallery
 *
 * @category  Studioforty9
 * @package   Studioforty9_Gallery
 * @author    StudioForty9 <info@studioforty9.com>
 * @copyright 2015 StudioForty9 (http://www.studioforty9.com)
 * @license   https://github.com/studioforty9/gallery/blob/master/LICENCE BSD
 * @version   1.0.0
 * @link      https://github.com/studioforty9/gallery
 */

/**
 * Studioforty9_Gallery_Model_Source_Album_Multiselect
 *
 * @category   Studioforty9
 * @package    Studioforty9_Gallery
 * @subpackage Model
 */
class Studioforty9_Gallery_Model_Source_Album_Multiselect
{
    /**
     * Create a list of multiselect options for selecting albums.
     *
     * @return array
     */
    public function toOptionsArray()
    {
        $albums = Mage::getModel('studioforty9_gallery/album')->getCollection()
            ->addFieldToSelect(array('name', 'entity_id'))
            ->addOrder('name', 'ASC')
            ->addFieldToFilter(
                'status', array(
                    'eq' => Studioforty9_Gallery_Model_Album::ENABLED
                )
            );

        $options = array();
        if ($albums->count() > 0) {
            foreach ($albums as $album) {
                $options[] = array(
                    'label' => $album->getName(),
                    'value' => (int) $album->getId()
                );
            }
        }

        return $options;
    }
}

<?php
/**
 * Studioforty9 Gallery
 *
 * @category  Studioforty9
 * @package   Studioforty9_Gallery
 * @author    StudioForty9 <info@studioforty9.com>
 * @copyright 2015 StudioForty9 (http://www.studioforty9.com)
 * @license   https://github.com/studioforty9/gallery/blob/master/LICENCE BSD
 * @version   1.0.0
 * @link      https://github.com/studioforty9/gallery
 */

/**
 * Studioforty9_Gallery_Model_Source_Album_Multiselect
 *
 * @category   Studioforty9
 * @package    Studioforty9_Gallery
 * @subpackage Model
 */
class Studioforty9_Gallery_Model_Source_Album_Multiselect
{
    /**
     * Create a list of multiselect options for selecting albums.
     *
     * @return array
     */
    public function toOptionsArray()
    {
        $albums = Mage::getModel('studioforty9_gallery/album')->getCollection()
            ->addFieldToSelect(array('name', 'entity_id'))
            ->addOrder('name', 'ASC');

        $options = array();
        if ($albums->count() > 0) {
            foreach ($albums as $album) {
                $options[] = array(
                    'label' => $album->getName(),
                    'value' => (int) $album->getId()
                );
            }
        }

        return $options;
    }
}

Remove status enable filter on multiselect source


<?php

/*
 * NOTICE OF LICENSE
 *
 * Part of the Rinvex Fort Package.
 *
 * This source file is subject to The MIT License (MIT)
 * that is bundled with this package in the LICENSE file.
 *
 * Package: Rinvex Fort Package
 * License: The MIT License (MIT)
 * Link:    https://rinvex.com
 */

namespace Rinvex\Fort\Http\Requests\Frontend;

use Rinvex\Support\Http\Requests\FormRequest;

class EmailVerificationRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return $this->isMethod('post') ? [
            'email' => 'required|email|max:255',
        ] : [
            'email' => 'required|email|max:255',
            'token' => 'required|regex:/^[0-9a-zA-Z]+$/',
        ];
    }
}

<?php

/*
 * NOTICE OF LICENSE
 *
 * Part of the Rinvex Fort Package.
 *
 * This source file is subject to The MIT License (MIT)
 * that is bundled with this package in the LICENSE file.
 *
 * Package: Rinvex Fort Package
 * License: The MIT License (MIT)
 * Link:    https://rinvex.com
 */

namespace Rinvex\Fort\Http\Requests\Frontend;

use Rinvex\Support\Http\Requests\FormRequest;

class EmailVerificationRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return $this->isMethod('post') ? [
            'email' => 'required|email|max:255',
        ] : [
            'token' => 'required|regex:/^[0-9a-zA-Z]+$/',
            'email' => 'required|email|max:255|exists:'.config('rinvex.fort.tables.users').',email',
        ];
    }

    /**
     * {@inheritdoc}
     */
    protected function getRedirectUrl()
    {
        if ($this->isMethod('post')) {
            return parent::getRedirectUrl();
        }

        return route('rinvex.fort.frontend.verification.email.request');
    }
}

Fix redirection loop when validation fails


        {{ $attributeTitle }}

        @if ($value)
            @if (is_scalar($value))
                @if (array_key_exists($value, $options['options']))
                    {{ $options['options'][$value] }}
                @else
                    {{ $value }}
                @endif
            @else
                @foreach ($value as $key => $value)
                    @if (!is_scalar($value) && array_key_exists($value->{$value->getKeyName()}, $options['options']))
                        {{ $options['options'][$value->{$value->getKeyName()}] }}

                    @else
                        @if (array_key_exists($value, $options['options']))
                            {{ $options['options'][$value] }}

                        @else
                            {{ $value }}

                        @endif
                    @endif
                @endforeach
            @endif
        @endif

        {{ $attributeTitle }}

        @if ($value)
            @if (is_scalar($value))
                @if (array_key_exists($value, $options['options']))
                    {{ $options['options'][$value] }}
                @else
                    {{ $value }}
                @endif
            @elseif (is_array($value))
                @foreach ($value as $key => $value)
                    @if (!is_scalar($value) && array_key_exists($value->{$value->getKeyName()}, $options['options']))
                        {{ $options['options'][$value->{$value->getKeyName()}] }}

                    @else
                        @if (array_key_exists($value, $options['options']))
                            {{ $options['options'][$value] }}

                        @else
                            {{ $value }}

                        @endif
                    @endif
                @endforeach
            @elseif ($value instanceof \Illuminate\Database\Eloquent\Model && $optionValue = $value->getKey())
                {{ $options['options'][$optionValue] }}
            @endif
        @endif

Fix to Select View Template for rendering Models selected from dropdown


<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\models\Log */

$this->title = 'Make a Widthdrawal';
$this->params['breadcrumbs'][] = ['label' => 'Logs', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

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

    <?= $this->render('_deposit_withdrawal_form', [
        'model' => $model,
    ]) ?>

<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\models\Log */

$this->title = 'Make a Withdrawal';
$this->params['breadcrumbs'][] = ['label' => 'Logs', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

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

    <?= $this->render('_deposit_withdrawal_form', [
        'model' => $model,
    ]) ?>

Fix to spelling of "Withdrawal" on its view.


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;

class SecurityController extends Controller
{
    public function loginAction(Request $request)
    {
        $session = $request->getSession();

        // get the login error if there is one
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR))
        {
            $error = $request->attributes->get(
                SecurityContext::AUTHENTICATION_ERROR
            );
        } else
        {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        return $this->render(
            'MunicipalesBundle::Security:login.html.twig',
            array(
                // last username entered by the user
                'last_username' => $session->get(SecurityContext::LAST_USERNAME),
                'error'         => $error,
            )
        );
    }
}

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;

class SecurityController extends Controller
{
    public function loginAction(Request $request)
    {
        $session = $request->getSession();

        // get the login error if there is one
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR))
        {
            $error = $request->attributes->get(
                SecurityContext::AUTHENTICATION_ERROR
            );
        } else
        {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        return $this->render(
            'MunicipalesBundle:Security:login.html.twig',
            array(
                // last username entered by the user
                'last_username' => $session->get(SecurityContext::LAST_USERNAME),
                'error'         => $error,
            )
        );
    }
}

Fix typo in route template security

Fix typo in route template security


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class DuesPackage extends Model
{
    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];

    /**
     * Get the DuesTransaction associated with the DuesPackage model.
     */
    public function transactions()
    {
        return $this->hasMany('App\DuesTransaction');
    }

    /**
     * Scope a query to only include active DuesPackages.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class DuesPackage extends Model
{
    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['is_active'];

    /**
     * Get the DuesTransaction associated with the DuesPackage model.
     */
    public function transactions()
    {
        return $this->hasMany('App\DuesTransaction');
    }

    /**
     * Scope a query to only include DuesPackages available for purchase.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeAvailableForPurchase($query)
    {
        return $query->where('available_for_purchase', 1);
    }

    /**
     * Scope a query to only include active DuesPackages.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        return $query->whereDate('effective_start', '<=', date('Y-m-d'))
            ->whereDate('effective_end', '>=', date('Y-m-d'));
    }

    /**
     * Get the is_active flag for the DuesPackage.
     *
     * @return bool
     */
    public function getIsActiveAttribute()
    {
        return ($this->attributes['effective_start'] <= date('Y-m-d') &&
                $this->attributes['effective_end'] >= date('Y-m-d'));
    }
}

Add is_active virtual attribute, available_for_purchase local scope, active local scope


Remove logo from Laravel forms

Remove logo from Laravel forms


<?php

include_once('../../config/init.php');
include_once($BASE_DIR . 'database/models.php');

function getComments($comments) {
    global $smarty;
    $smarty->assign("comments", $comments);
    $smarty->display('models/comments.tpl');
}

class CommentsHandler {
    function post($modelId) { // TODO: xhr
        global $BASE_DIR;
        global $smarty;

        insertComment(getLoggedId(), $modelId, $_POST['content']);

        header('Location: ' . $_SERVER['HTTP_REFERER']);
    }
}

<?php

include_once($BASE_DIR . 'database/models.php');

function getComments($comments) {
    global $smarty;
    $smarty->assign("comments", $comments);
    $smarty->display('models/comments.tpl');
}

class CommentsHandler {
    function post($modelId) { // TODO: xhr
        global $BASE_DIR;
        global $smarty;

        insertComment(getLoggedId(), $modelId, $_POST['content']);

        header('Location: ' . $_SERVER['HTTP_REFERER']);
    }
}

Revert "Popular expression: "A ver se pinta"."

This reverts commit ef47b8f8d174fcf8ded4be9d8f431cc4e54b5d3f.


<?php

/*
 * NOTICE OF LICENSE
 *
 * Part of the Rinvex Fort Package.
 *
 * This source file is subject to The MIT License (MIT)
 * that is bundled with this package in the LICENSE file.
 *
 * Package: Rinvex Fort Package
 * License: The MIT License (MIT)
 * Link:    https://rinvex.com
 */

namespace Rinvex\Fort\Http\Requests\Frontend;

use Illuminate\Support\Facades\Auth;

class PhoneVerificationSendRequest extends PhoneVerificationRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $user = Auth::guard()->user() ?: Auth::guard()->attemptUser();

        return $this->isMethod('post') ? [
            'phone'  => 'required|numeric|exists:'.config('rinvex.fort.tables.users').',phone,id,'.$user->id.',phone_verified,1',
            'method' => 'required',
        ] : [];
    }
}

<?php

/*
 * NOTICE OF LICENSE
 *
 * Part of the Rinvex Fort Package.
 *
 * This source file is subject to The MIT License (MIT)
 * that is bundled with this package in the LICENSE file.
 *
 * Package: Rinvex Fort Package
 * License: The MIT License (MIT)
 * Link:    https://rinvex.com
 */

namespace Rinvex\Fort\Http\Requests\Frontend;

class PhoneVerificationSendRequest extends PhoneVerificationRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return $this->isMethod('post') ? [
            'phone'  => 'required|numeric|exists:'.config('rinvex.fort.tables.users').',phone',
            'method' => 'required',
        ] : [];
    }
}

Fix wrong phone validation rule

Fix wrong phone validation rule


<?php

namespace App;

use Exception;

use ScoutEngines\Elasticsearch\ElasticsearchEngine as BaseEngine;

class ElasticsearchEngine extends BaseEngine
{

    /**
     * Update the given model in the index.
     *
     * @param  Collection  $models
     * @return void
     */
    public function update($models)
    {
        $params['body'] = [];

        $models->each(function($model) use (&$params)
        {
            $params['body'][] = [
                'update' => $this->getIdIndexType($model)
            ];
            $params['body'][] = [
                'doc' => $model->toSearchableArray(),
                'doc_as_upsert' => true
            ];
        });

        $result = $this->elastic->bulk($params);

        // TODO: Requeue only the models that failed?
        if (isset($result['errors']) && $result['errors'] === true)
        {
            $failedDocs = array_values(array_filter($result['items'], function($item) {
                return isset($item['update']['error']);
            }));

            foreach ($failedDocs as $doc)
            {
                try {
                    throw new Exception(json_encode($doc));
                } catch (Exception $e) {
                    // https://laravel.com/docs/5.7/errors - The `report` Helper
                    report($e);
                }
            }
        }
    }

}

<?php

namespace App;

use Exception;

use ScoutEngines\Elasticsearch\ElasticsearchEngine as BaseEngine;

class ElasticsearchEngine extends BaseEngine
{

    /**
     * Update the given model in the index.
     *
     * @param  Collection  $models
     * @return void
     */
    public function update($models)
    {
        $params['body'] = [];

        $models->each(function($model) use (&$params)
        {
            $params['body'][] = [
                'update' => $this->getIdIndexType($model)
            ];
            $params['body'][] = [
                'doc' => $model->toSearchableArray(),
                'doc_as_upsert' => true
            ];
        });

        $result = $this->elastic->bulk($params);

        // TODO: Requeue only the models that failed?
        if (isset($result['errors']) && $result['errors'] === true)
        {
            $failedDocs = array_values(array_filter($result['items'], function($item) {
                return isset($item['update']['error']);
            }));

            // If all docs failed, throw an uncaught exception
            if (count($failedDocs) === count($result['items']))
            {
                throw new Exception(json_encode($result));
            }

            foreach ($failedDocs as $doc)
            {
                try {
                    throw new Exception(json_encode($doc));
                } catch (Exception $e) {
                    // https://laravel.com/docs/5.7/errors - The `report` Helper
                    report($e);
                }
            }
        }
    }

}

Throw an uncaught exception if all docs failed


<?php

/*
 * This file is part of the FOSRestBundle package.
 *
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FOS\RestBundle\View;

use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\NavigatorContext;
use JMS\Serializer\Metadata\PropertyMetadata;
use JMS\Serializer\Exclusion\ExclusionStrategyInterface;
use JMS\Serializer\Exclusion\VersionExclusionStrategy;
use JMS\Serializer\Exclusion\GroupsExclusionStrategy;

class GroupsVersionExclusionStrategy implements ExclusionStrategyInterface
{
    private $groupExclusion;
    private $versionExclusion;

    public function __construct($groups, $version)
    {
        $this->groupExclusion = new GroupsExclusionStrategy((array) $groups);
        $this->versionExclusion = new VersionExclusionStrategy($version);
    }

    public function shouldSkipClass(ClassMetadata $metadata, NavigatorContext $navigatorContext)
    {
        return false;
    }

    public function shouldSkipProperty(PropertyMetadata $property, NavigatorContext $navigatorContext)
    {
        return $this->groupExclusion->shouldSkipProperty($property, $navigatorContext)
            || $this->versionExclusion->shouldSkipProperty($property, $navigatorContext)
        ;
    }
}

<?php

/*
 * This file is part of the FOSRestBundle package.
 *
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FOS\RestBundle\View;

use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Context;
use JMS\Serializer\Metadata\PropertyMetadata;
use JMS\Serializer\Exclusion\ExclusionStrategyInterface;
use JMS\Serializer\Exclusion\VersionExclusionStrategy;
use JMS\Serializer\Exclusion\GroupsExclusionStrategy;

class GroupsVersionExclusionStrategy implements ExclusionStrategyInterface
{
    private $groupExclusion;
    private $versionExclusion;

    public function __construct($groups, $version)
    {
        $this->groupExclusion = new GroupsExclusionStrategy((array) $groups);
        $this->versionExclusion = new VersionExclusionStrategy($version);
    }

    public function shouldSkipClass(ClassMetadata $metadata, Context $navigatorContext)
    {
        return false;
    }

    public function shouldSkipProperty(PropertyMetadata $property, Context $navigatorContext)
    {
        return $this->groupExclusion->shouldSkipProperty($property, $navigatorContext)
            || $this->versionExclusion->shouldSkipProperty($property, $navigatorContext)
        ;
    }
}

Fix method prototype to be compatible with new API


$('.form-group-url').removeClass('has-error')
    .find('.alert')
    .fadeOut();
$('#input-url').val('{{ $shortUrl }}').select();

{{--$('#btn-copy-url').focus();--}}
{{--$('#input-original-url').val('').focus();--}}

$('.form-group-url').removeClass('has-error')
    .find('.alert')
    .fadeOut();
$('#input-original-url').val('');
$('#input-url').val('{{ $shortUrl }}').select();

{{--$('#btn-copy-url').focus();--}}
{{--$('#input-original-url').val('').focus();--}}

Clean input field after url generation

Clean input field after url generation