<?php

namespace Doctrine\Tests\EventListener;

use Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs;
use Doctrine\ORM\Mapping\ClassMetadata;

class CacheMetadataListener
{
    /**
     * @param \Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs $event
     */
    public function loadClassMetadata(LoadClassMetadataEventArgs $event)
    {
        $metadata = $event->getClassMetadata();
        $cache    = array(
            'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE
        );

        /** @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */
        if (strstr($metadata->name, 'Doctrine\Tests\Models\Cache')) {
            return;
        }

        if ($metadata->isVersioned) {
            return;
        }

        $metadata->enableCache($cache);

        foreach ($metadata->associationMappings as $mapping) {
            $metadata->enableAssociationCache($mapping['fieldName'], $cache);
        }
    }
}

<?php

namespace Doctrine\Tests\EventListener;

use Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadata;

class CacheMetadataListener
{

    /**
     * Tracks which entities we have already forced caching enabled on. This is
     * important to avoid some potential infinite-recursion issues.
     * @var array
     */
    protected $enabledItems = array();

    /**
     * @param \Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs $event
     */
    public function loadClassMetadata(LoadClassMetadataEventArgs $event)
    {
        $metadata = $event->getClassMetadata();
        $em = $event->getObjectManager();

        /** @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */
        if (strstr($metadata->name, 'Doctrine\Tests\Models\Cache')) {
            return;
        }

        if( ! $em instanceof EntityManager){
            return;
        }

        $this->enableCaching($metadata, $em);
    }

    /**
     * @param ClassMetadata $metadata
     * @param EntityManager $em
     */
    protected function enableCaching(ClassMetadata $metadata, EntityManager $em){

        if(array_key_exists($metadata->getName(), $this->enabledItems)){
            return; // Already handled in the past
        }

        $cache    = array(
            'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE
        );

        if ($metadata->isVersioned) {
            return;
        }

        $metadata->enableCache($cache);

        $this->enabledItems[$metadata->getName()] = $metadata;

        /*
         * Only enable association-caching when the target has already been
         * given caching settings
         */
        foreach ($metadata->associationMappings as $mapping) {

            $targetMeta = $em->getClassMetadata($mapping['targetEntity']);
            $this->enableCaching($targetMeta, $em);

            if(array_key_exists($targetMeta->getName(), $this->enabledItems)){
                $metadata->enableAssociationCache($mapping['fieldName'], $cache);
            }
        }
    }
}

Change the test listener than layers on second-level-caching so that it is more conservative, only turning on caching-associations when it knows the target entity is cache-able.


<?php
/**
 * Public store inforamtion in JSON format
 *
 * @author 	Chris Rogers
 * @since 	2019-02-22
 */

class NaturalRemedyCo_NRCLayout_IndexController extends Mage_Core_Controller_Front_Action
{
	/**
	 * @var Mage_Core_Model_Store
	 */
	protected $_store;

	/**
	 * Magento's specific construtor (notice the single underscore)
	 */
	public function _construct()
	{
		$this->_store = Mage::app()->getStore();
	}

	/**
	 * Return store info as JSON using layout file <info_index_index>
	 * @return 	JSON
	 * @see 	Useful debugging: "Zend_Debug::dump($this->getLayout()->getUpdate()->getHandles()); exit;"
	 */
	public function indexAction()
	{
		$this->getResponse()->setHeader('Content-type', 'application/json');
		$this->loadLayout();
		// $this->getResponse()->setBody();
		$this->renderLayout();
	}
}
?>

<?php
/**
 * Public store inforamtion in JSON format
 *
 * @author 	Chris Rogers
 * @since 	2019-02-22
 */

class NaturalRemedyCo_NRCLayout_IndexController extends Mage_Core_Controller_Front_Action
{
	/**
	 * @var Mage_Core_Model_Store
	 */
	protected $_store;

	/**
	 * Magento's specific construtor (notice the single underscore)
	 */
	public function _construct()
	{
		header("Access-Control-Allow-Origin: *");
		$this->_store = Mage::app()->getStore();
	}

	/**
	 * Return store info as JSON using layout file <info_index_index>
	 * @return 	JSON
	 * @see 	Useful debugging: "Zend_Debug::dump($this->getLayout()->getUpdate()->getHandles()); exit;"
	 */
	public function indexAction()
	{
		$this->getResponse()->setHeader('Content-type', 'application/json');
		$this->loadLayout();
		// $this->getResponse()->setBody();
		$this->renderLayout();
	}
}
?>

Fix CORS issue with React App

Fix CORS issue with React App


<?php

namespace CSBill\CoreBundle\Menu\Core;

use CSBill\CoreBundle\Menu\Builder\BuilderInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
use SYmfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;

class AuthenticatedMenu extends ContainerAware implements BuilderInterface
{
    public function validate()
    {
        try {
            $security = $this->container->get('security.context');
        } catch (AuthenticationCredentialsNotFoundException $e) {
            return false;
        }

        return $security->isGranted('IS_AUTHENTICATED_FULLY');
    }
}

<?php

namespace CSBill\CoreBundle\Menu\Core;

use CSBill\CoreBundle\Menu\Builder\BuilderInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
use SYmfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;

class AuthenticatedMenu extends ContainerAware implements BuilderInterface
{
    public function validate()
    {
        try {
            $security = $this->container->get('security.context');
        } catch (AuthenticationCredentialsNotFoundException $e) {
            return false;
        }

        return $security->isGranted('IS_AUTHENTICATED_REMEMBERED');
    }
}

[CoreBundle] Change authenticated menu to check for authenticated remembered


<?php
namespace Sprockets\Filter;

use Sprockets\File;

class Scss extends Base
{
	private $parser;

	public function __construct()
	{
		$previous_error_reporting = error_reporting();
		error_reporting(E_ERROR);

		$this->parser = new \SassParser(array('syntax' => \SassFile::SCSS));

		error_reporting($previous_error_reporting);
	}

	public function __invoke($content, $file, $dir, $vars)
	{
		$content = preg_replace_callback('/@import\s+["\']([a-z0-9\/]+)["\']/i', function ($match) use ($dir)
		{
			if ($match[1] == '/')
				$filename = $match;
			else
				$filename = $dir . '/' . $match[1];

			if ($this->pipeline->locator->hasFile($filename, 'css'))
				$file = new File($filename . '.css');
			else if ($this->pipeline->locator->hasFile($index_file = $filename . '/index', 'css'))
				$file = new File($index_file . '.css');
			else
				throw new \Sprockets\Exception\FileNotFound($file, 'css');

			return '@import "' . str_replace('//', '/', $file->getFilepath()) . '"';
		}, $content);

		$content = $this->parser->toCss($content, false);

		return $content;
	}
}

<?php
namespace Sprockets\Filter;

use Sprockets\File;

class Scss extends Base
{
	private $parser;

	public function __construct()
	{
		$previous_error_reporting = error_reporting();
		error_reporting(E_ERROR);

		$this->parser = new \SassParser(array('syntax' => \SassFile::SCSS));

		error_reporting($previous_error_reporting);
	}

	public function __invoke($content, $file, $dir, $vars)
	{
		$content = preg_replace_callback('/@import\s+["\']([a-z0-9\/]+)["\']/i', function ($match) use ($dir)
		{
			if ($match[1] == '/')
				$filename = $match;
			else
				$filename = $dir . '/' . $match[1];

			if ($this->pipeline->locator->hasFile($filename, 'css'))
				$file = new File($filename . '.css');
			else if ($this->pipeline->locator->hasFile($index_file = $filename . '/index', 'css'))
				$file = new File($index_file . '.css');
			else
				throw new \Sprockets\Exception\FileNotFound($filename, 'css');

			return '@import "' . str_replace('//', '/', $file->getFilepath()) . '"';
		}, $content);

		$content = $this->parser->toCss($content, false);

		return $content;
	}
}

Fix exception to use the filename instead of a blank string.

The exception was not reporting the problem file due to using the wrong
variable.


<?php

use Rad\Application;

require __DIR__ . '/../vendor/autoload.php';
require dirname(__DIR__) . '/src/Config/paths.php';

Application::getInstance()->runCli();

#!/usr/bin/env php
<?php

use Rad\Application;

require __DIR__ . '/../vendor/autoload.php';
require dirname(__DIR__) . '/src/App/Resource/config/paths.php';

Application::getInstance()->runCli();

Add shebang and fix config path

Add shebang and fix config path


<?php

namespace ClientBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use ClientBundle\Entity\User;

/**
 * Class LoadUserData
 */
class LoadUserData implements FixtureInterface
{

    private $userName = 'testadmin';
    private $userPass = 'testpass';

    /**
     * @return string
     */
    public function getUserName()
    {
        return $this->userName;
    }

    /**
     * @return string
     */
    public function getUserPass()
    {
        return $this->userPass;
    }

    /**
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $userAdmin = new User();
        $userAdmin->setUsername($this->userName);
        $userAdmin->setPlainPassword($this->userPass);
        $userAdmin->setEmail('test@email.ua');
        $userAdmin->setSuperAdmin(true);
        $userAdmin->setEnabled(true);

        $manager->persist($userAdmin);
        $manager->flush();
    }
}

<?php

namespace ClientBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use ClientBundle\Entity\User;

/**
 * Class LoadUserData
 */
class LoadUserData implements FixtureInterface
{

    private $userName = 'sysadmin';
    private $userPass = 'sysadmin';

    /**
     * @return string
     */
    public function getUserName()
    {
        return $this->userName;
    }

    /**
     * @return string
     */
    public function getUserPass()
    {
        return $this->userPass;
    }

    /**
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $userAdmin = new User();
        $userAdmin->setUsername($this->userName);
        $userAdmin->setPlainPassword($this->userPass);
        $userAdmin->setEmail('test@email.ua');
        $userAdmin->setSuperAdmin(true);
        $userAdmin->setEnabled(true);

        $manager->persist($userAdmin);
        $manager->flush();
    }
}

Edit testadmin name and pass

Edit testadmin name and pass


<?php

use Illuminate\Support\Str;

class SupportStrTest extends PHPUnit_Framework_TestCase
{
  /**
   * Test the Str::limitWords method.
   *
   * @group laravel
   */
  public function testStringCanBeLimitedByWords()
  {
    $this->assertEquals('Taylor...', Str::limitWords('Taylor Otwell', 1));
    $this->assertEquals('Taylor___', Str::limitWords('Taylor Otwell', 1, '___'));
    $this->assertEquals('Taylor Otwell', Str::limitWords('Taylor Otwell', 3));
  }
}

<?php

use Illuminate\Support\Str;

class SupportStrTest extends PHPUnit_Framework_TestCase
{
  /**
   * Test the Str::words method.
   *
   * @group laravel
   */
  public function testStringCanBeLimitedByWords()
  {
    $this->assertEquals('Taylor...', Str::words('Taylor Otwell', 1));
    $this->assertEquals('Taylor___', Str::words('Taylor Otwell', 1, '___'));
    $this->assertEquals('Taylor Otwell', Str::words('Taylor Otwell', 3));
  }
}

Rename method Str::limitWords to Str::words


<?

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

	public $dbRefreshTables = array(
		'Blocks',
		'CollectionVersionBlocksOutputCache',
		'PermissionAccessList'
	);

	public function run() {
		$sp = Page::getByPath('/dashboard/system/seo/excluded');
		if (!is_object($sp) || $sp->isError()) {
			$sp = SinglePage::add('/dashboard/system/seo/excluded');
			$sp->update(array('cName'=>t('Excluded URL Word List')));
		}
		$bt = BlockType::getByHandle('next_previous');
		if (is_object($bt)) {
			$bt->refresh();
		}

		$db = Loader::db();
		$columns = $db->MetaColumns('Pages');
		if (isset($columns['PTID'])) {
			$db->Execute('alter table Pages drop column ptID');
		}
		if (isset($columns['CTID'])) {
			$db->Execute('alter table Pages drop column ctID');
		}

		$bt = BlockType::getByHandle('search');
		if (is_object($bt)) {
			$bt->refresh();
		}

	}

}

<?

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

	public $dbRefreshTables = array(
		'Blocks',
		'CollectionVersionBlocksOutputCache',
		'PermissionAccessList'
	);

	public function run() {
		$sp = Page::getByPath('/dashboard/system/seo/excluded');
		if (!is_object($sp) || $sp->isError()) {
			$sp = SinglePage::add('/dashboard/system/seo/excluded');
			$sp->update(array('cName'=>t('Excluded URL Word List')));
			$sp->setAttribute('meta_keywords', t('pretty, slug'));
		}
		$bt = BlockType::getByHandle('next_previous');
		if (is_object($bt)) {
			$bt->refresh();
		}

		$db = Loader::db();
		$columns = $db->MetaColumns('Pages');
		if (isset($columns['PTID'])) {
			$db->Execute('alter table Pages drop column ptID');
		}
		if (isset($columns['CTID'])) {
			$db->Execute('alter table Pages drop column ctID');
		}

		$bt = BlockType::getByHandle('search');
		if (is_object($bt)) {
			$bt->refresh();
		}

	}

}

Add page keywords for new 5.6.1 page

Add page keywords for new 5.6.1 page


<?php

namespace Craft;

/**
 * YouTube Video Model.
 *
 * Contains video data.
 *
 * @author    Bob Olde Hampsink <b.oldehampsink@itmundi.nl>
 * @copyright Copyright (c) 2015, Itmundi
 * @license   MIT
 *
 * @link      http://github.com/boboldehampsink
 */
class YouTube_VideoModel extends BaseModel
{
    /**
     * YouTube Embed URL prefix.
     */
    const YOUTUBE_EMBED_PREFIX = 'https://www.youtube.com/embed/';

    /**
     * YouTube Watch URL prefix.
     */
    const YOUTUBE_WATCH_PREFIX = 'https://www.youtube.com/watch?v=';

    /**
     * Define model attributes.
     *
     * @return array
     */
    public function defineAttributes()
    {
        return array(
            'id' => AttributeType::String,
        );
    }

    /**
     * Return full YouTube (embed) url.
     *
     * @param bool $embed
     *
     * @return string
     */
    public function getUrl($embed = true)
    {
        if ($embed) {
            return self::YOUTUBE_EMBED_PREFIX.$this->id;
        } else {
            return self::YOUTUBE_WATCH_PREFIX.$this->id;
        }
    }
}

<?php

namespace Craft;

/**
 * YouTube Video Model.
 *
 * Contains video data.
 *
 * @author    Bob Olde Hampsink <b.oldehampsink@itmundi.nl>
 * @copyright Copyright (c) 2015, Itmundi
 * @license   MIT
 *
 * @link      http://github.com/boboldehampsink
 */
class YouTube_VideoModel extends BaseModel
{
    /**
     * YouTube Embed URL prefix.
     */
    const YOUTUBE_EMBED_PREFIX = 'https://www.youtube.com/embed/';

    /**
     * YouTube Watch URL prefix.
     */
    const YOUTUBE_WATCH_PREFIX = 'https://www.youtube.com/watch?v=';

    /**
     * Define model attributes.
     *
     * @return array
     */
    public function defineAttributes()
    {
        return array(
            'id' => AttributeType::String,
        );
    }

    /**
     * Return ID as string.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->id;
    }

    /**
     * Return full YouTube (embed) url.
     *
     * @param bool $embed
     *
     * @return string
     */
    public function getUrl($embed = true)
    {
        if ($embed) {
            return self::YOUTUBE_EMBED_PREFIX.$this->id;
        } else {
            return self::YOUTUBE_WATCH_PREFIX.$this->id;
        }
    }
}

Return video model ID as model's string representation


<?php

class Meanbee_ConfigPoweredCss_Adminhtml_ConfigPoweredCssController extends Mage_Adminhtml_Controller_Action
{
    public function regenerateAction()
    {
        /** @var Mage_Adminhtml_Model_Session $session */
        $session = Mage::getSingleton('adminhtml/session');

        /** @var Meanbee_ConfigPoweredCss_Model_Css $css */
        $css = Mage::getModel('meanbee_configpoweredcss/css');

        $stores = Mage::app()->getStores();
        foreach ($stores as $storeId => $store) {
            try {
                Mage::app()->setCurrentStore($storeId);
                $css->publish($storeId);
            } catch (Exception $e) {
                $session->addError($e->getMessage());
                $this->_redirect('*/cache');
                return;
            }
        }

        Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

        $session->addSuccess("Successfully regenerated CSS file(s)");
        $this->_redirect('*/cache');
    }
}

<?php

class Meanbee_ConfigPoweredCss_Adminhtml_ConfigPoweredCssController extends Mage_Adminhtml_Controller_Action
{
    public function regenerateAction()
    {
        /** @var Mage_Adminhtml_Model_Session $session */
        $session = Mage::getSingleton('adminhtml/session');

        /** @var Meanbee_ConfigPoweredCss_Model_Css $css */
        $css = Mage::getModel('meanbee_configpoweredcss/css');

        $stores = Mage::app()->getStores();
        foreach ($stores as $storeId => $store) {
            try {
                Mage::app()->setCurrentStore($storeId);
                $css->publish($storeId);
            } catch (Exception $e) {
                Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
                $session->addError($e->getMessage());
                $this->_redirect('*/cache');
                return;
            }
        }

        Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

        $session->addSuccess("Successfully regenerated CSS file(s)");
        $this->_redirect('*/cache');
    }
}

Reset current store when an exception is caught


<?php

namespace Backend\Modules\Authentication\Actions;

use Backend\Core\Engine\Base\Action as BackendBaseAction;
use Backend\Core\Engine\Authentication as BackendAuthentication;
use Backend\Core\Engine\Model as BackendModel;

/**
 * This is the logout-action, it will logout the current user
 */
class Logout extends BackendBaseAction
{
    public function execute(): void
    {
        parent::execute();
        BackendAuthentication::logout();

        // redirect to login-screen
        $this->redirect(BackendModel::createUrlForAction('Index', $this->getModule()));
    }
}

<?php

namespace Backend\Modules\Authentication\Actions;

use Backend\Core\Engine\Base\Action as BackendBaseAction;
use Backend\Core\Engine\Authentication as BackendAuthentication;
use Backend\Core\Engine\Model as BackendModel;

/**
 * This is the logout-action, it will logout the current user
 */
class Logout extends BackendBaseAction
{
    public function execute(): void
    {
        parent::execute();
        $this->checkToken();
        BackendAuthentication::logout();

        // redirect to login-screen
        $this->redirect(BackendModel::createUrlForAction('Index', $this->getModule()));
    }
}

Check token before logging the backend user out


<?php namespace Algorit\Synchronizer;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\ServiceProvider;
use Algorit\Synchronizer\Request\Config;
use Algorit\Synchronizer\Storage\Sync;
use Algorit\Synchronizer\Storage\SyncEloquentRepository as SyncRepository;

class SynchronizerServiceProvider extends ServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->package('algorit/synchronizer');
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['synchronizer'] = $this->app->share(function($app)
		{
			$sync = new SyncRepository(new Sync);

			$builder = new Builder(new Sender, new Receiver, $sync);

			return new Loader(new Container, $builder, new Config($app['files']));
		});
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array();
	}

}

<?php namespace Algorit\Synchronizer;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\ServiceProvider;
use Algorit\Synchronizer\Request\Config;
use Algorit\Synchronizer\Storage\Sync;
use Algorit\Synchronizer\Storage\SyncEloquentRepository as SyncRepository;

class SynchronizerServiceProvider extends ServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->package('algorit/synchronizer');
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['synchronizer'] = $this->app->share(function()
		{
			$sync = new SyncRepository(new Sync);

			$builder = new Builder(new Sender, new Receiver, $sync);

			return new Loader(new Container, $builder, new Config(new Filesystem));
		});
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array();
	}

}

Use a new instance of Filesystem

Use a new instance of Filesystem


<?php

/*
 * This file is part of the Sonata Project package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\CoreBundle\Serializer;

if (!class_exists(\Sonata\Serializer\SerializerHandlerInterface::class, false)) {
    @trigger_error(
        'The '.__NAMESPACE__.'\SerializerHandlerInterface class is deprecated since version 3.x and will be removed in 4.0.'
        .' Use Sonata\Serializer\SerializerHandlerInterface instead.',
        E_USER_DEPRECATED
    );
}

class_alias(
    \Sonata\Serializer\SerializerHandlerInterface::class,
    __NAMESPACE__.'\SerializerHandlerInterface'
);

if (false) {
    /**
     * @deprecated Since version 3.x, to be removed in 4.0.
     */
    interface SerializerHandlerInterface extends \Sonata\Serializer\SerializerHandlerInterface
    {
        /**
         * @return string
         */
        public static function getType();
    }
}

<?php

/*
 * This file is part of the Sonata Project package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\CoreBundle\Serializer;

if (!interface_exists(\Sonata\Serializer\SerializerHandlerInterface::class, false)) {
    @trigger_error(
        'The '.__NAMESPACE__.'\SerializerHandlerInterface class is deprecated since version 3.x and will be removed in 4.0.'
        .' Use Sonata\Serializer\SerializerHandlerInterface instead.',
        E_USER_DEPRECATED
    );
}

class_alias(
    \Sonata\Serializer\SerializerHandlerInterface::class,
    __NAMESPACE__.'\SerializerHandlerInterface'
);

if (false) {
    /**
     * @deprecated Since version 3.x, to be removed in 4.0.
     */
    interface SerializerHandlerInterface extends \Sonata\Serializer\SerializerHandlerInterface
    {
        /**
         * @return string
         */
        public static function getType();
    }
}

Use the correct function to trigger autoload

I think this must be pedantic because there is no way you could know it
is actually an interface before loading the file.


<?php

declare(strict_types=1);

namespace BlockHorizons\BlockSniper\brush\types;

use BlockHorizons\BlockSniper\brush\BaseType;
use pocketmine\block\Block;
use pocketmine\math\Facing;

/*
 * Expands the terrain with blocks below it.
 */

class ExpandType extends BaseType{

	public const ID = self::TYPE_EXPAND;

	/**
	 * @return \Generator
	 */
	public function fill() : \Generator{
		$undoBlocks = [];
		foreach($this->blocks as $block){
			/** @var Block $block */
			if($block->getId() === Block::AIR){
				$closedSides = 0;
				foreach(Facing::ALL as $direction){
					$sideBlock = $this->side($block, $direction);
					if($sideBlock->getId() !== Block::AIR){
						$closedSides++;
					}
				}
				if($closedSides >= 2){
					$undoBlocks[] = $block;
				}
			}
		}
		foreach($undoBlocks as $selectedBlock){
			yield $selectedBlock;
			$this->putBlock($selectedBlock, $this->randomBrushBlock());
		}
	}

	/**
	 * @return string
	 */
	public function getName() : string{
		return "Expand";
	}

	/**
	 * @return bool
	 */
	public function usesBlocks() : bool{
		return false;
	}
}

<?php

declare(strict_types=1);

namespace BlockHorizons\BlockSniper\brush\types;

use BlockHorizons\BlockSniper\brush\BaseType;
use pocketmine\block\Block;
use pocketmine\math\Facing;

/*
 * Expands the terrain with blocks below it.
 */

class ExpandType extends BaseType{

	public const ID = self::TYPE_EXPAND;

	/**
	 * @return \Generator
	 */
	public function fill() : \Generator{
		$undoBlocks = [];
		foreach($this->blocks as $block){
			/** @var Block $block */
			if($block->getId() === Block::AIR){
				$closedSides = 0;
				foreach(Facing::ALL as $direction){
					$sideBlock = $this->side($block, $direction);
					if($sideBlock->getId() !== Block::AIR){
						$closedSides++;
					}
				}
				if($closedSides >= 2){
					$undoBlocks[] = $block;
				}
			}
		}
		foreach($undoBlocks as $selectedBlock){
			yield $selectedBlock;
			$this->putBlock($selectedBlock, $this->randomBrushBlock());
		}
	}

	/**
	 * @return string
	 */
	public function getName() : string{
		return "Expand";
	}
}

Expand type does use brush blocks.

Expand type does use brush blocks.


<?php
declare(strict_types=1);

namespace PerFi\PerFiBundle\EventListener;

use Avanzu\AdminThemeBundle\Event\SidebarMenuEvent;
use Avanzu\AdminThemeBundle\Model\MenuItemModel;
use Symfony\Component\HttpFoundation\Request;

class MenuItemListener
{
    public function onSetupMenu(SidebarMenuEvent $event)
    {
        $request = $event->getRequest();

        foreach ($this->getMenu($request) as $item) {
            $event->addItem($item);
        }
    }

    protected function getMenu(Request $request)
    {
        $menuItems = array(
            $homepage = new MenuItemModel('homepage', 'Home', 'homepage', [], 'iconclasses fa fa-home'),
            $accounts = new MenuItemModel('accounts', 'Accounts', null, [], 'iconclasses fa fa-bank'),
        );

        $accounts->addChild(
            new MenuItemModel('list_accounts', 'List of accounts', 'accounts', [], 'iconclasses fa fa-list')
        );

        $accounts->addChild(
            new MenuItemModel('create_account', 'Create account', 'create_account', [], 'iconclasses fa fa-plus')
        );

        return $this->activateByRoute($request->get('_route'), $menuItems);
    }

    protected function activateByRoute($route, $items)
    {
        foreach($items as $item) {
            if($item->hasChildren()) {
                $this->activateByRoute($route, $item->getChildren());
            } else {
                if($item->getRoute() == $route) {
                    $item->setIsActive(true);
                }
            }
        }

        return $items;
    }
}

<?php
declare(strict_types=1);

namespace PerFi\PerFiBundle\EventListener;

use Avanzu\AdminThemeBundle\Event\SidebarMenuEvent;
use Avanzu\AdminThemeBundle\Model\MenuItemModel;
use Symfony\Component\HttpFoundation\Request;

class MenuItemListener
{
    public function onSetupMenu(SidebarMenuEvent $event)
    {
        $request = $event->getRequest();

        foreach ($this->getMenu($request) as $item) {
            $event->addItem($item);
        }
    }

    protected function getMenu(Request $request)
    {
        $menuItems = array(
            $homepage = new MenuItemModel('menu-homepage', 'Home', 'homepage', [], 'iconclasses fa fa-home'),
            $accounts = new MenuItemModel('menu-accounts', 'Accounts', null, [], 'iconclasses fa fa-bank'),
        );

        $accounts->addChild(
            new MenuItemModel('menu-list_accounts', 'List of accounts', 'accounts', [], 'iconclasses fa fa-list')
        );

        $accounts->addChild(
            new MenuItemModel('menu-create_account', 'Create account', 'create_account', [], 'iconclasses fa fa-plus')
        );

        return $this->activateByRoute($request->get('_route'), $menuItems);
    }

    protected function activateByRoute($route, $items)
    {
        foreach($items as $item) {
            if($item->hasChildren()) {
                $this->activateByRoute($route, $item->getChildren());
            } else {
                if($item->getRoute() == $route) {
                    $item->setIsActive(true);
                }
            }
        }

        return $items;
    }
}

Prepend menu- to all menu item IDs

Prepend menu- to all menu item IDs


<?php

final class PhabricatorAuthMessagePHIDType extends PhabricatorPHIDType {

  const TYPECONST = 'AMSG';

  public function getTypeName() {
    return pht('Auth Message');
  }

  public function newObject() {
    return new PhabricatorAuthMessage();
  }

  public function getPHIDTypeApplicationClass() {
    return 'PhabricatorAuthApplication';
  }

  protected function buildQueryForObjects(
    PhabricatorObjectQuery $query,
    array $phids) {

    return id(new PhabricatorAuthMessageQuery())
      ->withPHIDs($phids);
  }

  public function loadHandles(
    PhabricatorHandleQuery $query,
    array $handles,
    array $objects) {
    return;
  }

}

<?php

final class PhabricatorAuthMessagePHIDType extends PhabricatorPHIDType {

  const TYPECONST = 'AMSG';

  public function getTypeName() {
    return pht('Auth Message');
  }

  public function newObject() {
    return new PhabricatorAuthMessage();
  }

  public function getPHIDTypeApplicationClass() {
    return 'PhabricatorAuthApplication';
  }

  protected function buildQueryForObjects(
    PhabricatorObjectQuery $query,
    array $phids) {

    return id(new PhabricatorAuthMessageQuery())
      ->withPHIDs($phids);
  }

  public function loadHandles(
    PhabricatorHandleQuery $query,
    array $handles,
    array $objects) {

    foreach ($handles as $phid => $handle) {
      $message = $objects[$phid];
      $handle->setURI($message->getURI());
    }
  }

}

Set a URI on Auth Messages, so the "Change Details" dialog from the transaction record has a cancel button

Summary:
If you edit an auth message in Auth > Customize Messages, then click "Show Details" in the transaction record, the resulting dialog uses the object's handle's URI to generate a "cancel" button.

Since these handles currently have no URI, the dialog currently has no cancel/done button to close it.

Test Plan: Edited an auth message, clicked "Show Details", was now able to click "Done" to close the dialog.

Reviewers: amckinley

Reviewed By: amckinley

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


<?php
namespace Payum\Core\Bridge\Symfony\Security;

use Payum\Core\Registry\StorageRegistryInterface;
use Payum\Core\Security\AbstractGenericTokenFactory;
use Payum\Core\Security\TokenInterface;
use Payum\Core\Storage\StorageInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class TokenFactory extends AbstractGenericTokenFactory
{
    /**
     * @var \Symfony\Component\Routing\RouterInterface
     */
    protected $urlGenerator;

    /**
     * @param UrlGeneratorInterface $urlGenerator
     * @param StorageInterface $tokenStorage
     * @param StorageRegistryInterface $storageRegistry
     * @param string $capturePath
     * @param string $notifyPath
     */
    public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath)
    {
        $this->urlGenerator = $urlGenerator;

        parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath);
    }

    /**
     * @param string $path
     * @param array $parameters
     *
     * @return string
     */
    protected function generateUrl($path, array $parameters = array())
    {
        return $this->urlGenerator->generate($path, $parameters, UrlGeneratorInterface::ABSOLUTE_URL);
    }
}

<?php
namespace Payum\Core\Bridge\Symfony\Security;

use Payum\Core\Registry\StorageRegistryInterface;
use Payum\Core\Security\AbstractGenericTokenFactory;
use Payum\Core\Storage\StorageInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class TokenFactory extends AbstractGenericTokenFactory
{
    /**
     * @var \Symfony\Component\Routing\RouterInterface
     */
    protected $urlGenerator;

    /**
     * @param UrlGeneratorInterface $urlGenerator
     * @param StorageInterface $tokenStorage
     * @param StorageRegistryInterface $storageRegistry
     * @param string $capturePath
     * @param string $notifyPath
     */
    public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath)
    {
        $this->urlGenerator = $urlGenerator;

        parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath);
    }

    /**
     * @param string $path
     * @param array $parameters
     *
     * @return string
     */
    protected function generateUrl($path, array $parameters = array())
    {
        return $this->urlGenerator->generate($path, $parameters, true);
    }
}

[security][symfony] Fix fatal error on old symfony versions.

PHP Fatal error:  Undefined class constant 'ABSOLUTE_URL' in ....


<form action="<?php echo url_for('account/login') ?>" method="POST">
    <?php echo $form['_csrf_token']; ?>

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

    <?php echo $form['remember_me']->renderError() ?>
    <?php echo $form['remember_me'] ?>
    <?php echo $form['remember_me']->renderLabel(null, array('id' => 'remember_label')) ?>

    <?php echo link_to('Change',"account/password"); ?>
    ·
    <?php echo link_to('I forgot',"http://limecast.com/tracker/reset-password"); ?>

  <input type="submit" class="submit" value="Sign in" />
</form>

<form action="<?php echo url_for('account/login') ?>" method="POST">
    <?php echo $form['_csrf_token']; ?>

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

    <?php echo link_to('Change',"account/password"); ?>
    ·
    <?php echo link_to('I forgot',"http://limecast.com/tracker/reset-password"); ?>

    <?php echo $form['remember_me']->renderError() ?>
    <?php echo $form['remember_me'] ?>
    <?php echo $form['remember_me']->renderLabel(null, array('id' => 'remember_label')) ?>

  <input type="submit" class="submit" value="Sign in" />
</form>

Change and forget links go above Remeber me, not after


<?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;

trigger_deprecation('symfony/security-core', '5.3', sprintf('The "%s" interface is deprecated, use "%s" on hasher implementations that deal with salts instead.', UserPasswordEncoderInterface::class, UserPasswordHasherInterface::class));

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

/**
 * UserPasswordEncoderInterface is the interface for the password encoder service.
 *
 * @author Ariel Ferrandini <arielferrandini@gmail.com>
 *
 * @deprecated since Symfony 5.3, use {@link UserPasswordHasherInterface} instead
 */
interface UserPasswordEncoderInterface
{
    /**
     * Encodes the plain password.
     *
     * @return string The encoded password
     */
    public function encodePassword(UserInterface $user, string $plainPassword);

    /**
     * @return bool true if the password is valid, false otherwise
     */
    public function isPasswordValid(UserInterface $user, string $raw);

    /**
     * Checks if an encoded password would benefit from rehashing.
     */
    public function needsRehash(UserInterface $user): bool;
}

<?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;

trigger_deprecation('symfony/security-core', '5.3', sprintf('The "%s" interface is deprecated, use "%s" instead.', UserPasswordEncoderInterface::class, UserPasswordHasherInterface::class));

use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * UserPasswordEncoderInterface is the interface for the password encoder service.
 *
 * @author Ariel Ferrandini <arielferrandini@gmail.com>
 *
 * @deprecated since Symfony 5.3, use {@link UserPasswordHasherInterface} instead
 */
interface UserPasswordEncoderInterface
{
    /**
     * Encodes the plain password.
     *
     * @return string The encoded password
     */
    public function encodePassword(UserInterface $user, string $plainPassword);

    /**
     * @return bool true if the password is valid, false otherwise
     */
    public function isPasswordValid(UserInterface $user, string $raw);

    /**
     * Checks if an encoded password would benefit from rehashing.
     */
    public function needsRehash(UserInterface $user): bool;
}

Fix some broken BC layers

[Security] Fix some broken BC layers


<?php
    date_default_timezone_set('America/Chicago');

    $file = $_FILES['uploadedfile']['tmp_name'];
    $names = $_FILES['uploadedfile']['name'];

    $target = 'In/'.$names;
    move_uploaded_file( $_FILES['uploadedfile']['tmp_name'], $target);

    $command = escapeshellcmd("python2.7 read.py $target");
    $output = shell_exec($command);
    echo "<pre>";
    print_r($output);
    echo "</pre>";

//  Re-route to directory to download the file.
//    $domain = $_SERVER['HTTP_HOST'];
//    $path = implode("/",$fullPath);
//    $toLogin = 'http://'.$domain.$path."/out";
//    header('Location:'.$toLogin);
?>

<?php
    date_default_timezone_set('America/Chicago');
    $dir = $_SERVER['HTTP_HOST']['DOCUMENT_ROOT'];

    $file = $_FILES['uploadedfile']['tmp_name'];
    $names = $_FILES['uploadedfile']['name'];

    $target = $dir.'In/'.$names;
    move_uploaded_file( $_FILES['uploadedfile']['tmp_name'], $target);

    $command = escapeshellcmd("python2.7 read.py $target");
    $output = shell_exec($command);
    echo "<pre>";
    print_r($output);
    echo "</pre>";

//  Re-route to directory to download the file.
//    $domain = $_SERVER['HTTP_HOST'];
//    $path = implode("/",$fullPath);
//    $toLogin = 'http://'.$domain.$path."/out";
//    header('Location:'.$toLogin);
?>

Correct the directory to full path

Correct the directory to full path


<?php /** @var \nochso\WriteMe\Markdown\InteractiveTemplate $this */ ?>
<?php $this->ask('composer.name', 'Enter the name as used on packagist', null, '/.+/'); ?>
# @composer.name@

<?php if ($this->ask('composer.description', 'Enter a one-line description of the project (optional)') !== ''): ?>
@composer.description@
<?php endif; ?>

<?php if ($this->getStdio()->confirm('Would you like to add table of contents of all sections?')): ?>
<?php $this->askForCustomPlaceholderOptionList('toc'); ?>
@toc@
<?php endif; ?>

# Installation
Installation through [Composer](https://getcomposer.org/) is preferred:

    composer require @composer.name@

<?php if ($this->getStdio()->confirm('Would you like to add a summary of all PHP classes and their methods?')): ?>
<?php $this->askForCustomPlaceholderOptionList('api'); ?>
# API summary
@api.summary@
<?php endif; ?>

<?php if ($this->ask('license.name', 'Enter the license name e.g. MIT, BSD2, etc. (optional)') !== ''): ?>
# License
This project is released under the @license.name@ license.

<?php endif; ?>

<?php /** @var \nochso\WriteMe\Markdown\InteractiveTemplate $this */ ?>
<?php $this->ask('composer.name', 'Enter the name as used on packagist', null, '/.+/'); ?>
# @composer.name@

<?php if ($this->ask('composer.description', 'Enter a one-line description of the project (optional)') !== ''): ?>
@composer.description@
<?php endif; ?>

<?php if ($this->getStdio()->confirm('Would you like to add table of contents of all sections?')): ?>
<?php $this->askForCustomPlaceholderOptionList('toc'); ?>
@toc@
<?php endif; ?>

# Installation
Installation through [Composer](https://getcomposer.org/) is preferred:

    composer require @composer.name@

<?php if ($this->getStdio()->confirm('Would you like to add a summary of all PHP classes and their methods?')): ?>
<?php $this->askForCustomPlaceholderOptionList('api'); ?>
# API summary
@api('summary')@
<?php endif; ?>

<?php if ($this->ask('license.name', 'Enter the license name e.g. MIT, BSD2, etc. (optional)') !== ''): ?>
# License
This project is released under the @license.name@ license.

<?php endif; ?>

Use new method call for API summary

fix: Use new method call for API summary


<?php

if (!defined('DIRECTORY_SEPERATOR')) {
    define('DIRECTORY_SEPERATOR', '/');
}

spl_autoload_register(function ($class) {
    $path = DIRECTORY_SEPERATOR . str_replace('\\', DIRECTORY_SEPERATOR, $class);
    $path = __DIR__ . $path . '.php';
    if (file_exists($path)) {
        require $path;
    }
});

<?php

spl_autoload_register(function ($class) {
    $path = '/' . str_replace('\\', '/', $class);
    $path = __DIR__ . $path . '.php';
    var_dump($path);
    if (file_exists($path)) {
        require $path;
    }
});

Revert "Now uses DIRECTORY_SEPERATOR. Removed var_dump."

This reverts commit 7d9602ea2f6fe1eca0735ac6f754a1d44cc9842d.


<?php

require "syno-repo.php";

if(!empty($_REQUEST['branch'])){
	$branch = $_REQUEST['branch'];
} else {
	$beta_channel =
		isset($_REQUEST['package_update_channel']) &&
		strtolower($_REQUEST['package_update_channel']) == 'beta';
	$branch = ($beta_channel) ? 'develop' : 'master';
}

// github token
$github_token = "xxx";

// github repos
$github_repos = array(
	array(
		'user' 		=> 'andreasgrill',
		'repo' 		=> 'vpnrouting',
		'branch'	=> $branch,
	)
);

// file/dir modes
$modes = array(
	'dir' => 0777,
	'file' => 0777);

syno_repo($github_repos, $github_token, $modes);

// file_put_contents("post.txt", var_export($_REQUEST, true). var_export($github_repos, true));
// chmod("post.txt", 0777);

?>

<?php

require "syno-repo.php";

if(!empty($_REQUEST["payload"])){
	$payload = json_decode(stripslashes($_REQUEST["payload"]), true);
	if(!empty($payload["ref"])){
		$_REQUEST['branch'] = preg_replace('/^.*?([^\/]+)$/', '$1', $payload["ref"]);
	}
}

if(!empty($_REQUEST['branch'])){
	$branch = $_REQUEST['branch'];
} else {
	$beta_channel =
		isset($_REQUEST['package_update_channel']) &&
		strtolower($_REQUEST['package_update_channel']) == 'beta';
	$branch = ($beta_channel) ? 'develop' : 'master';
}

// github token
$github_token = "xxx";

// github repos
$github_repos = array(
	array(
		'user' 		=> 'andreasgrill',
		'repo' 		=> 'vpnrouting',
		'branch'	=> $branch,
	)
);

// file/dir modes
$modes = array(
	'dir' => 0777,
	'file' => 0777);

syno_repo($github_repos, $github_token, $modes);

// file_put_contents("post.txt", var_export($_REQUEST, true). var_export($github_repos, true));
// chmod("post.txt", 0777);

?>

Support webhooks for different branches

Support webhooks for different branches


<?php
$sConfigFile = 'conf/production/config-itop.php';
$sStartPage = './pages/UI.php';
$sSetupPage = './setup/index.php';

/**
 * Check that the configuration file exists and has the appropriate access rights
 * If the file does not exist, launch the configuration wizard to create it
 */
if (file_exists($sConfigFile))
{
	if (!is_readable($sConfigFile))
	{
		echo "
Error: Unable to read the configuration file: '$sConfigFile'. Please check the access rights on this file.
";
	}
	else if (is_writable($sConfigFile))
	{
		echo "
Security Warning: the configuration file '$sConfigFile' should be read-only.
";
		echo "
Please modify the access rights to this file.
";
		echo "
Click here to ignore this warning and continue to run iTop.
";
	}
	else
	{
		header("Location: $sStartPage");
	}
}
else
{
	// Config file does not exist, need to run the setup wizard to create it
	header("Location: $sSetupPage");
}
?>

<?php
$sConfigFile = 'conf/production/config-itop.php';
$sStartPage = './pages/UI.php';
$sSetupPage = './setup/index.php';

/**
 * Check that the configuration file exists and has the appropriate access rights
 * If the file does not exist, launch the configuration wizard to create it
 */
if (file_exists(dirname(__FILE__).'/'.$sConfigFile))
{
	if (!is_readable($sConfigFile))
	{
		echo "
Error: Unable to read the configuration file: '$sConfigFile'. Please check the access rights on this file.
";
	}
	else if (is_writable($sConfigFile))
	{
		echo "
Security Warning: the configuration file '$sConfigFile' should be read-only.
";
		echo "
Please modify the access rights to this file.
";
		echo "
Click here to ignore this warning and continue to run iTop.
";
	}
	else
	{
		header("Location: $sStartPage");
	}
}
else
{
	// Config file does not exist, need to run the setup wizard to create it
	header("Location: $sSetupPage");
}
?>

Make sure that we reference the config file using an absolute path... just in case...

git-svn-id: efba275c3291004ad656db059d43564e37a1fae9@1775 60fe80c7-c1f8-43be-bd32-c3e8feb7a3b0


<?php

class ReportController extends AbstractController {

  function doGET(HttpRequest $request, HttpResponse $response) {
    $cols_raw = $request->get('cols');

    $col_list = explode(',', $cols_raw);

    // We need a list of tag objects in the order provided by the user
    $col_query = sprintf('select * from tag where tag in (%s)', implode(',', array_fill(0, count($col_list), '?')));
    $params = $col_list;
    array_unshift($params, $col_query);
    $cols = call_user_method_array('doQuery', $this, $params);
    foreach ($cols as $col) {
      $col_map[$col->tag] = $col;
    }
    $cols = array();
    foreach ($col_list as $col_tag) {
      array_push($cols, $col_map[$col_tag]);
    }

    // Now we need a list of matching values
    $value_query = sprintf('select V.* from value_view V join latest_import_view LI on V.import=LI.id where V.tag in (%s) order by V.row, V.col', implode(',', array_fill(0, count($col_list), '?')));
    $params = $col_list;
    array_unshift($params, $value_query);
    $values = call_user_method_array('doQuery', $this, $params);

    $response->setParameter('cols', $cols);
    $response->setParameter('values', $values);
    $response->setTemplate('report');
  }

}

<?php

class ReportController extends AbstractController {

  function doGET(HttpRequest $request, HttpResponse $response) {
    $cols_raw = $request->get('cols');

    $col_list = explode(',', $cols_raw);

    // We need a list of tag objects in the order provided by the user
    $col_query = sprintf('select * from tag where tag in (%s)', implode(',', array_fill(0, count($col_list), '?')));
    $params = $col_list;
    array_unshift($params, $col_query);
    $cols = call_user_method_array('doQuery', $this, $params);
    foreach ($cols as $col) {
      $col_map[$col->tag] = $col;
    }
    $cols = array();
    foreach ($col_list as $col_tag) {
      array_push($cols, $col_map[$col_tag]);
    }

    // Now we need a list of matching values
    $value_query = sprintf('select V.* from value_view V join latest_import_view LI using(import) where V.tag in (%s) order by V.row, V.col', implode(',', array_fill(0, count($col_list), '?')));
    $params = $col_list;
    array_unshift($params, $value_query);
    $values = call_user_method_array('doQuery', $this, $params);

    $response->setParameter('cols', $cols);
    $response->setParameter('values', $values);
    $response->setTemplate('report');
  }

}

Fix (unused) report page to use new schema.


<?php
namespace Goetas\Twital\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Goetas\Twital\EventDispatcher\TemplateEvent;
use Goetas\Twital\Twital;

/**
 *
 * @author Asmir Mustafic <goetas@gmail.com>
 *
 */
class IDNodeSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            'compiler.post_load' => array(
                array(
                    'addAttribute'
                )
            ),
            'compiler.pre_dump' => array(
                array(
                    'removeAttribute'
                )
            )
        );
    }

    public function addAttribute(TemplateEvent $event)
    {
        $doc = $event->getTemplate()->getDocument();
        $xp = new \DOMXPath($doc);
        $nodes = $xp->query("//*[@*[namespace-uri()='".Twital::NS."']]");
        $cnt = 0;
        foreach ($nodes as $node) {
            $node->setAttributeNS(Twital::NS, '__internal-id__', ++$cnt);
        }
    }

    public function removeAttribute(TemplateEvent $event)
    {
        $doc = $event->getTemplate()->getDocument();
        $xp = new \DOMXPath($doc);
        $xp->registerNamespace('twital', Twital::NS);
        $attributes = $xp->query("//@twital:__internal-id__");
        foreach ($attributes as $attribute) {
            $attribute->ownerElement->removeAttributeNode($attribute);
        }
    }
}

<?php
namespace Goetas\Twital\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Goetas\Twital\EventDispatcher\TemplateEvent;
use Goetas\Twital\Twital;

/**
 *
 * @author Asmir Mustafic <goetas@gmail.com>
 *
 */
class IDNodeSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            'compiler.post_load' => array(
                array(
                    'addAttribute'
                )
            ),
            'compiler.pre_dump' => array(
                array(
                    'removeAttribute'
                )
            )
        );
    }

    public function addAttribute(TemplateEvent $event)
    {
        $doc = $event->getTemplate()->getDocument();
        $xp = new \DOMXPath($doc);
        $nodes = $xp->query("//*[@*[namespace-uri()='".Twital::NS."']]");
        foreach ($nodes as $node) {
            $node->setAttributeNS(Twital::NS, '__internal-id__', microtime(1).mt_rand());
        }
    }

    public function removeAttribute(TemplateEvent $event)
    {
        $doc = $event->getTemplate()->getDocument();
        $xp = new \DOMXPath($doc);
        $xp->registerNamespace('twital', Twital::NS);
        $attributes = $xp->query("//@twital:__internal-id__");
        foreach ($attributes as $attribute) {
            $attribute->ownerElement->removeAttributeNode($attribute);
        }
    }
}

Change the id strategy, using random strings instead of counters


<?php

namespace ForkCMS\Modules\Backend\Backend\Actions;

use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use ForkCMS\Modules\Backend\Domain\Action\AbstractActionController;
use ForkCMS\Modules\Backend\Domain\UserGroup\UserGroup;
use Symfony\Component\HttpFoundation\Request;

/**
 *Overview of the available groups in the backend
 */
final class UserGroupIndex extends AbstractActionController
{
    protected function execute(Request $request): void
    {
        $this->assign(
            'groupDataGrid',
            $this->dataGridFactory->forEntity(UserGroup::class, static function (QueryBuilder $queryBuilder): void {
                $queryBuilder
                    ->leftJoin('UserGroup.users', 'Users', Join::WITH, 'Users.deleted = 0')
                    ->addSelect('Users');
            })
        );
    }
}

<?php

namespace ForkCMS\Modules\Backend\Backend\Actions;

use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use ForkCMS\Modules\Backend\Domain\Action\AbstractActionController;
use ForkCMS\Modules\Backend\Domain\UserGroup\UserGroup;
use Symfony\Component\HttpFoundation\Request;

/**
 *Overview of the available groups in the backend
 */
final class UserGroupIndex extends AbstractActionController
{
    protected function execute(Request $request): void
    {
        $this->assign(
            'groupDataGrid',
            $this->dataGridFactory->forEntity(UserGroup::class, static function (QueryBuilder $queryBuilder): void {
                $queryBuilder
                    ->leftJoin('UserGroup.users', 'Users', Join::WITH, 'Users.deletedAt IS NULL')
                    ->addSelect('Users');
            })
        );
    }
}

Fix filtering for deleted users

Fix filtering for deleted users


<?php
/**
 * @copyright Copyright © A.F.Schuurman, 2015
 * @package yii2-wizardwidget
 * @version 1.0.0
 */
namespace drsdre\wizardwidget;

use yii\web\AssetBundle;

/**
 * Asset bundle for Wizard Widget
 *
 * @author A.F.Schuurman <andre.schuurman+yii2-wizardwidget@gmail.com>
 * @since 1.0
 */
class WizardWidgetAsset extends AssetBundle
{
	public $sourcePath = '@drsdre/wizardwidget';
	public $css = [
		'css/wizardwidget.css',
	];
	public $js = [
		'js/wizardwidget.js'
	];
}

<?php
/**
 * @copyright Copyright © A.F.Schuurman, 2015
 * @package yii2-wizardwidget
 * @version 1.0.0
 */
namespace drsdre\wizardwidget;

use yii\web\AssetBundle;

/**
 * Asset bundle for Wizard Widget
 *
 * @author A.F.Schuurman <andre.schuurman+yii2-wizardwidget@gmail.com>
 * @since 1.0
 */
class WizardWidgetAsset extends AssetBundle
{
	public $sourcePath = '@drsdre/wizardwidget';
	public $depends = [ 'yii\web\YiiAsset' ];
	public $css = [
		'css/wizardwidget.css',
	];
	public $js = [
		'js/wizardwidget.js'
	];
}

Add missing dependency to YiiAsset in the asset manager.


<?php
    class Better_PHP_Cache
    {
        public function __construct()
        {

        }

        public function add($entry_name, $entry_value, $time_to_live)
        {
            if(!($entry_name && $entry_value && $time_to_live))
            {
                return FALSE;
            }

            return apc_store($entry_name, $entry_value, $time_to_live);
        }

        public function get($entry_name)
        {
            if(!$entry_name)
            {
                return FALSE;
            }

            return apc_fetch($entry_name);
        }

        public function delete($entry_name)
        {

        }
    }
?>

<?php
    class Better_PHP_Cache
    {
        public function __construct()
        {

        }

        public function store($entry_name, $entry_value, $time_to_live)
        {
            if(!($entry_name && $entry_value && $time_to_live))
            {
                return FALSE;
            }

            return apc_store($entry_name, $entry_value, $time_to_live);
        }

        public function fetch($entry_name)
        {
            if(!$entry_name)
            {
                return FALSE;
            }

            return apc_fetch($entry_name);
        }

        public function delete($entry_name)
        {

        }
    }
?>

Rename functions to match APC functions

Rename functions to match APC functions


{{--
    Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
    See the LICENCE file in the repository root for full licence text.
--}}

    <input
        class="account-edit-entry__input js-account-edit__input"
        name="user[{{ $field }}]"
        data-last-value="{{ Auth::user()->$field }}"
        @if (($maxLength = App\Models\User::MAX_FIELD_LENGTHS[$field]) !== null)
            maxlength="{{ $maxLength }}"
        @endif
        value="{{ Auth::user()->$field }}"
        @if (Auth::user()->isSilenced())
            disabled
        @endif
    >

        {{ osu_trans("accounts.edit.profile.user.{$field}") }}

    @include('accounts._edit_entry_status')

{{--
    Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
    See the LICENCE file in the repository root for full licence text.
--}}
@php
    $user = auth()->user();
@endphp

    <input
        class="account-edit-entry__input js-account-edit__input"
        name="user[{{ $field }}]"
        data-last-value="{{ $user->$field }}"
        maxlength="{{ $user::MAX_FIELD_LENGTHS[$field] }}"
        value="{{ $user->$field }}"
        @if ($user->isSilenced())
            disabled
        @endif
    >

        {{ osu_trans("accounts.edit.profile.user.{$field}") }}

    @include('accounts._edit_entry_status')

Clean up account edit simple entry view

Clean up account edit simple entry view

- set user variable instead of repeatedly call function
- remove null field length check because it doesn't make sense to have
  null limit and those without limit probably don't have entry in the
  first place and thus will cause error instead
- access const from instance instead of specifying full class name


<?php

class sspmod_ldap_Auth_Process_BaseFilter_Test extends PHPUnit_Framework_TestCase
{
    public function testVarExportHidesLdapPassword()
    {
        $stub = $this->getMockBuilder('sspmod_ldap_Auth_Process_BaseFilter')
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();

        $this->assertEquals(
            "array ( 'ldap.hostname' => 'ldap://172.17.101.32', 'ldap.port' => 389, 'ldap.password' => '********', )",
            $stub->var_export(array(
                'ldap.hostname' => 'ldap://172.17.101.32',
                'ldap.port' => 389,
                'ldap.password' => 'password',
            ))
        );
    }
}

<?php

class sspmod_ldap_Auth_Process_BaseFilter_Test extends PHPUnit_Framework_TestCase
{
    public function testVarExportHidesLdapPassword()
    {
        $stub = $this->getMockBuilder('sspmod_ldap_Auth_Process_BaseFilter')
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();
        $class = new \ReflectionClass($stub);
        $method = $class->getMethod('var_export');
        $method->setAccessible(true);

        $this->assertEquals(
            "array ( 'ldap.hostname' => 'ldap://172.17.101.32', 'ldap.port' => 389, 'ldap.password' => '********', )",
            $method->invokeArgs($stub, array(array(
                'ldap.hostname' => 'ldap://172.17.101.32',
                'ldap.port' => 389,
                'ldap.password' => 'password',
            )))
        );
    }
}

Fix test for method made protected.

bugfix: Fix test for method made protected.


<?php

namespace OwsProxy3\CoreBundle\DependencyInjection;

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

/**
 * @author Christian Wygoda
 */
class Configuration implements ConfigurationInterface
{

    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('ows_proxy3_core');

        $rootNode
                ->children()
                ->scalarNode('logging')
                ->defaultTrue()
                ->end()
                ->scalarNode('obfuscate_client_ip')
                ->defaultTrue()
                ->end()
                ->arrayNode("proxy")
                ->canBeUnset()
                ->addDefaultsIfNotSet()
                ->children()
                ->scalarNode('host')->defaultNull()->end()
                ->scalarNode('port')->defaultNull()->end()
                ->scalarNode('connecttimeout')->defaultNull()->end()
                ->scalarNode('timeout')->defaultNull()->end()
                ->scalarNode('user')->defaultNull()->end()
                ->scalarNode('password')->defaultNull()->end()
                ->scalarNode('checkssl')->defaultNull()->end()
                ->arrayNode("noproxy")
                ->prototype('scalar')->end()
                ->end()
                ->end()
                ->end()
                ->end();

        return $treeBuilder;
    }

}

<?php

namespace OwsProxy3\CoreBundle\DependencyInjection;

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

/**
 * @author Christian Wygoda
 */
class Configuration implements ConfigurationInterface
{

    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('ows_proxy3_core');

        $rootNode
            ->canBeUnset()->addDefaultsIfNotSet()
            ->children()
                ->booleanNode('logging')
                    ->defaultFalse()
                    ->treatNullLike(false)
                ->end()
                ->booleanNode('obfuscate_client_ip')
                    ->defaultTrue()
                    ->treatNullLike(true)
                ->end()
                ->arrayNode("proxy")
                ->canBeUnset()
                ->addDefaultsIfNotSet()
                ->children()
                ->scalarNode('host')->defaultNull()->end()
                ->scalarNode('port')->defaultNull()->end()
                ->scalarNode('connecttimeout')->defaultNull()->end()
                ->scalarNode('timeout')->defaultNull()->end()
                ->scalarNode('user')->defaultNull()->end()
                ->scalarNode('password')->defaultNull()->end()
                ->scalarNode('checkssl')->defaultNull()->end()
                ->arrayNode("noproxy")
                ->prototype('scalar')->end()
                ->end()
                ->end()
                ->end()
                ->end();

        return $treeBuilder;
    }

}

Change logging default true => false; accept nulls for logging and obfuscate_client_ip


<?php

/*
 * This file is part of the API Platform project.
 *
 * (c) Kévin Dunglas <dunglas@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace ApiPlatform\Doctrine\Orm\Util;

/**
 * @author Amrouche Hamza <hamza.simperfit@gmail.com>
 */
interface QueryNameGeneratorInterface
{
    /**
     * Generates a cacheable alias for DQL join.
     */
    public function generateJoinAlias(string $association): string;

    /**
     * Generates a cacheable parameter name for DQL query.
     */
    public function generateParameterName(string $name): string;
}

<?php

/*
 * This file is part of the API Platform project.
 *
 * (c) Kévin Dunglas <dunglas@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace ApiPlatform\Doctrine\Orm\Util;

/**
 * @author Amrouche Hamza <hamza.simperfit@gmail.com>
 */
interface QueryNameGeneratorInterface
{
    /**
     * Generates a cacheable alias for DQL join.
     *
     * @return literal-string
     */
    public function generateJoinAlias(string $association): string;

    /**
     * Generates a cacheable parameter name for DQL query.
     *
     * @return literal-string
     */
    public function generateParameterName(string $name): string;
}

Add missing return typehints to QueryNameGenerator

This will help to reduce static analysis warnings for consumers in apps baseline


<?php

namespace Terranet\Navigation;

class Manager
{
    public function providers()
    {
        return array_map(function ($provider) {
            return new $provider;
        }, config('navigation.providers', []));
    }
}

<?php

namespace Terranet\Navigation;

use App\Menu;

class Manager
{
    public function providers()
    {
        return array_map(function ($provider) {
            return new $provider;
        }, config('navigation.providers', []));
    }

    public function make($id)
    {
        return Menu::whereName($id)
            ->first()
            ->items
            ->map(function ($item) {
                return $item->assemble();
            });
    }
}

Add a make navigation method

Add a make navigation method


<?php
declare(strict_types=1);

namespace Onion\Framework\Hydrator\Interfaces;

/**
 * An interface representing the methods provided by the hydration
 * traits, that allow hydration and dehydration of the current object.
 *
 * Note that all (de)hydration is performed only on public methods/properties
 *
 * @package Onion\Framework\Hydrator\Interfaces
 */
interface HydratableInterface
{
    /**
     * Populates the current object with the provided data, according to
     * the used strategy
     *
     * @param array $data Data used to populate the object
     *
     * @return object A cloned, populated instance of the current object
     */
    public function hydrate(array $data);

    /**
     * Extract data from the current object. If $keys is provided
     * it will retrieve only those keys, otherwise all "public"
     * data will be extracted from the object.
     *
     * @param array $keys (Optional) List of specific keys to extract
     *
     * @return array The extracted data
     */
    public function extract(array $keys): array;
}

<?php
declare(strict_types=1);

namespace Onion\Framework\Hydrator\Interfaces;

/**
 * An interface representing the methods provided by the hydration
 * traits, that allow hydration and dehydration of the current object.
 *
 * Note that all (de)hydration is performed only on public methods/properties
 *
 * @package Onion\Framework\Hydrator\Interfaces
 */
interface HydratableInterface
{
    /**
     * Populates the current object with the provided data, according to
     * the used strategy
     *
     * @param array $data Data used to populate the object
     *
     * @return object A cloned, populated instance of the current object
     */
    public function hydrate(array $data);

    /**
     * Extract data from the current object. If $keys is provided
     * it will retrieve only those keys, otherwise all "public"
     * data will be extracted from the object.
     *
     * @param array $keys (Optional) List of specific keys to extract
     *
     * @return array The extracted data
     */
    public function extract(array $keys = []): array;
}

Add return type for the `extract` method


<?php

namespace IdeHelper\Test\TestCase\Generator\Task;

use App\Database\Type\UuidType;
use Cake\Database\Type;
use IdeHelper\Generator\Task\DatabaseTypeTask;
use Tools\TestSuite\TestCase;

class DatabaseTypeTaskTest extends TestCase {

	/**
	 * @var \IdeHelper\Generator\Task\DatabaseTypeTask
	 */
	protected $task;

	/**
	 * @return void
	 */
	public function setUp() {
		parent::setUp();

		$this->task = new DatabaseTypeTask();
	}

	/**
	 * @return void
	 */
	public function testCollect() {
		Type::map('uuid', UuidType::class);

		$result = $this->task->collect();

		$this->assertCount(1, $result);

		$expected = '\Cake\Database\Type\BinaryType::class';
		$this->assertSame($expected, $result['\Cake\Database\Type::build(0)']['binary']);

		$expected = '\App\Database\Type\UuidType::class';
		$this->assertSame($expected, $result['\Cake\Database\Type::build(0)']['uuid']);
	}

}

<?php

namespace IdeHelper\Test\TestCase\Generator\Task;

use App\Database\Type\UuidType;
use Cake\Database\Type;
use IdeHelper\Generator\Task\DatabaseTypeTask;
use Tools\TestSuite\TestCase;

class DatabaseTypeTaskTest extends TestCase {

	/**
	 * @var \IdeHelper\Generator\Task\DatabaseTypeTask
	 */
	protected $task;

	/**
	 * @return void
	 */
	public function setUp() {
		parent::setUp();

		$this->task = new DatabaseTypeTask();
	}

	/**
	 * @return void
	 */
	public function testCollect() {
		Type::set('uuid', new UuidType());

		$result = $this->task->collect();

		$this->assertCount(1, $result);

		$expected = '\Cake\Database\Type\BinaryType::class';
		$this->assertSame($expected, $result['\Cake\Database\Type::build(0)']['binary']);

		$expected = '\App\Database\Type\UuidType::class';
		$this->assertSame($expected, $result['\Cake\Database\Type::build(0)']['uuid']);
	}

}

Fix tests. map() does not reset the set() call for now (bugfix for master pending).


<?php
namespace Concrete\Core\Error\Provider;

use Concrete\Core\Error\Handler\ErrorHandler;
use Concrete\Core\Error\Handler\JsonErrorHandler;
use Concrete\Core\Foundation\Service\Provider;
use Whoops\Run;

class WhoopsServiceProvider extends Provider
{

    public function register()
    {
        if (function_exists('ini_set')) {
            ini_set('display_errors', 0);
        }
        $run = new Run;

        $handler = new ErrorHandler();
        $json_handler = new JsonErrorHandler();

        $run->pushHandler($handler);
        $run->pushHandler($json_handler);

        $run->register();
    }

}

<?php
namespace Concrete\Core\Error\Provider;

use Concrete\Core\Error\Handler\ErrorHandler;
use Concrete\Core\Error\Handler\JsonErrorHandler;
use Concrete\Core\Foundation\Service\Provider;
use Whoops\Handler\PlainTextHandler;
use Whoops\Run;

class WhoopsServiceProvider extends Provider
{

    public function register()
    {
        if (function_exists('ini_set')) {
            ini_set('display_errors', 0);
        }
        $run = new Run;

        $handler = new ErrorHandler();
        $json_handler = new JsonErrorHandler();
        $cli_handler = new PlainTextHandler();
        $cli_handler->onlyForCommandLine(true);

        $run->pushHandler($handler);
        $run->pushHandler($json_handler);
        $run->pushHandler($cli_handler);

        $run->register();
    }

}

Add plaintext error output for CLI

Add plaintext error output for CLI

Former-commit-id: f557439b3efa3e7f29b9ea071bed8cb2145ba453


<?php

class GoogleCodePrettify {
  private static $prettified = false;

  public static function parserHook($text, $args = array(), $parser) {
    $code_attributes = '';
    if (isset($args['lang']) && $args['lang']) {
      $lang = $args['lang'];
      $code_attributes .= " class=\"language-$lang\"";
    }
    self::$prettified = true;

    return "
$text
";
  }

  public static function beforePageDisplay(&$wgOut, &$sk) {
    if (self::$prettified) {
      $wgOut->addModules('ext.GoogleCodePrettify');
    }

    // Continue
    return true;
  }
}

<?php

class GoogleCodePrettify {
  private static $prettified = false;

  public static function parserHook($text, $args = array(), $parser) {
    $pre_classes = '';
    if (isset($args['lang']) && $args['lang']) {
      $lang = $args['lang'];
      $pre_classes .= " lang-$lang";
    }
    self::$prettified = true;

    return "
$text
";
  }

  public static function beforePageDisplay(&$wgOut, &$sk) {
    if (self::$prettified) {
      $wgOut->addModules('ext.GoogleCodePrettify');
    }

    // Continue
    return true;
  }
}

Use pre tag only without code to meet MediaWiki styling


<?php
use OuzoBreadcrumb\Breadcrumb;

class BreadcrumbHelper
{
    public static function showBreadcrumbs($options = array())
    {
        $options['class'] = isset($options['class']) ? $options['class'] : 'breadcrumb';
        $attr = self::_prepareAttributes($options);
        $breadcrumbs = '
';
        $breadcrumbsMap = Breadcrumb::getBreadcrumbs();
        foreach ($breadcrumbsMap as $breadcrumb) {
            $name = $breadcrumb->getName();
            $attribute = '';
            if (end($breadcrumbsMap) === $breadcrumb) {
                $attribute = 'class="active"';
            } else {
                $name = 'getPath() . '">' . $breadcrumb->getName() . '';
            }
            $breadcrumbs .= '
' . $name . '
 ';
        }
        $breadcrumbs .= '
 ';
        return $breadcrumbs;
    }

    private static function _prepareAttributes(array $attributes = array())
    {
        $attr = '';
        foreach ($attributes as $opt_key => $opt_value) {
            $attr .= $opt_key . '="' . $opt_value . '" ';
        }
        return trim($attr);
    }
}

<?php
use Ouzo\ControllerUrl;
use OuzoBreadcrumb\Breadcrumb;

class BreadcrumbHelper
{
    public static function showBreadcrumbs($options = array())
    {
        $options['class'] = isset($options['class']) ? $options['class'] : 'breadcrumb';
        $attr = self::_prepareAttributes($options);
        $breadcrumbs = '
';
        $breadcrumbsMap = Breadcrumb::getBreadcrumbs();
        foreach ($breadcrumbsMap as $breadcrumb) {
            $name = $breadcrumb->getName();
            $attribute = '';
            if (end($breadcrumbsMap) === $breadcrumb) {
                $attribute = 'class="active"';
            } else {
                $url = ControllerUrl::createUrl(array('string' => $breadcrumb->getPath()));
                $name = '' . $breadcrumb->getName() . '';
            }
            $breadcrumbs .= '
' . $name . '
 ';
        }
        $breadcrumbs .= '
 ';
        return $breadcrumbs;
    }

    private static function _prepareAttributes(array $attributes = array())
    {
        $attr = '';
        foreach ($attributes as $opt_key => $opt_value) {
            $attr .= $opt_key . '="' . $opt_value . '" ';
        }
        return trim($attr);
    }
}

Fix creating link with prefix system

Fix creating link with prefix system


<?php

namespace Oro\Bundle\TranslationBundle\Helper;

use Oro\Bundle\ConfigBundle\Config\ConfigManager;
use Oro\Bundle\LocaleBundle\DependencyInjection\Configuration;
use Oro\Bundle\TranslationBundle\Entity\Language;

class LanguageHelper
{
    /** @var ConfigManager */
    protected $configManager;

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

    /**
     * @param Language $language
     */
    public function updateSystemConfiguration(Language $language)
    {
        $languages = $this->configManager->get($this->getConfigurationName(), []);

        if ($language->isEnabled()) {
            !in_array($language->getCode(), $languages, true) and $languages[] = $language->getCode();
        } else {
            if (false !== ($index = array_search($language->getCode(), $languages, true))) {
                unset($languages[$index]);
            }
        }

        $this->configManager->set($this->getConfigurationName(), $languages);
        $this->configManager->flush();
    }

    /**
     * @return string
     */
    protected function getConfigurationName()
    {
        return Configuration::getConfigKeyByName(Configuration::LANGUAGES);
    }
}

<?php

namespace Oro\Bundle\TranslationBundle\Helper;

use Oro\Bundle\ConfigBundle\Config\ConfigManager;
use Oro\Bundle\LocaleBundle\DependencyInjection\Configuration;
use Oro\Bundle\TranslationBundle\Entity\Language;

class LanguageHelper
{
    /** @var ConfigManager */
    protected $configManager;

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

    /**
     * @param Language $language
     */
    public function updateSystemConfiguration(Language $language)
    {
        $languages = $this->configManager->get($this->getConfigurationName(), true);

        if ($language->isEnabled()) {
            if(!in_array($language->getCode(), $languages, true)){
                $languages[] = $language->getCode();
            }
        } else {
            if (false !== ($index = array_search($language->getCode(), $languages, true))) {
                unset($languages[$index]);
            }
        }

        $this->configManager->set($this->getConfigurationName(), $languages);
        $this->configManager->flush();
    }

    /**
     * @return string
     */
    protected function getConfigurationName()
    {
        return Configuration::getConfigKeyByName(Configuration::LANGUAGES);
    }
}

BAP-11412: Implement enable/disable operations
- CR Fixes


<?php
use Installer\App;
use Installer\Models\ConfirmForm;

if (isset($_POST['back'])) {
    header('Location: ' . App::$app->createUrl(['page' => 'config']));
	exit;
}

$action = isset($_POST['actionName']) ? trim($_POST['actionName']) : '';

$model = new ConfirmForm($this);
$model->run($action);
?>

        Перейти

<form action="" method="post" id="confirm-form">

    <button class="btn btn-default" type="submit" name="back">

        <?= App::t('Back') ?>
    </button>

	<button class="btn btn-primary" type="submit" name="submit">
		<?= App::t('Install') ?>
	</button>

</form>

<?php
use Installer\App;
use Installer\Models\ConfirmForm;

$action = isset($_POST['actionName']) ? trim($_POST['actionName']) : '';
$model = new ConfirmForm($this);
$model->run($action);
?>

        Перейти

<form action="" method="post" id="confirm-form">

    <a class="btn btn-default" href="<?= App::$app->createUrl(['page' => 'config']) ?>">

        <?= App::t('Back') ?>

	<button class="btn btn-primary" type="submit" name="submit">
		<?= App::t('Install') ?>
	</button>

</form>

Fix finish step submiting on the installer


<dropdown-trigger class="h-9 flex items-center" slot-scope="{toggle}" :handle-click="toggle">

        {{ auth()->user()->name }}

</dropdown-trigger>

<dropdown-menu slot="menu" width="100" direction="rtl">

                {{ __('Logout') }}

</dropdown-menu>

<dropdown-trigger class="h-9 flex items-center" slot-scope="{toggle}" :handle-click="toggle">

        {{ auth()->user()->name }}

</dropdown-trigger>

<dropdown-menu slot="menu" width="100" direction="rtl">

            user()->id }}" class="block no-underline text-90 hover:bg-30 p-3">
                Profile

                {{ __('Logout') }}

</dropdown-menu>

Add profile link to Nova user dropdown

Add profile link to Nova user dropdown


<?php

// Add dependencies to the Laravel autoloader
Autoloader::map(array(
    'Croppa' => Bundle::path('croppa').'library/Croppa.php',
    'PhpThumbFactory' => Bundle::path('croppa').'vendor/PHPThumb/src/ThumbLib.inc.php',
));

// Pass along the Config data so Croppa is decoupled from Laravel
Croppa::config(Config::get('croppa::croppa'));

// Subscribe to 404 events, these are how Croppa gets triggered
Event::listen('404', function() {

	// Pass Croppa the current URL
	Croppa::handle_404(Request::uri());
});

<?php

// Add dependencies to the Laravel autoloader
Autoloader::map(array(
    'Croppa' => Bundle::path('croppa').'library/Croppa.php',
    'PhpThumbFactory' => Bundle::path('croppa').'vendor/PHPThumb/src/ThumbLib.inc.php',
));

// Pass along the Config data so Croppa is decoupled from Laravel
Croppa::config(Config::get('croppa::croppa'));

// Subscribe to 404 events, these are how Croppa gets triggered
Event::listen('404', function() {

	// Increase memory limit, cause some images require a lot
	// too resize
	ini_set('memory_limit', '128M');

	// Pass Croppa the current URL
	Croppa::handle_404(Request::uri());
});

Increase the memory limit of the server to allow big images to be resized


<?php

class Monster implements Robbo\Presenter\PresentableInterface
{
    use MagicModel;

    protected $data;

    public function load($data)
    {
        $this->data = $data;
    }

    public function getPresenter()
    {
        return new Presenters\Monster($this);
    }

    public function getMinDamage()
    {
        return $this->melee_dice+$this->melee_cut;
    }

    public function getMaxDamage()
    {
        return ($this->melee_dice*$this->melee_dice_sides)+$this->melee_cut;
    }

    public function getAvgDamage()
    {
        return ($this->minDamage+$this->maxDamage)/2;
    }

    public function getSpecies()
    {
        return (array) $this->data->species;
    }

    public function getFlags()
    {
        return (array) $this->data->flags;
    }

    public function getId()
    {
        return $this->data->id;
    }
}

<?php

class Monster implements Robbo\Presenter\PresentableInterface
{
    use MagicModel;

    protected $data;

    public function load($data)
    {
        $this->data = $data;
    }

    public function getPresenter()
    {
        return new Presenters\Monster($this);
    }

    public function getMinDamage()
    {
        return $this->melee_dice+$this->melee_cut;
    }

    public function getMaxDamage()
    {
        return ($this->melee_dice*$this->melee_dice_sides)+$this->melee_cut;
    }

    public function getAvgDamage()
    {
        return ($this->minDamage+$this->maxDamage)/2;
    }

    public function getSpecies()
    {
        return (array) $this->data->species;
    }

    public function getFlags()
    {
        if(!isset($this->data->flags))
            return array();
        return (array) $this->data->flags;
    }

    public function getId()
    {
        return $this->data->id;
    }
}

Fix the condition when a monster has no flags.


<?php

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

class CreateInstanceTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('instances', function (Blueprint $table) {
            $table->increments('id');
            $table->string('uuid');
            $table->string('current_version');
            $table->string('latest_version')->nullable();
            $table->mediumText('latest_release_notes')->nullable();
            $table->integer('number_of_versions_since_current_version')->nullable();
            $table->timestamps();
        });

        $instance = new Instance;
        $instance->current_version = config('monica.app_version');
        $instance->uuid = uniqid();
        $instance->save();
    }
}

<?php

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

class CreateInstanceTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('instances', function (Blueprint $table) {
            $table->increments('id');
            $table->string('uuid');
            $table->string('current_version');
            $table->string('latest_version')->nullable();
            $table->mediumText('latest_release_notes')->nullable();
            $table->integer('number_of_versions_since_current_version')->nullable();
            $table->timestamps();
        });

        $instance = new Instance;
        $instance->current_version = config('monica.app_version');
        $instance->latest_version = config('monica.app_version');
        $instance->uuid = uniqid();
        $instance->save();
    }
}

Fix migration for the version checking

Fix migration for the version checking


<?php
/**
 * Nooku Platform - http://www.nooku.org/platform
 *
 * @copyright      Copyright (C) 2011 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net)
 * @license        GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link           https://github.com/nooku/nooku-platform for the canonical source repository
 */

use Nooku\Library;

/**
 * Article Controller
 *
 * @author  Johan Janssens <http://github.com/johanjanssens>
 * @package Component\Articles
 */
class ArticlesControllerArticle extends Library\ControllerModel
{
    protected function _initialize(Library\ObjectConfig $config)
    {
        $config->append(array(
            'behaviors' => array(
                'editable', 'persistable',
                'com:activities.controller.behavior.loggable',
                'com:revisions.controller.behavior.revisable',
                'com:attachments.controller.behavior.attachable',
                'com:tags.controller.behavior.taggable'
            )
        ));

        parent::_initialize($config);
    }
}

<?php
/**
 * Nooku Platform - http://www.nooku.org/platform
 *
 * @copyright      Copyright (C) 2011 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net)
 * @license        GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link           https://github.com/nooku/nooku-platform for the canonical source repository
 */

use Nooku\Library;

/**
 * Article Controller
 *
 * @author  Johan Janssens <http://github.com/johanjanssens>
 * @package Component\Articles
 */
class ArticlesControllerArticle extends Library\ControllerModel
{
    protected function _initialize(Library\ObjectConfig $config)
    {
        $config->append(array(
            'behaviors' => array(
                'editable', 'persistable',
                'com:activities.controller.behavior.loggable',
                'com:revisions.controller.behavior.revisable',
                'com:attachments.controller.behavior.attachable',
            )
        ));

        parent::_initialize($config);
    }
}

Move taggable behavior to bootstrapper.

Move taggable behavior to bootstrapper.


<?php

namespace Illuminate\Queue\Connectors;

use Pheanstalk\Pheanstalk;
use Illuminate\Support\Arr;
use Pheanstalk\PheanstalkInterface;
use Illuminate\Queue\BeanstalkdQueue;

class BeanstalkdConnector implements ConnectorInterface
{
    /**
     * Establish a queue connection.
     *
     * @param  array  $config
     * @return \Illuminate\Contracts\Queue\Queue
     */
    public function connect(array $config)
    {
        $pheanstalk = new Pheanstalk($config['host'], Arr::get($config, 'port', PheanstalkInterface::DEFAULT_PORT));

        return new BeanstalkdQueue(
            $pheanstalk, $config['queue'], Arr::get($config, 'ttr', Pheanstalk::DEFAULT_TTR)
        );
    }
}

<?php

namespace Illuminate\Queue\Connectors;

use Pheanstalk\Pheanstalk;
use Illuminate\Support\Arr;
use Pheanstalk\PheanstalkInterface;
use Illuminate\Queue\BeanstalkdQueue;

class BeanstalkdConnector implements ConnectorInterface
{
    /**
     * Establish a queue connection.
     *
     * @param  array  $config
     * @return \Illuminate\Contracts\Queue\Queue
     */
    public function connect(array $config)
    {
        $pheanstalk = new Pheanstalk($config['host'], Arr::get($config, 'port', PheanstalkInterface::DEFAULT_PORT));

        return new BeanstalkdQueue(
            $pheanstalk, $config['queue'], Arr::get($config, 'expire', Pheanstalk::DEFAULT_TTR)
        );
    }
}

Use "expire" to be consistent with other drivers.


<?php
namespace Minds\Core\Analytics\Dashboards\Metrics\Engagement;

use Minds\Core\Di\Di;
use Minds\Core\Session;
use Minds\Core\Data\ElasticSearch;
use Minds\Core\Analytics\Dashboards\Metrics\AbstractMetric;
use Minds\Core\Analytics\Dashboards\Metrics\MetricSummary;
use Minds\Core\Analytics\Dashboards\Metrics\Visualisations;
use Minds\Core\Analytics\Dashboards\Metrics\HistogramSegment;

class ReferralsMetric extends AbstractEngagementMetric
{
    public function __construct($es = null)
    {
        parent::__construct($es);
        $this->segments = [
            (new HistogramSegment())
                ->setAggField('referral::total')
                ->setAggType('sum'),
            (new HistogramSegment())
                ->setAggField('referral::active')
                ->setAggType('sum')
                ->setLabel('Active'),
        ];
    }

    /** @var string */
    protected $id = 'referrals';

    /** @var string */
    protected $label = 'Referrals';

    /** @var string */
    protected $description = "Number of comments you have received on your content";

    /** @var array */
    protected $permissions = [ 'user', 'admin' ];

    /** @var string */
    protected $aggField = 'referral::total';
}

<?php
namespace Minds\Core\Analytics\Dashboards\Metrics\Engagement;

use Minds\Core\Di\Di;
use Minds\Core\Session;
use Minds\Core\Data\ElasticSearch;
use Minds\Core\Analytics\Dashboards\Metrics\AbstractMetric;
use Minds\Core\Analytics\Dashboards\Metrics\MetricSummary;
use Minds\Core\Analytics\Dashboards\Metrics\Visualisations;
use Minds\Core\Analytics\Dashboards\Metrics\HistogramSegment;

class ReferralsMetric extends AbstractEngagementMetric
{
    public function __construct($es = null)
    {
        parent::__construct($es);
        $this->segments = [
            (new HistogramSegment())
                ->setAggField('referral::total')
                ->setAggType('sum'),
            (new HistogramSegment())
                ->setAggField('referral::active')
                ->setAggType('sum')
                ->setLabel('Active'),
        ];
    }

    /** @var string */
    protected $id = 'referrals';

    /** @var string */
    protected $label = 'Referrals';

    /** @var string */
    protected $description = "Earnings from content posted by users you referred to Minds";

    /** @var array */
    protected $permissions = [ 'user', 'admin' ];

    /** @var string */
    protected $aggField = 'referral::total';
}

Update tooltip copy for analytics referrals chart


<?php
/**
 * @author Jean Silva <me@jeancsil.com>
 * @license MIT
 */
namespace Jeancsil\FlightSpy\Service\Currency;

class PriceFormatter
{
    const CURRENCIES_FILE = 'currencies.json';

    private $currencies;

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

    /**
     * @param string $price
     * @param string $currencyCode
     * @return string
     */
    public function format($price, $currencyCode) {
        foreach ($this->currencies as $currency) {
            if ($currency['Code'] == $currencyCode) {
                if ($currency['SymbolOnLeft'] == 'true') {
                    return $currency['Symbol'] .
                        number_format(
                            $price,
                            2,
                            $currency['DecimalSeparator'],
                            $currency['ThousandsSeparator']
                        );
                }

                return number_format(
                    $price,
                    2,
                    $currency['DecimalSeparator'],
                    $currency['ThousandsSeparator']
                ) . $currency['Symbol'];
            }
        }
    }

    /**
     * @param $resourcesDir
     */
    private function initializeCurrenciesFile($resourcesDir)
    {
        if (!$this->currencies) {
            $currenciesFile = getcwd() . '/' . $resourcesDir . '/' . static::CURRENCIES_FILE;
            $currenciesArray = json_decode(file_get_contents($currenciesFile), true);
            $this->currencies = $currenciesArray['ReferenceServiceResponseDto']['Currencies']['CurrencyDto'];
        }
    }
}

Fix code style according to PSR standard.


		<meta charset="utf-8"/>
		<meta name="keywords" content="GURPS Character Sheet roleplaying games"/>
		<meta name="description" content="GURPS Character Sheet"/>
		<link rel="stylesheet" type="text/css" href="/main.css"/>
		<link rel="shortcut icon" href="/images/favicon.ico"/>

		<meta charset="utf-8"/>
		<meta name="keywords" content="GURPS Character Sheet roleplaying games"/>
		<meta name="description" content="GURPS Character Sheet"/>
		<meta name="norton-safeweb-site-verification" content="fnn0dveu85-ceabrbo2s7k1kw54q88sqmlvbun2sg86r82l9l01bxz6qlbq6ptnqojpmwzqs8v2viv1jkxhi3jo5ndv931j15xz3j49uup5blqxahylgkqquk-hg5uf9" />
		<link rel="stylesheet" type="text/css" href="/main.css"/>
		<link rel="shortcut icon" href="/images/favicon.ico"/>

Add Norton Safe Web verification

Add Norton Safe Web verification


<?php
register_shutdown_function('shutdown');
function shutdown() {
	global $lock_file;

	unlink($lock_file);
}

?>

<?php
register_shutdown_function('shutdown');
function shutdown() {
	global $lock_file;

	if (file_exists($lock_file))
		unlink($lock_file);
}

?>

Check if lock file exists to avoid warnings.


    @if($label) {!! $label !!} @if($required)*@endif@endif
    <select
    id="{{$name}}"
    name="{{$name}}"
    @if($value)value="{{$value}}" @endif
    @if($required)required @endif
    @if($placeholder)placeholder="{{$placeholder}}"@endif
    @foreach($attr as $key => $value)
    @if(is_int($key)){{$value}}@else{{$key}}="{{$value}}"@endif
    @endforeach
    >
    @if($placeholder !== null)<option disabled selected>Choisir une valeur</option>@endif
    @foreach($options as $option)
    <option value="{{$option['value']}}">{{$option['label']}}</option>
    @endforeach
    </select>
    @if($errors)

        @foreach ($errors as $error)

{{$error}}

        @endforeach

    @endif

    @if($label) {!! $label !!} @if($required)*@endif@endif
    <select
    id="{{$name}}"
    name="{{$name}}"
    @if($value)value="{{$value}}" @endif
    @if($required)required @endif
    @if($placeholder)placeholder="{{$placeholder}}"@endif
    @foreach($attr as $key => $value)
    @if(is_int($key)){{$value}}@else{{$key}}="{{$value}}"@endif
    @endforeach
    >
    @if($placeholder !== null)<option disabled selected>Choisir une valeur</option>@endif
    @foreach($options as $option)
    <option value="{{$option['value']}}" @if($option['value'] == $value)selected @endif >{{$option['label']}}</option>
    @endforeach
    </select>
    @if($errors)

        @foreach ($errors as $error)

{{$error}}

        @endforeach

    @endif

Fix selected value for select field.

Fix selected value for select field.


<?php

final class DiffusionGitBlameQuery extends DiffusionBlameQuery {

  protected function newBlameFuture(DiffusionRequest $request, $path) {
    $repository = $request->getRepository();

    $commit = $request->getCommit();

    return $repository->getLocalCommandFuture(
      '--no-pager blame -s -l %s -- %s',
      $commit,
      $path);
  }

  protected function resolveBlameFuture(ExecFuture $future) {
    list($err, $stdout) = $future->resolve();

    if ($err) {
      return null;
    }

    $result = array();

    $lines = phutil_split_lines($stdout);
    foreach ($lines as $line) {
      list($commit) = explode(' ', $line, 2);
      $result[] = $commit;
    }

    return $result;
  }

}

<?php

final class DiffusionGitBlameQuery extends DiffusionBlameQuery {

  protected function newBlameFuture(DiffusionRequest $request, $path) {
    $repository = $request->getRepository();

    $commit = $request->getCommit();

    // NOTE: The "--root" flag suppresses the addition of the "^" boundary
    // commit marker. Without it, root commits render with a "^" before them,
    // and one fewer character of the commit hash.

    return $repository->getLocalCommandFuture(
      '--no-pager blame --root -s -l %s -- %s',
      $commit,
      $path);
  }

  protected function resolveBlameFuture(ExecFuture $future) {
    list($err, $stdout) = $future->resolve();

    if ($err) {
      return null;
    }

    $result = array();

    $lines = phutil_split_lines($stdout);
    foreach ($lines as $line) {
      list($commit) = explode(' ', $line, 2);
      $result[] = $commit;
    }

    return $result;
  }

}

Stop "git blame" from printing "^" markers on root repository commits

Summary: Depends on D19391. Ref T13126. See that task for some details on what's going on here.

Test Plan:
  - Viewed a file which includes lines that were added during the first commit to the repository.
  - Before D19391: fatal.
  - After D19391: blank.
  - After this patch: accurate blame information.

Reviewers: amckinley

Reviewed By: amckinley

Maniphest Tasks: T13126

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


<?php

namespace club\assetrev\utilities;

use craft\base\Model;

abstract class Strategy implements StrategyContract
{
    protected $config = [];
    protected $basePath;

    public function __construct(Model $config, $basePath = null)
    {
        $this->config = $config;
        $this->basePath = $basePath;
    }

    protected function getAbsolutePath($path)
    {
        if (strpos($path, DIRECTORY_SEPARATOR) === 0) {
            return $path;
        }

        return $this->basePath . $path;
    }

    protected function normalisePath($path)
    {
        return rtrim($path, '/');
    }
}

<?php

namespace club\assetrev\utilities;

use craft\base\Model;

abstract class Strategy implements StrategyContract
{
    protected $config = [];
    protected $basePath;

    public function __construct(Model $config, $basePath = null)
    {
        $this->config = $config;
        $this->basePath = $basePath;
    }

    protected function getAbsolutePath($path)
    {
        if (strpos($path, DIRECTORY_SEPARATOR) === 0) {
            return $path;
        }

        return $this->basePath . DIRECTORY_SEPARATOR . $path;
    }

    protected function normalisePath($path)
    {
        return rtrim($path, '/');
    }
}

Add directory separator between basePath and path


<?php
$env = getenv('APPLICATION_ENV') ? : "local";

return array(
    'modules' => array(
        'DoctrineModule',
        'DoctrineORMModule',
    	'ProophEventStoreModule',
        'Application',
    	'Accounting',
    	'TaskManagement',
        'ZendOAuth2',
    	'User',
    	'Kanbanize'
    ),

    'module_listener_options' => array(
        'module_paths' => array(
            __DIR__.'/../../src/module',
            __DIR__.'/../../src/vendor',
        ),
        'config_glob_paths' => array(
            __DIR__.'/../../src/config/autoload/{,*.}{'.$env.',global}.php',
        ),
    )
);

<?php
$env = getenv('APPLICATION_ENV') ? : "local";

return array(
    'modules' => array(
        'DoctrineModule',
        'DoctrineORMModule',
    	'ProophEventStoreModule',
        'Application',
    	'Accounting',
    	'TaskManagement',
        'ZendOAuth2',
    	'User',
    ),

    'module_listener_options' => array(
        'module_paths' => array(
            __DIR__.'/../../src/module',
            __DIR__.'/../../src/vendor',
        ),
        'config_glob_paths' => array(
            __DIR__.'/../../src/config/autoload/{,*.}{'.$env.',global}.php',
        ),
    )
);

Fix unit test Kanbanize module loading

Fix unit test Kanbanize module loading