<?php  namespace Aedart\Util\Interfaces;

/**
 * Interface Populatable
 *
 * Components implementing this interface promise, that the given component can
 * be populated with some kind of data and thereby set its internal properties or
 * states to the given value(s)
 *
 * What kind of properties can be populated / set, is completely implementation
 * dependent.
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Util\Interfaces
 */
interface Populatable {

    /**
     * Populate this component via an array
     *
     * @param array $data Key-value pair, where the key corresponds to a
     * property name and the value to be set, e.g.

     *

     * [
     *  'myProperty' => 'myPropertyValue',
     *  'myOtherProperty' => 42.5
     * ]
     *

     *

     *
     * @return void
     *
     * @throws \Exception In case that one or more of the given array entries are invalid
     */
    public function populate(array $data);

}

<?php  namespace Aedart\Util\Interfaces;

/**
 * Interface Populatable
 *
 *

 *
 * Components implementing this interface promise, that the given component can
 * be populated with some kind of data and thereby set its internal properties or
 * states to the given value(s)
 *
 *

 *
 * What kind of properties can be populated / set, is completely implementation
 * dependent.
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Util\Interfaces
 */
interface Populatable {

    /**
     * Populate this component via an array
     *
     *

     *
     * If an empty array is provided, nothing is populated.
     *
     *

     *
     * If a value or property is not given via $data, then it
     * is NOT modified / changed.
     *
     * @param array $data Key-value pair, where the key corresponds to a
     * property name and the value to be set, e.g.

     *

     * [
     *  'myProperty' => 'myPropertyValue',
     *  'myOtherProperty' => 42.5
     * ]
     *

     *

     *
     * @return void
     *
     * @throws \Exception In case that one or more of the given array entries are invalid
     */
    public function populate(array $data = []);

}

Change populate method, allow empty array


<?php

if( posix_geteuid() ) {
	echo "\033[1;31mError:\033[0m Please run `ee` with root privileges.";
	return;
}

// Can be used by plugins/themes to check if EE is running or not
define( 'EE', true );
define( 'EE_VERSION', trim( file_get_contents( EE_ROOT . '/VERSION' ) ) );
define( 'EE_START_MICROTIME', microtime( true ) );
define( 'EE_CONF_ROOT', '/opt/easyengine' );

if ( file_exists( EE_ROOT . '/vendor/autoload.php' ) ) {
	define( 'EE_VENDOR_DIR', EE_ROOT . '/vendor' );
} elseif ( file_exists( dirname( dirname( EE_ROOT ) ) . '/autoload.php' ) ) {
	define( 'EE_VENDOR_DIR', dirname( dirname( EE_ROOT ) ) );
} else {
	define( 'EE_VENDOR_DIR', EE_ROOT . '/vendor' );
}

require_once EE_ROOT . '/php/bootstrap.php';
\EE\bootstrap();

<?php

if ( posix_geteuid() ) {
	fwrite( STDERR, "\033[1;31mError:\033[0m Please run `ee` with root privileges." );
	exit( 1 );
}

// Can be used by plugins/themes to check if EE is running or not
define( 'EE', true );
define( 'EE_VERSION', trim( file_get_contents( EE_ROOT . '/VERSION' ) ) );
define( 'EE_START_MICROTIME', microtime( true ) );
define( 'EE_CONF_ROOT', '/opt/easyengine' );

if ( file_exists( EE_ROOT . '/vendor/autoload.php' ) ) {
	define( 'EE_VENDOR_DIR', EE_ROOT . '/vendor' );
} elseif ( file_exists( dirname( dirname( EE_ROOT ) ) . '/autoload.php' ) ) {
	define( 'EE_VENDOR_DIR', dirname( dirname( EE_ROOT ) ) );
} else {
	define( 'EE_VENDOR_DIR', EE_ROOT . '/vendor' );
}

require_once EE_ROOT . '/php/bootstrap.php';
\EE\bootstrap();

Fix output stream and return code

Fix output stream and return code


                    id }}" class="note-title">
                         {{ $notes->notes_title }}

                    id }}}" class="note-title">

                    id }}}" class="note-title">
                        {{ $notes->notes_title }}

Set the element width inline

Set the element width inline


<?php

use Dedato\SoluForce\Setup;

/* ==========================================================================
   Timber Setup
   ========================================================================== */

if ( ! class_exists( 'Timber' ) ) {
	add_action( 'admin_notices', function() {
			echo '

Timber not activated. Make sure you activate the plugin in ' . esc_url( admin_url( 'plugins.php' ) ) . '

';
		} );
	return;
}
Timber::$dirname = array('views');

class StarterSite extends TimberSite {

  function __construct() {
		add_filter( 'timber_context', array( $this, 'add_to_context' ) );
		parent::__construct();
	}

	function add_to_context( $context ) {
		$context['top_menu']        = new TimberMenu('top_navigation');
		$context['main_menu']       = new TimberMenu('primary_navigation');
		$context['footer_menu']     = new TimberMenu('footer_navigation');
		$context['site']            = $this;
		$context['display_sidebar'] = Setup\display_sidebar();
		$context['sidebar_primary'] = Timber::get_widgets('sidebar-primary');
		return $context;
	}

}
new StarterSite();

<?php

use Dedato\SoluForce\Setup;

/* ==========================================================================
   Timber Setup
   ========================================================================== */

if ( ! class_exists( 'Timber' ) ) {
	add_action( 'admin_notices', function() {
			echo '

Timber not activated. Make sure you activate the plugin in ' . esc_url( admin_url( 'plugins.php' ) ) . '

';
		} );
	return;
}
Timber::$dirname = array('views');

class StarterSite extends TimberSite {

  function __construct() {
		add_filter( 'timber_context', array( $this, 'add_to_context' ) );
		parent::__construct();
	}

	function add_to_context( $context ) {
		$context['top_menu']        = new TimberMenu('top_navigation');
		$context['main_menu']       = new TimberMenu('primary_navigation');
		$context['footer_menu']     = new TimberMenu('footer_navigation');
		$context['site']            = $this;
		$context['display_sidebar'] = Setup\display_sidebar();
		$context['sidebar_primary'] = Timber::get_widgets('sidebar-primary');
		$context['options']         = get_fields('option');
		$context['split_content']   = TimberHelper::function_wrapper('Dedato\SoluForce\Extras\split_more_content');
		return $context;
	}

}
new StarterSite();

Add ACF options & split_content function


      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
        Toggle navigation

      </button>

      <a class="navbar-brand" href="<?php echo esc_url(home_url('/')); ?>"><?php bloginfo('name'); ?>

      <?php
        if (has_nav_menu('primary_navigation')) :
          wp_nav_menu(array('theme_location' => 'primary_navigation', 'walker' => new Roots_Nav_Walker(), 'menu_class' => 'nav navbar-nav navbar-right'));
        endif;
      ?>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
        Toggle navigation

      </button>
      <img class="navbar-brand" src=" wp-content/themes/<?php echo get_template(); ?>/assets/img/xsce-draft-icon.png" style="padding-bottom: 20px; padding-top: 22px;"/>
      <a class="navbar-brand" href="<?php echo esc_url(home_url('/')); ?>"><?php bloginfo('name'); ?>

      <?php
        if (has_nav_menu('primary_navigation')) :
          wp_nav_menu(array('theme_location' => 'primary_navigation', 'walker' => new Roots_Nav_Walker(), 'menu_class' => 'nav navbar-nav navbar-right'));
        endif;
      ?>

Fix path for xsce logo

Fix path for xsce logo


<?php
declare(strict_types = 1);

namespace Soliant\SimpleFM\Client\ResultSet\Transformer;

use Litipk\BigNumbers\Decimal;

final class NumberTransformer
{
    public function __invoke(string $value)
    {
        $cleanedValue = preg_replace_callback(
            '(^[^\d-\.]*(-?)([^.]*)(.?)(.*)$)',
            function (array $match) : string {
                return
                    $match[1]
                    . preg_replace('([^\d]+)', '', $match[2])
                    . $match[3]
                    . preg_replace('([^\d]+)', '', $match[4]);
            },
            $value
        );

        if ('' === $cleanedValue) {
            return null;
        }

        if ('-' === $cleanedValue) {
            $cleanedValue = '0';
        }

        if (0 === strpos($cleanedValue, '.')) {
            $cleanedValue = '0' . $cleanedValue;
        }

        return Decimal::fromString($cleanedValue);
    }
}

<?php
declare(strict_types = 1);

namespace Soliant\SimpleFM\Client\ResultSet\Transformer;

use Litipk\BigNumbers\Decimal;

final class NumberTransformer
{
    public function __invoke(string $value)
    {
        $cleanedValue = preg_replace_callback(
            '(^[^\d\-.]*(-?)([^.]*)(.?)(.*)$)',
            function (array $match) : string {
                return
                    $match[1]
                    . preg_replace('([^\d]+)', '', $match[2])
                    . $match[3]
                    . preg_replace('([^\d]+)', '', $match[4]);
            },
            $value
        );

        if ('' === $cleanedValue) {
            return null;
        }

        if ('-' === $cleanedValue) {
            $cleanedValue = '0';
        }

        if (0 === strpos($cleanedValue, '.')) {
            $cleanedValue = '0' . $cleanedValue;
        }

        return Decimal::fromString($cleanedValue);
    }
}

Fix escaping for stricter php7.3. Escaping the minus is the right fix.


<?php

declare(strict_types=1);

/**
 * This file is part of Laravel Zero.
 *
 * (c) Nuno Maduro <enunomaduro@gmail.com>
 *
 *  For the full copyright and license information, please view the LICENSE
 *  file that was distributed with this source code.
 */

namespace LaravelZero\Framework\Providers\GitVersion;

use Symfony\Component\Process\Process;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Foundation\Application;

/**
 * @codeCoverageIgnore
 * @internal
 */
final class GitVersionServiceProvider extends ServiceProvider
{
    /**
     * {@inheritdoc}
     */
    public function register(): void
    {
        $this->app->bind(
            'git.version',
            function (Application $app) {
                $task = 'git describe --tags $(git rev-list --tags --max-count=1)';

                $process = tap(new Process($task, $app->basePath()))->run();

                return trim($process->getOutput()) ?: 'unreleased';
            }
        );
    }
}

<?php

declare(strict_types=1);

/**
 * This file is part of Laravel Zero.
 *
 * (c) Nuno Maduro <enunomaduro@gmail.com>
 *
 *  For the full copyright and license information, please view the LICENSE
 *  file that was distributed with this source code.
 */

namespace LaravelZero\Framework\Providers\GitVersion;

use Symfony\Component\Process\Process;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Foundation\Application;

/**
 * @codeCoverageIgnore
 * @internal
 */
final class GitVersionServiceProvider extends ServiceProvider
{
    /**
     * {@inheritdoc}
     */
    public function register(): void
    {
        $this->app->bind(
            'git.version',
            function (Application $app) {
                $lastRevisionTag = '$(git rev-list --tags --max-count=1)';

                if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                    $taskGetLastRevisionTag = 'git rev-list --tags --max-count=1';

                    $process = tap(new Process($taskGetLastRevisionTag, $app->basePath()))->run();

                    $lastRevisionTag = trim($process->getOutput()) ?: 'unreleased';

                    if ($lastRevisionTag === 'unreleased') {
                        return 'unreleased';
                    }
                }
                $task = "git describe --tags $lastRevisionTag";

                $process = tap(new Process($task, $app->basePath()))->run();

                return trim($process->getOutput()) ?: 'unreleased';
            }
        );
    }
}

Add support for Windows OS.

Add support for Windows OS.

Windows cannot execute a subcommand like "$ ()".


<?php

namespace JMS\Tests\Composer\Graph;

use JMS\Composer\Graph\DependencyGraph;

class DependencyGraphTest extends \PHPUnit_Framework_TestCase
{
    public function testImplicitCreationOfRootPackage()
    {
        $graph = new DependencyGraph();
        $this->assertCount(1, $graph->getPackages());
        $this->assertTrue($graph->isRootPackage($graph->getPackages()['__root']));
    }
}

<?php

namespace JMS\Tests\Composer\Graph;

use JMS\Composer\Graph\DependencyGraph;

class DependencyGraphTest extends \PHPUnit_Framework_TestCase
{
    public function testImplicitCreationOfRootPackage()
    {
        $graph = new DependencyGraph();
        $packages = $graph->getPackages();

        $this->assertCount(1, $packages);
        $this->assertTrue($graph->isRootPackage($packages['__root']));
    }
}

Make sure tests work with PHP 5.3

Make sure tests work with PHP 5.3


<?php

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

class UpdateMiningActivitiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('mining_activities', function (Blueprint $table) {
            $table->bigInteger('refinery_id')->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('mining_activities', function (Blueprint $table) {
            $table->integer('refinery_id', 11)->change();
        });
    }
}

<?php

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

class UpdateMiningActivitiesTable2 extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('mining_activities', function (Blueprint $table) {
            $table->bigInteger('refinery_id')->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('mining_activities', function (Blueprint $table) {
            $table->integer('refinery_id', 11)->change();
        });
    }
}

Fix class name clash in database migrations.


<?php while (have_posts()) : the_post(); ?>
  <article <?php post_class(); ?>>

<?php the_title(); ?>

      <?php get_template_part('templates/entry-meta'); ?>

      <?php the_content(); ?>

      <?php wp_link_pages(array('before' => '
' . __('Pages:', 'roots'), 'after' => '
')); ?>
      <?php
        if ( function_exists('wp_related_posts') ) {
          wp_related_posts();
        }
      ?>

<?php endwhile; ?>

<?php while (have_posts()) : the_post(); ?>
  <article <?php post_class(); ?>>

<?php the_title(); ?>

      <?php get_template_part('templates/entry-meta'); ?>

      <?php the_content(); ?>

      <?php wp_link_pages(array('before' => '
' . __('Pages:', 'roots'), 'after' => '
')); ?>

<?php endwhile; ?>

Remove the related posts function

Remove the related posts function


<?php

namespace Oro\Bundle\SegmentBundle\Controller\Api\Rest;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class DeprecatedSegmentController extends Controller
{
    /**
     * Deprecated action!!! Get entity segments forward.
     *
     * @param $entityName
     * @return Response
     * @deprecated
     */
    public function getItemsAction($entityName)
    {
        return $this->forward('OroSegmentBundle:Api/Rest/Segment:getItems', [], ['entityName' => $entityName]);
    }
}

<?php

namespace Oro\Bundle\SegmentBundle\Controller\Api\Rest;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

/**
 * @deprecated
 */
class DeprecatedSegmentController extends Controller
{
    /**
     * Deprecated action!!! Get entity segments forward.
     *
     * @param $entityName
     * @return Response
     * @deprecated
     */
    public function getItemsAction($entityName)
    {
        return $this->forward('OroSegmentBundle:Api/Rest/Segment:getItems', [], ['entityName' => $entityName]);
    }
}

BAP-6912: Remove BC break of REST API after migration to new version of FOSRestBundle
 - small fix


<?php

namespace Bolt\Extension\Leskis\BoltFieldGeojson\Tests;

use Bolt\Tests\BoltUnitTest;
use Bolt\Extension\Leskis\BoltFieldGeojson\BoltFieldGeojsonExtension;

/**
 * BoltFieldGeojson testing class.
 *
 * @author Nicolas Béhier-Dévigne
 */
class ExtensionTest extends BoltUnitTest
{
    /**
     * Ensure that the BoltSendEmailForNewContent extension loads correctly.
     */
    public function testExtensionBasics()
    {
        $app = $this->getApp(false);
        $extension = new BoltSendEmailForNewContentExtension($app);

        $name = $extension->getName();
        $this->assertSame($name, 'BoltSendEmailForNewContent');
        $this->assertInstanceOf('\Bolt\Extension\ExtensionInterface', $extension);
    }

    public function testExtensionComposerJson()
    {
        $composerJson = json_decode(file_get_contents(dirname(__DIR__) . '/composer.json'), true);

        // Check that the 'bolt-class' key correctly matches an existing class
        $this->assertArrayHasKey('bolt-class', $composerJson['extra']);
        $this->assertTrue(class_exists($composerJson['extra']['bolt-class']));

        // Check that the 'bolt-assets' key points to the correct directory
        $this->assertArrayHasKey('bolt-assets', $composerJson['extra']);
        $this->assertSame('web', $composerJson['extra']['bolt-assets']);
    }
}

<?php

namespace Bolt\Extension\Leskis\BoltSendEmailForNewContent\Tests;

use Bolt\Tests\BoltUnitTest;
use Bolt\Extension\Leskis\BoltSendEmailForNewContent\BoltSendEmailForNewContentExtension;

/**
 * BoltSendEmailForNewContent testing class.
 *
 * @author Nicolas Béhier-Dévigne
 */
class ExtensionTest extends BoltUnitTest
{
    /**
     * Ensure that the BoltSendEmailForNewContent extension loads correctly.
     */
    public function testExtensionBasics()
    {
        $app = $this->getApp(false);
        $extension = new BoltSendEmailForNewContentExtension($app);

        $name = $extension->getName();
        $this->assertSame($name, 'BoltSendEmailForNewContent');
        $this->assertInstanceOf('\Bolt\Extension\ExtensionInterface', $extension);
    }

    public function testExtensionComposerJson()
    {
        $composerJson = json_decode(file_get_contents(dirname(__DIR__) . '/composer.json'), true);

        // Check that the 'bolt-class' key correctly matches an existing class
        $this->assertArrayHasKey('bolt-class', $composerJson['extra']);
        $this->assertTrue(class_exists($composerJson['extra']['bolt-class']));

        // Check that the 'bolt-assets' key points to the correct directory
        $this->assertArrayHasKey('bolt-assets', $composerJson['extra']);
        $this->assertSame('web', $composerJson['extra']['bolt-assets']);
    }
}

Fix first functional test class

Fix first functional test class


<?php

namespace {{ ns }};

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class {{ class }}Controller extends Controller
{
    public function indexAction($name)
    {
        return $this->render('', array('name' => $name));
    }
}

<?php

namespace {{ ns }};

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class {{ class }} extends Controller
{
    public function indexAction($name)
    {
        return $this->render('', array('name' => $name));
    }
}

Remove double Controller in classname

Remove double Controller in classname

When generating a new Controller, the classname had a double Controller word in it. eg. TestControllerController.
This removes one of them.


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\Utils\HttpFoundation;

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * AJAX response
 */
class AjaxResponse extends JsonResponse
{
    /**
     * @param string $html       HTML
     * @param bool   $success    Is success
     * @param string $message    Message
     * @param bool   $reloadPage Whether to reload page
     * @param array  $data       Additional data
     * @param int    $status     Response status code
     * @param array  $headers    Response headers
     */
    public function __construct(
        $html = '',
        $success = true,
        $message = null,
        $reloadPage = false,
        array $data = array(),
        $status = 200,
        array $headers = array()
    ) {
        parent::__construct(array_merge($data, array(
            'html'       => $html,
            'message'    => $message,
            'reloadPage' => $reloadPage,
            'success'    => $success,
        ), $status, $headers));
    }
}

<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\Utils\HttpFoundation;

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * AJAX response
 */
class AjaxResponse extends JsonResponse
{
    /**
     * @param string $html       HTML
     * @param bool   $success    Is success
     * @param string $message    Message
     * @param bool   $reloadPage Whether to reload page
     * @param array  $data       Additional data
     * @param int    $status     Response status code
     * @param array  $headers    Response headers
     */
    public function __construct(
        $html = '',
        $success = true,
        $message = null,
        $reloadPage = false,
        array $data = array(),
        $status = 200,
        array $headers = array()
    ) {
        parent::__construct(array_merge($data, array(
            'html'       => $html,
            'message'    => $message,
            'reloadPage' => $reloadPage,
            'success'    => $success,
        )), $status, $headers);
    }
}

Fix AJAX response class constructor.

Fix AJAX response class constructor.


<?php

namespace Guzzle\ConfigOperationsBundle\DependencyInjection\CompilerPass;

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

/**
 * Compiler pass that will add our definitions to Guzzle clients.
 *
 * @author Pierre Rolland <roll.pierre@gmail.com>
 */
class ClientCompilerPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $taggedServices = $container->findTaggedServiceIds(
            'guzzle.client'
        );

        $definitions = [];
        foreach ($taggedServices as $id => $tags) {
            foreach ($tags as $attributes) {
                $definitionId = sprintf('guzzle_client.%s', $attributes['alias']);
                if (!$container->has($definitionId)) {
                    $definition = new Definition();
                    $definition->setClass('Guzzle\ConfigOperationsBundle\GuzzleClient');
                    $definition->setFactory([
                        new Reference('guzzle_config_operations.factory'),
                        'getClient'
                    ]);
                    $definition->addArgument($id);
                    $definitions[$definitionId] = $definition;
                }
            }
        }

        $container->addDefinitions($definitions);
    }
}

<?php

namespace Guzzle\ConfigOperationsBundle\DependencyInjection\CompilerPass;

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

/**
 * Compiler pass that will add our definitions to Guzzle clients.
 *
 * @author Pierre Rolland <roll.pierre@gmail.com>
 */
class ClientCompilerPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $taggedServices = $container->findTaggedServiceIds(
            'guzzle.client'
        );

        $definitions = [];
        foreach ($taggedServices as $id => $tags) {
            foreach ($tags as $attributes) {
                $definitionId = sprintf('guzzle_client.%s', $attributes['alias']);
                if (!$container->has($definitionId)) {
                    $definition = new Definition();
                    $definition->setClass('Guzzle\ConfigOperationsBundle\GuzzleClient');
                    $definition->setFactory([
                        new Reference('guzzle_config_operations.factory'),
                        'getClient'
                    ]);
                    $definition->setPublic(true);
                    $definition->addArgument($id);
                    $definitions[$definitionId] = $definition;
                }
            }
        }

        $container->addDefinitions($definitions);
    }
}

Set created client to public

Set created client to public


<?php

namespace BOMO\IcalBundle\Provider;

use BOMO\IcalBundle\Model\Timezone,
    BOMO\IcalBundle\Model\Calendar,
    BOMO\IcalBundle\Model\Event,
    BOMO\IcalBundle\Model\Alarm
    ;

class IcsProvider
{
    public function createTimezone(array $config = array(), $timezoneType = FALSE)
    {
        return new Timezone($config, $timezoneType);
    }

    public function createCalendar(Timezone $tz = null, $allowNullTimezone = FALSE)
    {
        if (is_null($tz) && false === $allowNullTimezone) {
            $tz = $this->createTimezone();
        }
        return new Calendar($tz);
    }

    public function createEvent()
    {
        return new Event();
    }

    public function createAlarm()
    {
        return new Alarm();
    }
}

<?php

namespace BOMO\IcalBundle\Provider;

use BOMO\IcalBundle\Model\Timezone,
    BOMO\IcalBundle\Model\Calendar,
    BOMO\IcalBundle\Model\Event,
    BOMO\IcalBundle\Model\Alarm
    ;

class IcsProvider
{
    public function createTimezone(array $config = array())
    {
        return new Timezone($config);
    }

    public function createCalendar(Timezone $tz = null, $allowNullTimezone = FALSE)
    {
        if (is_null($tz) && false === $allowNullTimezone) {
            $tz = $this->createTimezone();
        }
        return new Calendar($tz);
    }

    public function createEvent()
    {
        return new Event();
    }

    public function createAlarm()
    {
        return new Alarm();
    }
}

Make sure that timezone information is included in calendar export


<?php
return [
    'method' => 'post',
    'elements' => [
        'secret' => ['hidden', []],

        'otp' => [
            'text',
            [
                'label' => __('Code from Authenticator App'),
                'description' => __('Enter the current code provided by your authenticator app to verify that it\'s working correctly.'),
                'class' => 'half-width',
                'required' => true,
                'label_class' => 'mb-2',
                'form_group_class' => 'col-sm-12 mt-3',
            ]
        ],

        'submit' => [
            'submit',
            [
                'type' => 'submit',
                'label' => __('Verify Authenticator'),
                'class' => 'btn btn-lg btn-primary',
                'form_group_class' => 'col-sm-12 mt-3',
            ],
        ],

    ],
];

<?php
return [
    'method' => 'post',
    'elements' => [
        'secret' => ['hidden', []],

        'otp' => [
            'text',
            [
                'label' => __('Code from Authenticator App'),
                'description' => __('Enter the current code provided by your authenticator app to verify that it\'s working correctly.'),
                'class' => 'half-width',
                'required' => true,
                'label_class' => 'mb-2',
            ]
        ],

        'submit' => [
            'submit',
            [
                'type' => 'submit',
                'label' => __('Verify Authenticator'),
                'class' => 'btn btn-lg btn-primary',
            ],
        ],

    ],
];

Clean up styling on 2FA enable form.

Clean up styling on 2FA enable form.


<?php

/*
 * (c) Kévin Dunglas <dunglas@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Dunglas\ActionBundle\Tests;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
class FunctionalTest extends WebTestCase
{
    public function testDummyAction()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/');
        $this->assertSame('Here we are!', $crawler->text());
    }

    public function testSensioFrameworkExtraActionAction()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/extra');
        $this->assertSame('How are you?', $crawler->text());
    }

    public function testRouteAnnotationAction()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/annotation');
        $this->assertSame('Hey, ho, let\'s go!', $crawler->text());
    }

    public function testOverrideAction()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/override');
        $this->assertSame('Override', $crawler->text());
    }
}

<?php

/*
 * (c) Kévin Dunglas <dunglas@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Dunglas\ActionBundle\Tests;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
class FunctionalTest extends WebTestCase
{
    public function testDummyAction()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/');
        $this->assertSame('Here we are!', $crawler->text());
    }

    public function testSensioFrameworkExtraActionAction()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/extra');
        $this->assertSame('How are you?', $crawler->text());
    }

    public function testRouteAnnotationAction()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/annotation');
        $this->assertSame('Hey, ho, let\'s go!', $crawler->text());
    }

    public function testOverrideAction()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/override');
        $this->assertSame('Override', $crawler->text());
    }

    public function testMultiController()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/first');
        $this->assertSame('first', $crawler->text());

        $crawler = $client->request('GET', '/second');
        $this->assertSame('second', $crawler->text());
    }
}

Test when a class contains several actions


<?php
	// If a feature image is set, get the id, so it can be injected as a css background property
	if ( has_post_thumbnail( $post->ID ) ) :
		$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
		$image = $image[0];
		?>

	<header id="featured-hero" role="banner" style="background-image: url('<?php echo $image ?>')">
	</header>
	<?php endif;

<?php
	// If a feature image is set, get the id, so it can be injected as a css background property
	if ( has_post_thumbnail( $post->ID ) ) :
		$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
		$image = $image[0];
		?>

	<header class="hero section" role="banner" style="background-image: url('<?php echo $image ?>')">
	</header>
	<?php endif;

Make the big hero image work.

Make the big hero image work.


<?php

namespace LinkValue\MobileNotifBundle\DependencyInjection\Compiler;

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

/**
 * Collect all mobile clients and store it to application domain.
 */
class MobileClientCompilerPass implements CompilerPassInterface
{
    /**
     * @{inherit_doc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('link_value_mobile_notif.mobile_notif')) {
            return;
        }

        $definition = $container->getDefinition('link_value_mobile_notif.mobile_notif');
        $tagged = $container->findTaggedServiceIds('link_value_mobile_notif.mobile_client');

        foreach ($tagged as $serviceId => $attributes) {
            foreach ($attributes as $attribute) {
                if (empty($attribute['support'])) {
                    throw new \InvalidArgumentException(sprintf('"link_value_mobile_notif.mobile_client" tag must define "support" key.'));
                }

                $definition->addMethodCall('addMobileClient', array(
                    $attribute['support'],
                    new Reference($serviceId),
                ));
            }
        }
    }
}

<?php

namespace LinkValue\MobileNotifBundle\DependencyInjection\Compiler;

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

/**
 * Collect all mobile clients and store it to application domain.
 */
class MobileClientCompilerPass implements CompilerPassInterface
{
    /**
     * @{inherit_doc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('link_value_mobile_notif.mobile_notif')) {
            return;
        }

        $definition = $container->getDefinition('link_value_mobile_notif.mobile_notif');
        $tagged = $container->findTaggedServiceIds('link_value_mobile_notif.mobile_client');

        foreach ($tagged as $serviceId => $attributes) {
            foreach ($attributes as $attribute) {
                if (empty($attribute['key'])) {
                    throw new \InvalidArgumentException(sprintf('"link_value_mobile_notif.mobile_client" tag must define "key" key.'));
                }

                $definition->addMethodCall('addMobileClient', array(
                    $attribute['key'],
                    new Reference($serviceId),
                ));
            }
        }
    }
}

Change support requirement to key

Change support requirement to key


<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">

    <?php foreach($config->styles as $file) echo "\n\t<link type='text/css' href='$file' rel='stylesheet' />"; ?>
    <?php foreach($config->scripts as $file) echo "\n\t"; ?>
    <title>GraphiQL</title>

Loading...

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">
    <?php foreach($config->styles as $file) echo "\n\t<link type='text/css' href='$file' rel='stylesheet' />"; ?>
    <title>GraphiQL</title>

Loading...

    <?php foreach($config->scripts as $file) echo "\n\t"; ?>

Put js at the end of the `<body>` tag.`

Put js at the end of the `<body>` tag.`


<?php
  get_header();

  if (have_posts()) {
    while (have_posts()) {
      the_post();
?>

      <?php the_content(); ?>

<?php
      if (is_page("tags")) {
?>

        <?php
          wp_list_categories(
            array(
              "hierarchical"      => 1,
              "title_li"          => __(""),
              "show_count"        => 1,
              "depth"             => 0,
              "exclude"           => "1,7,9,11,19,100,104,148"
            )
          );
        ?>

      <?php
        wp_get_archives(
          array(
            "type" => "yearly"
          )
        );
      ?>

      <?php
        wp_get_archives(
          array(
            "type" => "monthly"
          )
        );
      ?>

      <?php
        wp_get_archives(
          array(
            "type" => "daily"
          )
        );
      ?>

<?php
      }
?>

<?php
    }
  }

  get_footer();

?>

<?php
  get_header();

  if (have_posts()) {
    while (have_posts()) {
      the_post();
?>

      <?php the_content(); ?>

<?php
      if (is_page("tags")) {
?>

        <?php
          wp_list_categories(
            array(
              "hierarchical"      => 1,
              "title_li"          => __(""),
              "show_count"        => 1,
              "depth"             => 0,
              "exclude"           => "1,2,6,7,9,10,11,19,72,100,104,148"
            )
          );
        ?>

      <?php
        wp_get_archives(
          array(
            "type" => "yearly"
          )
        );
      ?>

      <?php
        wp_get_archives(
          array(
            "type" => "monthly"
          )
        );
      ?>

      <?php
        wp_get_archives(
          array(
            "type" => "daily"
          )
        );
      ?>

<?php
      }
?>

<?php
    }
  }

  get_footer();

?>

Exclude some no longer relevant categories


<?php

class FeedsController extends Zend_Controller_Action
{
    public function stationRssAction()
    {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if (!RestAuth::verifyAuth(true, true, $this)
            && (Application_Model_Preference::getStationPodcastPrivacy()
            && $this->getRequest()->getParam("sharing_token") != Application_Model_Preference::getStationPodcastDownloadKey())) {
            $this->getResponse()
                ->setHttpResponseCode(401);
            return;
        }

        header('Content-Type: text/xml; charset=UTF-8');

        echo Application_Service_PodcastService::createStationRssFeed();
    }
}

<?php

class FeedsController extends Zend_Controller_Action
{
    public function stationRssAction()
    {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if ((Application_Model_Preference::getStationPodcastPrivacy()
                && $this->getRequest()->getParam("sharing_token") != Application_Model_Preference::getStationPodcastDownloadKey())
                && !RestAuth::verifyAuth(true, true, $this)) {
            $this->getResponse()
                ->setHttpResponseCode(401);
            return;
        }

        header('Content-Type: text/xml; charset=UTF-8');

        echo Application_Service_PodcastService::createStationRssFeed();
    }
}

Fix bug where public station podcast feed would not display when logged out


<?php

/**
 * BankwireBundle for Symfony2
 *
 * This Bundle is part of Symfony2 Payment Suite
 *
 * @author Marc Morera <yuhu@mmoreram.com>
 * @package BankwireBundle
 *
 * Marc Morera 2013
 */

namespace PaymentSuite\BankwireBundle;

use PaymentSuite\PaymentCoreBundle\PaymentMethodInterface;

/**
 * BankwireMethod class
 */
class BankwireMethod implements PaymentMethodInterface
{
    /**
     * Method name
     */
    const METHOD_NAME = 'Bankwire';

    /**
     * Get Bankwire method name
     *
     * @return string Payment name
     */
    public function getPaymentName()
    {
        return $this::METHOD_NAME;
    }
}

<?php

/**
 * BankwireBundle for Symfony2
 *
 * This Bundle is part of Symfony2 Payment Suite
 *
 * @author Marc Morera <yuhu@mmoreram.com>
 * @package BankwireBundle
 *
 * Marc Morera 2013
 */

namespace PaymentSuite\BankwireBundle;

use PaymentSuite\PaymentCoreBundle\PaymentMethodInterface;

/**
 * BankwireMethod class
 */
class BankwireMethod implements PaymentMethodInterface
{
    /**
     * Method name
     */
    const METHOD_NAME = 'Bankwire';

    /**
     * Get Bankwire method name
     *
     * @return string Payment name
     */
    public function getPaymentName()
    {
        return self::METHOD_NAME;
    }
}

Use self instead of this

Use self instead of this


<?php

namespace Symfony\Component\Form\Tests\Fixtures;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class AlternatingRowType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $formFactory = $builder->getFormFactory();

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formFactory) {
            $form = $event->getForm();
            $type = 0 === $form->getName() % 2
                ? 'Symfony\Component\Form\Extension\Core\Type\TextType'
                : 'Symfony\Component\Form\Extension\Core\Type\TextareaType';
            $form->add('title', $type);
        });
    }
}

<?php

namespace Symfony\Component\Form\Tests\Fixtures;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class AlternatingRowType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
            $form = $event->getForm();
            $type = 0 === $form->getName() % 2
                ? 'Symfony\Component\Form\Extension\Core\Type\TextType'
                : 'Symfony\Component\Form\Extension\Core\Type\TextareaType';
            $form->add('title', $type);
        });
    }
}

[CS] Remove unused variables passed to closures


<?php
/**
 * CORS middleware service provider
 *
 * @package     phpnexus/cors-laravel
 * @copyright   Copyright (c) 2016 Mark Prosser
 * @license     http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link        https://github.com/phpnexus/cors-laravel
 */

namespace PhpNexus\CorsLaravel;

use Illuminate\Support\ServiceProvider;
use PhpNexus\CorsLaravel\Middleware as CorsMiddleware;

/**
 * CORS service provider class
 */
class CorsServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(CorsMiddleware::class, function ($app) {
            // Load cors configuration
            $app->configure('cors');

            // Create new CORS middleware, with config
            return new CorsMiddleware($app['config']['cors']);
        });
    }
}

<?php
/**
 * CORS service provider
 *
 * @package     phpnexus/cors-laravel
 * @copyright   Copyright (c) 2016 Mark Prosser
 * @license     http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link        https://github.com/phpnexus/cors-laravel
 */

namespace PhpNexus\CorsLaravel;

use Illuminate\Support\ServiceProvider;
use PhpNexus\Cors\CorsService;
use PhpNexus\CorsLaravel\Middleware as CorsMiddleware;

/**
 * CORS service provider class
 */
class CorsServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container
     *
     * @return void
     */
    public function register()
    {
        // CORS service
        $this->app->singleton(CorsService::class, function ($app) {
            // Load cors configuration
            $app->configure('cors');

            return new CorsService($app['config']['cors']);
        });

        // CORS middleware
        $this->app->singleton(CorsMiddleware::class, function ($app) {
            // Create new CorsMiddleware, with CorsService
            return new CorsMiddleware($app->make(CorsService::class));
        });
    }
}

Add CorsService to service provider

Add CorsService to service provider


<?php

namespace Lchski;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    protected $fillable = ['title'];

    public function links()
    {
        return $this->belongsToMany('\Lchski\Link');
    }

    public function items()
    {
        $items = [];

        foreach ($this->links as $link) {
            $items[] = $link->items()->whereNotIn('items.id', [$this->id])->get();
        }

        return $items;
    }
}

<?php

namespace Lchski;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    protected $fillable = ['title'];

    public function links()
    {
        return $this->belongsToMany('\Lchski\Link');
    }

    public function items()
    {
        $items = $this->with('links.items')->where('items.id', [$this->id])->get();

        return $items;
    }
}

Use better loading to cut down on DB queries


<?php
/**
 * File: facebook.php
 * User: zacharydubois
 * Date: 2016-01-04
 * Time: 20:49
 * Project: Digital-Footprint-Profile
 */

namespace dfp;

$denied = filter_input(INPUT_GET, 'denied');

$config = new Config();

if (!isset($denied) || array_key_exists('oauth_verifier', $_GET)) {
// Create twitter.
    $twitter = new Twitter($config, new Session($config));
    $twitter->accessToken();
    $twitter->getPosts();
}

header('Location: ' . Utility::buildFullLink($config, false, 'session'));

Add a model for the callback.

Add a model for the callback.


<?php

	require('DB_Config.php');
	require('Encrypt.class.php');

	class Authenticate {

		private $mysqli;

		//Get the table structure from DB_Config
		private $usertable = TABLE_OF_USERS;
		private $usercol = COLUMN_OF_USERS;
		private $passwordcol = COLUMN_OF_PASSWORDS;

	 	function __construct()
		{
			$mysqli = new mysqli(HOST, DB_USERNAME, DB_PASSWORD, DATABASE_NAME);
			$this -> mysqli = $mysqli;
		}

		function login($username, $password)
		{
		    //Fetch username and password from database
		    $query ="SELECT {$this -> usercol}, {$this -> passwordcol} FROM {$this -> usertable} WHERE {$this -> usercol} = '$username'";
			$result = $this -> mysqli -> query($query);
            $row = $result -> fetch_assoc();
            $hash = $row['password'];

            $encrypt = new Encrypt(12, FALSE);

            if($encrypt -> checkpassword($password, $hash))
            {
                return TRUE;
            }
        }

		function createUser($username, $password, $confirmpassword, $email)
		{

		}

		function logout()
		{

			session_destroy();

		}

		function resetPassword($username, $email)
		{

		}

		function isUserActive($active)
		{

		}

		function changePassword($username, $password, $newpassword, $confirmnewpassword)
		{

		}

	}

?>

<?php

	require('DB_Config.php');
	require('Encrypt.class.php');

	class Authenticate {

		private $mysqli;

		//Get the table structure from DB_Config
		private $usertable = TABLE_OF_USERS;
		private $usercol = COLUMN_OF_USERS;
		private $passwordcol = COLUMN_OF_PASSWORDS;

	 	function __construct()
		{
			$mysqli = new mysqli(HOST, DB_USERNAME, DB_PASSWORD, DATABASE_NAME);
			$this -> mysqli = $mysqli;
		}

		function login($username, $password)
		{
		    //Check variables exist
		    if(empty($username) || empty($password))
            {
                return FALSE;
            }

		    //Fetch password from database
			$stmt = $this -> mysqli -> prepare("SELECT {$this -> passwordcol} FROM {$this -> usertable} WHERE {$this -> usercol} = ?");
            $stmt -> bind_param('s', $username);
            $stmt -> execute();
            $stmt -> bind_result($hash);
            $stmt -> fetch();

            //Check if the password hashes match
            $encrypt = new Encrypt(12, FALSE);
            if($encrypt -> checkpassword($password, $hash))
            {
                return TRUE;
            }
        }

		function createUser($username, $password, $confirmpassword, $email)
		{

		}

		function logout()
		{

			session_destroy();

		}

		function resetPassword($username, $email)
		{

		}

		function changePassword($username, $password, $newpassword, $confirmnewpassword)
		{

		}

	}

?>

Switch to using MySQL Prepared Statements


<?php  namespace Mitch\LaravelDoctrine\Console;

use Illuminate\Console\Command;

class GenerateProxiesCommand extends Command {

    protected $name = 'doctrine:generate:proxies';
    protected $description = 'Generate proxies for entities.';

    public function fire() {
        $entityManager = $this->laravel->make('Doctrine\ORM\EntityManagerInterface');

        $this->info('Starting proxy generation....');
        $metadata = $entityManager->getMetadataFactory()->getAllMetadata();
        if (empty($metadata)) {
            $this->error('No metadata found to generate any entities.');
            exit;
        }
        $directory = $this->laravel['config']['doctrine::doctrine.proxy.directory'];
        if ( ! $directory) {
            $this->error('The proxy directory has not been set.');
            exit;
        }
        $this->info('Processing entities:');
        foreach ($metadata as $item)
            $this->line($item->name);
        $entityManager->getProxyFactory()->generateProxyClasses($metadata, $directory);
        $this->info('Proxies have been created.');
    }
}

<?php  namespace Mitch\LaravelDoctrine\Console;

use Illuminate\Console\Command;

class GenerateProxiesCommand extends Command {

    protected $name = 'doctrine:generate:proxies';
    protected $description = 'Generate proxies for entities.';

    public function fire() {
        $entityManager = $this->laravel->make('Doctrine\ORM\EntityManagerInterface');

        $this->info('Starting proxy generation....');
        $metadata = $entityManager->getMetadataFactory()->getAllMetadata();
        if (empty($metadata)) {
            $this->error('No metadata found to generate any entities.');
            exit;
        }
        $directory = $this->laravel['config']['doctrine.proxy.directory'];
        if ( ! $directory) {
            $this->error('The proxy directory has not been set.');
            exit;
        }
        $this->info('Processing entities:');
        foreach ($metadata as $item)
            $this->line($item->name);
        $entityManager->getProxyFactory()->generateProxyClasses($metadata, $directory);
        $this->info('Proxies have been created.');
    }
}

Load the config value correctly.

Load the config value correctly.


<?php

namespace Fuzz\ApiServer\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
	/**
	 * Load the application routes.
	 *
	 * @return void
	 */
	protected function loadRoutes()
	{
		// Always implement the token dance
		$this->app['router']->post(
			'oauth/access_token', 'Fuzz\ApiServer\Routing\OAuthController@issueAccessToken'
		);

		parent::loadRoutes();
	}
}

<?php

namespace Fuzz\ApiServer\Providers;

use Illuminate\Support\Str;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
	/**
	 * Load the application routes.
	 *
	 * @return void
	 */
	protected function loadRoutes()
	{
		// Always implement the token dance
		$this->app['router']->post(
			'oauth/access_token', 'Fuzz\ApiServer\Routing\OAuthController@issueAccessToken'
		);

		parent::loadRoutes();
	}

	/**
	 * Define the routes for the application.
	 *
	 * @param  \Illuminate\Routing\Router $router
	 * @return void
	 */
	public function map(Router $router)
	{
		// Register a handy macro for registering resource routes
		$router->macro('restful', function ($model_name, $resource_controller = 'ResourceController') use ($router) {
			$alias = Str::lower(Str::snake(Str::plural(class_basename($model_name)), '-'));

			$router->resource($alias, $resource_controller, [
				'only' => [
					'index',
					'store',
					'show',
					'update',
					'destroy',
				],
			]);
		});

		$router->group(['namespace' => $this->namespace], function ($router) {
			require app_path('Http/routes.php');
		});
	}
}

Move map method of route service provider into base api server route service provider


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

/**
 * String utility functions.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class StringUtils
{
    /**
     * This class should not be instantiated
     */
    private function __construct() {}

    /**
     * Compares two strings.
     *
     * This method implements a constant-time algorithm to compare strings.
     *
     * @param string $str1 The first string
     * @param string $str2 The second string
     *
     * @return Boolean true if the two strings are the same, false otherwise
     */
    public static function equals($str1, $str2)
    {
        if (strlen($str1) !== $c = strlen($str2)) {
            return false;
        }

        $result = 0;
        for ($i = 0; $i < $c; $i++) {
            $result |= ord($str1[$i]) ^ ord($str2[$i]);
        }

        return 0 === $result;
    }
}

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

/**
 * String utility functions.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class StringUtils
{
    /**
     * This class should not be instantiated
     */
    private function __construct() {}

    /**
     * Compares two strings.
     *
     * This method implements a constant-time algorithm to compare strings.
     *
     * @param string $knownString The string of known length to compare against
     * @param string $userInput   The string that the user can control
     *
     * @return Boolean true if the two strings are the same, false otherwise
     */
    public static function equals($knownString, $userInput)
    {
        // Prevent issues if string length is 0
        $knownString .= chr(0);
        $userInput .= chr(0);

        $knownLen = strlen($knownString);
        $userLen = strlen($userInput);

        // Set the result to the difference between the lengths
        $result = $knownLen - $userLen;

        // Note that we ALWAYS iterate over the user-supplied length
        // This is to prevent leaking length information
        for ($i = 0; $i < $userLen; $i++) {
            // Using % here is a trick to prevent notices
            // It's safe, since if the lengths are different
            // $result is already non-0
            $result |= (ord($knownString[$i % $knownLen]) ^ ord($userInput[$i]));
        }

        // They are only identical strings if $result is exactly 0...
        return $result === 0;
    }
}

Improve timing safe comparison function

Improve timing safe comparison function

Improve the timing safe comparison function to better handle cases where input is of different length.

Note that it is now important to always pass any string that the user can directly control to the second parameter of the function. Otherwise, length information may be leaked.


<?php
/**
 * This file is part of Railt package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
declare(strict_types=1);

namespace Railt\Testing\Feature;

/**
 * Trait BootableTraits
 */
trait BootableTraits
{
    /**
     * @return void
     */
    protected function setUpTestKernel(): void
    {
        foreach ($this->traits(true) as $trait) {
            $bootMethod = 'boot' . $trait;

            if (\method_exists($this, $bootMethod)) {
                $this->{$bootMethod}();
            }
        }
    }

    /**
     * @param bool $shortName
     * @return \Traversable
     */
    private function traits(bool $shortName = true): \Traversable
    {
        $traits = [];

        $parents = \class_parents(static::class);
        $class   = static::class;

        while ($class !== null) {
            $traits = \array_merge(\array_values(\class_uses($class)), $traits);

            $class = \count($parents) ? \array_shift($parents) : null;
        }

        yield from \array_unique($traits);
    }

    /**
     * @return void
     */
    protected function tearDownTestKernel(): void
    {
        foreach ($this->traits(true) as $trait) {
            $destroyMethod = 'destroy' . $trait;

            if (\method_exists($this, $destroyMethod)) {
                $this->{$destroyMethod}();
            }
        }
    }
}

<?php
/**
 * This file is part of Railt package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
declare(strict_types=1);

namespace Railt\Testing\Feature;

/**
 * Trait BootableTraits
 */
trait BootableTraits
{
    /**
     * @return void
     */
    protected function setUpTestKernel(): void
    {
        foreach ($this->traits() as $trait) {
            $bootMethod = 'boot' . \class_basename($trait);

            if (\method_exists($this, $bootMethod)) {
                $this->{$bootMethod}();
            }
        }
    }

    /**
     * @return \Traversable
     */
    private function traits(): \Traversable
    {
        $traits = [];

        $parents = \class_parents(static::class);
        $class   = static::class;

        while ($class !== null) {
            $traits = \array_merge(\array_values(\class_uses($class)), $traits);

            $class = \count($parents) ? \array_shift($parents) : null;
        }

        yield from \array_unique($traits);
    }

    /**
     * @return void
     */
    protected function tearDownTestKernel(): void
    {
        foreach ($this->traits() as $trait) {
            $destroyMethod = 'destroy' . \class_basename($trait);

            if (\method_exists($this, $destroyMethod)) {
                $this->{$destroyMethod}();
            }
        }
    }
}

Fix traits boot/destroy method names

Fix traits boot/destroy method names


<?php
/**
 * UsernameTest.php
 *
 * @copyright 2013 George D. Cooksey, III
 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
 */

namespace VeritasTest\Identity;

use PHPUnit_Framework_TestCase as TestCase;
use Veritas\Identity\Username;

class UsernameTest extends TestCase
{
    public function testClassExists()
    {
        $this->assertTrue(class_exists('Veritas\Identity\Username'));
    }

    public function testClassImplementsCredential()
    {
        $this->assertInstanceOf('Veritas\Identity\Credential', new Username('username'));
    }

    public function testConstructSetsValue()
    {
        $subject = new Username('username');
        $this->assertTrue($subject->verify('username'));
    }

    public function testConstructChecksMinimumLength()
    {
        $this->setExpectedException(
            'Veritas\Identity\Exception\UsernameLengthException',
            'Value must be a minimum of 8 characters'
        );
        new Username('bad');
    }

    public function testConstructChecksMaximumLength()
    {
        $this->setExpectedException(
            'Veritas\Identity\Exception\UsernameLengthException',
            'Value must be a maximum of 125 characters'
        );
        new Username(
            'asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf'
            . 'asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf'
        );
    }

    public function testToStringReturnsValue()
    {
        $subject = new Username('username');
        $this->assertEquals('username', (string) $subject);
    }
}

<?php
/**
 * UsernameTest.php
 *
 * @copyright 2013 George D. Cooksey, III
 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
 */

namespace VeritasTest\Identity;

use PHPUnit_Framework_TestCase as TestCase;
use Veritas\Identity\Username;

class UsernameTest extends TestCase
{
    public function testClassExists()
    {
        $this->assertTrue(class_exists('Veritas\Identity\Username'));
    }

    public function testClassImplementsCredential()
    {
        $this->assertInstanceOf('Veritas\Identity\Credential', new Username('username'));
    }

    public function testConstructSetsValue()
    {
        $subject = new Username('username');
        $this->assertTrue($subject->verify('username'));
    }

    public function testConstructChecksMinimumLength()
    {
        $this->setExpectedException('Veritas\Identity\Exception\UsernameLengthException');
        new Username('bad');
    }

    public function testConstructChecksMaximumLength()
    {
        $this->setExpectedException('Veritas\Identity\Exception\UsernameLengthException');
        new Username(
            'asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf'
            . 'asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf'
        );
    }

    public function testToStringReturnsValue()
    {
        $subject = new Username('username');
        $this->assertEquals('username', (string) $subject);
    }

    public function testEqualsReturnsBool()
    {
        $subject = new Username('username');
        $this->assertFalse($subject->equals(new Username('test failure')));
    }
}

Remove exception messages and add equality test


<?php

namespace App\Http\Controllers;

use App\Http\Requests\UniversityRegisterRequest;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\University;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class RegisterController extends Controller
{
    use CreateUserTrait;

    public function showRegister()
    {
        return view('auth.register');
    }

    /**
     * Create the university and a user instance.
     *
     * @param UniversityRegisterRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function register(UniversityRegisterRequest $request)
    {
        $university = University::create($request->all());
        $user = $this->createAuthenticableUserAndLogin($request, 'university', $university->contact_first_name . ' ' . $university->contact_last_name);

        if (Auth::attempt($user)) {
            return redirect('dashboard');
        }
    }
}

<?php

namespace App\Http\Controllers;

use App\Http\Requests\UniversityRegisterRequest;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\University;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class RegisterController extends Controller
{
    use CreateUserTrait;

    public function showRegister()
    {
        return view('auth.register');
    }

    /**
     * Create the university and a user instance.
     *
     * @param UniversityRegisterRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function register(UniversityRegisterRequest $request)
    {
        $university = University::create($request->all());
        $user = $this->createAuthenticableUserAndLogin($request, 'university', $university->contact_first_name . ' ' . $university->contact_last_name);
        Auth::login($user);
        return redirect('dashboard');
    }
}

Fix for redirect after signing up

Fix for redirect after signing up


<?php

use Galahad\LaravelAddressing\AdministrativeAreaCollection;
use Galahad\LaravelAddressing\Country;

/**
 * Class AdministrativeAreaCollectionTest
 *
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class AdministrativeAreaCollectionTest extends PHPUnit_Framework_TestCase
{
    public function testCollectionClass()
    {
        $country = new Country;
        $brazil = $country->getByCode('BR');
        $states = $brazil->getAdministrativeAreas();

        $this->assertInstanceOf(AdministrativeAreaCollection::class, $states);
    }

    public function testUSStatesCount()
    {
        $country = new Country;
        $us = $country->getByCode('US');
        $states = $us->getAdministrativeAreas();

        $this->assertEquals($states->count(), 62);
    }

    public function testBrazilianStatesCount()
    {
        $country = new Country;
        $brazil = $country->getByName('Brazil');
        $states = $brazil->getAdministrativeAreas();

        $this->assertEquals($states->count(), 27);
    }
}

<?php

use Galahad\LaravelAddressing\AdministrativeAreaCollection;
use Galahad\LaravelAddressing\Country;

/**
 * Class AdministrativeAreaCollectionTest
 *
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class AdministrativeAreaCollectionTest extends PHPUnit_Framework_TestCase
{
    public function testCollectionClass()
    {
        $country = new Country;
        $brazil = $country->getByCode('BR');
        $states = $brazil->getAdministrativeAreas();

        $this->assertInstanceOf(AdministrativeAreaCollection::class, $states);
    }

    public function testUSStatesCount()
    {
        $country = new Country;
        $us = $country->getByCode('US');
        $states = $us->getAdministrativeAreas();

        $this->assertEquals($states->count(), 62);
    }

    public function testBrazilianStatesCount()
    {
        $country = new Country;
        $brazil = $country->getByName('Brazil');
        $states = $brazil->getAdministrativeAreas();

        $this->assertEquals($states->count(), 27);
    }

    public function testCollectionList()
    {
        $country = new Country();
        $usStates = $country->getByCode('US')->getAdministrativeAreas()->toList();

        $this->assertTrue(isset($usStates['AL']));
        $this->assertTrue(isset($usStates['CO']));
        $this->assertTrue(isset($usStates['CA']));
    }
}

Test administrative area list feature

Test administrative area list feature


<?php
return array(
    'cdli-twostagesignup' => array(
        'test_database_schema_up'   => 'schema_up.mysql.sql',
        'test_database_schema_down' => 'schema_down.sql',
    ),
    'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => function ($sm) use ($dbParams) {
                return new Zend\Db\Adapter\Adapter(array(
                    'driver'    => 'pdo',
                    'dsn'       => 'mysql:dbname=travis_test;host=localhost',
                    'database'  => 'travis_test',
                    'username'  => 'root',
                    'password'  => '',
                    'hostname'  => 'localhost',
                ));
            },
        ),
    ),
);

<?php
return array(
    'cdli-twostagesignup' => array(
        'test_database_schema_up'   => 'schema_up.mysql.sql',
        'test_database_schema_down' => 'schema_down.sql',
    ),
    'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => function ($sm) {
                return new Zend\Db\Adapter\Adapter(array(
                    'driver'    => 'pdo',
                    'dsn'       => 'mysql:dbname=travis_test;host=localhost',
                    'database'  => 'travis_test',
                    'username'  => 'root',
                    'password'  => '',
                    'hostname'  => 'localhost',
                ));
            },
        ),
    ),
);

Remove unnecessary variable from SM factory closure ($dbParams)


<?php
$start = microtime(true);
set_time_limit(0);
require_once(dirname(__FILE__).'/../../alpha/config/sfrootdir.php');

// check cache before loading anything
require_once("../lib/KalturaResponseCacher.php");
$cache = new KalturaResponseCacher();
$cache->checkOrStart();

require_once("../bootstrap.php");

KalturaLog::setContext("syndicationFeedRenderer");

KalturaLog::debug(">------------------------------------- syndicationFeedRenderer -------------------------------------");
KalturaLog::info("syndicationFeedRenderer-start ");

$feedId = $_GET['feedId'];
$entryId = @$_GET['entryId'];
try
{
	$syndicationFeedRenderer = new KalturaSyndicationFeedRenderer($feedId);
	$syndicationFeedRenderer->addFlavorParamsAttachedFilter();

	if (isset($entryId))
		$syndicationFeedRenderer->addEntryAttachedFilter($entryId);

	$syndicationFeedRenderer->execute();
}
catch(Exception $ex)
{
	header('KalturaSyndication: '.$ex->getMessage());
	die;
}

$end = microtime(true);
KalturaLog::info("syndicationFeedRenderer-end [".($end - $start)."]");
KalturaLog::debug("<------------------------------------- syndicationFeedRenderer -------------------------------------");

$cache->end();

?>

<?php
$start = microtime(true);
set_time_limit(0);
require_once(dirname(__FILE__).'/../../alpha/config/sfrootdir.php');

// check cache before loading anything
require_once("../lib/KalturaResponseCacher.php");
$cache = new KalturaResponseCacher();
$cache->checkOrStart();

require_once("../bootstrap.php");

KalturaLog::setContext("syndicationFeedRenderer");

KalturaLog::debug(">------------------------------------- syndicationFeedRenderer -------------------------------------");
KalturaLog::info("syndicationFeedRenderer-start ");

kCurrentContext::$ps_vesion = 'ps3';
$feedId = $_GET['feedId'];
$entryId = @$_GET['entryId'];
try
{
	$syndicationFeedRenderer = new KalturaSyndicationFeedRenderer($feedId);
	$syndicationFeedRenderer->addFlavorParamsAttachedFilter();

	if (isset($entryId))
		$syndicationFeedRenderer->addEntryAttachedFilter($entryId);

	$syndicationFeedRenderer->execute();
}
catch(Exception $ex)
{
	header('KalturaSyndication: '.$ex->getMessage());
	die;
}

$end = microtime(true);
KalturaLog::info("syndicationFeedRenderer-end [".($end - $start)."]");
KalturaLog::debug("<------------------------------------- syndicationFeedRenderer -------------------------------------");

$cache->end();

?>

Set kCurrentContext::$ps_vesion = 'ps3' to support dynamic enums in mrss feeds

git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@63256 6b8eccd3-e8c5-4e7d-8186-e12b5326b719


<?php
/**
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
 * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com)
 */

namespace ZF\ApiProblem\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZF\ApiProblem\Listener\ApiProblemListener;

class ApiProblemListenerFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     * @return ApiProblemListener
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $filters = null;
        $config  = [];

        if ($serviceLocator->has('Config')) {
            $config = $serviceLocator->get('Config');
        }

        if (isset($config['zf-api-problem']['accept_filters'])) {
            $filters = $config['zf-api-problem']['accept_filters'];
        }

        return new ApiProblemListener($filters);
    }
}

<?php
/**
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
 * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com)
 */

namespace ZF\ApiProblem\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZF\ApiProblem\Listener\ApiProblemListener;

class ApiProblemListenerFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     * @return ApiProblemListener
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $filters = null;
        $config  = array();

        if ($serviceLocator->has('Config')) {
            $config = $serviceLocator->get('Config');
        }

        if (isset($config['zf-api-problem']['accept_filters'])) {
            $filters = $config['zf-api-problem']['accept_filters'];
        }

        return new ApiProblemListener($filters);
    }
}

Change minimimum required PHP version to 5.3.23

- Remove [] array notation


<?php

namespace Controllers;

use Widgets\HelloWidget;

/**
 * Widget Controller
 *
 * @author José María Valera Reales
 */
class WidgetController extends BaseController {

	/**
	 * Setup
	 */
	public static function setup() {
		HelloWidget::register();

	}
}

<?php

namespace Controllers;

use Widgets\HelloWidget;
use Widgets\LangWidget;
use Widgets\WidgetBase;

/**
 * Widget Controller
 *
 * @author José María Valera Reales
 */
class WidgetController extends BaseController {

	/**
	 * Setup
	 */
	public function setup() {
		$widgets = [
			new HelloWidget(),
			new LangWidget()
		];

		foreach ( $widgets as $w ) {
			$w->register();
		}
	}
}

Update WigdetController->register. Put the active widgets in array


<?php namespace Felixkiss\UniqueWithValidator;

use Illuminate\Support\ServiceProvider;

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

        // Registering the validator extension with the validator factory
        $this->app['validator']->resolver(
            function($translator, $data, $rules, $messages, $customAttributes = array())
            {
                return new ValidatorExtension(
                    $translator,
                    $data,
                    $rules,
                    $messages,
                    $customAttributes
                );
            }
        );
    }

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

    }
}

<?php namespace Felixkiss\UniqueWithValidator;

use Illuminate\Support\ServiceProvider;

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        // Whenever the validator factory is accessed in the container, we set
        // the custom resolver on it (this works in Larvel >= 5.2 as well).
        $this->app->resolving('validator', function ($factory, $app) {
            $factory->resolver(function ($translator, $data, $rules, $messages, $customAttributes = []) {
                return new ValidatorExtension(
                    $translator,
                    $data,
                    $rules,
                    $messages,
                    $customAttributes
                );
            });
        });
    }
}

Switch to a new way of setting the resolver on the validation factory

This is necessary, because since Laravel 5.2 the validator service provider is
deferred. We can't set it once at the beginning. Now it gets set in a callback
whenever someone resolves `validator` from the service container.

This also solves #18. We don't really need to defer anymore, because if the
validator service is not used, this service provider essentially only adds a
single entry to an array in the service container.


<?php

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

namespace Symfony\Bundle\FrameworkBundle\CacheWarmer;

use Symfony\Component\ClassLoader\ClassCollectionLoader;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;

/**
 * Generates the Class Cache (classes.php) file.
 *
 * @author Tugdual Saunier <tucksaun@gmail.com>
 */
class ClassCacheCacheWarmer implements CacheWarmerInterface
{
    /**
     * Warms up the cache.
     *
     * @param string $cacheDir The cache directory
     */
    public function warmUp($cacheDir)
    {
        $classmap = $cacheDir.'/classes.map';

        if (!is_file($classmap)) {
            return;
        }

        ClassCollectionLoader::load(include($classmap), $cacheDir, 'classes', false);
    }

    /**
     * Checks whether this warmer is optional or not.
     *
     * @return bool always true
     */
    public function isOptional()
    {
        return true;
    }
}

<?php

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

namespace Symfony\Bundle\FrameworkBundle\CacheWarmer;

use Symfony\Component\ClassLoader\ClassCollectionLoader;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;

/**
 * Generates the Class Cache (classes.php) file.
 *
 * @author Tugdual Saunier <tucksaun@gmail.com>
 */
class ClassCacheCacheWarmer implements CacheWarmerInterface
{
    /**
     * Warms up the cache.
     *
     * @param string $cacheDir The cache directory
     */
    public function warmUp($cacheDir)
    {
        $classmap = $cacheDir.'/classes.map';

        if (!is_file($classmap)) {
            return;
        }

        if (file_exists($cacheDir.'/classes.php')) {
            return;
        }

        ClassCollectionLoader::load(include($classmap), $cacheDir, 'classes', false);
    }

    /**
     * Checks whether this warmer is optional or not.
     *
     * @return bool always true
     */
    public function isOptional()
    {
        return true;
    }
}

[FrameworkBundle] Fix ClassCacheWarme when classes.php is already warmed


<?php

use Hubzero\Content\Migration\Base;

// No direct access
defined('_HZEXEC_') or die();

/**
 * Migration script for adding User - Auto-approve plugin
 **/
class Migration20180831000000PlgUserAutoapprove extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		$this->addPluginEntry('user', 'autoapprove');
	}

	/**
	 * Down
	 **/
	public function down()
	{
		$this->deletePluginEntry('user', 'autoapprove');
	}
}

<?php

use Hubzero\Content\Migration\Base;

// No direct access
defined('_HZEXEC_') or die();

/**
 * Migration script for adding User - Auto-approve plugin
 **/
class Migration20180831000000PlgUserAutoapprove extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		$this->addPluginEntry('user', 'autoapprove', 0);
	}

	/**
	 * Down
	 **/
	public function down()
	{
		$this->deletePluginEntry('user', 'autoapprove');
	}
}

Install as disabled by default

[fix] Install as disabled by default


<?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

function validator_username($input, $parameter = '', $message = '')
{
	global $prefs;
	$userlib = TikiLib::lib('user');
	if ($userlib->user_exists($input)) {
		return tra("User already exists");
	}
	if (!empty($prefs['username_pattern']) && !preg_match($prefs['username_pattern'], $input)) {
		return tra("Invalid character combination for username");
	}
	if (strtolower($input) == 'anonymous' || strtolower($input) == 'registered') {
		return tra("Invalid username");
	}
	if (strlen($input) > $prefs['max_username_length']) {
		$error = tr("Username cannot contain more than %0 characters", $prefs['max_username_length']);
		return $error;
	}
	if (strlen($input) < $prefs['min_username_length']) {
		$error = tr("Username must be at least %0 characters long", $prefs['min_username_length']);
		return $error;
	}
	return true;
}

<?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

function validator_username($input, $parameter = '', $message = '')
{
	global $prefs;
	$userlib = TikiLib::lib('user');
	if ($prefs['login_is_email'] === 'y') {
		if ($userlib->get_user_by_email($input)) {
			return tra("Email already in use");
		}
		if (!validate_email($input)){
			return tra("Invalid email");
		}
	} else {
		if ($userlib->user_exists($input)) {
			return tra("User already exists");
		}
		if (!empty($prefs['username_pattern']) && !preg_match($prefs['username_pattern'], $input)) {
			return tra("Invalid character combination for username");
		}
		if (strtolower($input) == 'anonymous' || strtolower($input) == 'registered') {
			return tra("Invalid username");
		}
		if (strlen($input) > $prefs['max_username_length']) {
			$error = tr("Username cannot contain more than %0 characters", $prefs['max_username_length']);
			return $error;
		}
		if (strlen($input) < $prefs['min_username_length']) {
			$error = tr("Username must be at least %0 characters long", $prefs['min_username_length']);
			return $error;
		}
	}
	return true;
}

[FIX] Fix email (as username) validation when login_is_email pref is on

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@59506 b456876b-0849-0410-b77d-98878d47e9d5


<?php

class ModLoader implements ISystemComponent
{

    public function __construct()
    {

        $this->loadAllMods ();

    }

    private function loadAllMods ()
    {

        $modFiles = scandir ("system/mods");

        for ($i = 0; $i <= 1; $i++)
            array_splice ($modFiles, 0, 1);

        foreach ($modFiles as $file)
            require_once ("system/mods/" . $file);

    }

    public static function getInstance()
    {

        return new self ();

    }

}

<?php

class ModLoader implements ISystemComponent
{

    public function __construct()
    {

        $this->loadAllMods ();

    }

    private function loadAllMods ()
    {

        $modFiles = glob ("system/mods/*.php");

        foreach ($modFiles as $file)
            require_once ("system/mods/" . $file);

    }

    public static function getInstance()
    {

        return new self ();

    }

}

Use glob instead of scandir

Use glob instead of scandir


<?php

namespace Couscous\Module\Template\Step;

use Couscous\Model\LazyFile;
use Couscous\Model\Project;
use Couscous\Step;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;

/**
 * Load asset files from the template directory.
 *
 * Assets are any file that is not a Twig template.
 *
 * @author Matthieu Napoli <matthieu@mnapoli.fr>
 */
class LoadAssets implements Step
{
    /**
     * @var Filesystem
     */
    private $filesystem;

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

    public function __invoke(Project $project)
    {
        if (! $project->metadata['template.directory']) {
            return;
        }

        $files = new Finder();
        $files->files()
            ->in($project->metadata['template.directory'])
            ->notName('*.twig');

        $project->watchlist->watchFiles($files);

        foreach ($files as $file) {
            /** @var SplFileInfo $file */
            $project->addFile(new LazyFile($file->getPathname(), $file->getRelativePathname()));
        }
    }
}

<?php

namespace Couscous\Module\Template\Step;

use Couscous\Model\LazyFile;
use Couscous\Model\Project;
use Couscous\Step;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;

/**
 * Load asset files from the template directory.
 *
 * Assets are any file that is not a Twig template.
 *
 * @author Matthieu Napoli <matthieu@mnapoli.fr>
 */
class LoadAssets implements Step
{
    /**
     * @var Filesystem
     */
    private $filesystem;

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

    public function __invoke(Project $project)
    {
        if (! $project->metadata['template.directory']) {
            return;
        }

        $files = new Finder();
        $files->files()
            ->in($project->metadata['template.directory'])
            ->ignoreDotFiles(false)
            ->notName('*.twig');

        $project->watchlist->watchFiles($files);

        foreach ($files as $file) {
            /** @var SplFileInfo $file */
            $project->addFile(new LazyFile($file->getPathname(), $file->getRelativePathname()));
        }
    }
}

Make sure that hidden files are taken into account (e.g. .nojekyll)


<?php
function parseArgs(){
	$env = Environment::getInstance();
	$editor = new Chigi\Sublime\Settings\Environment();
	$args=array();
	for ($i=0;$i<count($_SERVER['argv']);$i++){
		$currentArgs=strtolower($_SERVER['argv'][$i]);
		$currentValue="";
		$position=strpos($currentArgs,"=");
		if ($position >0) {
			$argsName=substr($currentArgs,0,$position);
			$argsValue=substr($currentArgs,$position+1);
			$args["$argsName"]=$argsValue;
		}
	}
	return $args;
}
?>

<?php
function parseArgs(){
	$env = Environment::getInstance();
	$editor = new Chigi\Sublime\Settings\Environment();
	$args=array();
	for ($i=0;$i<count($_SERVER['argv']);$i++){
		$currentArgs=strtolower($_SERVER['argv'][$i]);
		$currentValue="";
		$position=strpos($currentArgs,"=");
		if ($position >0) {
			$argsName=substr($currentArgs,0,$position);
			$argsValue=substr($currentArgs,$position+1);
			$args["$argsName"]=$argsValue;
		}
	}
	return $args;
}

// 设定 错误转异常控制器
set_error_handler('exceptions_error_handler');

function exceptions_error_handler($severity, $message, $filename, $lineno) {
    if (error_reporting() == 0) {
        return;
    }
    if (error_reporting() & $severity) {
        if(strpos($message,"Undefined offset:") !== FALSE){
            throw new \Chigi\Sublime\Exception\ArrayIndexOutOfBoundsException($message, 0, new ErrorException($message, 0, $severity, $filename, $lineno));
        }else{
            throw new ErrorException($message, 0, $severity, $filename, $lineno);
        }
    }
}

?>

ADD set_error_handler for error exception catch.

Signed-off-by: Richard Lea <5e20e57f18b15612bae274c2aef7dc395ee6b2a1@zoho.com>


<?php

/*
 * This file is part of the Liquid package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @package Liquid
 */

namespace Liquid\Tag;

use Liquid\TestCase;

class TagRawTest extends TestCase
{
	public function testRaw()
	{
		$this->assertTemplateResult(
			'{{ y | plus: x }}{{{hello}}} is equal to 11.',
			'{% raw %}{{ y | plus: x }}{{{hello}}}{% endraw %} is equal to 11.',
			array('x' => 5, 'y' => 6)
		);

		$this->assertTemplateResult('', '{% raw %}{% endraw %}');
	}
}

<?php

/*
 * This file is part of the Liquid package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @package Liquid
 */

namespace Liquid\Tag;

use Liquid\TestCase;

class TagRawTest extends TestCase
{
	public function testRaw()
	{
		$this->assertTemplateResult(
			'{{ y | plus: x }}{% if %} is equal to 11.',
			'{% raw %}{{ y | plus: x }}{% if %}{% endraw %} is equal to 11.',
			array('x' => 5, 'y' => 6)
		);

		$this->assertTemplateResult('', '{% raw %}{% endraw %}');
	}
}

Test that raw tag ignores other tags

Test that raw tag ignores other tags


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\AdminBundle\DataFixtures\ORM\Administrator;

use Darvin\AdminBundle\Entity\Administrator;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

/**
 * Load administrator data
 */
class LoadAdministratorData implements FixtureInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        $manager->persist($this->createAdministrator());
        $manager->flush();
    }

    /**
     * @return \Darvin\AdminBundle\Entity\Administrator
     */
    private function createAdministrator()
    {
        $administrator = new Administrator(array(Administrator::ROLE_SUPERADMIN));

        return $administrator
            ->setPlainPassword('123')
            ->setUsername('admin');
    }
}

<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2015, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\AdminBundle\DataFixtures\ORM\Administrator;

use Darvin\AdminBundle\Entity\Administrator;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

/**
 * Load administrator data
 */
class LoadAdministratorData implements FixtureInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        $manager->persist($this->createAdministrator());
        $manager->flush();
    }

    /**
     * @return \Darvin\AdminBundle\Entity\Administrator
     */
    private function createAdministrator()
    {
        $administrator = new Administrator(array(Administrator::ROLE_SUPERADMIN));

        return $administrator
            ->setPlainPassword('admin')
            ->setUsername('admin');
    }
}

Change password in administrator data fixture.


<?php
/**
 * Created by PhpStorm.
 * User: Nabeel
 * Date: 2015-10-16
 * Time: 6:42 PM
 */

namespace app\components;

use yii\base\Component;

class Crawler extends Component
{

    public function readTitle($url)
    {
        $content = $this->fetchUrl($url);
        $crawler = new \Symfony\Component\DomCrawler\Crawler();
        $crawler->addHtmlContent($content);
        $node = $crawler->filterXPath('html/head/title');
        if ($node->count() > 0)
            return $node->first()->text();
        return null;
    }

    private function fetchUrl($url){
        $curlOptions = [
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_CONNECTTIMEOUT => 30,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ];
        $curl = curl_init($url);

        foreach ($curlOptions as $option => $value) {
            curl_setopt($curl, $option, $value);
        }

        $response = curl_exec($curl);
        return $response;
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: Nabeel
 * Date: 2015-10-16
 * Time: 6:42 PM
 */

namespace app\components;

use yii\base\Component;
use yii\log\Logger;

class Crawler extends Component
{
    public $enabled = true;

    public function readTitle($url)
    {
        if (!$this->enabled)
            return null;

        try
        {
            $content = $this->fetchUrl($url);
        }
        catch (\Exception $e)
        {
            \Yii::getLogger()->log("Crawler fetchUrl exception: {$e->getMessage()}", Logger::LEVEL_ERROR);
            return null;
        }

        try
        {
            $crawler = new \Symfony\Component\DomCrawler\Crawler();
            $crawler->addHtmlContent($content);
            $node = $crawler->filterXPath('html/head/title');
            if ($node->count() > 0)
                return $node->first()->text();
        }
        catch (\Exception $e)
        {
            \Yii::getLogger()->log("Crawler DOM extraction exception: {$e->getMessage()}", Logger::LEVEL_ERROR);
        }
        return null;
    }

    private function fetchUrl($url){
        $curlOptions = [
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_CONNECTTIMEOUT => 30,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ];
        $curl = curl_init($url);

        foreach ($curlOptions as $option => $value) {
            curl_setopt($curl, $option, $value);
        }

        $response = curl_exec($curl);
        return $response;
    }
}

Add some error handling in the crawler

Add some error handling in the crawler

The crawler will silently return nothing if it's disabled or if fetch or parser error happen.


<?php

/*
 * This file is part of WordPlate.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

if (config('app.updates', false)) {

    /*
     * Remove option to update themes.
     */
    remove_action('load-update-core.php', 'wp_update_themes');
    wp_clear_scheduled_hook('wp_update_themes');

    /*
     * Prevent from seeing core updates.
     */
    wp_clear_scheduled_hook('wp_version_check');
    remove_action('wp_maybe_auto_update', 'wp_maybe_auto_update');
    remove_action('admin_init', 'wp_maybe_auto_update');
    remove_action('admin_init', 'wp_auto_update_core');
    wp_clear_scheduled_hook('wp_maybe_auto_update');

    /*
     * Removes plugin update notification.
     */
    remove_action('load-update-core.php', 'wp_update_plugins');
    wp_clear_scheduled_hook('wp_update_plugins');

    /*
     * Disable all automatic updates.
     */
    add_filter('auto_update_translation', '__return_false');
    add_filter('automatic_updater_disabled', '__return_true');
    add_filter('allow_minor_auto_core_updates', '__return_false');
    add_filter('allow_major_auto_core_updates', '__return_false');
    add_filter('allow_dev_auto_core_updates', '__return_false');
    add_filter('auto_update_core', '__return_false');
    add_filter('wp_auto_update_core', '__return_false');
    add_filter('auto_core_update_send_email', '__return_false');
    add_filter('send_core_update_notification_email', '__return_false');
    add_filter('auto_update_plugin', '__return_false');
    add_filter('auto_update_theme', '__return_false');
    add_filter('automatic_updates_send_debug_email', '__return_false');
    add_filter('automatic_updates_is_vcs_checkout', '__return_true');
    add_filter('pre_site_transient_update_plugins', '__return_null');
}

<?php

/*
 * This file is part of WordPlate.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

if (config('app.updates', false) && !current_user_can('manage_options')) {
    /*
     * Disable plugin and theme update and installation.
     */
    define('DISALLOW_FILE_MODS', true);
}

Disable Plugin and Theme Update and Installation

This closes #19


<?php

$elFinderPath = APPDIR .'Modules/MediaManager/Lib/elFinder/';

require $elFinderPath .'elFinderConnector.class.php';
require $elFinderPath .'elFinder.class.php';
require $elFinderPath .'elFinderVolumeDriver.class.php';
require $elFinderPath .'elFinderVolumeLocalFileSystem.class.php';

/**
 * Simple function to demonstrate how to control file access using "accessControl" callback.
 * This method will disable accessing files/folders starting from '.' (dot)
 *
 * @param  string  $attr  attribute name (read|write|locked|hidden)
 * @param  string  $path  file path relative to volume root directory started with directory separator
 * @return bool|null
 **/

function access($attr, $path, $data, $volume)
{
    return (strpos(basename($path), '.') === 0)       // if file/folder begins with '.' (dot)
            ? ! ($attr == 'read' || $attr == 'write') // set read+write to false, other (locked+hidden) set to true
            :  null;                                  // else elFinder decide it itself
}

// Retrieve the options.
$options = Config::get('elfinder');

// Create a elFinder instance.
$elfinder = new \elFinder($options);

$connector = new \elFinderConnector($elfinder, true);

// Run the elFinder Connector.
$connector->run();

<?php

$elFinderPath = APPDIR .'Modules/MediaManager/Lib/elFinder/';

require $elFinderPath .'elFinderConnector.class.php';
require $elFinderPath .'elFinder.class.php';
require $elFinderPath .'elFinderVolumeDriver.class.php';
require $elFinderPath .'elFinderVolumeLocalFileSystem.class.php';

/**
 * Simple function to demonstrate how to control file access using "accessControl" callback.
 * This method will disable accessing files/folders starting from '.' (dot)
 *
 * @param  string  $attr  attribute name (read|write|locked|hidden)
 * @param  string  $path  file path relative to volume root directory started with directory separator
 * @return bool|null
 **/

function access($attr, $path, $data, $volume)
{
    return (strpos(basename($path), '.') === 0)       // if file/folder begins with '.' (dot)
            ? ! ($attr == 'read' || $attr == 'write') // set read+write to false, other (locked+hidden) set to true
            :  null;                                  // else elFinder decide it itself
}

// Retrieve the options.
$options = Config::get('elfinder');

// Create a elFinder instance.
$elfinder = new elFinder($options);

// Create a elFinder Connector instance.
$connector = new elFinderConnector($elfinder, true);

// Run the elFinder Connector.
$connector->run();

Improve the elFinder connector on MediaManager Module