<?php

namespace Respect\Validation\Exceptions;

class IpException extends ValidationException
{

    public static $defaultTemplates = array(
        self::MODE_DEFAULT => array(
            self::STANDARD => '{{name}} must be an IP address',
        ),
        self::MODE_NEGATIVE => array(
            self::STANDARD => '{{name}} must not be an IP address',
        )
    );

}

<?php

namespace Respect\Validation\Exceptions;

class IpException extends ValidationException
{
    const STANDARD = 0;
    const NETWORK_RANGE = 1;

    public static $defaultTemplates = array(
        self::MODE_DEFAULT => array(
            self::STANDARD => '{{name}} must be an IP address',
            self::NETWORK_RANGE => '{{name}} must be an IP address in the {{range}} range',
        ),
        self::MODE_NEGATIVE => array(
            self::STANDARD => '{{name}} must not be an IP address',
            self::NETWORK_RANGE => '{{name}} must not be an IP address in the {{range}} range',
        )
    );

    public function configure($name, array $params=array())
    {
        if ($params['networkRange']) {
            $range = $params['networkRange'];
            $message = $range['min'];

            if (isset($range['max']))
                $message .= '-' . $range['max'];
            else
                $message .= '/' . $range['mask'];

            $params['range'] = $message;
        }

        return parent::configure($name, $params);
    }

    public function chooseTemplate()
    {
        if (!$this->getParam('networkRange'))
            return static::STANDARD;
        else
            return static::NETWORK_RANGE;
    }

}

Fix the exception message when the valitor has a network range


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

require_once ("../../lib/base.php");
OC_Util::checkLoggedIn();
OC_Util::checkAppEnabled('contacts');
$book = isset($_GET['bookid']) ? $_GET['bookid'] : NULL;
$contact = isset($_GET['contactid']) ? $_GET['contactid'] : NULL;
$nl = "\n";
if(isset($book)){
	$addressbook = OC_Contacts_App::getAddressbook($book);
	$cardobjects = OC_Contacts_VCard::all($book);
	header('Content-Type: text/directory');
	header('Content-Disposition: inline; filename=' . str_replace(' ', '_', $addressbook['displayname']) . '.vcf');

	foreach($cardobjects as $card) {
		echo $card['carddata'] . $nl;
	}
}elseif(isset($contact)){
	$data = OC_Contacts_App::getContactObject($contact);
	header('Content-Type: text/directory');
	header('Content-Disposition: inline; filename=' . str_replace(' ', '_', $data['fullname']) . '.vcf');
	echo $data['carddata'];
}
?>

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

require_once ("../../lib/base.php");
OC_Util::checkLoggedIn();
OC_Util::checkAppEnabled('contacts');
$bookid = isset($_GET['bookid']) ? $_GET['bookid'] : NULL;
$contactid = isset($_GET['contactid']) ? $_GET['contactid'] : NULL;
$nl = "\n";
if(isset($bookid)){
	$addressbook = OC_Contacts_App::getAddressbook($bookid);
	$cardobjects = OC_Contacts_VCard::all($bookid);
	header('Content-Type: text/directory');
	header('Content-Disposition: inline; filename=' . str_replace(' ', '_', $addressbook['displayname']) . '.vcf');

	foreach($cardobjects as $card) {
		echo $card['carddata'] . $nl;
	}
}elseif(isset($contactid)){
	$data = OC_Contacts_App::getContactObject($contactid);
	header('Content-Type: text/directory');
	header('Content-Disposition: inline; filename=' . str_replace(' ', '_', $data['fullname']) . '.vcf');
	echo $data['carddata'];
}
?>

Add id to vars with id in them

Contacts: Add id to vars with id in them


<?php
set_include_path('phar://' . __DIR__ . '/p2pear.phar');
error_reporting(E_ALL & ~(E_NOTICE | E_STRICT | E_DEPRECATED));
require __DIR__ . '/vendor/.composer/autoload.php';
require __DIR__ . '/conf/conf.inc.php';

<?php
if (file_exists(__DIR__ . '/p2pear.phar')) {
    set_include_path('phar://' . __DIR__ . '/p2pear.phar'
                     . PATH_SEPARATOR . get_include_path());
}
error_reporting(E_ALL & ~(E_NOTICE | E_STRICT | E_DEPRECATED));
require __DIR__ . '/vendor/.composer/autoload.php';
require __DIR__ . '/conf/conf.inc.php';

Change to use default include_path as fallback.


<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2019, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Affiliate / Controller
 */

namespace PH7;

use PH7\Framework\Url\Header;

class RouterController extends Controller
{
    /**
     * Set the reference to the visitor.
     *
     * @return void
     */
    public function refer()
    {
        if ($this->httpRequest->getExists('aff')) {
            $this->addUsernameReferer();
        }

        $this->redirectToWebsite();
    }

    private function addUsernameReferer()
    {
        if ((new ExistsCoreModel)->username($this->httpRequest->get('aff'), DbTableName::AFFILIATE)) {
            (new Affiliate)->addRefer($this->httpRequest->get('aff'));
        }
    }

    /**
     * Redirect the user to the website's homepage or a specific page if GET 'action' is specified.
     *
     * @return void
     */
    private function redirectToWebsite()
    {
        $sUrl = $this->registry->site_url . $this->httpRequest->get('action');
        Header::redirect($sUrl);
    }
}

<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2019, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Affiliate / Controller
 */

namespace PH7;

use PH7\Framework\Url\Header;

class RouterController extends Controller
{
    /**
     * Set the reference to the visitor.
     *
     * @return void
     */
    public function refer()
    {
        if ($this->httpRequest->getExists('aff')) {
            $this->addUsernameReferer();
        }

        $this->redirectToWebsite();
    }

    private function addUsernameReferer()
    {
        $sUsername = $this->httpRequest->get('aff');

        if ((new ExistsCoreModel)->username($sUsername, DbTableName::AFFILIATE)) {
            (new Affiliate)->addRefer($sUsername);
        }
    }

    /**
     * Redirect the user to the website's homepage or a specific page if GET 'action' is specified.
     *
     * @return void
     */
    private function redirectToWebsite()
    {
        $sUrl = $this->registry->site_url . $this->httpRequest->get('action');
        Header::redirect($sUrl);
    }
}

Store username referer into a variable

[Readability] Store username referer into a variable


<?php

/*
 * This file is part of the PhpTabs package.
 *
 * Copyright (c) landrok at github.com/landrok
 *
 * For the full copyright and license information, please see
 * <https://github.com/stdtabs/phptabs/blob/master/LICENSE>.
 */

namespace PhpTabs\Music;

class Scale
{
  private $notes = array(); // 12
  private $key;

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

  /**
   * @param int $key
   */
  public function setKey($key)
  {
    $this->key = $key;
  }

  /**
   * @return int
   */
  public function getKey()
  {
    return $this->key;
  }

  /**
   * @param int $note
   * @param int $on
   */
  public function setNote($note, $on)
  {
    $this->notes[$note] = $on;
  }

  /**
   * @param int $note
   *
   * @return int
   */
  public function getNote($note)
  {
    return $this->notes[(($note + (12 - $this->key)) % 12)];
  }

  public function clear()
  {
    $this->setKey(0);

    for ($i = 0; $i < count($this->notes); $i++)
    {
      $this->setNote($i, false);
    }
  }
}

<?php

/*
 * This file is part of the PhpTabs package.
 *
 * Copyright (c) landrok at github.com/landrok
 *
 * For the full copyright and license information, please see
 * <https://github.com/stdtabs/phptabs/blob/master/LICENSE>.
 */

namespace PhpTabs\Music;

class Scale
{
  private $notes = array(); // 12
  private $key;

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

  /**
   * @param int $key
   */
  public function setKey($key)
  {
    $this->key = $key;
  }

  /**
   * @return int
   */
  public function getKey()
  {
    return $this->key;
  }

  /**
   * @param int $note
   * @param int|boolean $on
   */
  public function setNote($note, $on)
  {
    $this->notes[$note] = $on;
  }

  /**
   * @param int $note
   *
   * @return int
   */
  public function getNote($note)
  {
    return $this->notes[(($note + (12 - $this->key)) % 12)];
  }

  public function clear()
  {
    $this->setKey(0);

    for ($i = 0; $i < count($this->notes); $i++)
    {
      $this->setNote($i, false);
    }
  }
}

Fix PHPDoc wrong type annotation

Fix PHPDoc wrong type annotation


<?php

/*
  PufferPanel - A Minecraft Server Management Panel
  Copyright (c) 2013 Dane Everitt

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

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

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

namespace PufferPanel\Core\Components;

use \Unirest;

/**
 * General Functions Trait
 */
trait Daemon {

    /**
     * Checks if the daemon is running.
     *
     * @param string $ip
     * @param int $port
     * @param int $timeout
     * @return bool
     */
    public function avaliable($ip, $port = 5656, $timeout = 3) {

        Unirest\Request::timeout($timeout);

        try {
            Unirest::get(\PufferPanel\Core\Daemon::buildBaseUrlForNode($ip, $port));
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

}

<?php

/*
  PufferPanel - A Minecraft Server Management Panel
  Copyright (c) 2013 Dane Everitt

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

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

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

namespace PufferPanel\Core\Components;

use \Unirest;

/**
 * General Functions Trait
 */
trait Daemon {

    /**
     * Checks if the daemon is running.
     *
     * @param string $ip
     * @param int $port
     * @param int $timeout
     * @return bool
     */
    public function avaliable($ip, $port = 5656, $timeout = 3) {

        Unirest\Request::timeout($timeout);

        try {
            Unirest\Request::get(\PufferPanel\Core\Daemon::buildBaseUrlForNode($ip, $port));
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

}

Fix call for status This might fix the UI call, but probably not


<?php

/** @var \Codeception\Scenario $scenario */

$scenario->incomplete('not yet implemented');

/*
$I = new AcceptanceTester($scenario);
$I->populateDBData1();

- Activate the long home page view, with hidden amendments

*/

<?php

/** @var \Codeception\Scenario $scenario */

$I = new AcceptanceTester($scenario);
$I->populateDBData1();

$I->gotoConsultationHome();
$page = $I->loginAsStdAdmin()->gotoStdAdminPage()->gotoConsultation();
$I->selectFueluxOption('#startLayoutType', '5');
$page->saveForm();

$I->gotoConsultationHome();
$I->seeElement('.motionRow2 .amendmentsToggler.closed');
$I->dontSeeElement('.amendmentRow1');

$I->executeJS('$(".motionRow2 .amendmentsToggler button").click();');

$I->seeElement('.amendmentRow1');

Add test case for new home page style

Add test case for new home page style


<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-console',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'console\controllers',
    'controllerMap' => [
        'fixture' => [
            'class' => 'yii\console\controllers\FixtureController',
            'namespace' => 'common\fixtures',
          ],
        'message' => [
            'class' => '@mobilejazz\yii2\cms\console\controllers\ExtendedMessageController'
        ],
        'migrate'=>[
            'class'=>'fishvision\migrate\controllers\MigrateController',
            'autoDiscover' => true,
            'migrationPaths'=>[
                '@vendor/yiisoft/yii2/rbac/migrations',
                '@vendor/mobilejazz/yii2-mj-cms/src/console/migrations',
                '@console/migrations'
            ]
        ]
    ],
    'components' => [
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
    ],
    'params' => $params,
];

<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-console',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'console\controllers',
    'controllerMap' => [
        'fixture' => [
            'class' => 'yii\console\controllers\FixtureController',
            'namespace' => 'common\fixtures',
          ],
        'message' => [
            'class' => 'mobilejazz\yii2\cms\console\controllers\ExtendedMessageController'
        ],
        'migrate'=>[
            'class'=>'fishvision\migrate\controllers\MigrateController',
            'autoDiscover' => true,
            'migrationPaths'=>[
                '@vendor/yiisoft/yii2/rbac/migrations',
                '@vendor/mobilejazz/yii2-mj-cms/src/console/migrations',
                '@console/migrations'
            ]
        ]
    ],
    'components' => [
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
    ],
    'params' => $params,
];

Correct config for console environment

Correct config for console environment


<?php

use OpenSRS\domains\lookup\LookupDomain;

class LookupDomainIntegrationTest extends PHPUnit_Framework_TestCase
{

    /**
     * Should be able to do a lookup on google.com
     *
     *
     * @return void
     */
    public function testlookupGoogle()
    {
        $data = (object) array (
            'func' => 'premiumDomain',
            'data' => (object) array (
                'domain' => 'google.com',
                'selected' => '.com',
            ),
        );

        $ld = new LookupDomain('array', $data);
        $this->assertEquals($ld->resultRaw[0]['status'], 'taken');
    }
}

<?php

use OpenSRS\domains\lookup\LookupDomain;

class LookupDomainIntegrationTest extends PHPUnit_Framework_TestCase
{

    /**
     * Should be able to do a lookup on google.com
     *
     *
     * @return void
     */
    public function testlookupGoogle()
    {
        $data = (object) array (
            'func' => 'lookupDomain',
            'data' => (object) array (
                'domain' => 'google.com',
            ),
        );

        $ld = new LookupDomain('array', $data);
        $this->assertEquals($ld->resultRaw[0]['status'], 'taken');
    }
}

Clean up lookupdomain int test

Clean up lookupdomain int test


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

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

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

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

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

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

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

What's next ?

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

',
                'meta_title' => 'Home page',
            ],
            'fr' => [
                'title' => 'Page d\'accueil',
                'slug' => 'accueil',
                'body' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum iure necessitatibus repellat sapiente sit. Alias dolore id, nam odit reiciendis similique vel voluptatem! Alias assumenda beatae doloremque iste magni provident quae reiciendis saepe tempora voluptatibus! Animi, asperiores consectetur cum delectus explicabo fuga neque, quam quidem reiciendis similique unde voluptates! Quibusdam.',
                'meta_title' => 'Page d\'accueil',
            ],
        ];
        $this->page->create($data);
    }
}

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

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

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

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

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

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

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

What's next ?

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

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

Remove the french home page data. Only seed an English page.


<?php

/**
 * Config for the connections for the test
 */
return [
    'mysql' => [
        'type'     => 'mysql',
        'host'     => 'localhost',
        'database' => 'sample_database',
        'user'     => 'sample_user',
        'password' => 'sample_password',
        'charset'  => 'utf8',
        'options'  => [
            PDO::ATTR_PERSISTENT         => true,
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
        ],
        'class' => \OlajosCs\QueryBuilder\MySQL\Connection::class // Needed only for testing
    ],

    'pgsql' => [
        'type'     => 'pgsql',
        'host'     => 'localhost',
        'database' => 'sample_database',
        'user'     => 'sample_user',
        'password' => 'sample_password',
        'options'  => [
            PDO::ATTR_PERSISTENT         => true,
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
        ],
        'class' => \OlajosCs\QueryBuilder\MySQL\Connection::class // Needed only for testing
    ]
];

<?php

/**
 * Config for the connections for the test
 */
return [
    'mysql' => [
        'type'     => 'mysql',
        'host'     => 'localhost',
        'database' => 'sample_database',
        'user'     => 'sample_user',
        'password' => 'sample_password',
        'charset'  => 'utf8',
        'options'  => [
            PDO::ATTR_PERSISTENT         => true,
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
        ],
        'class' => \OlajosCs\QueryBuilder\MySQL\Connection::class // Needed only for testing
    ],

    'pgsql' => [
        'type'     => 'pgsql',
        'host'     => 'localhost',
        'database' => 'sample_database',
        'user'     => 'sample_user',
        'password' => 'sample_password',
        'options'  => [
            PDO::ATTR_PERSISTENT         => true,
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
        ],
        'class' => \OlajosCs\QueryBuilder\PostgreSQL\Connection::class // Needed only for testing
    ]
];

Put classes into config file

Put classes into config file


<?php declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: alex
 * Date: 26/10/14
 * Time: 00:26
 */
namespace FeedIo\Rule;

use FeedIo\Feed\NodeInterface;
use FeedIo\RuleAbstract;

class Description extends RuleAbstract
{
    const NODE_NAME = 'description';

    /**
     * @param  NodeInterface $node
     * @param  \DOMElement   $element
     */
    public function setProperty(NodeInterface $node, \DOMElement $element) : void
    {
        $string = '';
        if ($element->firstChild && $element->firstChild->nodeType == XML_CDATA_SECTION_NODE) {
            $string = $element->firstChild->textContent;
        } else {
            foreach ($element->childNodes as $childNode) {
                $string .= $element->ownerDocument->saveXML($childNode);
            }
        }

        $node->setDescription(htmlspecialchars_decode($string));
    }

    /**
     * @inheritDoc
     */
    protected function hasValue(NodeInterface $node) : bool
    {
        return !! $node->getDescription();
    }

    /**
     * @inheritDoc
     */
    protected function addElement(\DomDocument $document, \DOMElement $rootElement, NodeInterface $node) : void
    {
        $description = htmlspecialchars($node->getDescription());
        $element = $document->createElement($this->getNodeName(), $description);
        if ($description !== $node->getDescription() && $this->getNodeName() != 'description') {
            $element->setAttribute('type', 'html');
        }

        $rootElement->appendChild($element);
    }
}

<?php declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: alex
 * Date: 26/10/14
 * Time: 00:26
 */
namespace FeedIo\Rule;

use FeedIo\Feed\NodeInterface;
use FeedIo\RuleAbstract;

class Description extends RuleAbstract
{
    const NODE_NAME = 'description';

    /**
     * @param  NodeInterface $node
     * @param  \DOMElement   $element
     */
    public function setProperty(NodeInterface $node, \DOMElement $element) : void
    {
        $string = '';
        foreach ($element->childNodes as $childNode) {
            if ($childNode->nodeType == XML_CDATA_SECTION_NODE) {
                $string .= $childNode->textContent;
            } else {
                $string .= $element->ownerDocument->saveXML($childNode);
            }
        }

        $node->setDescription(htmlspecialchars_decode($string));
    }

    /**
     * @inheritDoc
     */
    protected function hasValue(NodeInterface $node) : bool
    {
        return !! $node->getDescription();
    }

    /**
     * @inheritDoc
     */
    protected function addElement(\DomDocument $document, \DOMElement $rootElement, NodeInterface $node) : void
    {
        $description = htmlspecialchars($node->getDescription());
        $element = $document->createElement($this->getNodeName(), $description);
        if ($description !== $node->getDescription() && $this->getNodeName() != 'description') {
            $element->setAttribute('type', 'html');
        }

        $rootElement->appendChild($element);
    }
}

Support CDATA with leading spaces

Support CDATA with leading spaces


<?php
namespace Janitor\Models;

use Illuminate\Cache\Repository;
use Symfony\Component\Finder\Finder;

/**
 * The user's codebase
 *
 * @author Maxime Fabre <ehtnam6@gmail.com>
 */
class Codebase
{
	/**
	 * @type Repository
	 */
	private $cache;

	/**
	 * @type SplFileInfo[]
	 */
	protected $files = [];

	/**
	 * Build a new codebase
	 *
	 * @param Repository $cache
	 */
	public function __construct(Repository $cache)
	{
		$finder = new Finder();
		$files  = $finder->files()->name('/\.(php|twig)$/')->in(app_path());
		$files  = iterator_to_array($files);

		$this->files = $files;
		$this->cache = $cache;
	}

	/**
	 * Get a serialized version of the codebase
	 *
	 * @return string
	 */
	public function getSerialized()
	{
		$contents = [];
		foreach ($this->files as $key => $file) {
			$contents[$file->getBasename()] = $file->getContents();
		}

		return $contents;
	}
}

<?php
namespace Janitor\Models;

use Illuminate\Cache\Repository;
use Symfony\Component\Finder\Finder;

/**
 * The user's codebase
 *
 * @author Maxime Fabre <ehtnam6@gmail.com>
 */
class Codebase
{
	/**
	 * The files that are part of the codebase
	 *
	 * @type SplFileInfo[]
	 */
	protected $files = [];

	/**
	 * Serialized version of the codebase
	 *
	 * @type string[]
	 */
	protected $serialized;

	/**
	 * Build a new codebase
	 */
	public function __construct()
	{
		$finder = new Finder();
		$files  = $finder->files()->name('/\.(php|twig)$/')->in(app_path());
		$files  = iterator_to_array($files);

		$this->files = $files;
	}

	/**
	 * Get a serialized version of the codebase
	 *
	 * @return string[]
	 */
	public function getSerialized()
	{
		if (!$this->serialized) {
			foreach ($this->files as $key => $file) {
				$this->serialized[$file->getBasename()] = $file->getContents();
			}
		}

		return $this->serialized;
	}
}

Remove cache dependency from codebase

Remove cache dependency from codebase


<?php declare(strict_types=1);

namespace Siler\Test\Unit\Prelude;

use PHPUnit\Framework\TestCase;
use function Siler\Arr\set;

class ArrTest extends TestCase
{
    public function testSet()
    {
        $fixture = ['foo' => ['bar' => 'baz']];
        $expected = ['foo' => ['bar' => 'qux']];
        set($fixture, 'foo.bar', 'qux');
        $this->assertSame($expected, $fixture);
    }
}

<?php declare(strict_types=1);

namespace Siler\Test\Unit\Prelude;

use PHPUnit\Framework\TestCase;
use function Siler\Arr\set;

class ArrTest extends TestCase
{
    public function testSet()
    {
        $fixture = ['foo' => ['bar' => 'baz']];
        $expected = ['foo' => ['bar' => 'qux']];

        set($fixture, 'foo.bar', 'qux');

        $this->assertSame($expected, $fixture);
    }

    public function testSetDeeplyCreates()
    {
        $fixture = ['foo' => []];
        $expected = ['foo' => ['bar' => 'qux']];

        set($fixture, 'foo.bar', 'qux');

        $this->assertSame($expected, $fixture);
    }
}

Add test for inexistent key on Arr\set

Add test for inexistent key on Arr\set


<?php
/**
 * @copyright Copyright (c) 2016, ownCloud GmbH
 *
 * @author Thomas Müller <thomas.mueller@tmit.eu>
 * @author Louis Chemineau <louis@chmn.me>
 *
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program. If not, see <http://www.gnu.org/licenses/>
 *
 */
namespace OCA\DAV;

use OCP\Capabilities\ICapability;

class Capabilities implements ICapability {
	public function getCapabilities() {
		return [
			'dav' => [
				'chunking' => '1.0',
				'bulkupload' => '1.0',
			]
		];
	}
}

<?php
/**
 * @copyright Copyright (c) 2016, ownCloud GmbH
 *
 * @author Thomas Müller <thomas.mueller@tmit.eu>
 * @author Louis Chemineau <louis@chmn.me>
 *
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program. If not, see <http://www.gnu.org/licenses/>
 *
 */
namespace OCA\DAV;

use OCP\Capabilities\ICapability;

class Capabilities implements ICapability {
	public function getCapabilities() {
		return [
			'dav' => [
				'chunking' => '1.0',
// disabled because of https://github.com/nextcloud/desktop/issues/4243
//				'bulkupload' => '1.0',
			]
		];
	}
}

Disable bulk upload by not advertising it

It has been reported broken on many instances.
Disable it for now until it can be fixed.

Signed-off-by: Vincent Petry <87e1f221a672a14a323e57bb65eaea19d3ed3804@nextcloud.com>


<?php

//ModuleManager::uninstall($module_to_uninstall);
if (ModuleManager::is_installed('Base_EpesiStore') === -1)
    return;

PatchDBAlterColumn('epesi_store_modules', 'version', 'C(10)');

?>

<?php

//ModuleManager::uninstall($module_to_uninstall);
if (ModuleManager::is_installed('Base_EpesiStore') === -1)
    ModuleManager::install('Base_EpesiStore');
else
	PatchDBAlterColumn('epesi_store_modules', 'version', 'C(10)');

?>

Patch that installs epesi store

Patch that installs epesi store


<?php
/**
 * @package plugins.sphinxSearch
 * @subpackage lib
 */
class SphinxUtils
{
	public static function escapeString($str, $escapeType = SearchIndexFieldEscapeType::DEFAULT_ESCAPE, $iterations = 2)
	{
		return KalturaCriteria::escapeString($str, $escapeType, $iterations);
	}

}

Handle backslashes when filter is Equal or In


{{--
    Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
    See the LICENCE file in the repository root for full licence text.
--}}
@php
    $userCanModerate = priv_check('ForumModerate', $topic->forum)->can();

    if (!isset($stateText)) {
        if (method_exists($state, 'stateText')) {
            $stateText = $state->stateText();
        } elseif (is_bool($state)) {
            $stateText = $state ? '1' : '0';
        } else {
            $stateText = (string) $state;
        }
    }
@endphp
Timeout.set(0, function() {
    $('.js-forum-topic-{{ $type }}--extra[data-topic-id={{ $topic->topic_id }}]').remove();
    $('.js-forum-topic-{{ $type }}--state[data-topic-id={{ $topic->topic_id }}]')
        .attr('data-topic-{{ $type }}', '{{ $stateText }}');
    $('.js-forum-topic-{{ $type }}[data-topic-id={{ $topic->topic_id }}]')
        .replaceWith({!! json_encode(view(
            'forum.topics._'.$type,
            compact('topic', 'state', 'userCanModerate')
        )->render()) !!});

    osu.popup({!! json_encode(trans('forum.topics.'.$type.'.to_'.$stateText.'_done')) !!}, 'success');
});

{{--
    Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
    See the LICENCE file in the repository root for full licence text.
--}}
@php
    $userCanModerate = priv_check('ForumModerate', $topic->forum)->can();

    if (!isset($stateText)) {
        if (is_object($state) && method_exists($state, 'stateText')) {
            $stateText = $state->stateText();
        } elseif (is_bool($state)) {
            $stateText = $state ? '1' : '0';
        } else {
            $stateText = (string) $state;
        }
    }
@endphp
Timeout.set(0, function() {
    $('.js-forum-topic-{{ $type }}--extra[data-topic-id={{ $topic->topic_id }}]').remove();
    $('.js-forum-topic-{{ $type }}--state[data-topic-id={{ $topic->topic_id }}]')
        .attr('data-topic-{{ $type }}', '{{ $stateText }}');
    $('.js-forum-topic-{{ $type }}[data-topic-id={{ $topic->topic_id }}]')
        .replaceWith({!! json_encode(view(
            'forum.topics._'.$type,
            compact('topic', 'state', 'userCanModerate')
        )->render()) !!});

    osu.popup({!! json_encode(trans('forum.topics.'.$type.'.to_'.$stateText.'_done')) !!}, 'success');
});

Fix error when replacing forum button

Fix error when replacing forum button


<?php

final class PhabricatorDaemonLogEvent extends PhabricatorDaemonDAO {

  protected $logID;
  protected $logType;
  protected $message;
  protected $epoch;

  protected function getConfiguration() {
    return array(
      self::CONFIG_TIMESTAMPS => false,
      self::CONFIG_COLUMN_SCHEMA => array(
        'logType' => 'text4',
        'message' => 'text',
      ),
      self::CONFIG_KEY_SCHEMA => array(
        'logID' => array(
          'columns' => array('logID', 'epoch'),
        ),
      ),
    ) + parent::getConfiguration();
  }

}

<?php

final class PhabricatorDaemonLogEvent extends PhabricatorDaemonDAO {

  protected $logID;
  protected $logType;
  protected $message;
  protected $epoch;

  protected function getConfiguration() {
    return array(
      self::CONFIG_TIMESTAMPS => false,
      self::CONFIG_COLUMN_SCHEMA => array(
        'logType' => 'text4',
        'message' => 'text',
      ),
      self::CONFIG_KEY_SCHEMA => array(
        'logID' => array(
          'columns' => array('logID', 'epoch'),
        ),
        'key_epoch' => array(
          'columns' => array('epoch'),
        ),
      ),
    ) + parent::getConfiguration();
  }

}

Add a missing DaemonLogEvent key for garbage collection

Summary: See PHI176. This is issued periodically by the garbage collector. Normally this table is relatively small-ish so this missing key isn't hugely noticeable.

Test Plan:
Ran `./bin/garbage collect --collector daemon.processes --trace` to get the query the GC runs.

Ran ##DELETE FROM `daemon_logevent` WHERE epoch < 1508443504 LIMIT 100## before and after the key, saw a much better query plan afterward:

Before:

```
mysql> explain DELETE FROM `daemon_logevent` WHERE epoch < 1508443504 LIMIT 100;
+----+-------------+-----------------+------+---------------+------+---------+------+-------+-------------+
| id | select_type | table           | type | possible_keys | key  | key_len | ref  | rows  | Extra       |
+----+-------------+-----------------+------+---------------+------+---------+------+-------+-------------+
|  1 | SIMPLE      | daemon_logevent | ALL  | NULL          | NULL | NULL    | NULL | 19325 | Using where |
+----+-------------+-----------------+------+---------------+------+---------+------+-------+-------------+
1 row in set (0.00 sec)
```

After:

```
mysql> explain DELETE FROM `daemon_logevent` WHERE epoch < 1508443504 LIMIT 100;
+----+-------------+-----------------+-------+---------------+-----------+---------+-------+------+-------------+
| id | select_type | table           | type  | possible_keys | key       | key_len | ref   | rows | Extra       |
+----+-------------+-----------------+-------+---------------+-----------+---------+-------+------+-------------+
|  1 | SIMPLE      | daemon_logevent | range | key_epoch     | key_epoch | 4       | const |    1 | Using where |
+----+-------------+-----------------+-------+---------------+-----------+---------+-------+------+-------------+
1 row in set (0.00 sec)
```

Reviewers: amckinley

Reviewed By: amckinley

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


<?php

namespace Neblion\ScrumBundle\Tests\Controller;

use Neblion\ScrumBundle\Tests\WebTestCase;

class TeamControllerTest extends WebTestCase
{
    public function testShow()
    {
        $client = $this->login('admin', 'test');
        $crawler = $client->request('GET', '/team/1/show');
        // Test html template
        // Title of main widget-box
        $this->assertTrue($crawler->filter('html:contains("Team members")')->count() == 1);
        // 5 tr => 5 members for project->id = 1
        $this->assertEquals(5, $crawler->filter('table tbody tr')->count());
    }
}

<?php

namespace Neblion\ScrumBundle\Tests\Controller;

use Neblion\ScrumBundle\Tests\WebTestCase;

class TeamControllerTest extends WebTestCase
{
    public function testShow()
    {
        $client = $this->login('admin', 'test');
        $crawler = $client->request('GET', '/team/1/show');
        // Test html template
        // Title of main widget-box
        $this->assertTrue($crawler->filter('html:contains("Team members")')->count() == 1);
        // 5 tr => 5 members for project->id = 1
        $this->assertEquals(5, $crawler->filter('table#validated-members tbody tr')->count());
    }
}

Fix Team tests with table id

Fix Team tests with table id


<?php

namespace Feedme\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
}

<?php

namespace Feedme\AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

/**
 * Class DefaultController
 * @package Feedme\AppBundle\Controller
 */
class DefaultController extends Controller
{
    /**
     * @Route("/dashboard", name="dashboard")
     */
    public function indexAction()
    {
        echo "dashboard";die;
    }
}

Add new route for Dashboard

Add new route for Dashboard


<?php namespace Felixkiss\UniqueWithValidator;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

class ServiceProvider extends BaseServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->loadTranslationsFrom(
            __DIR__ . '/../../lang',
            'uniquewith-validator'
        );

        $message = $this->app->translator->get('uniquewith-validator::validation.unique_with');
        $this->app->validator->extend('unique_with', Validator::class . '@validateUniqueWith', $message);
        $this->app->validator->replacer('unique_with', function() {
            $translator = $this->app->translator;
            $validator = $this->app->make(Validator::class);
            return call_user_func_array([$validator, 'replaceUniqueWith'], array_merge(func_get_args(), [$translator]));
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {

    }
}

<?php namespace Felixkiss\UniqueWithValidator;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

class ServiceProvider extends BaseServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->loadTranslationsFrom(
            __DIR__ . '/../../lang',
            'uniquewith-validator'
        );

        $message = $this->app->translator->trans('uniquewith-validator::validation.unique_with');
        $this->app->validator->extend('unique_with', Validator::class . '@validateUniqueWith', $message);
        $this->app->validator->replacer('unique_with', function() {
            $translator = $this->app->translator;
            return call_user_func_array([new Validator, 'replaceUniqueWith'], array_merge(func_get_args(), [$translator]));
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {

    }
}

Use `$translator->trans()` instead of `$translator->get()`


<?php

class AchievementMasteryQueryFilter extends EnumSearchQueryFilter {
    protected static $REGIONS = [
        'Tyria' => 'Tyria',
        'Maguuma' => 'Maguuma (Path of Fire)',
        'Desert' => 'Crystal Desert (Heart of Thorns)'
    ];
    protected static $ANY = '*';

    public function __construct($name) {
        parent::__construct($name, [self::$ANY => 'Any mastery'] + self::$REGIONS);
    }

    public function query($query) {
        $value = $this->getValue();

        if($value && array_key_exists($value, self::$REGIONS)) {
            return $query->where('data_en', 'like', '%"type":"Mastery","region":"'. $value.'"%');
        } else if ($value === self::$ANY) {
            return $query->where('data_en', 'like', '%"type":"Mastery","region"%');
        }

        return $query;
    }
}

<?php

class AchievementMasteryQueryFilter extends EnumSearchQueryFilter {
    protected static $REGIONS = [
        'Tyria' => 'Tyria',
        'Maguuma' => 'Maguuma (Path of Fire)',
        'Desert' => 'Crystal Desert (Heart of Thorns)',
        'Tundra' => 'Tundra (Icebrood Saga)'
    ];
    protected static $ANY = '*';

    public function __construct($name) {
        parent::__construct($name, [self::$ANY => 'Any mastery'] + self::$REGIONS);
    }

    public function query($query) {
        $value = $this->getValue();

        if($value && array_key_exists($value, self::$REGIONS)) {
            return $query->where('data_en', 'like', '%"type":"Mastery","region":"'. $value.'"%');
        } else if ($value === self::$ANY) {
            return $query->where('data_en', 'like', '%"type":"Mastery","region"%');
        }

        return $query;
    }
}

Allow filtering for Icebrood Saga mastery points


<?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\VarDumper\Caster;

use Symfony\Component\VarDumper\Cloner\Stub;

/**
 * Casts a caster's Stub.
 *
 * @author Nicolas Grekas <p@tchwork.com>
 */
class StubCaster
{
    public static function castStub(Stub $c, array $a, Stub $stub, $isNested)
    {
        if ($isNested) {
            $stub->type = $c->type;
            $stub->class = $c->class;
            $stub->value = $c->value;
            $stub->handle = $c->handle;
            $stub->cut = $c->cut;

            return array();
        }
    }

    public static function cutInternals($obj, array $a, Stub $stub, $isNested)
    {
        if ($isNested) {
            $stub->cut += count($a);

            return array();
        }

        return $a;
    }
}

<?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\VarDumper\Caster;

use Symfony\Component\VarDumper\Cloner\Stub;

/**
 * Casts a caster's Stub.
 *
 * @author Nicolas Grekas <p@tchwork.com>
 */
class StubCaster
{
    public static function castStub(Stub $c, array $a, Stub $stub, $isNested)
    {
        if ($isNested) {
            $stub->type = $c->type;
            $stub->class = $c->class;
            $stub->value = $c->value;
            $stub->handle = $c->handle;
            $stub->cut = $c->cut;

            $a = array();
        }

        return $a;
    }

    public static function cutInternals($obj, array $a, Stub $stub, $isNested)
    {
        if ($isNested) {
            $stub->cut += count($a);

            return array();
        }

        return $a;
    }
}

Fix dumping of non-nested stubs

[VarDumper] Fix dumping of non-nested stubs


<?php

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

namespace Sylius\Component\Currency\Context;

/**
 * Interface to be implemented by the service providing the currently used
 * currency.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface CurrencyContextInterface
{
    // Key used to store the currency in storage.
    const STORAGE_KEY = '_sylius.currency';

    /**
     * Get the default currency.
     *
     * @return string
     */
    public function getDefaultCurrency();

    /**
     * Get the currently active currency.
     *
     * @return string
     */
    public function getCurrency();

    /**
     * Set the currently active currency.
     *
     * @param string $currency
     */
    public function setCurrency($currency);
}

<?php

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

namespace Sylius\Component\Currency\Context;

/**
 * Interface to be implemented by the service providing the currently used
 * currency.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface CurrencyContextInterface
{
    // Key used to store the currency in storage.
    const STORAGE_KEY = '_sylius_currency';

    /**
     * Get the default currency.
     *
     * @return string
     */
    public function getDefaultCurrency();

    /**
     * Get the currently active currency.
     *
     * @return string
     */
    public function getCurrency();

    /**
     * Set the currently active currency.
     *
     * @param string $currency
     */
    public function setCurrency($currency);
}

Make STORAGE_KEY work when using CookieStorage

Unfortunately PHP will convert **dot**s into underscore when parsing cookie names! So we have to remove dots in our `STORAKE_KEY`s so that is possible to use a CookieStorage.

[The full list of field-name characters that PHP converts to _](http://ca.php.net/manual/en/language.variables.external.php#81080)
[A random blog post](http://harrybailey.com/2009/04/dots-arent-allowed-in-php-cookie-names/)


<?php

require_once('tests/lib/simpletest/autorun.php');
require_once('framework/php/cashmusic.php');

class CashDataTests extends UnitTestCase {

    function testCASHSettings(){
        $data = new CASHSettings();
    }

}
?>

<?php

require_once('tests/lib/simpletest/autorun.php');
require_once('framework/php/cashmusic.php');

class CashDataTests extends UnitTestCase {

    function testCASHSettings(){
        $settings = new CASHSettings();
        $this->assertIsa($settings, 'CASHSettings');
    }

}
?>

Make the CASHSettings test actually assert that we get the correct object type


<?php

    // Trim is important here to avoid some empty lines at the beginning of the copy/paste.
    $xpathExpression = trim($_POST['xpath_expression']);
    $xmlInput = trim($_POST['xml_input']);

    // Also remove all break lines and tabs to allow a correct output indentation.
    $xmlInput = strtr($xmlInput, array("\t" => '', "\n" => '', "\r" => ''));

    // Execute XPath query
    $domDocument = new DOMDocument();
    $domDocument->loadXml($xmlInput);

    $domDocument->formatOutput = true;
    $domDocument->preserveWhiteSpace = true;

    $xpath = new DOMXPath($domDocument);
    $results = $xpath->query($xpathExpression);

    // Highlight matching elements by adding a correct span
    $output = htmlentities($domDocument->saveXML(), ENT_QUOTES, 'utf-8');

    $numberResults = $results->length;
    for($i = 0 ; $i < $numberResults ; $i++) {

        // Retrieve match XML
        $result = $results->item($i);
        $result = htmlentities($result->ownerDocument->saveXML($result), ENT_QUOTES, 'utf-8');

        // Highlight it
        $regex = '#'.preg_quote($result).'#';
        $replacingString = sprintf('%s', $result);
        $output = preg_replace($regex, $replacingString, $output);

    }

    echo $output;

<?php

    // Trim is important here to avoid some empty lines at the beginning of the copy/paste.
    $xpathExpression = trim($_POST['xpath_expression']);
    $xmlInput = trim($_POST['xml_input']);

    // Also remove all break lines and tabs to allow a correct output indentation.
    $xmlInput = strtr($xmlInput, array("\t" => '', "\n" => '', "\r" => ''));

    // And turn xmlns root attribute to ns to be able to parse document
    $xmlInput = str_replace('xmlns=', 'ns=', $xmlInput);

    // Execute XPath query
    $domDocument = new DOMDocument();
    $domDocument->loadXml($xmlInput);

    $domDocument->formatOutput = true;
    $domDocument->preserveWhiteSpace = true;

    $xpath = new DOMXPath($domDocument);
    $results = $xpath->query($xpathExpression);

    // Highlight matching elements by adding a correct span
    $output = htmlentities($domDocument->saveXML(), ENT_QUOTES, 'utf-8');

    $numberResults = $results->length;
    for($i = 0 ; $i < $numberResults ; $i++) {

        // Retrieve match XML
        $result = $results->item($i);
        $result = htmlentities($result->ownerDocument->saveXML($result), ENT_QUOTES, 'utf-8');

        // Highlight it
        $regex = '#'.preg_quote($result).'#';
        $replacingString = sprintf('%s', $result);
        $output = preg_replace($regex, $replacingString, $output);

    }

    echo $output;

Enable querying even if a xmlns attribute is present


<?php namespace App\Http\Controllers;

use Topic;
use Discussion;
use Illuminate\Http\Request;

class TopicsController extends Controller
{
	public function __construct()
	{
		parent::__construct();
	}
		if ($topic->exists) {
			$discussions = $topic->discussions()->latest()->get();
		} else {
			$discussions = Discussion::latest()->get();
		}

		return view('pages.discussions.index', compact('discussions'));
	}
}

<?php namespace App\Http\Controllers;

use Topic;
use Discussion;
use Illuminate\Http\Request;
use App\Filters\DiscussionFilters;

class TopicsController extends Controller
{
	public function __construct()
	{
		parent::__construct();
	}

	public function discussions(Topic $topic, DiscussionFilters $filters)
	{
		$discussions = Discussion::latest()->filter($filters);

		if ($topic->exists) {
			$discussions->where('topic_id', $topic->id);
		}

		$discussions = $discussions->get();

		return view('pages.discussions.index', compact('discussions'));
	}
}

Add filters to topics controller

Add filters to topics controller


<?php

namespace OpenOrchestra\BaseApi\Exceptions\HttpException;

/**
 * Class ClientAccessDeniedHttpException
 */
class ClientAccessDeniedHttpException extends ApiException
{
    const DEVELOPER_MESSAGE  = 'client.access_denied';
    const HUMAN_MESSAGE      = 'api.exception.client_access_denied';
    const STATUS_CODE        = '404';
    const ERROR_CODE         = 'x';
    const ERROR_SUPPORT      = 'global_platform_main_contact_contact';
    const REDIRECTION        = 'logout';

    /**
     * Constructor
     */
    public function __construct()
    {
        $developerMessage   = self::DEVELOPER_MESSAGE;
        $humanMessage       = self::HUMAN_MESSAGE;
        $statusCode         = self::STATUS_CODE;
        $errorCode          = self::ERROR_CODE;
        $errorSupport       = self::ERROR_SUPPORT;
        $redirection        = self::REDIRECTION;

        parent::__construct($statusCode, $errorCode, $errorSupport, $developerMessage, $humanMessage, $redirection);
    }
}

<?php

namespace OpenOrchestra\BaseApi\Exceptions\HttpException;

/**
 * Class ClientAccessDeniedHttpException
 */
class ClientAccessDeniedHttpException extends ApiException
{
    const DEVELOPER_MESSAGE  = 'client.access_denied';
    const HUMAN_MESSAGE      = 'api.exception.client_access_denied';
    const STATUS_CODE        = '401';
    const ERROR_CODE         = 'x';
    const ERROR_SUPPORT      = 'global_platform_main_contact_contact';
    const REDIRECTION        = 'logout';

    /**
     * Constructor
     */
    public function __construct()
    {
        $developerMessage   = self::DEVELOPER_MESSAGE;
        $humanMessage       = self::HUMAN_MESSAGE;
        $statusCode         = self::STATUS_CODE;
        $errorCode          = self::ERROR_CODE;
        $errorSupport       = self::ERROR_SUPPORT;
        $redirection        = self::REDIRECTION;

        parent::__construct($statusCode, $errorCode, $errorSupport, $developerMessage, $humanMessage, $redirection);
    }
}

Change access denied http code to 401

Change access denied http code to 401


<?php

require_once(__DIR__ . '/../../opensrs/openSRS_loader.php');

class openSRS_OpsTest extends PHPUnit_Framework_TestCase
{
    /**
     * Should convert specials chars, & encode in utf8
     *
     * @return void
     */
    public function testQuoteXMLChars()
    {
        $ops = new openSRS_ops;
        $data = 'This is my & < > \' " string';
        $result = $ops->_quoteXMLChars($data);

        /// chars should be converted
        $this->assertEquals($result, 'This is my & < > ' " string');

        // should be utf8
        $this->assertTrue(mb_check_encoding($result, 'UTF-8'));
    }
}

<?php

require_once(__DIR__ . '/../../opensrs/openSRS_loader.php');

class openSRS_OpsTest extends PHPUnit_Framework_TestCase
{
    /**
     * Should convert specials chars, & encode in utf8
     *
     * @return void
     */
    public function testQuoteXMLChars()
    {
        $ops = new openSRS_ops;
        $data = 'This is my & < > \' " string';
        $result = $ops->_quoteXMLChars($data);

        /// chars should be converted
        $this->assertEquals($result, 'This is my & < > ' " string');

        // should be utf8
        $this->assertTrue(mb_check_encoding($result, 'UTF-8'));
    }

    /**
     * Should return true for associative, and false for plain
     *
     * @return void
     */
    public function testIsAssoc()
    {
        $ops = new openSRS_ops;
        $no = array(1, 2, 3, 4);
        $yes = array('this' => 'is', 'associative');

        $this->assertfalse($ops->_is_assoc($no));
        $this->assertTrue($ops->_is_assoc($yes));
    }
}

Add test for Ops is associative

Add test for Ops is associative


<?php

namespace Tests\CryptoSystem;

use Rosio\EncryptedCookie\CryptoSystem\AES_SHA1;

class AES_SHA1Test extends \PHPUnit_Framework_TestCase
{
	protected $cryptoSystem;

	function setUp ()
	{
		$this->cryptoSystem = new AES_SHA1('symkey', 'hmackey');
	}

	public function testEncryptDecrypt ()
	{
		$data = 'Some data. Special characters: ' . chr(1) . chr(2) . chr(3) . '.';

		$encData = $this->cryptoSystem->encrypt($data);
		$decData = $this->cryptoSystem->decrypt($data);

		$this->assertEquals($data, $decData);
	}
}

<?php

namespace Tests\CryptoSystem;

use Rosio\EncryptedCookie\CryptoSystem\AES_SHA1;

class AES_SHA1Test extends \PHPUnit_Framework_TestCase
{
	protected $cryptoSystem;

	function setUp ()
	{
		$this->cryptoSystem = new AES_SHA1('symkey', 'hmackey');
	}

	public function testEncryptDecrypt ()
	{
		$data = 'Some data. Special characters: ' . chr(1) . chr(2) . chr(3) . '.';

		$encData = $this->cryptoSystem->encrypt($data);
		$decData = $this->cryptoSystem->decrypt($encData);

		$this->assertEquals($data, $decData);
	}
}

Fix bug in AES_SHA1 test

Fix bug in AES_SHA1 test


<?php
namespace App\Http\Middleware;
use Closure;
class PrivateCORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (env('APP_ENV', 'prod') === "dev") {
            return $next($request);
        }

        if(in_array($_SERVER['REQUEST_METHOD'], ["GET","PUT","DELETE","POST"])) {
            if (!isset($_SERVER['HTTP_ORIGIN']) || !preg_match("~^(http|https)://[^/]+\.vatusa\.net~i", $_SERVER['HTTP_ORIGIN'])) {
                abort(400, "Malformed origin " . $_SERVER['HTTP_ORIGIN']);
            }
        }

        return $next($request)
            ->header("Access-Control-Allow-Credentials", "true")
            ->header("Access-Control-Allow-Headers", "x-csrf-token")
            ->header("Access-Control-Allow-Methods", $_SERVER['REQUEST_METHOD'])
            ->header("Access-Control-Allow-Origin", $_SERVER['HTTP_ORIGIN']);
    }
}

<?php

namespace App\Http\Middleware;

use Closure;

class PrivateCORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (env('APP_ENV', 'prod') === "prod") {
            if (in_array(
                $_SERVER['REQUEST_METHOD'], ["GET", "PUT", "DELETE", "POST"]
            )
            ) {
                if (!isset($_SERVER['HTTP_ORIGIN'])
                    || !preg_match(
                        "~^(http|https)://[^/]+\.vatusa\.net~i",
                        $_SERVER['HTTP_ORIGIN']
                    )
                ) {
                    abort(400, "Malformed origin " . $_SERVER['HTTP_ORIGIN']);
                }
            }
        } else {
            if (in_array(
                $_SERVER['REQUEST_METHOD'], ["GET", "PUT", "DELETE", "POST"]
            )
            ) {
                if (!isset($_SERVER['HTTP_ORIGIN'])
                    || !preg_match(
                        "~^(http|https)://[^/]+\.vatusa\.net~i",
                        $_SERVER['HTTP_ORIGIN']
                    )
                    || !preg_match(
                        "~^(http|https)://[^/]+\.vatusa\.devel~i",
                        $_SERVER['HTTP_ORIGIN']

                    )
                ) {
                    abort(400, "Malformed origin " . $_SERVER['HTTP_ORIGIN']);
                }
            }
        }

        return $next($request)
            ->header("Access-Control-Allow-Credentials", "true")
            ->header("Access-Control-Allow-Headers", "x-csrf-token")
            ->header("Access-Control-Allow-Methods", $_SERVER['REQUEST_METHOD'])
            ->header("Access-Control-Allow-Origin", $_SERVER['HTTP_ORIGIN']);
    }
}

Add devel TLD to permitted origins on private middleware


<?php

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

class CreateApiLogTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('api_log', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->nullable()->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->integer('api_key_id')->nullable();
            $table->foreign('api_key_id')->references('id')->on('api_keys');
            $table->text('images');
            $table->timestamps();
        });
    }

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

<?php

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

class CreateApiLogTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('api_log', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->nullable()->unsigned();
            $table->foreign('user_id')->references('id')->on('users');

            $table->integer('api_key_id')->nullable();

            $table->text('images');
            $table->timestamps();
        });
    }

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

Remove a foreign key constraint from a migration


<?php

namespace HotfixBundle\Job;

/**
 * This hotfix allows to see the daemon status with the overriden job queue command.
 */
class Daemon extends \Oro\Bundle\CronBundle\Job\Daemon
{
    /**
     * {@inheritdoc}
     */
    public function getPid()
    {
        if (!$this->pid) {
            $this->pid = $this->findProcessPid(
                sprintf('%sconsole hotfix:jms-job-queue:run', $this->rootDir . DIRECTORY_SEPARATOR)
            );
        }

        return $this->pid;
    }
}

<?php

namespace HotfixBundle\Job;

/**
 * This hotfix allows to see the daemon status with the overriden job queue command.
 */
class Daemon extends \Oro\Bundle\CronBundle\Job\Daemon
{
    /**
     * {@inheritdoc}
     */
    public function getPid()
    {
        if (!$this->pid) {
            $this->pid = $this->findProcessPid(
                sprintf('%sconsole hotfix:jms-job-queue:run', realpath($this->rootDir).DIRECTORY_SEPARATOR)
            );
        }

        return $this->pid;
    }
}

Add realpath calculation to daemon pid detection command


<?php

if ( ! class_exists( 'FAQ_Taxonomy_Type' ) ) {
	require_once __DIR__ . '/faq-Taxonomy-type.php';
}

class FAQ_Extra_Taxonomy_Type extends FAQ_Taxonomy_Type {

	/**
	 * Define our Taxonomy Type meta data.
	 *
	 * @return array
	 */
	public function meta() {
		return [
			'name'         => 'FAQ Extra taxonomy',
			'description'  => 'This is a faq extra taxonomy',
			'template'     => 'pages/faq-extra-taxonomy.php'
		];
	}

	/**
	 * Define our properties.
	 */
	public function register() {
		$this->box( 'Content', [
			papi_property( [
				'description' => 'FAQ 2',
				'post_type'   => 'faq',
				'type'        => 'string',
				'title'       => 'Name'
			] )
		] );
	}
}

<?php

if ( ! class_exists( 'FAQ_Taxonomy_Type' ) ) {
	require_once __DIR__ . '/faq-taxonomy-type.php';
}

class FAQ_Extra_Taxonomy_Type extends FAQ_Taxonomy_Type {

	/**
	 * Define our Taxonomy Type meta data.
	 *
	 * @return array
	 */
	public function meta() {
		return [
			'name'         => 'FAQ Extra taxonomy',
			'description'  => 'This is a faq extra taxonomy',
			'template'     => 'pages/faq-extra-taxonomy.php'
		];
	}

	/**
	 * Define our properties.
	 */
	public function register() {
		$this->box( 'Content', [
			papi_property( [
				'description' => 'FAQ 2',
				'post_type'   => 'faq',
				'type'        => 'string',
				'title'       => 'Name'
			] )
		] );
	}
}

Fix require once issue in faq taxonomy type


<?php
/**
 * This is the output for an event listing in icalendar format.
 * @package UNL_UCBCN_Frontend
 */
foreach ($this->events as $e) {
	$eventdatetime = $e->getLink('id','eventdatetime','event_id');
	$out = array();
	$out[] = 'BEGIN:VEVENT';
	//$out[] = 'SEQUENCE:5';
	if (isset($eventdatetime->starttime)) {
        $out[] = 'DTSTART;TZID=US/Central:'.date('Ymd\THis',strtotime($eventdatetime->starttime));
    }
	$out[] = 'DTSTAMP:'.date('Ymd\THis',strtotime($e->datecreated));
	$out[] = 'SUMMARY:'.strip_tags($e->title);
	$out[] = 'DESCRIPTION:'.strip_tags($e->description);
	//$out[] = 'URL:http://abc.com/pub/calendars/jsmith/mytime.ics';
	//$out[] = 'UID:EC9439B1-FF65-11D6-9973-003065F99D04';
	if (isset($eventdatetime->endtime)) {
    	$out[] = 'DTEND;TZID=US/Central:'.date('Ymd\THis',strtotime($eventdatetime->endtime));
    }
	$out[] = 'END:VEVENT';
	echo implode("\n",$out)."\n";
} ?>

<?php
/**
 * This is the output for an event listing in icalendar format.
 * @package UNL_UCBCN_Frontend
 */
foreach ($this->events as $e) {
	$out = array();
	$out[] = 'BEGIN:VEVENT';
	//$out[] = 'SEQUENCE:5';
	if (isset($e->eventdatetime->starttime)) {
        $out[] = 'DTSTART;TZID=US/Central:'.date('Ymd\THis',strtotime($e->eventdatetime->starttime));
    }
	$out[] = 'DTSTAMP:'.date('Ymd\THis',strtotime($e->event->datecreated));
	$out[] = 'SUMMARY:'.strip_tags($e->event->title);
	$out[] = 'DESCRIPTION:'.strip_tags($e->event->description);
	//$out[] = 'URL:http://abc.com/pub/calendars/jsmith/mytime.ics';
	//$out[] = 'UID:EC9439B1-FF65-11D6-9973-003065F99D04';
	if (isset($eventdatetime->endtime)) {
    	$out[] = 'DTEND;TZID=US/Central:'.date('Ymd\THis',strtotime($e->eventdatetime->endtime));
    }
	$out[] = 'END:VEVENT';
	echo implode("\n",$out)."\n";
} ?>

Switch icalendar event listing frontend to use event instances instead of events.


<?php
/**
 *
 * @author newloki
 */
namespace Tests\Language\Languages\Indo\German;
use Language\Languages\Indo\English\EnglishAbstract,
    Language\Languages\Indo\IndoAbstract,
    Language\Languages\Indo\English\UK\Uk;

require_once realpath(LIBRARY_PATH . '/Language/Languages/Indo/English/UK/Uk.php');
require_once realpath(LIBRARY_PATH . '/Language/Languages/Indo/IndoAbstract.php');
class UkTest extends \PHPUnit_Framework_TestCase
{
    protected $_language;

    protected $_name = 'english_uk';

    public function setUp()
    {
        $this->_language = new Uk();
    }

    public function testShouldReturnRightName()
    {
        $this->assertEquals($this->_name, $this->_language->getName());
    }

    public function testIfYIsAVocalByDefault()
    {
        $mappingVC = $this->_language->getCVMapping();
        $this->assertEquals($mappingVC['y'], IndoAbstract::VOCAL);
        $this->assertNotEquals($mappingVC['y'], IndoAbstract::CONSONANT);
    }

}

<?php
/**
 *
 * @author newloki
 */
namespace Tests\Language\Languages\Indo\German;
use Language\Languages\Indo\English\EnglishAbstract,
    Language\Languages\Indo\IndoAbstract,
    Language\Languages\Indo\English\UK\Uk;

require_once realpath(LIBRARY_PATH . '/Language/Languages/Indo/English/UK/Uk.php');
require_once realpath(LIBRARY_PATH . '/Language/Languages/Indo/IndoAbstract.php');
class UkTest extends \PHPUnit_Framework_TestCase
{
    protected $_language;

    protected $_name = 'english_uk';

    public function setUp()
    {
        $this->_language = new Uk();
    }

    public function testShouldReturnRightName()
    {
        $this->assertEquals($this->_name, $this->_language->getName());
    }
}

Add move test that in english Y is an vocal to english abstract test


<?php

namespace Oro\Bundle\DashboardBundle\Migrations\Schema\v1_7;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\OrderedMigrationInterface;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class OroDashboardBundle implements Migration
{
    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        /**
         * After v1_3 migration
         * Undefined table: 7 ERROR:  relation "oro_dashboard_active_id_seq" does not exist
         */
        $queries->addPostQuery(
            'ALTER SEQUENCE IF EXISTS oro_dashboard_active_copy_id_seq RENAME TO oro_dashboard_active_id_seq;'
        );
    }
}

<?php

namespace Oro\Bundle\DashboardBundle\Migrations\Schema\v1_7;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Extension\DatabasePlatformAwareInterface;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class OroDashboardBundle implements Migration, DatabasePlatformAwareInterface
{
    /**
     * @var AbstractPlatform
     */
    protected $platform;

    /**
     * {@inheritdoc}
     */
    public function setDatabasePlatform(AbstractPlatform $platform)
    {
        $this->platform = $platform;
    }

    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        /**
         * After v1_3 migration
         * Undefined table: 7 ERROR:  relation "oro_dashboard_active_id_seq" does not exist
         */
        if ($this->platform->supportsSequences()) {
            $queries->addPostQuery(
                'ALTER SEQUENCE IF EXISTS oro_dashboard_active_copy_id_seq RENAME TO oro_dashboard_active_id_seq;'
            );
        }
    }
}

BB-1505: Check performance
- run if sequences supported


<?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\Bundle\DebugBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Registers the file link format for the {@link \Symfony\Component\HttpKernel\DataCollector\DumpDataCollector\DumpDataCollector}.
 *
 * @author Christian Flothmann <christian.flothmann@xabbuh.de>
 */
class DumpDataCollectorPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('data_collector.dump')) {
            return;
        }

        $definition = $container->getDefinition('data_collector.dump');

        if ($container->hasParameter('templating.helper.code.file_link_format')) {
            $definition->replaceArgument(1, $container->getParameter('templating.helper.code.file_link_format'));
        }
    }
}

<?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\Bundle\DebugBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Registers the file link format for the {@link \Symfony\Component\HttpKernel\DataCollector\DumpDataCollector}.
 *
 * @author Christian Flothmann <christian.flothmann@xabbuh.de>
 */
class DumpDataCollectorPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('data_collector.dump')) {
            return;
        }

        $definition = $container->getDefinition('data_collector.dump');

        if ($container->hasParameter('templating.helper.code.file_link_format')) {
            $definition->replaceArgument(1, $container->getParameter('templating.helper.code.file_link_format'));
        }
    }
}

Fix deprecated use of DebugClassLoader

[Debug] Fix deprecated use of DebugClassLoader


<?php

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class DateTimeValidator extends ConstraintValidator
{
    const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/';

    public function isValid($value, Constraint $constraint)
    {
        if ($value === null) {
            return true;
        }

        if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
            throw new UnexpectedTypeException($value, 'string');
        }

        $value = (string)$value;

        if (!preg_match(self::PATTERN, $value, $matches)) {
            $this->setMessage($constraint->message, array('value' => $value));

            return false;
        }

        return checkdate($matches[2], $matches[3], $matches[1]);
    }
}

<?php

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class DateTimeValidator extends ConstraintValidator
{
    const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/';

    public function isValid($value, Constraint $constraint)
    {
        if ($value === null) {
            return true;
        }

        if ($value instanceof \DateTime) {
            return true;
        }

        if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
            throw new UnexpectedTypeException($value, 'string');
        }

        $value = (string)$value;

        if (!preg_match(self::PATTERN, $value, $matches)) {
            $this->setMessage($constraint->message, array('value' => $value));

            return false;
        }

        return checkdate($matches[2], $matches[3], $matches[1]);
    }
}

[Validator] Allow DateTime objects as valid DateTimes


<?php

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

class CreateLikeTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

<?php

/*
 * This file is part of santakani.com
 *
 * (c) Guo Yunhe <guoyunhebrave@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

/**
 * CreateLikeTable
 *
 * Database migration to create "like" and "like_count" table.
 *
 * @author Guo Yunhe <guoyunhebrave@gmail.com>
 * @see https://github.com/santakani/santakani.com/wiki/Like
 */
class CreateLikeTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('like', function (Blueprint $table) {
            $table->increments('id');

            $table->string('likeable_type');
            $table->integer('likeable_id')->unsigned();
            $table->integer('user_id')->unsigned();

            $table->timestamps();

            $table->unique(['likeable_type', 'likeable_id', 'user_id']);

            $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
        });

        Schema::create('like_count', function (Blueprint $table) {
            $table->increments('id');

            $table->string('likeable_type');
            $table->integer('likeable_id')->unsigned();
            $table->integer('count')->unsigned()->default(0);

            $table->timestamps();

            $table->unique(['likeable_type', 'likeable_id']);
        });
    }

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

        Schema::drop('like');
    }
}

Create like and like_count tables.

Create like and like_count tables.


<?php

namespace Milax\Mconsole\Providers;

use Illuminate\Support\ServiceProvider;

class MconsoleServiceProvider extends ServiceProvider
{
	public function register()
	{
		$this->app->bind('mconsole', function ($app) {
			return new Mconsole;
		});
	}

	public function boot()
	{
		require __DIR__ . '/../Http/routes.php';

		$this->loadViewsFrom(__DIR__ . '/../../views', 'mconsole');
		$this->publishes([
			__DIR__ . '/migrations/2015_09_28_140312_modify_users_table_add_admin_column.php' => base_path('database/migrations/2015_09_28_140312_modify_users_table_add_admin_column.php'),
		]);
	}
}

<?php

namespace Milax\Mconsole\Providers;

use Illuminate\Support\ServiceProvider;

class MconsoleServiceProvider extends ServiceProvider
{
	public function register()
	{
		$this->app->bind('mconsole', function ($app) {
			return new Mconsole;
		});
	}

	public function boot()
	{
		require __DIR__ . '/../Http/routes.php';

		$this->loadViewsFrom(__DIR__ . '/../../views', 'mconsole');
		$this->publishes([
			__DIR__ . '/migrations/2015_09_28_140312_modify_users_table_add_admin_column.php' => base_path('database/migrations/2015_09_28_140312_modify_users_table_add_admin_column.php'),
		], 'migrations');
	}
}

Tag for migrations publish array.

Tag for migrations publish array.


<?php

final class PhabricatorQueryIterator extends PhutilBufferedIterator {

  private $query;
  private $pager;

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

  protected function didRewind() {
    $this->pager = new AphrontCursorPagerView();
  }

  public function key() {
    return $this->current()->getID();
  }

  protected function loadPage() {
    if (!$this->pager) {
      return array();
    }

    $pager = clone $this->pager;
    $query = clone $this->query;

    $results = $query->executeWithCursorPager($pager);

    // If we got less than a full page of results, this was the last set of
    // results. Throw away the pager so we end iteration.
    if (count($results) < $pager->getPageSize()) {
      $this->pager = null;
    } else {
      $this->pager->setAfterID($pager->getNextPageID());
    }

    return $results;
  }

}

<?php

final class PhabricatorQueryIterator extends PhutilBufferedIterator {

  private $query;
  private $pager;

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

  protected function didRewind() {
    $this->pager = new AphrontCursorPagerView();
  }

  public function key() {
    return $this->current()->getID();
  }

  protected function loadPage() {
    if (!$this->pager) {
      return array();
    }

    $pager = clone $this->pager;
    $query = clone $this->query;

    $results = $query->executeWithCursorPager($pager);

    // If we got less than a full page of results, this was the last set of
    // results. Throw away the pager so we end iteration.
    if (!$pager->getHasMoreResults()) {
      $this->pager = null;
    } else {
      $this->pager->setAfterID($pager->getNextPageID());
    }

    return $results;
  }

}

Fix loop in QueryIterator when row count is an exact multiple of page size

Summary: Ref T13152. The pager does a bit of magic here and doesn't populate `nextPageID` when it knows it got an exact final page. The logic misfired in this case and sent us back to the start.

Test Plan:
  - Set page size to 1 to guarantee rows were an exact multiple of page size.
  - Ran `rebuild-identities` (I no-op'd the actual logic to make it faster).
  - Before: looped forever.
  - After: clean exit after processing everything.

Reviewers: amckinley

Reviewed By: amckinley

Maniphest Tasks: T13152

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


<?php

namespace Tests\AppBundle\API\Listing;

use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;

class TraitsTest extends WebserviceTestCase
{

    public function testExecute()
    {
        $default_db = $this->default_db;
        $service = $this->webservice->factory('listing', 'traits');
        $results = $service->execute(
            new ParameterBag(array('dbversion' => $default_db, 'search' => '')),
            null
        );
        $expected = array(
            array(
                "name" => "PlantHabit",
                "trait_type_id" => 1,
                "frequency" => 48916
            )
        );
        $this->assertEquals($expected, $results, 'Search without term and limit, result should be a list of all traits');

        $results = $service->execute(
            new ParameterBag(array('dbversion' => $default_db, 'search' => 'SomethingThatWillNeverBeATraitType')),
            null
        );
        $expected = array();
        $this->assertEquals($expected, $results, 'Search term does not hit, result should be an empty array');
    }
}

<?php

namespace Tests\AppBundle\API\Listing;

use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;

class TraitsTest extends WebserviceTestCase
{

    public function testExecute()
    {
        $default_db = $this->default_db;
        $service = $this->webservice->factory('listing', 'traits');
        $results = $service->execute(
            new ParameterBag(array('dbversion' => $default_db, 'search' => '')),
            null
        );
        $expected = array(
            array(
                "name" => "Plant Habit",
                "trait_type_id" => 1,
                "frequency" => 48842
            )
        );
        $this->assertEquals($expected, $results, 'Search without term and limit, result should be a list of all traits');

        $results = $service->execute(
            new ParameterBag(array('dbversion' => $default_db, 'search' => 'SomethingThatWillNeverBeATraitType')),
            null
        );
        $expected = array();
        $this->assertEquals($expected, $results, 'Search term does not hit, result should be an empty array');
    }
}

Fix expectation for number of traits

Fix expectation for number of traits


<?php

namespace Knp\Bundle\GaufretteBundle\DependencyInjection\Factory;

use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\DefinitionDecorator;

/**
 * Ftp Adapter Factory
 */
class FtpAdapterFactory implements AdapterFactoryInterface
{
    /**
     * {@inheritDoc}
     */
    function create(ContainerBuilder $container, $id, array $config)
    {
        $container
            ->setDefinition($id, new DefinitionDecorator('knp_gaufrette.adapter.ftp'))
            ->addArgument($config['directory'])
            ->addArgument($config['host'])
            ->addArgument($config)
        ;
    }

    /**
     * {@inheritDoc}
     */
    function getKey()
    {
        return 'ftp';
    }

    /**
     * {@inheritDoc}
     */
    function addConfiguration(NodeDefinition $builder)
    {
        $builder
            ->children()
                ->scalarNode('directory')->isRequired()->end()
                ->scalarNode('host')->isRequired()->end()
                ->scalarNode('port')->defaultValue(21)->end()
                ->scalarNode('username')->defaultNull()->end()
                ->scalarNode('password')->defaultNull()->end()
                ->booleanNode('passive')->defaultFalse()->end()
                ->booleanNode('create')->defaultFalse()->end()
                ->scalarNode('mode')
                    ->defaultValue(defined('FTP_ASCII') ? FTP_ASCII : null)
                    ->beforeNormalization()
                    ->ifString()
                    ->then(function($v) { return constant($v); })
                ->end()
            ->end()
        ;
    }
}

<?php

namespace Knp\Bundle\GaufretteBundle\DependencyInjection\Factory;

use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\DefinitionDecorator;

/**
 * Ftp Adapter Factory
 */
class FtpAdapterFactory implements AdapterFactoryInterface
{
    /**
     * {@inheritDoc}
     */
    function create(ContainerBuilder $container, $id, array $config)
    {
        $container
            ->setDefinition($id, new DefinitionDecorator('knp_gaufrette.adapter.ftp'))
            ->addArgument($config['directory'])
            ->addArgument($config['host'])
            ->addArgument($config)
        ;
    }

    /**
     * {@inheritDoc}
     */
    function getKey()
    {
        return 'ftp';
    }

    /**
     * {@inheritDoc}
     */
    function addConfiguration(NodeDefinition $builder)
    {
        $builder
            ->children()
                ->scalarNode('directory')->isRequired()->end()
                ->scalarNode('host')->isRequired()->end()
                ->scalarNode('port')->defaultValue(21)->end()
                ->scalarNode('username')->defaultNull()->end()
                ->scalarNode('password')->defaultNull()->end()
                ->booleanNode('passive')->defaultFalse()->end()
                ->booleanNode('create')->defaultFalse()->end()
                ->scalarNode('mode')
                    ->defaultValue(defined('FTP_ASCII') ? FTP_ASCII : null)
                    ->beforeNormalization()
                    ->ifString()
                    ->then(function($v) { return constant($v); })
                ->booleanNode('ssl')->defaultFalse()->end()
                ->end()
            ->end()
        ;
    }
}

Add SSL option to work with modified Gaufrette that use SSL/TSL FTP


<?php

/*
 * (c) Jeroen van den Enden <info@endroid.nl>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Endroid\Bundle\QrCodeBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

use Endroid\QrCode\QrCode;

/**
 * QR code controller.
 */
class QrCodeController extends Controller
{
    /**
     *
     * @Route("/{size}/{text}.{extension}", name="endroid_qrcode", requirements={"text"="[\w\W]+", "extension"="jpg|png|gif"})
     *
     */
    public function generateAction($text, $extension, $size)
    {
        $qrCode = new QrCode();
        $qrCode->setSize($size);
        $qrCode->setText($text);
        $qrCode = $qrCode->get($extension);

        $mime_type = 'image/'.$extension;
        if ($extension == 'jpg') {
            $mime_type = 'image/jpeg';
        }

        return new Response($qrCode, 200, array('Content-Type' => $mime_type));
    }
}

<?php

/*
 * (c) Jeroen van den Enden <info@endroid.nl>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Endroid\Bundle\QrCodeBundle\Controller;

use Endroid\QrCode\QrCode;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

/**
 * QR code controller.
 */
class QrCodeController extends Controller
{
    /**
     *
     * @Route("/{text}.{extension}", name="endroid_qrcode", requirements={"text"="[\w\W]+", "extension"="jpg|png|gif"})
     *
     */
    public function generateAction(Request $request, $text, $extension)
    {
        $qrCode = new QrCode();
        if ($size = $request->get('size')) {
            $qrCode->setSize($size);
        }
        $qrCode->setText($text);
        $qrCode = $qrCode->get($extension);

        $mime_type = 'image/'.$extension;
        if ($extension == 'jpg') {
            $mime_type = 'image/jpeg';
        }

        return new Response($qrCode, 200, array('Content-Type' => $mime_type));
    }
}

Move size parameter back to query string


function remove_empty_title_attributes($attr) {
  if($attr['title'] == '') {
    unset($attr['title']);
  }
  return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'remove_empty_title_attributes');

function remove_empty_title_attributes($attr) {
  if(!strlen(trim($attr['title'])) {
    unset($attr['title']);
  }
  return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'remove_empty_title_attributes');

Improve checking for empty title attributes


<?php
/**
 * Tlumx Framework (https://framework.tlumx.xyz/)
 *
 * @author    Yaroslav Kharitonchuk <yarik.proger@gmail.com>
 * @link      https://github.com/tlumx/framework
 * @copyright Copyright (c) 2016-2017 Yaroslav Kharitonchuk
 * @license   https://framework.tlumx.xyz/license  (MIT License)
 */
namespace Tlumx\Db\Exception;

class DbException extends \Exception
{
}

Add newline at end of file.

Add newline at end of file.


<?php

namespace ParserReflection\Locator;

use Composer\Autoload\ClassLoader;
use ParserReflection\LocatorInterface;

class ComposerLocator implements LocatorInterface
{
    /**
     * @var ClassLoader
     */
    private $loader;

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

    /**
     * Returns a path to the file for given class name
     *
     * @param string $className Name of the class
     *
     * @return string|false Path to the file with given class or false if not found
     */
    public function locateClass($className)
    {
        return $this->loader->findFile($className);
    }
}

<?php

namespace ParserReflection\Locator;

use Composer\Autoload\ClassLoader;
use ParserReflection\LocatorInterface;
use ParserReflection\ReflectionException;

class ComposerLocator implements LocatorInterface
{
    /**
     * @var ClassLoader
     */
    private $loader;

    public function __construct(ClassLoader $loader = null)
    {
        if (!$loader) {
            $loaders = spl_autoload_functions();
            foreach ($loaders as $loader) {
                if (is_array($loader) && $loader[0] instanceof ClassLoader) {
                    $loader = $loader[0];
                }
            }
            if (!$loader) {
                throw new ReflectionException("Can not found a correct composer loader");
            }
        }
        $this->loader = $loader;
    }

    /**
     * Returns a path to the file for given class name
     *
     * @param string $className Name of the class
     *
     * @return string|false Path to the file with given class or false if not found
     */
    public function locateClass($className)
    {
        return $this->loader->findFile($className);
    }
}

Add auto-detection of composer loader from spl stack


<?php

namespace Uptime\Runtime\Windows;

use Uptime\Runtime\RuntimeInterface;

class Boottime implements RuntimeInterface
{

    public function read($command = 'wmic os get lastbootuptime')
    {
        return trim( explode( "\n", shell_exec($command) )[1] );
    }
}

<?php

namespace Uptime\Runtime\Windows;

use Uptime\Runtime\RuntimeInterface;

class Boottime implements RuntimeInterface
{

    public function read($command = 'wmic os get lastbootuptime')
    {
        $dateTime = \DateTime::createFromFormat(
            'YmdHis.uO',
            trim( explode( "\n", shell_exec($command) )[1] )
        );
        return $dateTime->getTimestamp();
    }
}

Fix for windows boottime to convert returned string format to a timestamp


<?php

declare(strict_types=1);

namespace League\Flysystem;

use LogicException;

class UnableToMountFilesystem extends LogicException implements FilesystemException
{
    /**
     * @param mixed $key
     */
    public static function becauseTheKeyIsNotValid($key): UnableToMountFilesystem
    {
        return new UnableToMountFilesystem(
            'Unable to mount filesystem, key was invalid. String expected, received: ' . gettype($key)
        );
    }

    /**
     * @param mixed $filesystem
     */
    public static function becauseTheFilesystemWasNotValid($filesystem): UnableToMountFilesystem
    {
        return new UnableToMountFilesystem(
            'Unable to mount filesystem, key was invalid. Instance of ' . FilesystemOperator::class . ' expected, received: ' . gettype(
                $filesystem
            )
        );
    }
}

<?php

declare(strict_types=1);

namespace League\Flysystem;

use LogicException;

class UnableToMountFilesystem extends LogicException implements FilesystemException
{
    /**
     * @param mixed $key
     */
    public static function becauseTheKeyIsNotValid($key): UnableToMountFilesystem
    {
        return new UnableToMountFilesystem(
            'Unable to mount filesystem, key was invalid. String expected, received: ' . gettype($key)
        );
    }

    /**
     * @param mixed $filesystem
     */
    public static function becauseTheFilesystemWasNotValid($filesystem): UnableToMountFilesystem
    {
        $received = is_object($filesystem) ? get_class($filesystem) : gettype($filesystem);

        return new UnableToMountFilesystem(
            'Unable to mount filesystem, filesystem was invalid. Instance of ' . FilesystemOperator::class . ' expected, received: ' . $received
        );
    }
}

Add information about invalid filesystem


<?php

function phutil_get_library_root($library = null) {
  if (!$library) {
    $library = phutil_get_current_library_name();
  }
  $bootloader = PhutilBootloader::getInstance();
  return $bootloader->getLibraryRoot($library);
}

function phutil_get_library_root_for_path($path) {
  foreach (Filesystem::walkToRoot($path) as $dir) {
    if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) {
      return $dir;
    }
  }
  return null;
}

function phutil_get_library_name_for_root($path) {
  $path = rtrim(Filesystem::resolvePath($path), '/');

  $bootloader = PhutilBootloader::getInstance();
  $libraries = $bootloader->getAllLibraries();
  foreach ($libraries as $library) {
    $root = $bootloader->getLibraryRoot($library);
    if (rtrim(Filesystem::resolvePath($root), '/') == $path) {
      return $library;
    }
  }

  return null;
}

function phutil_get_current_library_name() {
  $caller = head(debug_backtrace(false));

  $root = phutil_get_library_root_for_path($caller['file']);
  return phutil_get_library_name_for_root($root);
}

/**
 * Warns about use of deprecated behavior.
 */
function phutil_deprecated($what, $why) {
  PhutilErrorHandler::dispatchErrorMessage(
    PhutilErrorHandler::DEPRECATED,
    $what,
    array(
      'why' => $why,
    ));
}

<?php

function phutil_get_library_root($library) {
  $bootloader = PhutilBootloader::getInstance();
  return $bootloader->getLibraryRoot($library);
}

function phutil_get_library_root_for_path($path) {
  foreach (Filesystem::walkToRoot($path) as $dir) {
    if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) {
      return $dir;
    }
  }
  return null;
}

function phutil_get_library_name_for_root($path) {
  $path = rtrim(Filesystem::resolvePath($path), '/');

  $bootloader = PhutilBootloader::getInstance();
  $libraries = $bootloader->getAllLibraries();
  foreach ($libraries as $library) {
    $root = $bootloader->getLibraryRoot($library);
    if (rtrim(Filesystem::resolvePath($root), '/') == $path) {
      return $library;
    }
  }

  return null;
}

function phutil_get_current_library_name() {
  $caller = head(debug_backtrace(false));

  $root = phutil_get_library_root_for_path($caller['file']);
  return phutil_get_library_name_for_root($root);
}

/**
 * Warns about use of deprecated behavior.
 */
function phutil_deprecated($what, $why) {
  PhutilErrorHandler::dispatchErrorMessage(
    PhutilErrorHandler::DEPRECATED,
    $what,
    array(
      'why' => $why,
    ));
}

Revert "Simplify the use of `phutil_get_library_root`"

Summary:
This reverts commit 67a17d0efb025665237d0d174d55d1887f9a6064.

This doesn't actually work because the call to `phutil_get_current_library_name()` always occurs within `libphutil`.

Test Plan: N/A

Reviewers: epriestley, #blessed_reviewers

Reviewed By: epriestley, #blessed_reviewers

Subscribers: Korvin, epriestley

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


<?php

namespace Igniter\Flame\Location;

use DateInterval;
use DatePeriod;
use DateTimeInterface;
use Illuminate\Support\Collection;

class WorkingTimeslot extends Collection
{
    public function generate(DateTimeInterface $date, DateInterval $interval, ?DateInterval $leadTime = null)
    {
        $items = [];

        foreach ($this->items as $range) {
            $start = $range->start()->toDateTime($date);
            $end = $range->end()->toDateTime($date);

            if ($range->endsNextDay())
                $end->add(new DateInterval('P1D'));

            if (!is_null($leadTime))
                $start = $start->add($leadTime);

            $datePeriod = new DatePeriod($start, $interval, $end);
            foreach ($datePeriod as $dateTime) {
                $items[] = $dateTime;
            }
        }

        return new static($items);
    }
}

<?php

namespace Igniter\Flame\Location;

use DateInterval;
use DatePeriod;
use DateTimeInterface;
use Illuminate\Support\Collection;

class WorkingTimeslot extends Collection
{
    public function generate(DateTimeInterface $date, DateInterval $interval, ?DateInterval $leadTime = null)
    {
        $items = [];

        foreach ($this->items as $range) {
            $start = $range->start()->toDateTime($date);
            $end = $range->end()->toDateTime($date);

            if ($range->endsNextDay())
                $end->add(new DateInterval('P1D'));

            if (!is_null($leadTime))
                $start = $start->add($leadTime);

            if ($interval->format('%i') < 5)
                $interval->i = 5;

            $datePeriod = new DatePeriod($start, $interval, $end);
            foreach ($datePeriod as $dateTime) {
                $items[] = $dateTime;
            }
        }

        return new static($items);
    }
}

Fix out of memory error caused when generating timeslot


<?php namespace Anomaly\PagesModule\Page\Command;

use Anomaly\PagesModule\Page\Contract\PageInterface;
use Anomaly\PagesModule\Page\Contract\PageRepositoryInterface;
use Illuminate\Contracts\Bus\SelfHandling;

/**
 * Class UpdatePaths
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 * @package       Anomaly\PagesModule\Page\Command
 */
class UpdatePaths implements SelfHandling
{

    /**
     * The page instance.
     *
     * @var PageInterface
     */
    protected $page;

    /**
     * Create a new UpdatePaths instance.
     *
     * @param PageInterface $page
     */
    public function __construct(PageInterface $page)
    {
        $this->page = $page;
    }

    /**
     * Handle the command.
     *
     * @param PageRepositoryInterface $pages
     */
    public function handle(PageRepositoryInterface $pages)
    {
        /* @var PageInterface $page */
        foreach ($this->page->getChildren() as $page) {
            if ($page->isEnabled()) {
                $pages->save($page->setAttribute('path', $this->page->getPath() . '/' . $page->getSlug()));
            }
        }
    }
}

<?php namespace Anomaly\PagesModule\Page\Command;

use Anomaly\PagesModule\Page\Contract\PageInterface;
use Anomaly\PagesModule\Page\Contract\PageRepositoryInterface;
use Illuminate\Contracts\Bus\SelfHandling;

/**
 * Class UpdatePaths
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 * @package       Anomaly\PagesModule\Page\Command
 */
class UpdatePaths implements SelfHandling
{

    /**
     * The page instance.
     *
     * @var PageInterface
     */
    protected $page;

    /**
     * Create a new UpdatePaths instance.
     *
     * @param PageInterface $page
     */
    public function __construct(PageInterface $page)
    {
        $this->page = $page;
    }

    /**
     * Handle the command.
     *
     * @param PageRepositoryInterface $pages
     */
    public function handle(PageRepositoryInterface $pages)
    {
        foreach ($this->page->getChildren() as $page) {
            if ($page instanceof PageInterface && $page->isEnabled()) {
                $pages->save($page->setAttribute('path', $this->page->getPath() . '/' . $page->getSlug()));
            }
        }
    }
}

Make sure we're working with a page internface.