<?php

class DeliveryProfileLiveAppleHttpToMulticast extends DeliveryProfileLiveAppleHttp {

	function __construct() {
		parent::__construct();
		$this->DEFAULT_RENDERER_CLASS = 'kF4MManifestRenderer';
	}

	/* (non-PHPdoc)
	 * @see DeliveryProfileLive::serve()
	 */
	public function doServe($baseUrl, $backupUrl)
	{
		$flavor = $this->getFlavorAssetInfo('', $baseUrl);		// passing the url as urlPrefix so that only the path will be tokenized
		$renderer = $this->getRenderer(array($flavor));
		return $renderer;
	}

	public function getEdgeServerUrls($primaryUrl, $backupUrl)
	{
		list($primaryUrl, $backupUrl) = parent::getEdgeServerUrls($primaryUrl, null);
		preg_replace('/' . EdgeServer::EDGE_SERVER_DEFAULT_LIVE_CACHE_APPLICATION_NAME . '/', EdgeServer::EDGE_SERVER_DEFAULT_LIVE_UNICAST_TO_MC_APPLICATION_NAME , $primaryUrl, 1);

		return array($primaryUrl, null);
	}
}

<?php

class DeliveryProfileLiveAppleHttpToMulticast extends DeliveryProfileLiveAppleHttp {

	function __construct() {
		parent::__construct();
		$this->DEFAULT_RENDERER_CLASS = 'kF4MManifestRenderer';
	}

	/* (non-PHPdoc)
	 * @see DeliveryProfileLive::serve()
	 */
	public function doServe($baseUrl, $backupUrl)
	{
		$flavor = $this->getFlavorAssetInfo('', $baseUrl);		// passing the url as urlPrefix so that only the path will be tokenized
		$renderer = $this->getRenderer(array($flavor));
		return $renderer;
	}

	public function getEdgeServerUrls($primaryUrl, $backupUrl)
	{
		list($primaryUrl, $backupUrl) = parent::getEdgeServerUrls($primaryUrl, null);
		$primaryUrl = preg_replace('/' . EdgeServer::EDGE_SERVER_DEFAULT_LIVE_CACHE_APPLICATION_NAME . '/', EdgeServer::EDGE_SERVER_DEFAULT_LIVE_UNICAST_TO_MC_APPLICATION_NAME , $primaryUrl, 1);

		return array($primaryUrl, null);
	}
}

Add return value to preg_replace

Add return value to preg_replace


Editing format for podcast <?php echo link_to($podcast->getTitle(),'podcast/edit?id='.$podcast->getId()) ?>

  <form action="<?php echo url_for('podcast_feed/edit') ?>" method="POST" enctype="multipart/form-data">

    <?php echo $form ?>

        <input type="submit" value="Save"/>

  </form>

  <?php echo delete_form_for_object($podcast_feed,'podcast_feed/delete'); ?>

Editing format for podcast <?php echo link_to($podcast->getTitle(),'podcast/edit?id='.$podcast->getId()) ?>

  <form action="<?php echo url_for('podcast_feed/edit') ?>" method="POST" enctype="multipart/form-data">

	<?php echo $form['title']->renderLabel() ?>

			<?php echo $form['title'] ?>

Becomes (empty) in torrent filenames

			<?php echo $form['title']->renderError() ?>

			<?php echo $form['title']->getValue(); ?>
			edit

	<?php echo $form['rss_url']->renderLabel() ?>

			<?php echo $form['rss_url'] ?>

Url for the format's feed

			<?php echo $form['rss_url']->renderError() ?>

			<?php echo $form['rss_url']->getValue(); ?>
			edit

        <input type="submit" value="Save"/>

  </form>

  <?php echo delete_form_for_object($podcast_feed,'podcast_feed/delete'); ?>

Make format form work the same as other forms


<?php

final class PhabricatorFileTransformTestCase extends PhabricatorTestCase {

  public function testGetAllTransforms() {
    PhabricatorFileTransform::getAllTransforms();
    $this->assertTrue(true);
  }

}

<?php

final class PhabricatorFileTransformTestCase extends PhabricatorTestCase {

  protected function getPhabricatorTestCaseConfiguration() {
    return array(
      self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true,
    );
  }

  public function testGetAllTransforms() {
    PhabricatorFileTransform::getAllTransforms();
    $this->assertTrue(true);
  }

  public function testThumbTransformDefaults() {
    $xforms = PhabricatorFileTransform::getAllTransforms();
    $file = new PhabricatorFile();

    foreach ($xforms as $xform) {
      if (!($xform instanceof PhabricatorFileThumbnailTransform)) {
        continue;
      }

      // For thumbnails, generate the default thumbnail. This should be able
      // to generate something rather than throwing an exception because we
      // forgot to add a default file to the builtin resources. See T12614.
      $xform->getDefaultTransform($file);

      $this->assertTrue(true);
    }
  }

}

Add unit tests for file thumbnail generation

Summary: Fixes T12614.

Test Plan:
  - Ran tests, saw them pass.
  - Changed a thumbnail to 800x800, saw tests detect that the default image was missing.

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T12614

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


<?php

namespace CultuurNet\UDB3\ReadModel\Index;

use ValueObjects\Enum\Enum;

class EntityType extends Enum
{
    const EVENT = 'event';
    const ORGANIZER = 'organizer';
    const PLACE = 'place';
}

<?php

namespace CultuurNet\UDB3\ReadModel\Index;

use ValueObjects\Enum\Enum;

/**
 * @method EntityType EVENT
 * @method EntityType ORGANIZER
 * @method EntityType PLACE
 */
class EntityType extends Enum
{
    const EVENT = 'event';
    const ORGANIZER = 'organizer';
    const PLACE = 'place';
}

III-359: Add doc annotations for the magic methods


<?php

if (!function_exists('gae_instance')) {
    function gae_instance() {
        return empty($_SERVER['GAE_INSTANCE']) ? '' : $_SERVER['GAE_INSTANCE'];
    }
}

if (!function_exists('gae_project')) {
    function gae_project() {
        return empty($_SERVER['GCLOUD_PROJECT']) ? '' : $_SERVER['GCLOUD_PROJECT'];
    }
}

if (!function_exists('gae_service')) {
    function gae_service() {
        return empty($_SERVER['GAE_SERVICE']) ? '' : $_SERVER['GAE_SERVICE'];
    }
}

if (!function_exists('gae_version')) {
    function gae_version() {
        return empty($_SERVER['GAE_VERSION']) ? '' : $_SERVER['GAE_VERSION'];
    }
}

<?php

if (!function_exists('gae_instance')) {
    function gae_instance() {
        if ( is_gae_std() ) {
            return $_SERVER['INSTANCE_ID'];
        } else if ( is_gae_flex() ) {
            return $_SERVER['GAE_INSTANCE'];
        } else {
            return false;
        }
    }
}

if (!function_exists('gae_project')) {
    function gae_project() {
        if ( is_gae_std() ) {
            return explode("~", $_SERVER['APPLICATION_ID'])[1];
        } else if ( is_gae_flex() ) {
            return $_SERVER['GCLOUD_PROJECT'];
        } else {
            return false;
        }
    }
}

if (!function_exists('gae_service')) {
    function gae_service() {
        if ( is_gae_std() ) {
            return $_SERVER['CURRENT_MODULE_ID'];
        } else if ( is_gae_flex() ) {
            return $_SERVER['GAE_SERVICE'];
        } else {
            return false;
        }
    }
}

if (!function_exists('gae_version')) {
    function gae_version() {
        if ( is_gae_std() ) {
            return $_SERVER['CURRENT_VERSION_ID'];
        } else if ( is_gae_flex() ) {
            return $_SERVER['GAE_VERSION'];
        } else {
            return false;
        }
    }
}

if (!function_exists('is_gae')) {
    function is_gae() {
        return ( is_gae_std() || is_gae_flex() );
    }
}

if (!function_exists('is_gae_std')) {
    function is_gae_std() {
        return isset( $_SERVER['SERVER_SOFTWARE'] ) && strpos( $_SERVER['SERVER_SOFTWARE'], 'Google App Engine' ) !== false;
    }
}

if (!function_exists('is_gae_flex')) {
    function is_gae_flex() {
        return isset( $_SERVER['GAE_INSTANCE'] );
    }
}

Update Helpers for Std & Flex

Update Helpers for Std & Flex


<?php

namespace Monolol\Lolifiers;

use Monolog\Logger;

class HashTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider testHandlingProvider
     */
    public function testHandling($level, $expected)
    {
        $record = array('level' => $level);

        $lolifier = new Hash();

        $this->assertSame($expected, $lolifier->isHandling($record));
    }

    public function testHandlingProvider()
    {
        return array(
            'debug' => array(Logger::DEBUG, true),
            'info' => array(Logger::INFO, true),
            'notice' => array(Logger::NOTICE, true),
            'warning' => array(Logger::WARNING, true),
            'error' => array(Logger::ERROR, true),
            'critical' => array(Logger::CRITICAL, true),
            'alert' => array(Logger::ALERT, true),
            'emergency' => array(Logger::EMERGENCY, true),
        );
    }

    public function testHash()
    {
        $record = array('message' => 'my littlest pony', 'datetime' => new \DateTime());

        $lolifier = new Hash();
        $lolified = $lolifier->lolify($record);

        $this->assertNotSame($record, $lolified);
    }
}

<?php

namespace Monolol\Lolifiers;

use Monolog\Logger;

class HashTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider testHandlingProvider
     */
    public function testHandling($level)
    {
        $record = array('level' => $level);

        $lolifier = new Hash();

        $this->assertTrue($lolifier->isHandling($record));
    }

    public function testHandlingProvider()
    {
        return array(
            'debug' => array(Logger::DEBUG),
            'info' => array(Logger::INFO),
            'notice' => array(Logger::NOTICE),
            'warning' => array(Logger::WARNING),
            'error' => array(Logger::ERROR),
            'critical' => array(Logger::CRITICAL),
            'alert' => array(Logger::ALERT),
            'emergency' => array(Logger::EMERGENCY),
        );
    }

    public function testHash()
    {
        $record = array('message' => 'my littlest pony', 'datetime' => new \DateTime());

        $lolifier = new Hash();
        $lolified = $lolifier->lolify($record);

        $this->assertNotSame($record, $lolified);
    }
}

fix: Fix useless parameter in Hash handling test data provider


<?php

namespace Respect\Foundation\InfoProviders;

class ProjectLicense extends AbstractProvider
{
	public function providerPackageIni()
	{
		$iniPath = realpath($this->projectFolder.'/package.ini');

		if (!file_exists($iniPath))
			return;

		$ini = parse_ini_file($iniPath, true);
		return $ini['package']['license'];
	}

	public function providerPackageXml()
	{
		$xmlPath = realpath($this->projectFolder.'/package.xml');

		if (!file_exists($xmlPath))
			return;

		$xml = simplexml_load_file($xmlPath);
		return (string) $xml->license;
	}
}

<?php

namespace Respect\Foundation\InfoProviders;

class ProjectLicense extends AbstractProvider
{
	public function providerPackageIni()
	{
		$iniPath = realpath($this->projectFolder.'/package.ini');

		if (!file_exists($iniPath))
			return;

		$ini = parse_ini_file($iniPath, true);
		return $ini['package']['license'];
	}

	public function providerPackageXml()
	{
		$xmlPath = realpath($this->projectFolder.'/package.xml');

		if (!file_exists($xmlPath))
			return;

		$xml = simplexml_load_file($xmlPath);
		return (string) $xml->license;
	}

	public function providerDefaultValue() {
        $licenseIdx = "\n";
        // this is a long shot, works for now but will need refinement
        if (file_exists($license = $this->projectFolder.'/LICENSE')) {
            //get first line of license file
            $firstline = preg_replace("/\n.*/", '', file_get_contents($license));
            //find first license first line at http://www.spdx.org/licenses/ and grab first licenseId
            $licenseIdx =  trim(preg_replace("/[\s\S]*{$firstline}[\s\S]*spdx:licenseId\"\>(.*)\<[\s\S]*$/iU" , '$1',
                file_get_contents('http://www.spdx.org/licenses/')));
        }
        if (false === strpos($licenseIdx, "\n"))
            return $licenseIdx;
		return 'BSD-4-Clause';
	}
}

Make an attempt to identify unknown license

If a LICENSE file is present the see if we can find it's first line on http://www.spdx.org/licenses/


<?php

namespace Frontend\Modules\Tags\Tests\Engine;

use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Tags\Engine\Model;
use Common\WebTestCase;

final class ModelTest extends WebTestCase
{
    public function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Frontend');
        }

        $client = self::createClient();
        $this->loadFixtures($client);
    }
}

<?php

namespace Frontend\Modules\Tags\Tests\Engine;

use Frontend\Core\Engine\Exception as FrontendException;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Search\Engine\Model as SearchModel;
use Frontend\Modules\Tags\Engine\Model as TagsModel;
use Common\WebTestCase;

final class ModelTest extends WebTestCase
{
    public function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Frontend');
        }

        $client = self::createClient();
        $this->loadFixtures($client);
    }

    public function testCallFromInterfaceOnModuleThatDoesNotImplementIt(): void
    {
        $module = 'Search';
        $this->expectException(FrontendException::class);
        $this->expectExceptionMessage(
            'To use the tags module you need
            to implement the FrontendTagsInterface
            in the model of your module
            (' . $module . ').'
        );
        TagsModel::callFromInterface($module, SearchModel::class, 'getIdForTags', null);
    }

}

Test that an exception is thrown when the interface isn't implemented


<?php

namespace Okapon\DoctrineSetTypeBundle\Tests\DependencyInjection;

use Okapon\DoctrineSetTypeBundle\DependencyInjection\OkaponDoctrineSetTypeExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class OkaponDoctrineSetTypeExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testDefault()
    {
        $container = new ContainerBuilder();
        $loader = new OkaponDoctrineSetTypeExtension();
        $loader->load(array(array()), $container);
        $this->assertTrue($container->hasDefinition('doctrine_set_type.set_type_guesser'), 'SetTypeGuesser is loaded');
    }
}

<?php

namespace Okapon\DoctrineSetTypeBundle\Tests\DependencyInjection;

use Okapon\DoctrineSetTypeBundle\DependencyInjection\OkaponDoctrineSetTypeExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class OkaponDoctrineSetTypeExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testDefault()
    {
        $container = new ContainerBuilder();
        $loader = new OkaponDoctrineSetTypeExtension();
        $loader->load(array(array()), $container);
        $this->assertTrue($container->hasDefinition('doctrine_set_type.set_type_guesser'), 'SetTypeGuesser is loaded');
        $this->assertEquals('Okapon\DoctrineSetTypeBundle\DBAL\Types\AbstractSetType', $container->getParameter('doctrine_set_type.set_type.class_name'));
        $this->assertEquals('Okapon\DoctrineSetTypeBundle\Form\Guess\SetTypeGuesser', $container->getParameter('doctrine_set_type.set_type_guesser.class'));
    }
}

Add test to confirm parameters is loaded


<?php
class RandomIntTest extends PHPUnit_Framework_TestCase
{
    public function testFuncExists()
    {
        $this->assertTrue(function_exists('random_int'));
    }

    public function testOutput()
    {
        $integers = array(
            random_int(0, 1000),
            random_int(1001,2000),
            random_int(-100, -10),
            random_int(-1000, 1000)
        );

        $this->assertFalse($integers[0] === $integers[1]);
        $this->assertTrue($integers[0] >= 0 && $integers[0] <= 1000);
        $this->assertTrue($integers[1] >= 1001 && $integers[1] <= 2000);
        $this->assertTrue($integers[2] >= -100 && $integers[2] <= -10);
        $this->assertTrue($integers[2] >= -1000 && $integers[2] <= 1000);
    }
}

<?php
class RandomIntTest extends PHPUnit_Framework_TestCase
{
    public function testFuncExists()
    {
        $this->assertTrue(function_exists('random_int'));
    }

    public function testOutput()
    {
        $integers = array(
            random_int(0, 1000),
            random_int(1001,2000),
            random_int(-100, -10),
            random_int(-1000, 1000),
            random_int(-PHP_INT_MAX + 1, PHP_INT_MAX)
        );

        $this->assertFalse($integers[0] === $integers[1]);
        $this->assertTrue($integers[0] >= 0 && $integers[0] <= 1000);
        $this->assertTrue($integers[1] >= 1001 && $integers[1] <= 2000);
        $this->assertTrue($integers[2] >= -100 && $integers[2] <= -10);
        $this->assertTrue($integers[3] >= -1000 && $integers[3] <= 1000);
        $this->assertTrue($integers[3] >= -1000 && $integers[3] <= 1000);
        $this->assertTrue($integers[4] >= -PHP_INT_MAX + 1 && $integers[4] <= PHP_INT_MAX);
    }
}

Add unit tests for updated random_int()

Add unit tests for updated random_int()


<?php
/**
 * Copyright (C) 2015 David Young
 *
 * Sets up PHPUnit tests
 */
require_once __DIR__ . "/../vendor/autoload.php";

// Set the default timezone in case the test server doesn't have it already set
date_default_timezone_set("UTC");

<?php
/**
 * Copyright (C) 2015 David Young
 *
 * Sets up PHPUnit tests
 */
require_once __DIR__ . "/../vendor/autoload.php";

// Turn on error reporting
ini_set("error_reporting", E_ALL);
ini_set("display_errors", "1");
ini_set("display_startup_errors", "1");

// Set the default timezone in case the test server doesn't have it already set
date_default_timezone_set("UTC");

Set PHPUnit to display errors to track down PHP7 bug


			<?php print_unescaped(str_replace(
					['{linkstart}', '{linkend}'],
					['', ''],
					$l->t('This application requires JavaScript for correct operation. Please {linkstart}enable JavaScript{linkend} and reload the page.')
				)); ?>

Update enable javascript link to https

Update enable javascript link to https


<?php
require_once('tests/php/base.php');
require_once('framework/php/classes/plants/PeoplePlant.php');

class PeoplePlantTests extends UnitTestCase {
	function testPeoplePlant(){
		$r = array();
		$p = new PeoplePlant('people', $r);
		$this->assertIsa($p, 'PeoplePlant');

		$p->doListSync(1);
		$this->assertTrue(1, 'Called doListSync');

		$api_key = getenv("MAILCHIMP_API_KEY");
		// an already-created list for testing
		$test_id = "b607c6d911";
		if($api_key) {
			// add syncing from a local list to $test_id mailchimp list
			// editList, then verify it worked
			// deleteList, then verify local list is removed and remote list is unchanged
		}
	}
}

?>

<?php
require_once('tests/php/base.php');
require_once('framework/php/classes/plants/PeoplePlant.php');

class PeoplePlantTests extends UnitTestCase {
	function testPeoplePlant(){
		$r = array();
		$p = new PeoplePlant('people', $r);
		$this->assertIsa($p, 'PeoplePlant');

		$p->doListSync(1);
		$this->assertTrue(1, 'Called doListSync');

		$api_key = getenv("MAILCHIMP_API_KEY");
		// an already-created list for testing
		$test_id = "b607c6d911";
		if($api_key) {
			// add syncing from a local list to $test_id mailchimp list
			// editList, then verify it worked
			// deleteList, then verify local list is removed and remote list is unchanged
			$c = new CASHSettings();
			$c->setSettings('MailChimp', 'com.mailchimp',
				array( "key", $api_key, "list", $test_id) );
		}
	}
}

?>

Add a mailchimp connection in the PeoplePlant tests if the proper api key is available


<?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\Security\Core\Encoder;

/**
 * PasswordEncoderInterface is the interface for all encoders.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface PasswordEncoderInterface
{
    /**
     * Encodes the raw password.
     *
     * @param string $raw  The password to encode
     * @param string $salt The salt
     *
     * @return string The encoded password
     */
    public function encodePassword($raw, $salt);

    /**
     * Checks a raw password against an encoded password.
     *
     * @param string $encoded An encoded password
     * @param string $raw     A raw password
     * @param string $salt    The salt
     *
     * @return bool true if the password is valid, false otherwise
     */
    public function isPasswordValid($encoded, $raw, $salt);
}

<?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\Security\Core\Encoder;

use Symfony\Component\Security\Core\Exception\BadCredentialsException;

/**
 * PasswordEncoderInterface is the interface for all encoders.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface PasswordEncoderInterface
{
    /**
     * Encodes the raw password.
     *
     * @param string $raw  The password to encode
     * @param string $salt The salt
     *
     * @return string The encoded password
     *
     * @throws BadCredentialsException   If the raw password is invalid, e.g. excessively long
     * @throws \InvalidArgumentException If the salt is invalid
     */
    public function encodePassword($raw, $salt);

    /**
     * Checks a raw password against an encoded password.
     *
     * @param string $encoded An encoded password
     * @param string $raw     A raw password
     * @param string $salt    The salt
     *
     * @return bool true if the password is valid, false otherwise
     *
     * @throws \InvalidArgumentException If the salt is invalid
     */
    public function isPasswordValid($encoded, $raw, $salt);
}

Declare exceptions that are already thrown by implementations


<?php

namespace Styleguide\Pages;

class NewsView extends Page
{
    /** {@inheritdoc} **/
    public $path = '/styleguide/news/item-1';

    /**
     * {@inheritdoc}
     */
    public function getPageData()
    {
        return app('Factories\Page')->create(1, true, [
            'page' => [
                'controller' => 'NewsController',
                'title' => 'News View',
                'id' => null,
            ],
        ]);
    }
}

<?php

namespace Styleguide\Pages;

class NewsView extends Page
{
    /** {@inheritdoc} **/
    public $path;

    /**
     * {@inheritdoc}
     */
    public function getPageData()
    {
        $this->path = '/styleguide/'.config('base.news_listing_route').'/item-1';

        return app('Factories\Page')->create(1, true, [
            'page' => [
                'controller' => 'NewsController',
                'title' => 'News View',
                'id' => null,
            ],
        ]);
    }
}

Move the path so we can use the config value for the route


Made with ♥ by RoboJackets • Privacy Policy

        fullUrl()}}">Make a Wish
@if(\Sentry\Laravel\Integration::currentTracingSpan() !== null)
@if(auth()->user()->hasRole('admin'))
• getTraceId() }}">Trace ID: {{ \Sentry\Laravel\Integration::currentTracingSpan()->getTraceId() }}
@else
• Trace ID: {{ \Sentry\Laravel\Integration::currentTracingSpan()->getTraceId() }}
@endif
@endif

Add trace ID to footer of member UI

Add trace ID to footer of member UI


<?php

namespace App\Models\Web;

use App\Models\WebModel;

class StaticPage extends WebModel
{

    protected function transformMappingInternal()
    {

        return [
            [
                "name" => 'web_url',
                "doc" => "The URL to this page on our website",
                "type" => "string",
                'elasticsearch_type' => 'keyword',
                "value" => function() { return $this->web_url; },
            ],
        ];

    }

}

<?php

namespace App\Models\Web;

use App\Models\WebModel;

class StaticPage extends WebModel
{

    protected function transformMappingInternal()
    {

        return [
            [
                "name" => 'web_url',
                "doc" => "The URL to this page on our website",
                "type" => "string",
                'elasticsearch_type' => 'keyword',
                "value" => function() { return $this->web_url; },
            ],
            [
                "name" => 'is_published',
                "doc" => "Whether this static page is available to view (always true)",
                "type" => "boolean",
                'elasticsearch_type' => 'boolean',
                "value" => function() { return true; },
            ],
        ];

    }

}

Add `is_published` to static pages

Add `is_published` to static pages [WEB-714]

Necessary to support `Search::scopePublished` in that codebase.


<?php

class ExamplesTest extends \PHPUnit_Framework_TestCase {

  public function testParsePhpLikeArrayExample() {
    $array_keyword = Parser::str('array');
    $comma = Parser::char(',');
    $identifier = Parser::satisfyChar(function ($c) { return ctype_alnum($c); });
    $item = Parser::many1($identifier);
    $items_list = Parser::product(
      Parser::many(Parser::product($item, $comma)),
      $item
    );
    $open = Parser::char('(');
    $close = Parser::char(')');
    $array = Parser::product(
      $array_keyword,
      Parser::product(Parser::product($open, $items_list), $close)
              ->or_(Parser::product($open, $close))
    );

    $t1 = 'array(lbas2d,aaa,aaaaa)';
    $t2 = 'array(a,a,a)';
    $t3 = 'array(9)';
    $t4 = 'array()';

    $test = function ($input) use ($array) {
      $this->assertEquals(
        new Good($input, strlen($input)),
        Parser::slice($array)->run($input),
        'PHP-like array example'
      );
    };

    $test($t1);
    $test($t2);
    $test($t3);
    $test($t4);

  }

}

<?php

class ExamplesTest extends \PHPUnit_Framework_TestCase {

  public function testParsePhpLikeArrayExample() {
    $array_keyword = Parser::str('array');
    $comma = Parser::char(',');
    $identifier = Parser::satisfyChar(function ($c) { return ctype_alnum($c); });
    $item = Parser::many1($identifier);
    $items_list = Parser::product(
      Parser::many(Parser::skipR($item, $comma)),
      $item
    );
    $open = Parser::char('(');
    $close = Parser::char(')');
    $array = Parser::skipL(
      $array_keyword,
      Parser::skipR(Parser::skipL($open, $items_list), $close)
              ->or_(Parser::product($open, $close))
    );

    $t1 = 'array(lbas2d,aaa,aaaaa)';
    $t2 = 'array(a,a,a)';
    $t3 = 'array(9)';
    $t4 = 'array()';

    $test = function ($input) use ($array) {
      $this->assertEquals(
        new Good($input, strlen($input)),
        Parser::slice($array)->run($input),
        'PHP-like array example'
      );
    };

    $test($t1);
    $test($t2);
    $test($t3);
    $test($t4);

  }

}

Use skip combinators in example test.

Use skip combinators in example test.


<?php

class KeyValueTest extends \PHPUnit_Framework_TestCase
{
    protected $maker;

    public function setUp()
    {
        $this->maker = new PeterColes\Countries\Maker;
    }

    public function testDefaultSettings()
    {
        $keyValue = $this->maker->keyValue();

        $this->assertEquals(253, $keyValue->count());
        $this->assertEquals((object)[ 'key' => 'AF', 'value' => 'Afghanistan' ], $keyValue->first());
    }

    public function testAlternativeLocale()
    {
        $keyValue = $this->maker->keyValue('es');

        $this->assertEquals((object)[ 'key' => 'AF', 'value' => 'Afganistán' ], $keyValue->first());
    }

    public function testAlternativeKeys()
    {
        $keyValue = $this->maker->keyValue(null, 'label', 'text');

        $this->assertEquals((object)[ 'label' => 'ZW', 'text' => 'Zimbabwe' ], $keyValue->last());
    }
}

<?php

class KeyValueTest extends \PHPUnit_Framework_TestCase
{
    protected $maker;

    public function setUp()
    {
        $this->maker = new PeterColes\Countries\Maker;
    }

    public function testDefaultSettings()
    {
        $keyValue = $this->maker->keyValue();

        $this->assertEquals(255, $keyValue->count());
        $this->assertEquals((object)[ 'key' => 'AF', 'value' => 'Afghanistan' ], $keyValue->first());
    }

    public function testAlternativeLocale()
    {
        $keyValue = $this->maker->keyValue('es');

        $this->assertEquals((object)[ 'key' => 'AF', 'value' => 'Afganistán' ], $keyValue->first());
    }

    public function testAlternativeKeys()
    {
        $keyValue = $this->maker->keyValue(null, 'label', 'text');

        $this->assertEquals((object)[ 'label' => 'ZW', 'text' => 'Zimbabwe' ], $keyValue->last());
    }
}

Fix broken test (new "countries" added to data)


<?php

namespace rrsoacis\component\setting\cluster;

use rrsoacis\manager\ClusterManager;
use ZipArchive;
use rrsoacis\component\common\AbstractController;
use rrsoacis\manager\MapManager;
use rrsoacis\system\Config;

class SettingsClusterUpdateController extends AbstractController
{
	public function post()
    {
        $name = $_POST['name'];
        if ($name === '')
        {
            $name = null;
        }

        $a_host = $_POST['a_host'];
        $f_host = $_POST['f_host'];
        $p_host = $_POST['p_host'];
        $s_host = $_POST['s_host'];
        $archiver = $_POST['archiver'];
        $hosts_pass = $_POST['hosts_pass'];

        if ($a_host !== '' && $s_host !== '' && $f_host !== ''
            && $p_host !== '' && $archiver !== "" && $hosts_pass !== "")
        {
            ClusterManager::updateCluster($name, $a_host, $f_host, $p_host, $s_host, $archiver, $hosts_pass);
        }

        if ($name == null)
        { header('location: '.Config::$TOP_PATH.'settings-clusters'); }
        else
        { header('location: '.Config::$TOP_PATH.'settings-cluster/'.$name); }
	}
}

?>

<?php

namespace rrsoacis\component\setting\cluster;

use rrsoacis\manager\ClusterManager;
use ZipArchive;
use rrsoacis\component\common\AbstractController;
use rrsoacis\manager\MapManager;
use rrsoacis\system\Config;

class SettingsClusterUpdateController extends AbstractController
{
    public function post()
    {
        $name = null;
        if (isset($_POST['name']) && $_POST['name'] !== '')
        {
            $name = $_POST['name'];
        }

        $a_host = $_POST['a_host'];
        $f_host = $_POST['f_host'];
        $p_host = $_POST['p_host'];
        $s_host = $_POST['s_host'];
        $archiver = $_POST['archiver'];
        $hosts_pass = $_POST['hosts_pass'];

        if ($a_host !== '' && $s_host !== '' && $f_host !== ''
            && $p_host !== '' && $archiver !== "" && $hosts_pass !== "")
        {
            ClusterManager::updateCluster($name, $a_host, $f_host, $p_host, $s_host, $archiver, $hosts_pass);
        }

        if ($name == null)
        { header('location: '.Config::$TOP_PATH.'settings-clusters'); }
        else
        { header('location: '.Config::$TOP_PATH.'settings-cluster/'.$name); }
    }
}

?>

RESOLVE an error with undefined index

RESOLVE an error with undefined index


<?php namespace Laravel\Database\Query\Grammars;

use Laravel\Database\Query;

class SQLite extends Grammar
{

	/**
	 * Compile the ORDER BY clause for a query.
	 *
	 * @param  Query   $query
	 * @return string
	 */
	protected function orderings(Query $query)
	{
		foreach ($query->orderings as $ordering)
		{
			$sql[] = $this->wrap($ordering['column']).' COLLATE NOCASE '.strtoupper($ordering['direction']);
		}

		return 'ORDER BY '.implode(', ', $sql);
	}

}

<?php namespace Laravel\Database\Query\Grammars;

use Laravel\Database\Query;

class SQLite extends Grammar
{

	/**
	 * Compile the ORDER BY clause for a query.
	 *
	 * @param  Query   $query
	 * @return string
	 */
	protected function orderings(Query $query)
	{
		foreach ($query->orderings as $ordering)
		{
			$sql[] = $this->wrap($ordering['column']).' COLLATE NOCASE '.strtoupper($ordering['direction']);
		}

		return 'ORDER BY '.implode(', ', $sql);
	}

	/**
	 * Compile a SQL INSERT statement from a Query instance.
	 *
	 * This method handles the compilation of single row inserts and batch inserts.
	 *
	 * @param  Query   $query
	 * @param  array   $values
	 * @return string
	 */
	public function insert(Query $query, $values)
	{
		// Essentially we will force every insert to be treated as a batch insert which
		// simply makes creating the SQL easier for us since we can utilize the same
		// basic routine regardless of an amount of records given to us to insert.
		$table = $this->wrap_table($query->from);

		if ( ! is_array(reset($values)))
		{
			$values = array($values);
		}

		// If there is only one record being inserted, we will just use the usual query
		// grammar insert builder because no special syntax is needed for the single
		// row inserts in SQLite. However, if there are multiples, we'll continue.
		if (count($values) == 1)
		{
			return parent::insert($query, $values[0]);
		}

		$names = $this->columnize(array_keys($values[0]));

		$columns = array();

		// SQLite requires us to build the multi-row insert as a listing of select with
		// unions joining them together. So we'll build out this list of columns and
		// then join them all together with select unions to complete the queries.
		foreach (array_keys($values[0]) as $column)
		{
			$columns[] = '? AS '.$this->wrap($column);
		}

		$columns = array_fill(9, count($values), implode(', ', $columns));

		return "INSERT INTO $table ($names) SELECT ".implode(' UNION SELECT ', $columns);
	}

}

Fix multi inserts in SQLite.

Fix multi inserts in SQLite.


<?php

// Объект - Получатель
class MultiShip_Recipient extends MultiShip_Object
{
  var $_prefix = "recipient_";
  var $_fields = array("first_name", "middle_name", "last_name", "phone", "email", "comment");
  var $_critical = array("first_name", "last_name", "phone");

  function fixField($name, $value)
  {
	  switch($name)
	  {
		  case "phone":
		  {
			  $value = preg_replace("/[^1-9]/", '', $value);
		  }
	  }
	  return parent::fixField($name, $value);
  }
}

<?php

// Объект - Получатель
class MultiShip_Recipient extends MultiShip_Object
{
  var $_prefix = "recipient_";
  var $_fields = array("first_name", "middle_name", "last_name", "phone", "email", "comment");
  var $_critical = array("first_name", "last_name", "phone");

  function fixField($name, $value)
  {
	  switch($name)
	  {
		  case "phone":
		  {
			  $value = preg_replace("/[^0-9]/", '', $value);
		  }
	  }
	  return parent::fixField($name, $value);
  }
}

Fix bug with zero in phone number (wrong filtration)


<?php

require('ErrorsContainer.php');

    class AddSegmentsErrors extends ErrorsContainer {

        public function __constructor() {
            $this->errors = [
                'missingAlbum' => false,
                'missingAuthor' => false,
                'missingName' => false,
                'missingAdNumber' => false,
                'missingStartTime' => false,
                'startTimeInvalidFormat' => false,
                'outOfEpisodeBounds' => false
            ];
        }

        public function markAlbumMissing() {
            $this->errors['missingAlbum'] = true;
        }

        public function markAuthorMissing() {
            $this->errors['missingAuthor'] = true;
        }

        public function markNameMissing() {
            $this->errors['missingName'] = true;
        }

        public function markAdNumberMissing() {
            $this->errors['missingAdNumber'] = true;
        }

        public function markStartTimeMissing() {
            $this->errors['missingStartTime'] = true;
        }

        public function markStartTimeInvalidFormat() {
            $this->errors['startTimeInvalidFormat'] = true;
        }

        public function markStartTimeOutOfEpisodeBounds() {
            $this->errors['outOfEpisodeBounds'] = true;
        }
    }

<?php

require('ErrorsContainer.php');

    class AddSegmentsErrors extends ErrorsContainer {

        public function __constructor() {
            $this->errors = [
                'missingCategory' => false,
                'categoryInvalidFormat' => false,
                'missingAlbum' => false,
                'missingAuthor' => false,
                'missingName' => false,
                'missingAdNumber' => false,
                'missingStartTime' => false,
                'startTimeInvalidFormat' => false,
                'outOfEpisodeBounds' => false
            ];
        }

        public function markCategoryMissing() {
            $this->errors['misisngCategory'] = true;
        }

        public function markCategoryInvalidFormat() {
            $this->errors['categoryInvalidFormat'] = true;
        }

        public function markAlbumMissing() {
            $this->errors['missingAlbum'] = true;
        }

        public function markAuthorMissing() {
            $this->errors['missingAuthor'] = true;
        }

        public function markNameMissing() {
            $this->errors['missingName'] = true;
        }

        public function markAdNumberMissing() {
            $this->errors['missingAdNumber'] = true;
        }

        public function markStartTimeMissing() {
            $this->errors['missingStartTime'] = true;
        }

        public function markStartTimeInvalidFormat() {
            $this->errors['startTimeInvalidFormat'] = true;
        }

        public function markStartTimeOutOfEpisodeBounds() {
            $this->errors['outOfEpisodeBounds'] = true;
        }
    }

Add changes missing from commit a3a01cd

Add changes missing from commit a3a01cd


<?php

namespace Avalanche\Bundle\ImagineBundle\Imagine;

use Symfony\Component\Routing\RouterInterface;

class CachePathResolver
{
    /**
     * @var string
     */
    private $webRoot;

    /**
     * @var RouterInterface
     */
    private $router;

    /**
     * Constructs cache path resolver with a given web root and cache prefix
     *
     * @param string          $webRoot
     * @param RouterInterface $router
     */
    public function __construct($webRoot, RouterInterface $router)
    {
        $this->webRoot = $webRoot;
        $this->router  = $router;
    }

    /**
     * Gets filtered path for rendering in the browser
     *
     * @param string  $path
     * @param string  $filter
     * @param boolean $absolute
     *
     * @return mixed
     */
    public function getBrowserPath($path, $filter, $absolute = false)
    {
        $realPath = realpath($this->webRoot . $path);

        $path = ltrim($path, '/');
        $uri  = $this->router->generate('_imagine_' . $filter, ['path' => $path], $absolute);
        $uri  = str_replace(urlencode($path), urldecode($path), $uri);

        $cached = realpath($this->webRoot . $uri);

        if (file_exists($cached) && !is_dir($cached) && filemtime($realPath) > filemtime($cached)) {
            unlink($cached);
        }

        return $uri;
    }
}

<?php

namespace Avalanche\Bundle\ImagineBundle\Imagine;

use Symfony\Component\Routing\RouterInterface;

class CachePathResolver
{
    /**
     * @var string
     */
    private $webRoot;

    /**
     * @var RouterInterface
     */
    private $router;

    /**
     * Constructs cache path resolver with a given web root and cache prefix
     *
     * @param string          $webRoot
     * @param RouterInterface $router
     */
    public function __construct($webRoot, RouterInterface $router)
    {
        $this->webRoot = $webRoot;
        $this->router  = $router;
    }

    /**
     * Gets filtered path for rendering in the browser
     *
     * @param string  $path
     * @param string  $filter
     * @param boolean $absolute
     *
     * @return mixed
     */
    public function getBrowserPath($path, $filter, $absolute = false)
    {
        $realPath = realpath($this->webRoot . $path);

        $path = ltrim($path, '/');
        $uri  = $this->router->generate('_imagine_' . $filter, ['path' => $path], $absolute);
        $uri  = str_replace(urlencode($path), urldecode($path), $uri);

        // TODO: find better way then this hack.
        if (preg_match('#^/\w+[.]php(/.*?)$#i', $uri, $m)) {
            $uri = $m[1];
        }

        $cached = realpath($this->webRoot . $uri);

        if (file_exists($cached) && !is_dir($cached) && filemtime($realPath) > filemtime($cached)) {
            unlink($cached);
        }

        return $uri;
    }
}

Add hack to deal with PHP entry files

Add hack to deal with PHP entry files

In case we're using dev environment (or any other the prod one) we'll
incorrect asset url.
This hack tryies to deal with it in an ugly, but working way.
TODO: deal with absolute URLs (or remove that option if it's never used).


<?php
defined('C5_EXECUTE') or die(_("Access Denied."));
echo $this->controller->getOpenTag();
echo $this->controller->getTitle();
$format = (strlen($this->controller->dateFormat)?$this->controller->dateFormat:"m/d/y");
echo date($format,strtotime($this->controller->getContent()));
echo $this->controller->getCloseTag();

<?php
defined('C5_EXECUTE') or die(_("Access Denied."));
$dh = Core::make('helper/date'); /* @var $dh \Concrete\Core\Localization\Service\Date */
echo $this->controller->getOpenTag();
echo $this->controller->getTitle();
$format = (strlen($this->controller->dateFormat)?$this->controller->dateFormat:"m/d/y");
echo $dh->formatCustom($format, $this->controller->getContent());
echo $this->controller->getCloseTag();

Use date helper in date time template of page_attribute_display block

Makes use of correct locale on multilingual websites


<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Events\PaymentSuccess;
use App\Models\Payment;
use App\Notifications\Payment\ConfirmationNotification;
use Spatie\WebhookClient\ProcessWebhookJob;

class ProcessSquareWebhook extends ProcessWebhookJob
{

    /**
     * The queue this job will run on. This is fairly arbitrary since it only touches the local DB.
     *
     * @var string
     */
    public $queue = 'square';

    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 1;

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        if ('payment.created' !== $this->webhookCall->payload['type']) {
            return;
        }

        $details = $this->webhookCall->payload['data']['object']['payment'];

        $payment = Payment::firstOrFail($details['reference_id']);
        $payment->processing_fee = $details['processing_fee'];
        $payment->amount = $details['amount_money']['amount'] / 100;
        $payment->order_id = $details['order_id'];
        $payment->save();

        $payment->payable->user->notify(new ConfirmationNotification($payment));
        event(new PaymentSuccess($payment));
    }
}

<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Events\PaymentSuccess;
use App\Models\Payment;
use App\Notifications\Payment\ConfirmationNotification;
use Spatie\WebhookClient\ProcessWebhookJob;

class ProcessSquareWebhook extends ProcessWebhookJob
{

    /**
     * The queue this job will run on. This is fairly arbitrary since it only touches the local DB.
     *
     * @var string
     */
    public $queue = 'square';

    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 1;

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        if ('payment.created' !== $this->webhookCall->payload['type']) {
            return;
        }

        $details = $this->webhookCall->payload['data']['object']['payment'];

        $payment = Payment::firstOrFail($details['reference_id']);
        $payment->amount = $details['amount_money']['amount'] / 100;
        $payment->processing_fee = $details['processing_fee'];
        $payment->order_id = $details['order_id'];
        $payment->notes = 'Checkout flow completed';
        $payment->save();

        $payment->payable->user->notify(new ConfirmationNotification($payment));
        event(new PaymentSuccess($payment));
    }
}

Add notes to square webhook job

Add notes to square webhook job


<?php

use Phalcon\Text;

class NewController extends \Phalcon\Mvc\Controller
{
    public function indexAction()
    {
        // No view needed since this is all backend stuff.
        $this->view->disable();

        // Generate random ids until we find one not in use.
        // This will cause one additional SQL query at minimum when creating a paste.
        $id;
        do
        {
            $id = Text::random(Text::RANDOM_ALNUM, rand(5,13));
        }
        while (Paste::findFirstByid($id));

        $paste = new Paste();
        $paste->id = $id;
        $paste->content = $this->request->getPost("content");
        $paste->lang = $this->request->getPost("lang");
        // No sanitisation needed if we accept anything at all to mean true and nothing to mean false.
        // Also addresses http://stackoverflow.com/a/14067312
        $paste->private = $this->request->getPost("private") == null ? 0 : 1;
        $paste->owner_addr = $this->request->getClientAddress();
        $paste->size_bytes = strlen($paste->content);

        if (!$paste->save())
        {
            foreach ($paste->getMessages() as $message)
            {
                $this->flash->error($message->getMessage());
            }
            return $this->response->redirect();
        }
        return $this->response->redirect($this->url->get("v/$id"));
    }
}

<?php

use Phalcon\Text;

class NewController extends \Phalcon\Mvc\Controller
{
    public function indexAction()
    {
        // No view needed since this is all backend stuff.
        $this->view->disable();

        // Generate random ids until we find one not in use.
        // This will cause one additional SQL query at minimum when creating a paste.
        $id;
        do
        {
            $id = Text::random(Text::RANDOM_ALNUM, rand(5,13));
        }
        while (Paste::findFirstByid($id));

        $paste = new Paste();
        $paste->id = $id;
        $paste->content = $this->request->getPost("content");
        $paste->lang = $this->request->getPost("lang") == null ? "auto" : $this->request->getPost("lang");
        // No sanitisation needed if we accept anything at all to mean true and nothing to mean false.
        // Also addresses http://stackoverflow.com/a/14067312
        $paste->private = $this->request->getPost("private") == null ? 0 : 1;
        $paste->owner_addr = $this->request->getClientAddress();
        $paste->size_bytes = strlen($paste->content);

        if (!$paste->save())
        {
            foreach ($paste->getMessages() as $message)
            {
                $this->flash->error($message->getMessage());
            }
            return $this->response->redirect();
        }
        return $this->response->redirect($this->url->get("v/$id"));
    }
}

Allow lang to be omitted from post

Allow lang to be omitted from post


<?php

/**
 * This file is part of the Stippers project (available here: https://github.com/Stannieman/stippers/).
 * The license and all terms en conditions that apply to Stippers also apply to this file.
 *
 * @author Stan Wijckmans
 *
 * Middleware to do some session cleanup. It removes data from session that's irrelevant for the page you're going to.
 */

require_once "IMiddleware.php";

abstract class SessionCleanup implements IMiddleware {

    public static function run(array $requestData) {

        if ($requestData['requestedPage'] != 'manageuser' && $requestData['requestedPage'] != 'edituser' && $requestData['requestedPage'] != 'sendemailtousers')
            unset($_SESSION['Stippers']['ManageUserSearch']);

        if ($requestData['requestedPage'] != 'edituser')
            unset($_SESSION['Stippers']['EditUser']);

        if ($requestData['requestedPage'] != 'editbrowser')
            unset($_SESSION['Stippers']['EditBrowser']);

        if ($requestData['requestedPage'] != 'renewuser')
            unset($_SESSION['Stippers']['RenewUser']);

        if ($requestData['requestedPage'] != 'profile')
            unset($_SESSION['Stippers']['Profile']);

        if ($requestData['requestedPage'] != 'changepassword')
            unset($_SESSION['Stippers']['ChangePassword']);

        return true;
    }
}

<?php

/**
 * This file is part of the Stippers project (available here: https://github.com/Stannieman/stippers/).
 * The license and all terms en conditions that apply to Stippers also apply to this file.
 *
 * @author Stan Wijckmans
 *
 * Middleware to do some session cleanup. It removes data from session that's irrelevant for the page you're going to.
 */

require_once "IMiddleware.php";

abstract class SessionCleanup implements IMiddleware {

    public static function run(array $requestData) {

        if ($requestData['requestedPage'] != 'manageuser' && $requestData['requestedPage'] != 'edituser' && $requestData['requestedPage'] != 'sendemailtousers')
            unset($_SESSION['Stippers']['ManageUserSearch']);

        if ($requestData['requestedPage'] != 'edituser')
            unset($_SESSION['Stippers']['EditUser']);

        if ($requestData['requestedPage'] != 'editbrowser')
            unset($_SESSION['Stippers']['EditBrowser']);

        if ($requestData['requestedPage'] != 'renewuser')
            unset($_SESSION['Stippers']['RenewUser']);

        if ($requestData['requestedPage'] != 'profile')
            unset($_SESSION['Stippers']['Profile']);

        if ($requestData['requestedPage'] != 'changepassword')
            unset($_SESSION['Stippers']['ChangePassword']);

        if ($requestData['requestedPage'] != 'cashregister')
            unset($_SESSION['Stippers']['CashRegister']);

        return true;
    }
}

Add new page for register to session cleanup.


<?php

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

class OrchestraAuthAddRememberTokenToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->rememberToken()->after('status');
        });
    }

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

<?php

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

class OrchestraAuthAddRememberTokenToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('remember_token', 100)->nullable()->after('status');
        });
    }

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

Revert use rememberToken() because not possible to chain the return value at the moment.

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


<?php
/**
 * html-form-validator (https://github.com/xtreamwayz/html-form-validator)
 *
 * @see       https://github.com/xtreamwayz/html-form-validator for the canonical source repository
 * @copyright Copyright (c) 2016 Geert Eltink (https://xtreamwayz.com/)
 * @license   https://github.com/xtreamwayz/html-form-validator/blob/master/LICENSE.md MIT
 */

declare(strict_types = 1);

namespace Xtreamwayz\HTMLFormValidator\FormElement;

use Zend\Filter\StripNewlines as StripNewlinesFilter;
use Zend\Validator\Regex as RegexValidator;
use Zend\Validator\StringLength as StringLengthValidator;

class Password extends BaseFormElement
{
    protected function getFilters() : array
    {
        return [
            ['name' => StripNewlinesFilter::class],
        ];
    }

    protected function getValidators() : array
    {
        $validators = [];

        if ($this->node->hasAttribute('minlength') || $this->node->hasAttribute('maxlength')) {
            $validators[] = [
                'name'    => StringLengthValidator::class,
                'options' => [
                    'min' => $this->node->getAttribute('minlength') ?: 0,
                    'max' => $this->node->getAttribute('maxlength') ?: null,
                ],
            ];
        }

        if ($this->node->hasAttribute('pattern')) {
            $validators[] = [
                'name'    => RegexValidator::class,
                'options' => [
                    'pattern' => sprintf('/%s/', $this->node->getAttribute('pattern')),
                ],
            ];
        }

        return $validators;
    }
}

<?php
/**
 * html-form-validator (https://github.com/xtreamwayz/html-form-validator)
 *
 * @see       https://github.com/xtreamwayz/html-form-validator for the canonical source repository
 * @copyright Copyright (c) 2016 Geert Eltink (https://xtreamwayz.com/)
 * @license   https://github.com/xtreamwayz/html-form-validator/blob/master/LICENSE.md MIT
 */

declare(strict_types = 1);

namespace Xtreamwayz\HTMLFormValidator\FormElement;

use Xtreamwayz\HTMLFormValidator\FormElement\Text as TextElement;

class Password extends TextElement
{
}

Remove duplicate code in the password element


<?php namespace NZTim\Logger\Handlers;

use NZTim\Logger\Entry;
use Monolog\Logger as MonologLogger;
use Monolog\Handler\StreamHandler;

class FileHandler implements Handler
{
    /**
     * @param Entry $entry
     * @return null
     */
    public function write(Entry $entry)
    {
        $log = new MonologLogger($entry->getChannel());
        $log->pushHandler(new StreamHandler($this->getPath($entry->getChannel()), $entry->getCode()));
        $log->addRecord($entry->getCode(), $entry->getMessage(), $entry->getContext());
    }

    /**
     * @param string $channel
     * @return string
     */
    protected function getPath($channel)
    {
        $ds = DIRECTORY_SEPARATOR;
        $path = storage_path() . "{$ds}logs{$ds}custom";
        if (!file_exists($path)) {
            mkdir($path, 0755);
        }
        return "{$path}{$ds}{$channel}.log";
    }
}

<?php namespace NZTim\Logger\Handlers;

use NZTim\Logger\Entry;
use Monolog\Logger as MonologLogger;
use Monolog\Handler\StreamHandler;

class FileHandler implements Handler
{
    /**
     * @param Entry $entry
     * @return null
     */
    public function write(Entry $entry)
    {
        $log = new MonologLogger($entry->getChannel());
        $log->pushHandler(new StreamHandler($this->getPath($entry->getChannel()), $entry->getCode()));
        $log->addRecord($entry->getCode(), $entry->getMessage(), $entry->getContext());
    }

    /**
     * @param string $channel
     * @return string
     */
    protected function getPath($channel)
    {
        $ds = DIRECTORY_SEPARATOR;
        $path = storage_path() . "{$ds}logs{$ds}custom";
        if (!is_dir($path) && !file_exists($path)) {
            mkdir($path, 0755);
        }
        return "{$path}{$ds}{$channel}.log";
    }
}

Change directory check to prevent PHP warning


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User_model extends CI_Model {

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

	// Return user credentials
	public function exist()
	{
		$config = array(
				'username' => $this->input->post('username'),
				'password' => $this->input->post('password')
			);

		$query = $this->db->select('a.id, a.username, a.password, a.fullname, a.email, b.role_id, c.user_type')
				->from('users_tbl AS a')
				->join('users_role_tbl AS b', 'a.id = b.user_id', 'INNER')
				->join('role_tbl AS c', 'b.role_id = c.id', 'INNER')
				->where($config)
				->get();

		if ($query->num_rows())
		{
			return $query->row_array();
		}

		return false;
	}

}

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User_model extends CI_Model {

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

	// Return user credentials
	public function exist()
	{
		$config = array(
				'username' => $this->input->post('username'),
				'password' => $this->input->post('password')
			);

		$fields = array(
				'a.id',
				'a.username',
				'a.password',
				'a.fullname',
				'a.email',
				'a.emp_id',
				'a.emp_no',
				'a.supervisor_email',
				'b.role_id',
				'c.user_type'
			);

		$query = $this->db->select($fields)
				->from('users_tbl AS a')
				->join('users_role_tbl AS b', 'a.id = b.user_id', 'INNER')
				->join('role_tbl AS c', 'b.role_id = c.id', 'INNER')
				->where($config)
				->get();

		if ($query->num_rows())
		{
			return $query->row_array();
		}

		return false;
	}

}

Store the fields in array

Store the fields in array


<?php

declare(strict_types=1);

namespace DiContainerBenchmarks\TestSuite;

final class TestSuites
{
    public static function getTestSuite(int $number): ?TestSuiteInterface
    {
        return match ($number) {
            1 => new TestSuite1(),
            2 => new TestSuite2(),
            3 => new TestSuite3(),
            4 => new TestSuite4(),
            5 => new TestSuite5(),
            6 => new TestSuite6(),
            default => null,
        };
    }
}

<?php

declare(strict_types=1);

namespace DiContainerBenchmarks\TestSuite;

final class TestSuites
{
    public static function getTestSuite(int $number): ?TestSuiteInterface
    {
        switch ($number) {
            case 1:
                return new TestSuite1();
            case 2:
                return new TestSuite2();
            case 3:
                return new TestSuite3();
            case 4:
                return new TestSuite4();
            case 5:
                return new TestSuite5();
            case 6:
                return new TestSuite6();
            default:
                return null;
        }
    }
}

Remove PHP 8 only syntax

Remove PHP 8 only syntax


@if ((int) count($categories) === 0)

         Info:
        Er zijn geen categorieen gevonden voor de helpdesk in het systeem.

@else

                #
                Aangemaakt door:
                Categorie:
                Vragen:	 {{-- Colspan 2 is needed because the functions are embedded. --}}

            @foreach($categories as $category)

                    #C{{ $category->id }}
                    {{ $category->creator->name }}
                    {{ $category->category }}
                    {{ count($category->question) }} Vragen

                    {{-- Functions --}}

                            Bekijken
                            Verwijder

                    {{-- /Functions --}}

            @endforeach

@endif

@if ((int) count($categories) === 0)

         Info:
        Er zijn geen categorieen gevonden voor de helpdesk in het systeem.

@else

                #
                Aangemaakt door:
                Categorie:
                Vragen:	 {{-- Colspan 2 is needed because the functions are embedded. --}}

            @foreach($categories as $category)

                    #C{{ $category->id }}
                    {{ $category->creator->name }}
                    {{ $category->category }}
                    {{ count($category->question) }} Vragen

                    {{-- Functions --}}

                            Bekijken
                            id) }}" class="label label-danger">Verwijder

                    {{-- /Functions --}}

            @endforeach

@endif

Implement destroy function for category destroy


<?php

declare(strict_types=1);

namespace Cortex\Auth\Console\Commands;

use Illuminate\Console\Command;

class RollbackCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:rollback:auth {--force : Force the operation to run when in production.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Rollback Cortex Auth Tables.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $this->alert($this->description);

        if (file_exists($path = 'database/migrations/cortex/auth')) {
            $this->call('migrate:reset', [
                '--step' => true,
                '--path' => $path,
                '--force' => $this->option('force'),
            ]);
        } else {
            $this->warn('No migrations found! Consider publish them first: <fg=green>php artisan cortex:publish:auth</>');
        }
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Auth\Console\Commands;

use Illuminate\Console\Command;

class RollbackCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:rollback:auth {--force : Force the operation to run when in production.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Rollback Cortex Auth Tables.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $this->alert($this->description);

        if (file_exists($path = 'database/migrations/cortex/auth')) {
            $this->call('migrate:reset', [
                '--path' => $path,
                '--force' => $this->option('force'),
            ]);
        } else {
            $this->warn('No migrations found! Consider publish them first: <fg=green>php artisan cortex:publish:auth</>');
        }
    }
}

Fix `migrate:reset` args as it doesn't accept --step


<?php
/**
 * Class Csrf
 *
 * @package Faulancer\Security
 * @author Florian Knapp <office@florianknapp.de>
 */
namespace Faulancer\Security;

use Faulancer\Session\SessionManager;

/**
 * Class Csrf
 */
class Csrf
{

    /**
     * Generates a token and save it to session
     * @return string
     */
    public static function getToken()
    {
        $token = bin2hex(random_bytes(32));
        self::saveToSession($token);
        return $token;
    }

    /**
     * Check if token is valid
     * @return boolean
     */
    public static function isValid()
    {
        return isset($_POST['csrf']) && $_POST['csrf'] === SessionManager::instance()->getFlashbag('csrf');
    }

    /**
     * Saves token into session
     * @param $token
     */
    private static function saveToSession($token)
    {
        SessionManager::instance()->setFlashbag('csrf', $token);
    }

}

<?php
/**
 * Class Csrf
 *
 * @package Faulancer\Security
 * @author Florian Knapp <office@florianknapp.de>
 */
namespace Faulancer\Security;

use Faulancer\Session\SessionManager;

/**
 * Class Csrf
 */
class Csrf
{

    /**
     * Generates a token and save it to session
     * @return string
     */
    public static function getToken()
    {
        $token = bin2hex(openssl_random_pseudo_bytes(32));
        self::saveToSession($token);
        return $token;
    }

    /**
     * Check if token is valid
     * @return boolean
     */
    public static function isValid()
    {
        return isset($_POST['csrf']) && $_POST['csrf'] === SessionManager::instance()->getFlashbag('csrf');
    }

    /**
     * Saves token into session
     * @param $token
     */
    private static function saveToSession($token)
    {
        SessionManager::instance()->setFlashbag('csrf', $token);
    }

}

Add ssl random bytes generator

Add ssl random bytes generator


<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 *
 * @var WC_Aplazame $aplazame
 */
global $aplazame;
if ( ! $aplazame->enabled ) {
	return;
}

/**
 *
 * @var WooCommerce $woocommerce
 */
global $woocommerce;
?>

	Paga en 15 días tu compra con Aplazame.

	Obtén financiación al instante sólo con tu Nombre y Apellidos, DNI/NIE, Teléfono y tarjeta de débito o crédito.

	Sin comisiones ocultas ni letra pequeña.

<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 *
 * @var WC_Aplazame $aplazame
 */
global $aplazame;
if ( ! $aplazame->enabled ) {
	return;
}

/**
 *
 * @var WooCommerce $woocommerce
 */
global $woocommerce;
?>

	Paga en 15 días tu compra con Aplazame.

	Obtén financiación al instante sólo con tu Nombre y Apellidos, Teléfono y tarjeta de débito o crédito.

	Sin comisiones ocultas ni letra pequeña.

Remove reference to Spanish document ID in pay later


<?php
	class Controller {
        function view($file,$data=false){
			require Views_DIR.$file.'.php';
        }
	}
?>

<?php
	class Controller {
        function view($file,$data=false){
					header('X-Frame-Options:DENY');
			require Views_DIR.$file.'.php';
        }
	}
?>

Add X-Frame-Options header, requires review


<?php

namespace Armd\UserBundle\Security;

use Symfony\Component\Security\Http\Logout\DefaultLogoutSuccessHandler;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class LogoutSuccessHandler extends DefaultLogoutSuccessHandler implements ContainerAwareInterface
{
    protected $container;

    function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    function onLogoutSuccess(Request $request)
    {
        $response = parent::onLogoutSuccess($request);
        $this->clearCookies($response);

        return $response;
    }

    function clearCookies(Response $response)
    {
        $domain = $this->container->getParameter('domain');

        $response->headers->clearCookie('_USER_ID', '/', $domain);
        $response->headers->clearCookie('_USER_HASH', '/', $domain);
    }
}

<?php

namespace Armd\UserBundle\Security;

use Symfony\Component\Security\Http\Logout\DefaultLogoutSuccessHandler;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class LogoutSuccessHandler extends DefaultLogoutSuccessHandler implements ContainerAwareInterface
{
    protected $container;

    function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    function onLogoutSuccess(Request $request)
    {
        $response = parent::onLogoutSuccess($request);
        $this->clearCookies($response);
        $this->addRedirect($request, $response);

        return $response;
    }

    function clearCookies(Response $response)
    {
        $domain = $this->container->getParameter('domain');

        $response->headers->clearCookie('_USER_ID', '/', $domain);
        $response->headers->clearCookie('_USER_HASH', '/', $domain);
    }

    function addRedirect(Request $request, Response $response)
    {
        $returnUrl = $request->get('return_url');
        if (!empty($returnUrl)) {
            $response->headers->set('Location', $returnUrl);
        }
    }

}

Add return_url for logout action

[+] Add return_url for logout action


<?php

namespace Kunstmaan\MediaBundle\Repository;

use Doctrine\ORM\EntityNotFoundException;
use Doctrine\ORM\EntityRepository;
use Kunstmaan\MediaBundle\Entity\Media;

/**
 * MediaRepository
 */
class MediaRepository extends EntityRepository
{
    /**
     * @param Media $media
     */
    public function save(Media $media)
    {
        $em = $this->getEntityManager();
        $em->persist($media);
        $em->flush();
    }

    /**
     * @param Media $media
     */
    public function delete(Media $media)
    {
        $em = $this->getEntityManager();
        $media->setDeleted(true);
        $em->persist($media);
        $em->flush();
    }

    /**
     * @param int $mediaId
     *
     * @return object
     *
     * @throws EntityNotFoundException
     */
    public function getMedia($mediaId)
    {
        $media = $this->find($mediaId);
        if (!$media) {
            throw new EntityNotFoundException();
        }

        return $media;
    }

    /**
     * @param int $pictureId
     *
     * @return object
     *
     * @throws EntityNotFoundException
     */
    public function getPicture($pictureId)
    {
        $em = $this->getEntityManager();

        $picture = $em->getRepository(\Kunstmaan\MediaBundle\Entity\Image::class)->find($pictureId);
        if (!$picture) {
            throw new EntityNotFoundException();
        }

        return $picture;
    }

    /**
     * Finds all Media  that has their deleted flag set to 1
     * and have their remove_from_file_system flag set to 0
     *
     * @return object[]
     */
    public function findAllDeleted()
    {
        return $this->findBy(['deleted' => true, 'removedFromFileSystem' => false]);
    }
}

<?php

namespace Kunstmaan\MediaBundle\Repository;

use Doctrine\ORM\EntityNotFoundException;
use Doctrine\ORM\EntityRepository;
use Kunstmaan\MediaBundle\Entity\Media;

/**
 * MediaRepository
 */
class MediaRepository extends EntityRepository
{
    /**
     * @param Media $media
     */
    public function save(Media $media)
    {
        $em = $this->getEntityManager();
        $em->persist($media);
        $em->flush();
    }

    /**
     * @param Media $media
     */
    public function delete(Media $media)
    {
        $em = $this->getEntityManager();
        $media->setDeleted(true);
        $em->persist($media);
        $em->flush();
    }

    /**
     * @param int $mediaId
     *
     * @return object
     *
     * @throws EntityNotFoundException
     */
    public function getMedia($mediaId)
    {
        $media = $this->find($mediaId);
        if (!$media) {
            throw new EntityNotFoundException();
        }

        return $media;
    }

    /**
     * Finds all Media  that has their deleted flag set to 1
     * and have their remove_from_file_system flag set to 0
     *
     * @return object[]
     */
    public function findAllDeleted()
    {
        return $this->findBy(['deleted' => true, 'removedFromFileSystem' => false]);
    }
}

[MediaBundle] Remove non working method which causes issues


<?php
namespace mpcmf\modules\authex\controllers;

use mpcmf\modules\authex\mappers\inviteMapper;
use mpcmf\modules\moduleBase\controllers\controllerBase;
use mpcmf\modules\moduleBase\exceptions\mapperException;
use mpcmf\system\helper\io\codes;
use mpcmf\system\pattern\singleton;

/**
 * Class inviteController
 *
 * Invite system
 *
 *
  * @generated by mpcmf/codeManager
 *
 * @package mpcmf\modules\authex\controllers;
 * @date 2015-10-01 12:35:13
 *
 * @author Dmitry Emelyanov <gilberg.vrn@gmail.com>
 */
class inviteController
    extends controllerBase
{

    use singleton;

    public function _invite($invite)
    {
        try {
            inviteMapper::getInstance()->getBy([
                inviteMapper::FIELD__INVITE => $invite
            ]);
        } catch (mapperException $mapperException) {
            $message = $mapperException->getMessage();

            if (mb_strpos($message, 'not found') === false) {
                return self::error($mapperException->getMessage(), $mapperException->getCode(), codes::RESPONSE_CODE_NOT_FOUND);
            }

            return self::nothing([]);
        }

        $this->getSlim()->redirectTo('/authex/user/register', ['invite' => $invite]);

        return self::nothing([]);
    }
}

<?php
namespace mpcmf\modules\authex\controllers;

use mpcmf\modules\authex\mappers\inviteMapper;
use mpcmf\modules\moduleBase\controllers\controllerBase;
use mpcmf\modules\moduleBase\exceptions\mapperException;
use mpcmf\system\helper\io\codes;
use mpcmf\system\pattern\singleton;

/**
 * Class inviteController
 *
 * Invite system
 *
 *
  * @generated by mpcmf/codeManager
 *
 * @package mpcmf\modules\authex\controllers;
 * @date 2015-10-01 12:35:13
 *
 * @author Dmitry Emelyanov <gilberg.vrn@gmail.com>
 */
class inviteController
    extends controllerBase
{

    use singleton;

    public function _invite($invite)
    {
        try {
            inviteMapper::getInstance()->getBy([
                inviteMapper::FIELD__INVITE => $invite,
                inviteMapper::FIELD__USED => false,
            ]);
        } catch (mapperException $mapperException) {
            $message = $mapperException->getMessage();

            if (mb_strpos($message, 'not found') === false) {
                return self::error($mapperException->getMessage(), $mapperException->getCode(), codes::RESPONSE_CODE_NOT_FOUND);
            }

            return self::nothing([]);
        }

        $this->getSlim()->redirectTo('/authex/user/register', ['invite' => $invite]);

        return self::nothing([]);
    }
}

Add check for used invites

Add check for used invites


<?php

final class PhabricatorYoutubeRemarkupRule extends PhutilRemarkupRule {

  private $uri;

  public function getPriority() {
    return 350.0;
  }

  public function apply($text) {
    $this->uri = new PhutilURI($text);

    if ($this->uri->getDomain() &&
        preg_match('/(^|\.)youtube\.com$/', $this->uri->getDomain()) &&
        idx($this->uri->getQueryParams(), 'v')) {
      return $this->markupYoutubeLink();
    }

    return $text;
  }

  public function markupYoutubeLink() {
    $v = idx($this->uri->getQueryParams(), 'v');
    $text_mode = $this->getEngine()->isTextMode();
    $mail_mode = $this->getEngine()->isHTMLMailMode();

    if ($text_mode || $mail_mode) {
      return $this->getEngine()->storeText('http://youtu.be/'.$v);
    }

    $youtube_src = 'https://www.youtube.com/embed/'.$v;
    $iframe = $this->newTag(
      'div',
      array(
        'class' => 'embedded-youtube-video',
      ),
      $this->newTag(
        'iframe',
        array(
          'width'       => '650',
          'height'      => '400',
          'style'       => 'margin: 1em auto; border: 0px;',
          'src'         => $youtube_src,
          'frameborder' => 0,
        ),
        ''));
    return $this->getEngine()->storeText($iframe);
  }

}

<?php

final class PhabricatorYoutubeRemarkupRule extends PhutilRemarkupRule {

  public function getPriority() {
    return 350.0;
  }

  public function apply($text) {
    try {
      $uri = new PhutilURI($text);
    } catch (Exception $ex) {
      return $text;
    }

    $domain = $uri->getDomain();
    if (!preg_match('/(^|\.)youtube\.com\z/', $domain)) {
      return $text;
    }

    $params = $uri->getQueryParams();
    $v_param = idx($params, 'v');
    if (!strlen($v_param)) {
      return $text;
    }

    $text_mode = $this->getEngine()->isTextMode();
    $mail_mode = $this->getEngine()->isHTMLMailMode();

    if ($text_mode || $mail_mode) {
      return $text;
    }

    $youtube_src = 'https://www.youtube.com/embed/'.$v_param;

    $iframe = $this->newTag(
      'div',
      array(
        'class' => 'embedded-youtube-video',
      ),
      $this->newTag(
        'iframe',
        array(
          'width'       => '650',
          'height'      => '400',
          'style'       => 'margin: 1em auto; border: 0px;',
          'src'         => $youtube_src,
          'frameborder' => 0,
        ),
        ''));

    return $this->getEngine()->storeText($iframe);
  }

}

Fix ambiguous URI parsing in Youtube Remarkup rule

Summary:
Fixes T12867. Also:

  - Simplify the code a little.
  - Stop mutating this on text/mobile -- there's no inherent value in the "youtu.be" link so I think this just changes the text the user wrote unnecessarily.

Test Plan: {F5013804}

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T12867

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


<?php

namespace com\xcitestudios\Generic\Test\Data\Manipulation\Interfaces;

class SerializationInterfaceTest extends \PHPUnit_Framework_TestCase
{
    public function testSerialization()
    {
        $testObject = new \stdClass();
        $testObject->a = 5;
        $testObject->b = 's';

        $obj = new SerializationInterfaceTestClass();
        $obj->setFloatA(1.1);
        $obj->setIntA(5);
        $obj->setObjA($testObject);
        $obj->setStringA('stringy');

        $string = $obj->serialize();

        $this->assertInternalType('string', $string);

        $newObj = new SerializationInterfaceTestClass();
        $newObj->deserialize($string);

        $this->assertEquals($obj->getFloatA(), $newObj->getFloatA());
        $this->assertEquals($obj->getIntA(), $newObj->getIntA());
        $this->assertEquals($obj->getStringA(), $newObj->getStringA());
        $this->assertEquals($obj->getObjA(), $newObj->getObjA());
    }
}

<?php

namespace com\xcitestudios\Generic\Test\Data\Manipulation\Interfaces;

class SerializationInterfaceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * While testing an interface is pointless, it was a way of giving an example of how
     * to implement the interface and ensure the example remains valid!
     */
    public function testSerialization()
    {
        $testObject = new \stdClass();
        $testObject->a = 5;
        $testObject->b = 's';

        $obj = new SerializationInterfaceTestClass();
        $obj->setFloatA(1.1);
        $obj->setIntA(5);
        $obj->setObjA($testObject);
        $obj->setStringA('stringy');

        $string = $obj->serialize();

        $this->assertInternalType('string', $string);

        $newObj = new SerializationInterfaceTestClass();
        $newObj->deserialize($string);

        $this->assertEquals($obj->getFloatA(), $newObj->getFloatA());
        $this->assertEquals($obj->getIntA(), $newObj->getIntA());
        $this->assertEquals($obj->getStringA(), $newObj->getStringA());
        $this->assertEquals($obj->getObjA(), $newObj->getObjA());
    }
}

Comment as to why there is a test for an interface


<?php
/**
 * We made this code.
 * By pH7 (Pierre-Henry SORIA).
 */

namespace PFBC\Validation;

use PH7\Framework\Mvc\Model\DbConfig;

class Password extends \PFBC\Validation
{
    protected $iMin, $iMax;

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

        $this->iMin = DbConfig::getSetting('minPasswordLength');
        $this->iMax = DbConfig::getSetting('maxPasswordLength');
        $this->message = t('Error: Your password has to contain from %0% to %1% characters.', $this->iMin, $this->iMax);
    }

    public function isValid($sValue)
    {
        if ($this->isNotApplicable($sValue)) return true;
        return $this->oValidate->password($sValue, $this->iMin, $this->iMax);
    }
}

<?php
/**
 * We made this code.
 * By pH7 (Pierre-Henry SORIA).
 */

namespace PFBC\Validation;

use PH7\Framework\Mvc\Model\DbConfig;

class Password extends \PFBC\Validation
{
    protected $iMin, $iMax;

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

        $this->iMin = DbConfig::getSetting('minPasswordLength');
        $this->iMax = DbConfig::getSetting('maxPasswordLength');
        $this->message = t('Error: Your password has to contain from %0% to %1% characters.', $this->iMin, $this->iMax);
    }

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

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

Add curly brackets for better readability


<?php

interface IPost
{
    public function link(): string;
}

/**
 * Class Post
 * The Post Model
 */
class Post extends Volcano implements IPost
{
    public function __construct(
        protected string $filepath = '',
    ) {
    }

    /**
     * Generate a post link.
     * Removes the POSTS directory path and file extension.
     *
     * @return string
     */
    public function link(): string
    {
        $noDirectoryName = explode('/', str_replace($this->getPath('posts'), '', $this->filepath));
        return str_replace('.md', '', str_replace('\\', '/', end($noDirectoryName)));
    }
}

<?php

namespace Volcano\Models;

use Volcano\Volcano;

interface IPost
{
    public function link(): string;
    public function meta(string $type): string;
}

/**
 * Class Post 📧
 * The Post Model
 * @package Volcano\Models
 */
class Post extends Volcano implements IPost
{
    public function __construct(
        public string $filepath = '',
    ) {
    }

    /**
     * Generate a post link.
     * Removes the POSTS directory path and file extension.
     * @return string
     */
    public function link(): string
    {
        $noDirectoryName = explode('/', str_replace($this->getPath('posts'), '', $this->filepath));
        return str_replace('.md', '', str_replace('\\', '/', end($noDirectoryName)));
    }

    /**
     * Get meta data.
     * @param string $type
     * @return string
     */
    public function meta(string $type): string
    {
        return $this->getMeta($type, $this);
    }
}

Use namespace and add meta()

Use namespace and add meta()


<?php

namespace OuterEdge\Base\Plugin;

use Closure;
use Magento\Framework\App\FrontController;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Module\Plugin\DbStatusValidator as MagentoDbStatusValidator;

class DbStatusValidator extends MagentoDbStatusValidator
{
    protected $errors;

    public function aroundDispatch(FrontController $subject, Closure $proceed, RequestInterface $request)
    {
        try {
            parent::aroundDispatch($subject, $proceed, $request);
        } catch (LocalizedException $ex) {
            $this->errors = $ex->getMessage();
        }

        return $proceed($request);
    }

    public function hasErrors()
    {
        return !empty($this->errors);
    }

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

<?php

namespace OuterEdge\Base\Plugin;

use Closure;
use Magento\Framework\App\FrontController;
use Magento\Framework\App\ProductMetadataInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Cache\FrontendInterface as FrontendCacheInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Module\DbVersionInfo;
use Magento\Framework\Module\Plugin\DbStatusValidator as MagentoDbStatusValidator;

class DbStatusValidator extends MagentoDbStatusValidator
{
    protected $errors;

    protected $productMetadata;

    public function __construct(FrontendCacheInterface $cache, DbVersionInfo $dbVersionInfo, ProductMetadataInterface $productMetadata)
    {
        $this->productMetadata = $productMetadata;
        parent::__construct($cache, $dbVersionInfo);
    }

    public function beforeDispatch(FrontController $subject, RequestInterface $request)
    {
        if (version_compare($this->productMetadata->getVersion(), '2.2.0') != -1) {
            try {
                parent::beforeDispatch($subject, $request);
            } catch (LocalizedException $ex) {
                $this->errors = $ex->getMessage();
            }
        }
    }

    public function aroundDispatch(FrontController $subject, Closure $proceed, RequestInterface $request)
    {
        if (version_compare($this->productMetadata->getVersion(), '2.2.0') == -1) {
            try {
                parent::aroundDispatch($subject, $proceed, $request);
            } catch (LocalizedException $ex) {
                $this->errors = $ex->getMessage();
            }
        }

        return $proceed($request);
    }

    public function hasErrors()
    {
        return !empty($this->errors);
    }

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

Add compatibility with Magento 2.2

Add compatibility with Magento 2.2


<?php

/**
 *
 * @author Pawel Rojek <pawel at pawelrojek.com>
 * @author Ian Reinhart Geiser <igeiser at devonit.com>
 *
 * This file is licensed under the Affero General Public License version 3 or later.
 *
 **/

namespace OCA\Drawio\AppInfo;

use OCP\App;

App::registerAdmin("drawio", "settings");

$app = new Application();

<?php

/**
 *
 * @author Pawel Rojek <pawel at pawelrojek.com>
 * @author Ian Reinhart Geiser <igeiser at devonit.com>
 *
 * This file is licensed under the Affero General Public License version 3 or later.
 *
 **/

namespace OCA\Drawio\AppInfo;

use OCP\App;

$app = new Application();

Remove superflous admin section registration.

This removes the registerAdmin() call in the App initialization. It is
not necessary as we already declared the admin class in the
appinfo/info.xml. Leaving it there causes the settings to appear twice.

This should finally fix #4 without causing the issue described in #63.

Signed-off-by: Jan Losinski <577c4104c61edf9f052c616c0c23e67bef4a9955@wh2.tu-dresden.de>


@extends('layouts.admin')

@section('content')

List of Categories

                                Category Name
                                Type
                                Edit
                                Delete

                        @foreach($categories as $category)

                                {{ $category->name }}
                                {{ $category->type->name }}
                                 $category->id] ) }}">Edit
                                  $category->id] ) }}">Delete

                        @endforeach

                    Add Category

@endsection

@extends('layouts.admin')

@section('content')

                    List of Categories

<button class="btn btn-xs btn-primary">Add Category</button>

                                #
                                Name
                                Type
                                Actions

                            @foreach($categories as $category)

                                    {{ $category->id }}
                                    {{ $category->name }}
                                    {{ $category->type->name }}

                                       $category->id] ) }}"><button class="btn btn-xs btn-primary">Edit</button>
                                       $category->id] ) }}"><button class="btn btn-xs btn-primary">Delete</button>

                            @endforeach

@endsection

Update Interface to Category Index page

feat(shop): Update Interface to Category Index page

Update Interface to Category Index page

see #298


@extends('layouts.app')
@section('content')

Survey Count Graphs

  {{--
  {!! Charts::assets(['google']) !!}

{!! $allYears->render() !!}

  @foreach ($yearCharts as $yearChart)

{!! $yearChart->render() !!}

  --}}

@endsection

Make the chart bigger and add hook for colours


<?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\Order\Model;
use Sylius\Component\Resource\Model\ResourceInterface;

/**
 * @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
 */
interface OrderItemUnitInterface extends ResourceInterface, AdjustableInterface
{
    /**
     * @return int
     */
    public function getTotal();

    /**
     * @return OrderItemInterface
     */
    public function getOrderItem();
}

[Core] Change ``UnitPercentageDiscountAction`` to count discount on unit


<?php

namespace App\Nova\Filters;

use App\Team;
use Illuminate\Http\Request;
use Laravel\Nova\Filters\Filter;

class UserTeam extends Filter
{
    /**
     * The filter's component.
     *
     * @var string
     */
    public $component = 'select-filter';

    /**
     * Apply the filter to the given query.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  mixed  $value
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function apply(Request $request, $query, $value)
    {
        return $query->whereHas('teams', function ($query) use ($value) {
            $query->where('id', '=', $value);
        });
    }

    /**
     * Get the filter's available options.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function options(Request $request)
    {
        $teams = [];
        if ($request->user()->can('read-teams')) {
            $teams = Team::where('attendable', 1)
                ->when($request->user()->cant('read-teams-hidden'), function ($query) {
                    $query->where('visible', 1);
                })->get()
                ->mapWithKeys(function ($item) {
                    return [$item['name'] => $item['id']];
                })->toArray();
        }

        return $teams;
    }
}

<?php

namespace App\Nova\Filters;

use App\Team;
use Illuminate\Http\Request;
use Laravel\Nova\Filters\Filter;

class UserTeam extends Filter
{
    /**
     * The filter's component.
     *
     * @var string
     */
    public $component = 'select-filter';

    /**
     * Apply the filter to the given query.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  mixed  $value
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function apply(Request $request, $query, $value)
    {
        return $query->whereHas('teams', function ($query) use ($value) {
            $query->where('teams.id', '=', $value);
        });
    }

    /**
     * Get the filter's available options.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function options(Request $request)
    {
        $teams = [];
        if ($request->user()->can('read-teams')) {
            $teams = Team::where('attendable', 1)
                ->when($request->user()->cant('read-teams-hidden'), function ($query) {
                    $query->where('visible', 1);
                })->get()
                ->mapWithKeys(function ($item) {
                    return [$item['name'] => $item['id']];
                })->toArray();
        }

        return $teams;
    }
}

Fix SQL for team filter

Fix SQL for team filter


<?php
namespace CrudJsonApi\Listener;

use Cake\Event\Event;
use Cake\ORM\Table;
use Crud\Listener\BaseListener;
use RuntimeException;

class SearchListener extends BaseListener
{

    /**
     * Settings
     *
     * @var array
     */
    protected $_defaultConfig = [
        'enabled' => [
            'Crud.beforeLookup',
            'Crud.beforePaginate'
        ],
        'collection' => 'default'
    ];

    /**
     * Returns a list of all events that will fire in the controller during its lifecycle.
     * You can override this function to add your own listener callbacks
     *
     * @return array
     */
    public function implementedEvents()
    {
        return [
            'Crud.beforeLookup' => ['callable' => 'injectSearch'],
            'Crud.beforePaginate' => ['callable' => 'injectSearch']
        ];
    }

    /**
     * Inject search conditions into the query object.
     *
     * @param \Cake\Event\Event $event Event
     * @return void
     */
    public function injectSearch(Event $event)
    {
        if (!in_array($event->getName(), $this->getConfig('enabled'))) {
            return;
        }

        $repository = $this->_table();
        if ($repository instanceof Table && !$repository->behaviors()->has('Search')) {
            throw new RuntimeException(sprintf(
                'Missing Search.Search behavior on %s',
                get_class($repository)
            ));
        }

        $filterParams = ['search' => $this->_request()->getQuery('filter')];

        $filterParams['collection'] = $this->getConfig('collection');
        $event->getSubject()->query->find('search', $filterParams);
    }
}

<?php
namespace CrudJsonApi\Listener;

use Cake\Event\Event;
use Cake\ORM\Table;
use Crud\Listener\BaseListener;
use RuntimeException;

class SearchListener extends BaseListener
{

    /**
     * Settings
     *
     * @var array
     */
    protected $_defaultConfig = [
        'enabled' => [
            'Crud.beforeLookup',
            'Crud.beforePaginate'
        ],
        'collection' => 'default'
    ];

    /**
     * Returns a list of all events that will fire in the controller during its lifecycle.
     * You can override this function to add your own listener callbacks
     *
     * @return array
     */
    public function implementedEvents()
    {
        return [
            'Crud.beforeLookup' => ['callable' => 'injectSearch'],
            'Crud.beforePaginate' => ['callable' => 'injectSearch']
        ];
    }

    /**
     * Inject search conditions into the query object.
     *
     * @param \Cake\Event\Event $event Event
     * @return void
     */
    public function injectSearch(Event $event)
    {
        if (!in_array($event->getName(), $this->getConfig('enabled'))) {
            return;
        }

        $repository = $this->_table();
        if ($repository instanceof Table && !$repository->behaviors()->has('Search')) {
            throw new RuntimeException(sprintf(
                'Missing Search.Search behavior on %s',
                get_class($repository)
            ));
        }

        $filterParams = ['search' => $this->_request()->getQuery('filter', [])];

        $filterParams['collection'] = $this->getConfig('collection');
        $event->getSubject()->query->find('search', $filterParams);
    }
}

Add an empty array as default to prevent breakage when no filters are passed


<?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\WebProfilerBundle\Tests\Resources;

use PHPUnit\Framework\TestCase;

class IconTest extends TestCase
{
    /**
     * @dataProvider provideIconFilePaths
     */
    public function testIconFileContents($iconFilePath)
    {
        $this->assertMatchesRegularExpression('~<svg xmlns="http://www.w3.org/2000/svg" width="\d+" height="\d+" viewBox="0 0 \d+ \d+">.*</svg>~s', file_get_contents($iconFilePath), sprintf('The SVG metadata of the %s icon is different than expected (use the same as the other icons).', $iconFilePath));
    }

    public function provideIconFilePaths()
    {
        return array_map(function ($filePath) { return (array) $filePath; }, glob(__DIR__.'/../../Resources/views/Icon/*.svg'));
    }
}

<?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\WebProfilerBundle\Tests\Resources;

use PHPUnit\Framework\TestCase;

class IconTest extends TestCase
{
    /**
     * @dataProvider provideIconFilePaths
     */
    public function testIconFileContents($iconFilePath)
    {
        $this->assertMatchesRegularExpression('~<svg xmlns="http://www.w3.org/2000/svg" width="\d+" height="\d+" viewBox="0 0 \d+ \d+"[^>]*+>.*</svg>~s', file_get_contents($iconFilePath), sprintf('The SVG metadata of the %s icon is different than expected (use the same as the other icons).', $iconFilePath));
    }

    public function provideIconFilePaths()
    {
        return array_map(function ($filePath) { return (array) $filePath; }, glob(__DIR__.'/../../Resources/views/Icon/*.svg'));
    }
}

Fix tests about web profiler icons

[WebProfilerBundle] Fix tests about web profiler icons


<?php

namespace Bolt\Asset;

/**
 * Trait for handling queue priority sorting.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
trait AssetSortTrait
{
    /**
     * Do a Schwartzian Transform for stable sort.
     *
     * @see http://en.wikipedia.org/wiki/Schwartzian_transform
     *
     * @param AssetInterface[] $assets
     *
     * @return AssetInterface[]
     */
    protected function sort(array $assets)
    {
        array_walk(
            $assets,
            function (&$v, $k) {
                /** @var AssetInterface $v */
                $v = [$v->getPriority(), $k, $v];
            }
        );

        sort($assets);

        array_walk(
            $assets,
            function (&$v) {
                $v = $v[2];
            }
        );

        return $assets;
    }
}

<?php

namespace Bolt\Asset;

/**
 * Trait for handling queue priority sorting.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
trait AssetSortTrait
{
    /**
     * Do a Schwartzian Transform for stable sort.
     *
     * @see http://en.wikipedia.org/wiki/Schwartzian_transform
     *
     * @param AssetInterface[] $assets
     *
     * @return AssetInterface[]
     */
    protected function sort(array $assets)
    {
        array_walk(
            $assets,
            function (&$v, $k) {
                /** @var AssetInterface $v */
                $v = [$v->getPriority(), $k, $v];
            }
        );

        rsort($assets);

        array_walk(
            $assets,
            function (&$v) {
                $v = $v[2];
            }
        );

        return $assets;
    }
}

Revert asset sort priority so higher numbers have higher priority


<?php
namespace ParagonIE\Halite\Asymmetric;

use ParagonIE\Halite\Alerts\{
    CannotPerformOperation,
    InvalidType
};
use ParagonIE\Halite\HiddenString;
use ParagonIE\Halite\Key;

/**
 * Class SecretKey
 * @package ParagonIE\Halite\Asymmetric
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
class SecretKey extends Key
{
    /**
     * SecretKey constructor.
     * @param HiddenString $keyMaterial - The actual key data
     *
     * @throws CannotPerformOperation
     * @throws InvalidType
     */
    public function __construct(HiddenString $keyMaterial)
    {
        parent::__construct($keyMaterial);
        $this->isAsymmetricKey = true;
    }

    /**
     * See the appropriate derived class.
     * @throws CannotPerformOperation
     * @return void
     */
    public function derivePublicKey()
    {
        throw new CannotPerformOperation(
            'This is not implemented in the base class'
        );
    }
}

<?php
namespace ParagonIE\Halite\Asymmetric;

use ParagonIE\Halite\Alerts\{
    CannotPerformOperation,
    InvalidType
};
use ParagonIE\Halite\HiddenString;
use ParagonIE\Halite\Key;

/**
 * Class SecretKey
 * @package ParagonIE\Halite\Asymmetric
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
class SecretKey extends Key
{
    /**
     * SecretKey constructor.
     * @param HiddenString $keyMaterial - The actual key data
     *
     * @throws CannotPerformOperation
     * @throws InvalidType
     */
    public function __construct(HiddenString $keyMaterial)
    {
        parent::__construct($keyMaterial);
        $this->isAsymmetricKey = true;
    }

    /**
     * See the appropriate derived class.
     * @throws CannotPerformOperation
     * @return mixed
     */
    public function derivePublicKey()
    {
        throw new CannotPerformOperation(
            'This is not implemented in the base class'
        );
    }
}

Use different type hint here.

Use different type hint here.