<?php
namespace Concrete\Core\Updater\Migrations\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Comparator;
use Doctrine\DBAL\Schema\Schema;

class Version5704 extends AbstractMigration
{

    public function getName()
    {
        return '20140930000000';
    }

    public function up(Schema $schema)
    {
        $config = $schema->getTable('Config');
        $fromConfig = clone $config;
        $db = \Database::get();
        $platform = $db->getDatabasePlatform();
        $config->dropPrimaryKey();
        $config->setPrimaryKey(array('configNamespace', 'configGroup', 'configItem'));
        $comparator = new Comparator();
        $diff = $comparator->diffTable($fromConfig, $config);
        $sql = $platform->getAlterTableSQL($diff);
        if (is_array($sql) && count($sql)) {
            foreach ($sql as $q) {
                $db->query($q);
            }
        }
    }

    public function down(Schema $schema)
    {
    }
}

<?php
namespace Concrete\Core\Updater\Migrations\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Comparator;
use Doctrine\DBAL\Schema\Schema;

class Version5704 extends AbstractMigration
{

    public function getName()
    {
        return '20140930000000';
    }

    public function up(Schema $schema)
    {
        \Database::query('UPDATE Config SET configNamespace="" WHERE configNamespace IS NULL');

        $config = $schema->getTable('Config');
        $fromConfig = clone $config;
        $db = \Database::get();
        $platform = $db->getDatabasePlatform();
        $config->dropPrimaryKey();
        $config->setPrimaryKey(array('configNamespace', 'configGroup', 'configItem'));
        $comparator = new Comparator();
        $diff = $comparator->diffTable($fromConfig, $config);
        $sql = $platform->getAlterTableSQL($diff);
        if (is_array($sql) && count($sql)) {
            foreach ($sql as $q) {
                $db->query($q);
            }
        }
    }

    public function down(Schema $schema)
    {
    }
}

Change null namespaces to empty string on upgrade

Former-commit-id: d7c529c257869772bce5cf4b06520a241904a808


<?php

namespace DeltaCli\Extension;

use DeltaCli\Console\Output\Banner;
use DeltaCli\Project;
use DeltaCli\Script\InstallFsevents;
use DeltaCli\Script\SshFixKeyPermissions as SshFixKeyPermissionsScript;
use DeltaCli\Script\SshInstallKey as SshInstallKeyScript;
use Symfony\Component\Console\Output\OutputInterface;

class DefaultScripts implements ExtensionInterface
{
    public function extend(Project $project)
    {
        $project->addScript(new InstallFsevents($project));
        $project->addScript(new SshFixKeyPermissionsScript($project));
        $project->addScript(new SshInstallKeyScript($project));

        $project->createScript('deploy', 'Deploy this project.')
            ->requireEnvironment()
            ->addDefaultStep($project->gitStatusIsClean())
            ->addDefaultStep($project->gitBranchMatchesEnvironment())
            ->addDefaultStep($project->fixSshKeyPermissions())
            ->setPlaceholderCallback(
                function (OutputInterface $output) {
                    $banner = new Banner($output);
                    $banner->setBackground('cyan');
                    $banner->render('A deploy script has not yet been created for this project.');

                    $output->writeln(
                        [
                            'Learn more about how to write a good deploy script for your project on Github at:',
                            '<fg=blue;options=underscore>https://github.com/DeltaSystems/delta-cli-tools</>'
                        ]
                    );
                }
            );
    }
}

<?php

namespace DeltaCli\Extension;

use DeltaCli\Console\Output\Banner;
use DeltaCli\Project;
use DeltaCli\Script\InstallFsevents;
use DeltaCli\Script\SshFixKeyPermissions as SshFixKeyPermissionsScript;
use DeltaCli\Script\SshInstallKey as SshInstallKeyScript;
use Symfony\Component\Console\Output\OutputInterface;

class DefaultScripts implements ExtensionInterface
{
    public function extend(Project $project)
    {
        $project->addScript(new InstallFsevents($project));
        $project->addScript(new SshFixKeyPermissionsScript($project));
        $project->addScript(new SshInstallKeyScript($project));

        $project->createScript('deploy', 'Deploy this project.')
            ->requireEnvironment()
            ->addDefaultStep($project->gitStatusIsClean())
            ->addDefaultStep($project->gitBranchMatchesEnvironment())
            ->addDefaultStep($project->fixSshKeyPermissions())
            ->addDefaultStep($project->logAndSendNotifications())
            ->setPlaceholderCallback(
                function (OutputInterface $output) {
                    $banner = new Banner($output);
                    $banner->setBackground('cyan');
                    $banner->render('A deploy script has not yet been created for this project.');

                    $output->writeln(
                        [
                            'Learn more about how to write a good deploy script for your project on Github at:',
                            '<fg=blue;options=underscore>https://github.com/DeltaSystems/delta-cli-tools</>'
                        ]
                    );
                }
            );
    }
}

Add logAndSendNotifications() to deploy script by default.


<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller {

	public function action_index()
	{
		$this->response->body('hello, world!');
	}

} // End Welcome

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller {

	public function action_index()
	{
		$this->response->body('Welcome to your app!');
	}

} // End Welcome

Change message for the default Controller


<?php
/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Flarum\Settings\SettingsRepositoryInterface;

return [
    'up' => function (SettingsRepositoryInterface $settings) {
        $settings->set('flarum-tags.max_primary_tags', '1');
        $settings->set('flarum-tags.min_primary_tags', '1');
        $settings->set('flarum-tags.max_secondary_tags', '3');
        $settings->set('flarum-tags.min_secondary_tags', '0');
    },

    'down' => function (SettingsRepositoryInterface $settings) {
        $settings->delete('flarum-tags.max_primary_tags');
        $settings->delete('flarum-tags.max_secondary_tags');
        $settings->delete('flarum-tags.min_primary_tags');
        $settings->delete('flarum-tags.min_secondary_tags');
    }
];

<?php
/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Flarum\Database\Migration;

return Migration::addSettings([
    'flarum-tags.max_primary_tags' => '1',
    'flarum-tags.min_primary_tags' => '1',
    'flarum-tags.max_secondary_tags' => '3',
    'flarum-tags.min_secondary_tags' => '0',
]);

Use new shortcut for default settings migration


<?php

/**
 * Testimonial model
 *
 * @package     Nails
 * @subpackage  module-testimonial
 * @category    Model
 * @author      Nails Dev Team
 * @link
 */

namespace Nails\Testimonial\Model;

use Nails\Common\Model\Base;

class Testimonial extends Base
{
    /**
     * Model constructor
     **/
    public function __construct()
    {
        parent::__construct();
        $this->table             = NAILS_DB_PREFIX . 'testimonial';
        $this->defaultSortColumn = 'quote';
        $this->searchableFields  = ['quote', 'quote_by'];
    }
}

<?php

/**
 * Testimonial model
 *
 * @package     Nails
 * @subpackage  module-testimonial
 * @category    Model
 * @author      Nails Dev Team
 * @link
 */

namespace Nails\Testimonial\Model;

use Nails\Common\Model\Base;

class Testimonial extends Base
{
    const TABLE               = NAILS_DB_PREFIX . 'testimonial';
    const DEFAULT_SORT_COLUMN = 'quote';

    // --------------------------------------------------------------------------

    /**
     * Model constructor
     **/
    public function __construct()
    {
        parent::__construct();
        $this->searchableFields  = ['quote', 'quote_by'];
    }
}

Use constants for model configuration

Use constants for model configuration


<?php
require_once('class/3rdparty/OAuth.php');
require_once('class/3rdparty/twitter.class.php');

/**
  * Generate tweet string
  **/
class Tweet
{
    /**
     * Generate tweet from body
     * Returns array of tweets
     *
     * @param $body
     * @return array or false if no data
     */
    public function generate($status)
    {
        if ($status == '') return null;
        $tweetlength = 140;

        // Splits into tweet-length number of characters, breaking at
        // new line
        $tweet_lines = explode("\n", $status);
        $tweets = [''];
        foreach ($tweet_lines as $n => $line) {
                $current_tweet_id = count($tweets) - 1;
                $length_of_current_tweet = strlen($tweets[$current_tweet_id]);
                $length_of_line_to_add = strlen($line);
                if ($length_of_current_tweet + $length_of_line_to_add < $tweetlength) {
                    $tweets[$current_tweet_id] .= $line . "\n";
                } else {
                    $tweets[] = $line;
                }
        }

        return $tweets;
    }

    public function post($tweet)
    {
        if (true == MMS_DEBUG) {
            echo $tweet;
        } else {
            $twitter = new Twitter(
                TWITTER_CONSUMERKEY,
                TWITTER_CONSUMERSECRET,
                TWITTER_ACCESSTOKEN,
                TWITTER_ACCESSTOKENSECRET
            );
            $twitter->send($tweet);
        }
    }
}

<?php
require_once('class/3rdparty/OAuth.php');
require_once('class/3rdparty/twitter.class.php');

/**
  * Generate tweet string
  **/
class Tweet
{
    /**
     * Generate tweet from body
     * Returns array of tweets
     *
     * @param $body
     * @return array or false if no data
     */
    public function generate($status)
    {
        if ($status == '') return null;
        $tweetlength = 140;

        // Splits into tweet-length number of characters, breaking at
        // new line
        $tweet_lines = explode("\n", $status);
        $tweets = [''];
        foreach ($tweet_lines as $n => $line) {
                $current_tweet_id = count($tweets) - 1;
                $length_of_current_tweet = strlen($tweets[$current_tweet_id]);
                $length_of_line_to_add = strlen($line);
                if ($length_of_current_tweet + $length_of_line_to_add < $tweetlength) {
                    $tweets[$current_tweet_id] .= $line . "\n";
                } else {
                    $tweets[] = $line . "\n";
                }
        }

        return $tweets;
    }

    public function post($tweet)
    {
        if (true == MMS_DEBUG) {
            echo $tweet;
        } else {
            $twitter = new Twitter(
                TWITTER_CONSUMERKEY,
                TWITTER_CONSUMERSECRET,
                TWITTER_ACCESSTOKEN,
                TWITTER_ACCESSTOKENSECRET
            );
            $twitter->send($tweet);
        }
    }
}

Add missing line break on the first status line


<?php

namespace Amp\Dns\Test;

use Amp\Dns;
use Amp\Dns\Record;
use Amp\Loop;
use Amp\PHPUnit\TestCase;

class IntegrationTest extends TestCase {
    /**
     * @param string $hostname
     * @group internet
     * @dataProvider provideHostnames
     */
    public function testResolve($hostname) {
        Loop::run(function () use ($hostname) {
            $result = yield Dns\resolve($hostname);

            /** @var Record $record */
            $record = $result[0];
            $inAddr = @\inet_pton($record->getValue());
            $this->assertNotFalse(
                $inAddr,
                "Server name $hostname did not resolve to a valid IP address"
            );
        });
    }

    public function testPtrLookup() {
        Loop::run(function () {
            $result = yield Dns\query("8.8.4.4", Record::PTR);

            /** @var Record $record */
            $record = $result[0];
            $this->assertSame("google-public-dns-b.google.com", $record->getValue());
            $this->assertSame(Record::PTR, $record->getType());
        });
    }

    public function provideHostnames() {
        return [
            ["google.com"],
            ["github.com"],
            ["stackoverflow.com"],
            ["localhost"],
            ["192.168.0.1"],
            ["::1"],
        ];
    }

    public function provideServers() {
        return [
            ["8.8.8.8"],
            ["8.8.8.8:53"],
        ];
    }
}

<?php

namespace Amp\Dns\Test;

use Amp\Dns;
use Amp\Dns\Record;
use Amp\Loop;
use Amp\PHPUnit\TestCase;

class IntegrationTest extends TestCase {
    /**
     * @param string $hostname
     * @group internet
     * @dataProvider provideHostnames
     */
    public function testResolve($hostname) {
        Loop::run(function () use ($hostname) {
            $result = yield Dns\resolve($hostname);

            /** @var Record $record */
            $record = $result[0];
            $inAddr = @\inet_pton($record->getValue());
            $this->assertNotFalse(
                $inAddr,
                "Server name $hostname did not resolve to a valid IP address"
            );
        });
    }

    public function testPtrLookup() {
        Loop::run(function () {
            $result = yield Dns\query("8.8.4.4", Record::PTR);

            /** @var Record $record */
            $record = $result[0];
            $this->assertSame("google-public-dns-b.google.com", $record->getValue());
            $this->assertSame(Record::PTR, $record->getType());
        });
    }

    public function provideHostnames() {
        return [
            ["google.com"],
            ["github.com"],
            ["stackoverflow.com"],
            ["blog.kelunik.com"], /* that's a CNAME to GH pages */
            ["localhost"],
            ["192.168.0.1"],
            ["::1"],
        ];
    }

    public function provideServers() {
        return [
            ["8.8.8.8"],
            ["8.8.8.8:53"],
        ];
    }
}

Add test domain that has a CNAME

Add test domain that has a CNAME


<?php

$config = [];
if (in_array('gs', stream_get_wrappers())) {
    $config = require 'gs://' . getenv('GOOGLE_CLOUD_PROJECT') .'.appspot.com/config/config.php';
}

return array_merge_recursive([
    'DB' => [
        'CONNECTION' => getenv('DB_CONNECTION'),
        'HOST' => getenv('DB_HOST'),
        'PORT' => getenv('DB_PORT'),
        'DATABASE' => getenv('DB_DATABASE'),
        'USERNAME' => getenv('DB_USERNAME'),
        'PASSWORD' => getenv('DB_PASSWORD'),
        'PREFIX' => getenv('DB_PREFIX')
    ],

    'OAUTH' => [
        'identifier' => getenv('OAUTH_CLIENT_ID'),
        "secret" => getenv('OAUTH_CLIENT_SECRET'),
        'callback_uri' => getenv('OAUTH_CALLBACK_URI')
    ],

    'MEMCACHED' => [
        'host' => getenv('MEMCACHED_HOST'),
        'port' => getenv('MEMCACHED_PORT')
    ],

    'BOOTSTRAP' => [
        'path' => __DIR__ . DIRECTORY_SEPARATOR . 'bootstrap'
    ],
    'ROUTER' => [
        'path' => __DIR__ . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'GUI'
    ],
    'PHPVIEW' => [
        'path' => __DIR__ . DIRECTORY_SEPARATOR . 'phpview'
    ],
    'ASSETS' => [
        'path' => __DIR__ . DIRECTORY_SEPARATOR . 'assets'
    ]
], $config);

<?php

$config = [];
if (in_array('gs', stream_get_wrappers())) {
    $config = include 'gs://teach-242612.appspot.com/config/config.php';
}

return array_merge_recursive([
    'DB' => [
        'CONNECTION' => getenv('DB_CONNECTION'),
        'HOST' => getenv('DB_HOST'),
        'PORT' => getenv('DB_PORT'),
        'DATABASE' => getenv('DB_DATABASE'),
        'USERNAME' => getenv('DB_USERNAME'),
        'PASSWORD' => getenv('DB_PASSWORD'),
        'PREFIX' => getenv('DB_PREFIX')
    ],

    'OAUTH' => [
        'identifier' => getenv('OAUTH_CLIENT_ID'),
        "secret" => getenv('OAUTH_CLIENT_SECRET'),
        'callback_uri' => getenv('OAUTH_CALLBACK_URI')
    ],

    'MEMCACHED' => [
        'host' => getenv('MEMCACHED_HOST'),
        'port' => getenv('MEMCACHED_PORT')
    ],

    'BOOTSTRAP' => [
        'path' => __DIR__ . DIRECTORY_SEPARATOR . 'bootstrap'
    ],
    'ROUTER' => [
        'path' => __DIR__ . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'GUI'
    ],
    'PHPVIEW' => [
        'path' => __DIR__ . DIRECTORY_SEPARATOR . 'phpview'
    ],
    'ASSETS' => [
        'path' => __DIR__ . DIRECTORY_SEPARATOR . 'assets'
    ]
], $config);

Revert "enforce including configuration on gae"

This reverts commit f60e153b


<?php

/*
	Copyright (c) 2012 Colin Rotherham, http://colinr.com
	https://github.com/colinrotherham
*/

	namespace CRD\Core;

	class App
	{
		public static $name = '';
		public static $path = '';

		public static $templates = array();
		public static $partials = array();

		public static $cache_enabled = true;
		public static $cache_length = 3600;

		public static $credentials;
		public static $queries;

		public static $debug = false;

		public static function init()
		{
			self::$credentials = (object) array();
			self::$queries = (object) array();
		}
	}

<?php

/*
	Copyright (c) 2012 Colin Rotherham, http://colinr.com
	https://github.com/colinrotherham
*/

	namespace CRD\Core;

	class App
	{
        public static $version = '';

		public static $name = '';
		public static $path = '';

		public static $templates = array();
		public static $partials = array();

		public static $cache_enabled = true;
		public static $cache_length = 3600;

		public static $credentials;
		public static $queries;

		public static $debug = false;

		public static function init()
		{
			self::$credentials = (object) array();
			self::$queries = (object) array();
		}
	}

Add version string to app class

Add version string to app class


<?php

namespace Emphloyer;

/**
 * Cli is the class used by the command line runner to execute input commands.
 */
class Cli {
  protected $lastSignal;
  protected $pipeline;
  protected $numberOfEmployees = 0;

  /**
   * Configure with PHP code from a file.
   */
  public function configure($filename) {
    require $filename;
    $this->numberOfEmployees = $numberOfEmployees;
    $this->pipeline = new Pipeline($pipelineBackend);
  }

  /**
   * Run jobs.
   */
  public function run() {
    $this->workshop = new Workshop(new Boss($this->pipeline), $this->numberOfEmployees);

    declare(ticks = 100);
    pcntl_signal(\SIGINT, array($this, 'handleSignal'));
    $this->workshop->run();
  }

  /**
   * Clear all jobs from the pipeline.
   */
  public function clear() {
    $this->pipeline->clear();
  }

  /**
   * Signal handler.
   * @param int $signo
   */
  public function handleSignal($signo) {
    switch ($signo) {
    case \SIGINT:
      if (!is_null($this->lastSignal) && $this->lastSignal <= (time() - 5)) {
        $this->workshop->stopNow();
      } else {
        $this->lastSignal = time();
        $this->workshop->stop();
      }
      break;
    }
  }
}

<?php

namespace Emphloyer;

/**
 * Cli is the class used by the command line runner to execute input commands.
 */
class Cli {
  protected $lastSignal;
  protected $pipeline;
  protected $numberOfEmployees = 0;

  /**
   * Configure with PHP code from a file.
   */
  public function configure($filename) {
    require $filename;
    $this->numberOfEmployees = $numberOfEmployees;
    $this->pipeline = new Pipeline($pipelineBackend);
  }

  /**
   * Run jobs.
   */
  public function run() {
    $this->workshop = new Workshop(new Boss($this->pipeline), $this->numberOfEmployees);

    declare(ticks = 100);
    pcntl_signal(\SIGINT, array($this, 'handleSignal'));
    pcntl_signal(\SIGTERM, array($this, 'handleSignal'));
    $this->workshop->run();
  }

  /**
   * Clear all jobs from the pipeline.
   */
  public function clear() {
    $this->pipeline->clear();
  }

  /**
   * Signal handler.
   * @param int $signo
   */
  public function handleSignal($signo) {
    switch ($signo) {
    case \SIGINT:
    case \SIGTERM:
      if (!is_null($this->lastSignal) && $this->lastSignal <= (time() - 5)) {
        $this->workshop->stopNow();
      } else {
        $this->lastSignal = time();
        $this->workshop->stop();
      }
      break;
    }
  }
}

Handle the TERM signal like the INT signal


<?php
    if (!isset($_SESSION)) {
        session_start();
    }
?>
<!DOCTYPE html>

<?php
  $beginning = '

      Navigation Bar

';
  $frontLink = '
 <a class="" href="';
  $endLink = '
';

  if (isset($_SESSION['user-type'])) {
      echo $beginning;
      $email = $_SESSION['email'];

      switch ($_SESSION['user-type']) {
      case 'doctor':
		$result = getDoctorDetails($email);
		$speciality = $result['speciality'];

        echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
        echo $frontLink.'patient_info.php?speciality='.$speciality.'"> Upcomming Appointments '.$endLink;
        break;
      case 'clerk':
        echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
        echo $frontLink.'patient_info.php"> All Appointments '.$endLink;
        break;
      default:
        // code...
        break;
    }
      echo '

';
  }

?>

<?php
    if (!isset($_SESSION)) {
        session_start();
    }
?>
<!DOCTYPE html>

<?php
  $beginning = '

      Navigation Bar

';
  $frontLink = '
 <a class="" href="';
  $endLink = '
';

  if (isset($_SESSION['user-type'])) {
      echo $beginning;

      switch ($_SESSION['user-type']) {
      case 'doctor':
		$email = $_SESSION['email'];
		$result = getDoctorDetails($email);
		$speciality = $result['speciality'];

        echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
        echo $frontLink.'patient_info.php?speciality='.$speciality.'"> Upcomming Appointments '.$endLink;
        break;
      case 'clerk':
        echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
        echo $frontLink.'patient_info.php"> All Appointments '.$endLink;
        break;
      default:
        // code...
        break;
    }
      echo '

';
  }

?>

Fix errors showing up because 'email' is not set


<!Doctype html>

    <title><?php wp_title( '·', true, 'right' ); ?></title>

    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="cleartype" content="on">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" href="<?= get_stylesheet_directory_uri(); ?>/assets/images/favicon.ico">
    <link rel="apple-touch-icon" href="<?= get_stylesheet_directory_uri(); ?>/assets/images/apple-touch-icon.png">

    <?php wp_head(); ?>

  <body <?php body_class(); ?>>

<a href="<?= home_url(); ?>"><?php bloginfo( 'name' ); ?>

<?php bloginfo( 'description' ); ?>

      <?php wp_nav_menu(); ?>

      <?php get_search_form(); ?>

<!Doctype html>
<html class="no-js" <?php language_attributes() ?>>

    <title><?php wp_title( '·', true, 'right' ); ?></title>

    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="cleartype" content="on">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" href="<?= get_stylesheet_directory_uri(); ?>/assets/images/favicon.ico">
    <link rel="apple-touch-icon" href="<?= get_stylesheet_directory_uri(); ?>/assets/images/apple-touch-icon.png">

    <?php wp_head(); ?>

  <body <?php body_class(); ?>>

<a href="<?= home_url(); ?>"><?php bloginfo( 'name' ); ?>

<?php bloginfo( 'description' ); ?>

      <?php wp_nav_menu(); ?>

      <?php get_search_form(); ?>

Add language attributes to html tag

Add language attributes to html tag


<?php

namespace Oro\Bundle\NotificationBundle;

use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Oro\Bundle\MessageQueueBundle\DependencyInjection\Compiler\AddTopicMetaPass;
use Oro\Bundle\NotificationBundle\Async\Topics;
use Oro\Bundle\NotificationBundle\DependencyInjection\Compiler\EventsCompilerPass;
use Oro\Bundle\NotificationBundle\DependencyInjection\Compiler\NotificationHandlerPass;

class OroNotificationBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new NotificationHandlerPass());
        $container->addCompilerPass(new EventsCompilerPass(), PassConfig::TYPE_AFTER_REMOVING);

        $addTopicPass = AddTopicMetaPass::create()
            ->add(Topics::SEND_NOTIFICATION_EMAIL)
        ;
        $container->addCompilerPass($addTopicPass);
    }
}

<?php

namespace Oro\Bundle\NotificationBundle;

use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Oro\Bundle\MessageQueueBundle\DependencyInjection\Compiler\AddTopicMetaPass;
use Oro\Bundle\NotificationBundle\Async\Topics;
use Oro\Bundle\NotificationBundle\DependencyInjection\Compiler\EventsCompilerPass;
use Oro\Bundle\NotificationBundle\DependencyInjection\Compiler\NotificationHandlerPass;

class OroNotificationBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new NotificationHandlerPass());
        $container->addCompilerPass(new EventsCompilerPass(), PassConfig::TYPE_AFTER_REMOVING);

        $addTopicPass = AddTopicMetaPass::create()
            ->add(Topics::SEND_NOTIFICATION_EMAIL, 'Sending email notifications')
        ;
        $container->addCompilerPass($addTopicPass);
    }
}

BAP-11752: Replace JMS Job with Message Queue in NotificationBundle

 - registering topic in the bundle


<?php

namespace Phive\Twig\Extensions\Deferred;

class DeferredNodeVisitor implements \Twig_NodeVisitorInterface
{
    public function enterNode(\Twig_NodeInterface $node, \Twig_Environment $env)
    {
        return $node;
    }

    public function leaveNode(\Twig_NodeInterface $node, \Twig_Environment $env)
    {
        return ($node instanceof \Twig_Node_Module)
            ? new DeferredModuleNode($node)
            : $node;
    }

    public function getPriority()
    {
        return 0;
    }
}

<?php

namespace Phive\Twig\Extensions\Deferred;

class DeferredNodeVisitor implements \Twig_NodeVisitorInterface
{
    private $hasDeferred = false;

    public function enterNode(\Twig_NodeInterface $node, \Twig_Environment $env)
    {
        if (!$this->hasDeferred && $node instanceof DeferredNode) {
            $this->hasDeferred = true;
        }

        return $node;
    }

    public function leaveNode(\Twig_NodeInterface $node, \Twig_Environment $env)
    {
        if ($this->hasDeferred && $node instanceof \Twig_Node_Module) {
            $node = new DeferredModuleNode($node);
            $this->hasDeferred = false;
        }

        return $node;
    }

    public function getPriority()
    {
        return 0;
    }
}

Resolve deferred blocks only when it's necessary


<?php
    class Game extends ActiveRecordBase {
        public $id;
        public $created;
        public $width;
        public $height;
        public $rounds;

        public function __construct( $id = false ) {
            if ( $id ) {
                $this->exists = true;
                $game_info = dbSelectOne( 'games', array( 'created', 'width', 'height' ), compact( 'id' ) );
                $this->id = $gameid = $id;
                $this->created = $game_info[ 'created' ];
                $this->width = $game_info[ 'width' ];
                $this->height = $game_info[ 'height' ];
                $rounds = dbSelect( 'roundcreatures', array( 'roundid' ), compact( 'gameid' ) );
                for ( $i = 0; $i <= count( $rounds ); ++$i ) {
                    $this->rounds[ $i ] = new Round( $this, $i );
                }
                $this->created = date('Y-m-d H:i:s');
            }
        }

        protected function validate() {
            if ( !is_int( $this->width ) ) {
                throw new ModelValidationException( 'width_not_valid' );
            }
            if ( !is_int( $this->height ) ) {
                throw new ModelValidationException( 'height_not_valid' );
            }
        }

        protected function create() {
            $width = $this->width;
            $height = $this->height;
            $created = $this->created;
            $this->id = dbInsert(
                'games',
                compact( 'width', 'height', 'created' )
            );
        }
    }
?>

<?php
    class Game extends ActiveRecordBase {
        public $id;
        public $created;
        public $width;
        public $height;
        public $rounds;

        public function __construct( $id = false ) {
            if ( $id ) {
                $this->exists = true;
                $game_info = dbSelectOne( 'games', array( 'created', 'width', 'height' ), compact( 'id' ) );
                $this->id = $gameid = $id;
                $this->created = $game_info[ 'created' ];
                $this->width = $game_info[ 'width' ];
                $this->height = $game_info[ 'height' ];
                $rounds = dbSelect( 'roundcreatures', array( 'roundid' ), compact( 'gameid' ) );
                for ( $i = 0; $i <= count( $rounds ); ++$i ) {
                    $this->rounds[ $i ] = new Round( $this, $i );
                }
            }
        }

        protected function validate() {
            if ( !is_int( $this->width ) ) {
                throw new ModelValidationException( 'width_not_valid' );
            }
            if ( !is_int( $this->height ) ) {
                throw new ModelValidationException( 'height_not_valid' );
            }
        }

        protected function create() {
            $width = $this->width;
            $height = $this->height;
            $created = $this->created = date('Y-m-d H:i:s');
            $this->id = dbInsert(
                'games',
                compact( 'width', 'height', 'created' )
            );
        }
    }
?>

Move created from construct to create

Move created from construct to create


<?php namespace Aedart\Scaffold\Contracts\Templates\Data;

use Aedart\Model\Contracts\Arrays\ChoicesAware;
use Aedart\Model\Contracts\Integers\IdAware;
use Aedart\Model\Contracts\Integers\TypeAware;
use Aedart\Model\Contracts\Strings\QuestionAware;
use Aedart\Model\Contracts\Strings\ValueAware;
use Aedart\Util\Interfaces\Populatable;
use ArrayAccess;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use JsonSerializable;

/**
 * Template Data Property
 *
 * TODO: Desc...
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Contracts\Templates\Data
 */
interface Property extends IdAware,
    TypeAware,
    QuestionAware,
    ChoicesAware,
    ValueAware,
    ValidationAware,
    PostProcessAware,

    ArrayAccess,
    Arrayable,
    Jsonable,
    JsonSerializable,
    Populatable
{

}

<?php namespace Aedart\Scaffold\Contracts\Templates\Data;

use Aedart\Model\Contracts\Arrays\ChoicesAware;
use Aedart\Model\Contracts\Integers\IdAware;
use Aedart\Model\Contracts\Integers\TypeAware;
use Aedart\Model\Contracts\Strings\QuestionAware;
use Aedart\Model\Contracts\Strings\ValueAware;
use Aedart\Util\Interfaces\Populatable;
use ArrayAccess;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use JsonSerializable;

/**
 * Template Data Property
 *
 * A data object that contains the final
 * value which can be used inside a template and or
 * meta information on how to obtain the value.
 *
 * Each property has a type, which can be used to
 * determine how the value must be obtained.
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Contracts\Templates\Data
 */
interface Property extends IdAware,
    TypeAware,
    QuestionAware,
    ChoicesAware,
    ValueAware,
    ValidationAware,
    PostProcessAware,
    ArrayAccess,
    Arrayable,
    Jsonable,
    JsonSerializable,
    Populatable
{

}

Add interface documentation and cleanup

Add interface documentation and cleanup


<?php
namespace LBChat\Command\Server;

use LBChat\ChatClient;
use LBChat\ChatServer;
use LBChat\Utils\String;

class ChatCommand extends Command implements IServerCommand {
	protected $from;
	protected $to;
	protected $message;

	public function __construct(ChatServer $server, ChatClient $from, ChatClient $to = null, $message) {
		parent::__construct($server);
		$this->from = $from;
		$this->to = $to;
		$this->message = $message;
	}

	public function execute(ChatClient $client) {
		$username    = String::encodeSpaces($this->from->getUsername());
		$display     = String::encodeSpaces($this->from->getDisplayName());
		$destination = "";
		$access = $this->from->getAccess();
		$message = urlencode($this->message);

		if ($this->to !== null)
			$destination = String::encodeSpaces($this->to->getDisplayName());

		//TODO: Invisible user chats to mods+ only
		//TODO: Shadow banning

		//Broadcast a chat message to everyone
		//TODO: Send commands
		$client->send("CHAT $username $display $destination $access $message");
	}
}

<?php
namespace LBChat\Command\Server;

use LBChat\ChatClient;
use LBChat\ChatServer;
use LBChat\Utils\String;

class ChatCommand extends Command implements IServerCommand {
	protected $from;
	protected $to;
	protected $message;

	public function __construct(ChatServer $server, ChatClient $from, ChatClient $to = null, $message) {
		parent::__construct($server);
		$this->from = $from;
		$this->to = $to;
		$this->message = $message;
	}

	public function execute(ChatClient $client) {
		$username    = String::encodeSpaces($this->from->getUsername());
		$display     = String::encodeSpaces($this->from->getDisplayName());
		$destination = "";
		$access = $this->from->getAccess();
		$message = urlencode($this->message);

		if ($this->to !== null)
			$destination = String::encodeSpaces($this->to->getUsername());

		//TODO: Invisible user chats to mods+ only
		//TODO: Shadow banning

		//Broadcast a chat message to everyone
		//TODO: Send commands
		$client->send("CHAT $username $display $destination $access $message");
	}
}

Use username, not display name, for recipient


<?php
/**
 * Yii2 FancyBox Extension
 * @author Paul P <bigpaulie25ro@yahoo.com>
 * @license MIT
 */
namespace bigpaulie\fancybox;

use yii\web\AssetBundle;

class FancyBoxAsset extends AssetBundle{

    public $sourcePath = '@bower/fancybox';

    public $css = [
        'source/jquery.fancybox.css',
        'source/helpers/fancybox-buttons.css',
        'source/helpers/fancybox-thumbs.css',
    ];

    public $js = [
        'source/jquery.fancybox.js',
        'lib/jquery.mousewheel-3.0.6.pack.js',
        'source/helpers/jquery.fancybox-buttons.js',
        'source/helpers/jquery.fancybox-thumbs.js',
    ];

    public $depends = [
        'yii\web\JqueryAsset',
    ];

}

<?php
/**
 * Yii2 FancyBox Extension
 * @author Paul P <bigpaulie25ro@yahoo.com>
 * @license MIT
 */
namespace bigpaulie\fancybox;

use yii\web\AssetBundle;

class FancyBoxAsset extends AssetBundle{

    public $sourcePath = '@bower/fancybox';

    public $css = [
        'source/jquery.fancybox.css',
        'source/helpers/jquery.fancybox-buttons.css',
        'source/helpers/jquery.fancybox-thumbs.css',
    ];

    public $js = [
        'source/jquery.fancybox.js',
        'lib/jquery.mousewheel-3.0.6.pack.js',
        'source/helpers/jquery.fancybox-buttons.js',
        'source/helpers/jquery.fancybox-thumbs.js',
    ];

    public $depends = [
        'yii\web\JqueryAsset',
    ];

}

Fix bug helpers css path

Fix bug helpers css path


<?php
namespace Sil\SilAuth\auth;

use Psr\Log\LoggerInterface;
use Sil\Idp\IdBroker\Client\IdBrokerClient;

class IdBroker
{
    /** @var IdBrokerClient */
    protected $client;

    /** @var LoggerInterface */
    protected $logger;

    /**
     *
     * @param string $baseUri The base of the API's URL.
     *     Example: 'https://api.example.com/'.
     * @param string $accessToken Your authorization access (bearer) token.
     * @param LoggerInterface $logger
     */
    public function __construct($baseUri, $accessToken, LoggerInterface $logger)
    {
        $this->logger = $logger;
        $this->client = new IdBrokerClient($baseUri, $accessToken);
    }

    /**
     * Attempt to authenticate with the given username and password, returning
     * the attributes for that user if the credentials were acceptable (or null
     * if they were not acceptable, since there is no authenticated user in that
     * situation).
     *
     * @param string $username The username.
     * @param string $password The password.
     * @return array|null The user's attributes (if successful), otherwise null.
     */
    public function getAuthenticatedUser(string $username, string $password)
    {
        $result = $this->client->authenticate([
            'username' => $username,
            'password' => $password,
        ]);
        $statusCode = $result['statusCode'] ?? null;
        if (intval($statusCode) === 200) {
            unset($result['statusCode']);
            return $result;
        }
        return null;
    }
}

<?php
namespace Sil\SilAuth\auth;

use Psr\Log\LoggerInterface;
use Sil\Idp\IdBroker\Client\IdBrokerClient;

class IdBroker
{
    /** @var IdBrokerClient */
    protected $client;

    /** @var LoggerInterface */
    protected $logger;

    /**
     *
     * @param string $baseUri The base of the API's URL.
     *     Example: 'https://api.example.com/'.
     * @param string $accessToken Your authorization access (bearer) token.
     * @param LoggerInterface $logger
     */
    public function __construct(
        string $baseUri,
        string $accessToken,
        LoggerInterface $logger
    ) {
        $this->logger = $logger;
        $this->client = new IdBrokerClient($baseUri, $accessToken);
    }

    /**
     * Attempt to authenticate with the given username and password, returning
     * the attributes for that user if the credentials were acceptable (or null
     * if they were not acceptable, since there is no authenticated user in that
     * situation).
     *
     * @param string $username The username.
     * @param string $password The password.
     * @return array|null The user's attributes (if successful), otherwise null.
     */
    public function getAuthenticatedUser(string $username, string $password)
    {
        $result = $this->client->authenticate([
            'username' => $username,
            'password' => $password,
        ]);
        $statusCode = $result['statusCode'] ?? null;
        if (intval($statusCode) === 200) {
            unset($result['statusCode']);
            return $result;
        }
        return null;
    }
}

Make argument types more specific.

Make argument types more specific.


<?php
class Kwc_Basic_LinkTag_Trl_Admin extends Kwc_Basic_LinkTag_Admin
{
    public function getPagePropertiesForm()
    {
        $ret = new Kwc_Basic_LinkTag_Trl_Form(null, $this->_class);
        $fs = new Kwf_Form_Container_FieldSet(trlKwf('Link'));
        foreach ($ret as $f) {
            $ret->fields->remove($f);
            $fs->add($f);
        }
        $ret->add($fs);
        return $ret;
    }
}

<?php
class Kwc_Basic_LinkTag_Trl_Admin extends Kwc_Basic_LinkTag_Admin
{
    public function getPagePropertiesForm()
    {
        $ret = new Kwc_Abstract_Cards_Trl_Form(null, $this->_class);
        $fs = new Kwf_Form_Container_FieldSet(trlKwf('Link'));
        foreach ($ret as $f) {
            $ret->fields->remove($f);
            $fs->add($f);
        }
        $ret->add($fs);
        return $ret;
    }
}

Set correct class-name for form.

Set correct class-name for form.

Old class wasn't existing anymore because it was moved in kwc_abstract_cards


<?php

// Setup
require_once '../cassowary/cassowary-setup.php';

// force CAS authentication

if (phpCAS::isAuthenticated()) {
	phpCAS::logoutWithRedirectService($_SERVER["SCRIPT_URI"]);
}
?>
<!DOCTYPE html>

		<title>403 Forbidden</title>
		<meta name="viewport" content="width=device-width, initial-scale=1">

Logout successful

You have successfully logged out.

Click here to login again

For security reasons, exit your web browser.

<?php

// Setup
require_once '../cassowary/cassowary-setup.php';

// force CAS authentication

if (phpCAS::isAuthenticated()) {
	phpCAS::logoutWithRedirectService($_SERVER["SCRIPT_URI"]);
}
?>
<!DOCTYPE html>

		<title>403 Forbidden</title>
		<meta name="viewport" content="width=device-width, initial-scale=1">

Logout successful

You have successfully logged out.

Click here to login to <?php echo $_SERVER["HTTP_HOST"] ?> again

For security reasons, exit your web browser.

Make login link explicit about host.

Make login link explicit about host.


<?php

namespace Alchemy\RestBundle\EventListener;

use Alchemy\RestBundle\Rest\Request\SortOptionsFactory;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class SortParamRequestListener implements EventSubscriberInterface
{
    /**
     * @var SortOptionsFactory
     */
    private $factory;

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

    /**
     * @param GetResponseEvent $event
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        $attributes = $request->attributes;

        if (($config = $attributes->get('_sort', false)) === false) {
            return;
        }

        if (! is_array($config)) {
            return;
        }

        $request->attributes->set('sort', $this->factory->create($request->query->all(), $config));
    }

    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::REQUEST => array('onKernelRequest', -2048)
        );
    }
}

<?php

namespace Alchemy\RestBundle\EventListener;

use Alchemy\RestBundle\Rest\Request\SortOptionsFactory;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class SortParamRequestListener implements EventSubscriberInterface
{
    /**
     * @var SortOptionsFactory
     */
    private $factory;

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

    /**
     * @param GetResponseEvent $event
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        $attributes = $request->attributes;

        if (($config = $attributes->get('_sort', false)) === false) {
            return;
        }

        if (! is_array($config)) {
            $config = array();
        }

        $request->attributes->set('sort', $this->factory->create($request->query->all(), $config));
    }

    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::REQUEST => array('onKernelRequest', -2048)
        );
    }
}

Make sort param request listener accept non-array configuration


@extends('layouts.app')

@section('content')

Modalities

@foreach ($modalities->chunk(2) as $chunk )

		@foreach ($chunk as $modality)
			{{ $modality->id }}
			{{ $modality->modality }}
			<form action="/admin/modalities/{{ $modality->id }}/edit" method="POST">
				<button type="submit">Edit</button>
			</form>
		@endforeach

@endforeach

Add a Modality

<form action="/admin/modalities" method="POST">
	{{ csrf_field() }}
New Modality: <input type="TEXT" name="modality" size="25" />
<button type="SUBMIT">Add modality</button> / Main
</form>

@endsection

@extends('layouts.app')

@section('content')

Modalities

Click a modality to edit

@foreach ($modalities->chunk(2) as $chunk )

		@foreach ($chunk as $modality)
			{{ $modality->id }}
			id }}/edit">{{ $modality->modality }}
		@endforeach

@endforeach

Add a Modality

<form class="form-inline" action="/admin/modalities" method="POST">

		{{ csrf_field() }}
		New Modality: <input type="TEXT" class="form-control" id="modality" name="modality" size="25" />
		<button class="btn btn-default" type="SUBMIT">Add modality</button> / Main

</form>

@endsection

Make each modality a link to the edit page instead of using a form


<?php

namespace SimplyTestable\WorkerBundle\Controller;

use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputArgument;
use SimplyTestable\WorkerBundle\Services\WorkerService;

class StatusController extends BaseController
{

    public function indexAction()
    {
        $thisWorker = $this->getWorkerService()->get();
        return $this->sendResponse($thisWorker);
    }

    /**
     *
     * @return WorkerService
     */
    private function getWorkerService() {
        return $this->container->get('simplytestable.services.workerservice');
    }
}

<?php

namespace SimplyTestable\WorkerBundle\Controller;

use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputArgument;
use SimplyTestable\WorkerBundle\Services\WorkerService;

class StatusController extends BaseController
{

    public function indexAction()
    {
        $status = array();
        $thisWorker = $this->getWorkerService()->get();

        $status['hostname'] = $thisWorker->getHostname();
        $status['state'] = $thisWorker->getState()->getName();
        $status['version'] = $this->getLatestGitHash();

       // var_dump($)

        return $this->sendResponse($status);
    }

    private function getLatestGitHash() {
        return trim(shell_exec("git log | head -1 | awk {'print $2;'}"));
    }

    /**
     *
     * @return WorkerService
     */
    private function getWorkerService() {
        return $this->container->get('simplytestable.services.workerservice');
    }
}

Add latest git hash to status output

Add latest git hash to status output


@!@
entity_id = configRegistry.get('saml/idp/entityID',
		'https://%(hostname)s.%(domainname)s/simplesamlphp/saml2/idp/metadata.php'
		% configRegistry)

hostname = baseConfig.get('hostname')
domainname = baseConfig.get('domainname')
url = baseConfig.get('privacyidea/saml/url', 'https://%s.%s/privacyidea' % (hostname, domainname))
realm = baseConfig.get('privacyidea/saml/realm', '')
verifyhost = baseConfig.get('privacyidea/saml/verifyhost', 'True')
verifypeer = baseConfig.get('privacyidea/saml/verifypeer', 'True')
uid = baseConfig.get('privacyidea/saml/uidkey', 'uid')
enabled = baseConfig.get('privacyidea/saml/enable')

if enabled == 'authsource' or enabled == 'true':
	print "$metadata['%s']['auth'] = 'privacyidea';" % (entity_id,)
elif enabled == 'authproc':
	print """
    $metadata['%s']['authproc'] = array(
		25 => array(
			'class' => 'privacyidea:privacyidea',
			'privacyideaserver' => '%s',
			'realm' => '%s',
			'uidKey' => '%s',
			'sslverifyhost' => %s,
			'sslverifypeer' => %s,
		),
	);
	""" % (entity_id, url, realm, uid, verifyhost, verifypeer)
@!@

@!@
entity_id = configRegistry.get('saml/idp/entityID',
		'https://%(hostname)s.%(domainname)s/simplesamlphp/saml2/idp/metadata.php'
		% configRegistry)

hostname = baseConfig.get('hostname')
domainname = baseConfig.get('domainname')
url = baseConfig.get('privacyidea/saml/url', 'https://%s.%s/privacyidea' % (hostname, domainname))
realm = baseConfig.get('privacyidea/saml/realm', '')
verifyhost = baseConfig.get('privacyidea/saml/verifyhost', 'True')
verifypeer = baseConfig.get('privacyidea/saml/verifypeer', 'True')
uid = baseConfig.get('privacyidea/saml/uidkey', 'uid')
enabled = baseConfig.get('privacyidea/saml/enable')

if enabled == 'authsource' or enabled.lower() == 'true':
	print "$metadata['%s']['auth'] = 'privacyidea';" % (entity_id,)
elif enabled == 'authproc':
	print """
    $metadata['%s']['authproc'] = array(
		25 => array(
			'class' => 'privacyidea:privacyidea',
			'privacyideaserver' => '%s',
			'realm' => '%s',
			'uidKey' => '%s',
			'sslverifyhost' => %s,
			'sslverifypeer' => %s,
		),
	);
	""" % (entity_id, url, realm, uid, verifyhost, verifypeer)
@!@

Make template accept "True" and "true"

Make template accept "True" and "true"


<?php namespace StudioBonito\SilverStripe\TypeKit\Extensions;

use FieldList;
use TextField;

/**
 * Add configuration option to SiteConfig for setting the TypeKit ID.
 *
 * @author       Tom Densham <tom.densham@studiobonito.co.uk>
 * @copyright    Studio Bonito Ltd.
 */
class TypeKitSiteConfigExtension extends \DataExtension
{
    /**
     * List of database fields. {@link DataObject::$db}
     *
     * @var array
     */
    private static $db = array(
        'TypeKitID' => 'Varchar(32)'
    );

    public function updateCMSFields(FieldList $fields)
    {
        $fields->addFieldToTab(
            'Root.TypeKit',
            TextField::create('TypeKitID')
        );
    }
}

<?php namespace StudioBonito\SilverStripe\TypeKit\Extensions;

use FieldList;
use TextField;

/**
 * Add configuration option to SiteConfig for setting the TypeKit ID.
 *
 * @author       Tom Densham <tom.densham@studiobonito.co.uk>
 * @copyright    Studio Bonito Ltd.
 */
class TypeKitSiteConfigExtension extends \DataExtension
{
    /**
     * List of database fields. {@link DataObject::$db}
     *
     * @var array
     */
    private static $db = array(
        'TypeKitID' => 'Varchar(32)'
    );

    public function updateCMSFields(FieldList $fields)
    {
        $fields->addFieldToTab(
            'Root.Services.TypeKit',
            TextField::create('TypeKitID')
        );
    }
}

Move typekit id field to services tab

ADD: Move typekit id field to services tab


<?php declare(strict_types = 1);
namespace PharIo\Phive;

use PharIo\FileSystem\Filename;

class HomePharsXmlMigration extends InternalFileMigration {
    public function __construct(Config $config) {
        parent::__construct(
            $config->getHomeDirectory()->file('phars.xml'),
            $config->getRegistry()
        );
    }

    public function mustMigrate(): bool {
        return true;
    }

    public function getDescription(): string {
        return 'Change the name of the list of all installed Phars file.';
    }

    protected function doMigrate(Filename $legacy, Filename $new): void {
        $new->putContent($legacy->read()->getContent());
    }

    protected function getFileDescription(): string {
        return 'list of installed phars';
    }
}

<?php declare(strict_types = 1);
namespace PharIo\Phive;

use PharIo\FileSystem\Filename;

class HomePharsXmlMigration extends InternalFileMigration {
    public function __construct(Config $config) {
        parent::__construct(
            $config->getHomeDirectory()->file('phars.xml'),
            $config->getRegistry()
        );
    }

    public function mustMigrate(): bool {
        return true;
    }

    public function getDescription(): string {
        return 'Rename internal storage file from `phars.xml` to `registry.xml`.';
    }

    protected function doMigrate(Filename $legacy, Filename $new): void {
        $new->putContent($legacy->read()->getContent());
    }

}

Change description message on internal migration

First step to address #258


<?php

namespace MessageBird\Common;

use MessageBird\Exceptions;

/**
 * Class ResponseError
 *
 * @package MessageBird\Common
 */
class ResponseError
{

    const SUCCESS = 1;

    const REQUEST_NOT_ALLOWED = 2;

    const MISSING_PARAMS = 9;
    const INVALID_PARAMS = 10;

    const NOT_FOUND = 20;

    const NOT_ENOUGH_CREDIT = 25;

    public $errors = array ();

    /**
     * Load the error data into an array.
     * Throw an exception when important errors are found.
     *
     * @param $body
     *
     * @throws Exceptions\BalanceException
     * @throws Exceptions\AuthenticateException
     */
    public function __construct($body)
    {
        if (!empty($body->errors)) {
            foreach ($body->errors AS $error) {

                if ($error->code === self::NOT_ENOUGH_CREDIT) {
                    throw new Exceptions\BalanceException;
                } elseif ($error->code === self::REQUEST_NOT_ALLOWED) {
                    throw new Exceptions\AuthenticateException;
                }

                $this->errors[] = $error;
            }
        }
    }

    /**
     * Get the error string to show in the Exception message.
     *
     * @return string
     */
    public function getErrorString()
    {
        $errorString = array ();
        foreach ($this->errors AS $error) {
            $errorString[] = $error->description;
        }

        return implode(', ', $errorString);
    }
}

<?php

namespace MessageBird\Common;

use MessageBird\Exceptions;

/**
 * Class ResponseError
 *
 * @package MessageBird\Common
 */
class ResponseError
{

    const SUCCESS = 1;

    const REQUEST_NOT_ALLOWED = 2;

    const MISSING_PARAMS = 9;
    const INVALID_PARAMS = 10;

    const NOT_FOUND = 20;

    const NOT_ENOUGH_CREDIT = 25;

    const CHAT_API_AUTH_ERROR = 1001;

    public $errors = array ();

    /**
     * Load the error data into an array.
     * Throw an exception when important errors are found.
     *
     * @param $body
     *
     * @throws Exceptions\BalanceException
     * @throws Exceptions\AuthenticateException
     */
    public function __construct($body)
    {
        if (!empty($body->errors)) {
            foreach ($body->errors AS $error) {

                if ($error->code === self::NOT_ENOUGH_CREDIT) {
                    throw new Exceptions\BalanceException;
                } elseif ($error->code === self::REQUEST_NOT_ALLOWED) {
                    throw new Exceptions\AuthenticateException;
                } elseif ($error->code === self::CHAT_API_AUTH_ERROR) {
                    throw new Exceptions\AuthenticateException;
                }

                $this->errors[] = $error;
            }
        }
    }

    /**
     * Get the error string to show in the Exception message.
     *
     * @return string
     */
    public function getErrorString()
    {
        $errorString = array ();
        foreach ($this->errors AS $error) {
            $errorString[] = $error->description;
        }

        return implode(', ', $errorString);
    }
}

Throw an appropriate AuthenticateException when a chat-api authentication error code is encountered.


<?php
class Kwc_TextImage_ApiContent implements Kwf_Component_ApiContent_Interface
{
    public function getContent(Kwf_Component_Data $data)
    {
        $ret = array();
        $row = $data->getComponent()->getRow();
        if ($row->image) {
            if ($row->position) {
                $ret['position'] = $row->position;
            }
            if ($row->image_width) {
                $ret['imageWidth'] = $row->image_width;
            }
            if ($row->flow) {
                $ret['flow'] = $row->flow;
            }
            $ret['image'] = $data->getChildComponent('-image');
        }
        $ret['text'] = $data->getChildComponent('-text');
        return $ret;
    }
}

<?php
class Kwc_TextImage_ApiContent implements Kwf_Component_ApiContent_Interface
{
    public function getContent(Kwf_Component_Data $data)
    {
        $ret = array();
        $row = $data->getComponent()->getRow();
        if ($row->image) {
            if ($row->position) {
                $ret['position'] = $row->position;
            }
            if ($row->image_width) {
                $ret['imageWidth'] = $row->image_width;
            }
            if ($row->flow) {
                $ret['flow'] = !!$row->flow;
            }
            $ret['image'] = $data->getChildComponent('-image');
        }
        $ret['text'] = $data->getChildComponent('-text');
        return $ret;
    }
}

TextImage: Improve data-type of flow attribute in content-api


<?php namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler {

	/**
	 * A list of the exception types that should not be reported.
	 *
	 * @var array
	 */
	protected $dontReport = [
		'Symfony\Component\HttpKernel\Exception\HttpException'
	];

	/**
	 * Report or log an exception.
	 *
	 * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
	 *
	 * @param  \Exception  $e
	 * @return void
	 */
	public function report(Exception $e)
	{
		return parent::report($e);
	}

	/**
	 * Render an exception into a response.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Exception  $e
	 * @return \Illuminate\Http\Response
	 */
	public function render($request, Exception $e)
	{
		if ($this->isHttpException($e))
		{
			return $this->renderHttpException($e);
		}
		else
		{
			return parent::render($request, $e);
		}
	}

}

<?php namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler {

	/**
	 * A list of the exception types that should not be reported.
	 *
	 * @var array
	 */
	protected $dontReport = [
		'Symfony\Component\HttpKernel\Exception\HttpException'
	];

	/**
	 * Report or log an exception.
	 *
	 * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
	 *
	 * @param  \Exception  $e
	 * @return void
	 */
	public function report(Exception $e)
	{
		return parent::report($e);
	}

	/**
	 * Render an exception into an HTTP response.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Exception  $e
	 * @return \Illuminate\Http\Response
	 */
	public function render($request, Exception $e)
	{
		if ($this->isHttpException($e))
		{
			return $this->renderHttpException($e);
		}
		else
		{
			return parent::render($request, $e);
		}
	}

}

Clarify the type of response we're looking for.


<?php

namespace Longman\TelegramBot\Entities;

abstract class Factory
{
    abstract public static function make(array $data, string $bot_username): Entity;

    public static function resolveEntityClass(string $class, mixed $property, string $bot_username = ''): Entity
    {
        if (is_a($property, $class)) {
            return $property;
        } elseif (is_subclass_of($class, Factory::class)) {
            return $class::make($property, $bot_username);
        }

        return new $class($property, $bot_username);
    }
}

<?php

namespace Longman\TelegramBot\Entities;

abstract class Factory
{
    abstract public static function make(array $data, string $bot_username): Entity;

    public static function resolveEntityClass(string $class, mixed $property, string $bot_username = ''): Entity
    {
        if (is_a($property, $class)) {
            return $property;
        }

        if (is_subclass_of($class, Factory::class)) {
            return $class::make($property, $bot_username);
        }

        return new $class($property, $bot_username);
    }
}

Make use of early returns

Make use of early returns

Co-authored-by: Armando Lüscher <26943035120015382c5c160fee1d053cebeae5a6@noplanman.ch>


<?php

/** @var $di \Aura\Di\Container */

$di->setter["MattyG\Framework\Core\Entity\Database"]["setDB"] = $di->get("db");
$di->setter["MattyG\Framework\Core\Entity\DatabaseCollection"]["setDB"] = $di->get("db");

Add DB setter for DatabaseCollection.

Add DB setter for DatabaseCollection.

Even though DatabaseCollection uses Database, Database won't show up in
the return array from class_uses(). Why, PHP? Why?


<?php

namespace Orchestra\Testbench\Dusk;

use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;

abstract class TestCase extends Foundation
{
    /**
     * Prepare for Dusk test execution.
     *
     * @beforeClass
     *
     * @return void
     */
    public static function prepare()
    {
        static::startChromeDriver();
    }

    /**
     * Create the RemoteWebDriver instance.
     *
     * @return \Facebook\WebDriver\Remote\RemoteWebDriver
     */
    protected function driver()
    {
        $options = (new ChromeOptions())->addArguments([
            '--headless',
            '--disable-gpu',
        ]);

        return RemoteWebDriver::create(
            'http://localhost:9515',
            DesiredCapabilities::chrome()->setCapability(
                ChromeOptions::CAPABILITY,
                $options
            )
        );
    }

    /**
     * Begin a server for the tests.
     */
    public static function setUpBeforeClass()
    {
        static::serve();
    }

    /**
     * Kill our server.
     */
    public static function tearDownAfterClass()
    {
        static::stopServing();
    }
}

<?php

namespace Orchestra\Testbench\Dusk;

use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;

abstract class TestCase extends Foundation
{
    /**
     * Prepare for Dusk test execution.
     *
     * @beforeClass
     *
     * @return void
     */
    public static function prepare()
    {
        static::startChromeDriver();
    }

    /**
     * Create the RemoteWebDriver instance.
     *
     * @return \Facebook\WebDriver\Remote\RemoteWebDriver
     */
    protected function driver()
    {
        $options = (new ChromeOptions())->addArguments([
            '--disable-gpu',
        ]);

        return RemoteWebDriver::create(
            'http://localhost:9515',
            DesiredCapabilities::chrome()->setCapability(
                ChromeOptions::CAPABILITY,
                $options
            )
        );
    }

    /**
     * Begin a server for the tests.
     */
    public static function setUpBeforeClass()
    {
        static::serve();
    }

    /**
     * Kill our server.
     */
    public static function tearDownAfterClass()
    {
        static::stopServing();
    }
}

Remove headless option for Webdriver

Remove headless option for Webdriver

Snuck in during the merge.


<?php

/*
 * This file is part of the yandex-pdd-api project.
 *
 * (c) AmaxLab 2017 <http://www.amaxlab.ru>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AmaxLab\YandexPddApi\Curl;

/**
 * @author Egor Zyuskin <ezyuskin@amaxlab.ru>
 */
class CurlResponse
{
    const STATUS_CODE_OK = 200;

    /**
     * @var string
     */
    private $content;

    /**
     * @var int
     */
    private $statusCode;

    /**
     * @param int $statusCode
     * @param string $content
     */
    public function __construct($statusCode, $content)
    {
        $this->statusCode = $statusCode;
        $this->content = $content;
    }

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

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

    /**
     * @return object
     */
    public function getJson()
    {
        return json_decode($this->getContent());
    }
}

<?php

/*
 * This file is part of the yandex-pdd-api project.
 *
 * (c) AmaxLab 2017 <http://www.amaxlab.ru>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AmaxLab\YandexPddApi\Curl;

/**
 * @author Egor Zyuskin <ezyuskin@amaxlab.ru>
 */
class CurlResponse
{
    const STATUS_CODE_OK = 200;

    /**
     * @var string
     */
    private $content;

    /**
     * @var int
     */
    private $statusCode;

    /**
     * @param int $statusCode
     * @param string $content
     */
    public function __construct($statusCode, $content)
    {
        //print $content;
        $this->statusCode = $statusCode;
        $this->content = $content;
    }

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

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

    /**
     * @return object
     */
    public function getJson()
    {
        return json_decode($this->getContent());
    }
}

Add debug for curl response

Add debug for curl response


<?php namespace Orchestra\Support\Providers;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

abstract class CommandServiceProvider extends BaseServiceProvider
{
    /**
     * The commands to be registered.
     *
     * @var array
     */
    protected $commands = [];

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        foreach (array_keys($this->commands) as $command) {
            $method = "register{$command}Command";

            call_user_func_array([$this, $method], []);
        }

        $this->commands(array_values($this->commands));
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array_values($this->commands);
    }
}

<?php namespace Orchestra\Support\Providers;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

abstract class CommandServiceProvider extends BaseServiceProvider
{
    /**
     * The commands to be registered.
     *
     * @var array
     */
    protected $commands = [];

    /**
     * Additional provides.
     *
     * @var array
     */
    protected $provides = [];

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        foreach (array_keys($this->commands) as $command) {
            $method = "register{$command}Command";

            call_user_func_array([$this, $method], []);
        }

        $this->commands(array_values($this->commands));
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array_values($this->commands);
    }
}

Allow to register additional service location other than command.

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


<?php
// This may take a looong time

// nuke output buffering
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
ob_implicit_flush(1);
ini_set('max_execution_time',180000);
ini_set('memory_limit',"512M");

foreach (array("client","comment","item","project","task","timeSheet","wiki") as $i) {
  flush();
  //echo "<br>Optimizing index: ".$i." ... ";
  $index = Zend_Search_Lucene::open(ATTACHMENTS_DIR.'search/'.$i);
  $index->optimize();
  //echo "done.";
  flush();
}

?>

<?php
// This may take a looong time

// nuke output buffering
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
ob_implicit_flush(1);
ini_set('max_execution_time',180000);
ini_set('memory_limit',"512M");

foreach (array("client","comment","item","project","task","timeSheet","wiki") as $i) {

  rename(ATTACHMENTS_DIR.'search'.DIRECTORY_SEPARATOR.$i,
         ATTACHMENTS_DIR.'search'.DIRECTORY_SEPARATOR.$i."_backup_".date("Y-m-d"));

  if (!is_dir(ATTACHMENTS_DIR.'search'.DIRECTORY_SEPARATOR.$i)) {
    $index = Zend_Search_Lucene::create(ATTACHMENTS_DIR.'search'.DIRECTORY_SEPARATOR.$i);
    $index->commit();
  }
  $index = Zend_Search_Lucene::open(ATTACHMENTS_DIR.'search'.DIRECTORY_SEPARATOR.$i);
  $index->optimize();
}

?>

Modify search index optimize() patch to remove and re-create indexes.


<?php

use Illuminate\Database\Migrations\Migration;
use Orchestra\App;
use Orchestra\Model\Role;

class OrchestraControlSeedAcls extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		$role    = Role::admin();
		$acl     = App::acl();
		$actions = array('Manage Roles', 'Manage Acl');

		$acl->actions()->fill($actions);
		$acl->allow($role->name, $actions);
	}

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

}

<?php

use Illuminate\Database\Migrations\Migration;
use Orchestra\Support\Facades\App;
use Orchestra\Model\Role;

class OrchestraControlSeedAcls extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		$role    = Role::admin();
		$acl     = App::acl();
		$actions = array('Manage Roles', 'Manage Acl');

		$acl->actions()->fill($actions);
		$acl->allow($role->name, $actions);
	}

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

}

Use facade instead of alias.

Use facade instead of alias.

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


<?php

namespace SumoCoders\FrameworkMultiUserBundle\Command;

use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidPasswordConfirmationException;
use SumoCoders\FrameworkMultiUserBundle\User\UserRepositoryCollection;

class PasswordResetHandler
{
    /**
     * @var UserRepositoryCollection
     */
    private $userRepositoryCollection;

    public function __construct(UserRepositoryCollection $userRepositoryCollection)
    {
        $this->userRepositoryCollection = $userRepositoryCollection;
    }

    /**
     * @param ResetPassword $command
     *
     * @throws InvalidPasswordConfirmationException
     */
    public function handle(ResetPassword $command)
    {
        if ($command->passwordConfirmationIsValid()) {
            $user = $command->getUser();
            $updatedUser = clone $user;
            $updatedUser->setPassword($command->getPassword());
            $updatedUser->clearPasswordResetToken();
            $repository = $this->userRepositoryCollection->findRepositoryByClassName(get_class($user));
            $repository->update($user, $updatedUser);

            return;
        }

        throw new InvalidPasswordConfirmationException('The password confirmation isn\'t valid');
    }
}

<?php

namespace SumoCoders\FrameworkMultiUserBundle\Command;

use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidPasswordConfirmationException;
use SumoCoders\FrameworkMultiUserBundle\User\UserRepositoryCollection;

class PasswordResetHandler
{
    /**
     * @var UserRepositoryCollection
     */
    private $userRepositoryCollection;

    public function __construct(UserRepositoryCollection $userRepositoryCollection)
    {
        $this->userRepositoryCollection = $userRepositoryCollection;
    }

    /**
     * @param ResetPassword $command
     *
     * @throws InvalidPasswordConfirmationException
     */
    public function handle(ResetPassword $command)
    {
        if (!$command->passwordConfirmationIsValid()) {
            throw new InvalidPasswordConfirmationException('The password confirmation isn\'t valid');
        }

        $user = $command->getUser();
        $updatedUser = clone $user;
        $updatedUser->setPassword($command->getPassword());
        $updatedUser->clearPasswordResetToken();
        $repository = $this->userRepositoryCollection->findRepositoryByClassName(get_class($user));
        $repository->update($user, $updatedUser);

        return;
    }
}

Refactor Password resetHandler handle function


<?php

namespace JWX\JWT\Parameter\Feature;

use JWX\Util\Base64;

/**
 * Trait for parameter having Base64url value.
 */
trait Base64URLValue
{
	/**
	 * Initialize from native value.
	 *
	 * Value shall be encoded using Base64url encoding.
	 *
	 * @param string $value
	 * @return self
	 */
	public static function fromString($value) {
		return new static(Base64::urlEncode($value));
	}

	/**
	 * Validate that value is validly base64url encoded.
	 *
	 * @param string $value
	 * @throws \UnexpectedValueException
	 * @return self
	 */
	protected function _validateEncoding($value) {
		if (!Base64::isValidURLEncoding($value)) {
			throw new \UnexpectedValueException(
				"Value must be base64url encoded.");
		}
		return $this;
	}
}

<?php

namespace JWX\JWT\Parameter\Feature;

use JWX\Util\Base64;

/**
 * Trait for parameter having Base64url value.
 */
trait Base64URLValue
{
	/**
	 * Constructor
	 *
	 * @param mixed ...$args
	 */
	abstract public function __construct(...$args);

	/**
	 * Initialize from native value.
	 *
	 * Value shall be encoded using Base64url encoding.
	 *
	 * @param string $value
	 * @return self
	 */
	public static function fromString($value) {
		return new static(Base64::urlEncode($value));
	}

	/**
	 * Validate that value is validly base64url encoded.
	 *
	 * @param string $value
	 * @throws \UnexpectedValueException
	 * @return self
	 */
	protected function _validateEncoding($value) {
		if (!Base64::isValidURLEncoding($value)) {
			throw new \UnexpectedValueException(
				"Value must be base64url encoded.");
		}
		return $this;
	}
}

Revert back abstract constructor with variable args


<?php

namespace BournemouthData\TaxiRank;

class TaxiRank
{
	private $id;
	private $name;
	private $description;
	private $lat;
	private $lng;

	public function __construct($id, $name, $description, $lat, $lng)
    {
        $this->id = $id;
        $this->name = ucwords(strtolower($name));
        $this->description = $description;
        $this->lat = (double)$lat;
        $this->lng = (double)$lng;
    }

    public function getDescription()
    {
        return $this->description;
    }

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

    public function getLat()
    {
        return $this->lat;
    }

    public function getLng()
    {
        return $this->lng;
    }

    public function getName()
    {
        return $this->name;
    }
}

Convert tabs to spaces. Looking at YOU sublime

Signed-off-by: Alex Ross <d74d0b805f1f1a75a685a24ac9c38635e4306e23@gmail.com>


@extends('layouts/edit-form', [
    'createText' => trans('admin/accessories/general.create') ,
    'updateText' => trans('admin/accessories/general.update'),
    'helpTitle' => trans('admin/accessories/general.about_accessories_title'),
    'helpText' => trans('admin/accessories/general.about_accessories_text')
])

{{-- Page content --}}
@section('inputFields')

@include ('partials.forms.edit.company')
@include ('partials.forms.edit.name', ['translated_name' => trans('admin/accessories/general.accessory_name')])
@include ('partials.forms.edit.category')
@include ('partials.forms.edit.manufacturer')
@include ('partials.forms.edit.location')
@include ('partials.forms.edit.order_number')
@include ('partials.forms.edit.purchase_date')
@include ('partials.forms.edit.purchase_cost')
@include ('partials.forms.edit.quantity')
@include ('partials.forms.edit.minimum_quantity')

@stop

@extends('layouts/edit-form', [
    'createText' => trans('admin/accessories/general.create') ,
    'updateText' => trans('admin/accessories/general.update'),
    'helpTitle' => trans('admin/accessories/general.about_accessories_title'),
    'helpText' => trans('admin/accessories/general.about_accessories_text')
])

{{-- Page content --}}
@section('inputFields')

@include ('partials.forms.edit.company')
@include ('partials.forms.edit.name', ['translated_name' => trans('admin/accessories/general.accessory_name')])
@include ('partials.forms.edit.category')
@include ('partials.forms.edit.manufacturer')
@include ('partials.forms.edit.location')
@include ('partials.forms.edit.model_number')
@include ('partials.forms.edit.order_number')
@include ('partials.forms.edit.purchase_date')
@include ('partials.forms.edit.purchase_cost')
@include ('partials.forms.edit.quantity')
@include ('partials.forms.edit.minimum_quantity')

@stop

Add accessory model to accessories

Add accessory model to accessories


<?php

/**
 * Block delete handler.
 */

$this->require_acl ('admin', 'admin/delete', 'blocks');

$page->layout = 'admin';

if (! isset ($_POST['id'])) {
	$this->redirect ('/blocks/admin');
}

$lock = new Lock ('Block', $_POST['id']);
if ($lock->exists ()) {
	$page->title = __ ('Editing Locked');
	echo $tpl->render ('admin/locked', $lock->info ());
	return;
}

$b = new Block ($_POST['id']);

$_POST = array_merge ($_POST, (array) $b->orig ());

if (! $b->remove ()) {
	$page->title = __ ('An Error Occurred');
	echo __ ('Error Message') . ': ' . $b->error;
	return;
}

$this->hook ('blocks/delete', $_POST);

$this->add_notification (__ ('Block deleted.'));
if (isset ($_POST['return'])) {
	$_POST['return'] = filter_var ($_POST['return'], FILTER_SANITIZE_URL);

	if (Validator::validate ($_POST['return'], 'localpath')) {
		$_POST['return'] = $_POST['return'];
	}

	$this->redirect ('/blocks/admin');
}

<?php

/**
 * Block delete handler.
 */

$this->require_acl ('admin', 'admin/delete', 'blocks');

$page->layout = 'admin';

if (! isset ($_POST['id'])) {
	$this->redirect ('/blocks/admin');
}

$lock = new Lock ('Block', $_POST['id']);
if ($lock->exists ()) {
	$page->title = __ ('Editing Locked');
	echo $tpl->render ('admin/locked', $lock->info ());
	return;
}

$b = new Block ($_POST['id']);

$_POST = array_merge ($_POST, (array) $b->orig ());

if (! $b->remove ()) {
	$page->title = __ ('An Error Occurred');
	echo __ ('Error Message') . ': ' . $b->error;
	return;
}

$this->hook ('blocks/delete', $_POST);

$this->add_notification (__ ('Block deleted.'));
if (isset ($_POST['return'])) {
	$_POST['return'] = filter_var ($_POST['return'], FILTER_SANITIZE_URL);

	if (Validator::validate ($_POST['return'], 'localpath')) {
		$this->redirect ($_POST['return']);
	}

	$this->redirect ('/blocks/admin');
}

Return to page fixed on block deletion

Return to page fixed on block deletion


<?php

namespace Movim;

class Cookie
{
    public static function set()
    {
        if (SESSION_ID == false) {
            self::renew();
        } else {
            self::setCookie(SESSION_ID);
        }
    }

    public static function refresh()
    {
        if (isset($_COOKIE['MOVIM_SESSION_ID'])) {
            self::setCookie($_COOKIE['MOVIM_SESSION_ID']);
        }
    }

    public static function renew()
    {
        self::setCookie(generateKey(32));
    }

    public static function getTime()
    {
        return time()+604800;
    }

    public static function clearCookieHeader()
    {
        header_remove('Set-Cookie');
    }

    private static function setCookie($key)
    {
        if (!headers_sent()) {
            self::clearCookieHeader();
            setcookie('MOVIM_SESSION_ID', $key, [
                'expires' => self::getTime(),
                'path' => '/',
                'secure' => false
            ]);
        }
    }
}

<?php

namespace Movim;

class Cookie
{
    public static function set()
    {
        if (SESSION_ID == false) {
            self::renew();
        } else {
            self::setCookie(SESSION_ID);
        }
    }

    public static function refresh()
    {
        if (isset($_COOKIE['MOVIM_SESSION_ID'])) {
            self::setCookie($_COOKIE['MOVIM_SESSION_ID']);
        }
    }

    public static function renew()
    {
        self::setCookie(generateKey(32));
    }

    public static function getTime()
    {
        return time()+604800;
    }

    public static function clearCookieHeader()
    {
        header_remove('Set-Cookie');
    }

    private static function setCookie($key)
    {
        if (!headers_sent()) {
            self::clearCookieHeader();
            setcookie('MOVIM_SESSION_ID', $key, [
                'expires' => self::getTime(),
                'path' => '/',
                'secure' => true,
                'samesite' => 'lax',
            ]);
        }
    }
}

Enforce secure cookies and SameSite: Lax


<?php /** @noinspection PhpFullyQualifiedNameUsageInspection */

declare(strict_types=1);

use Rector\Core\Configuration\Option;
use Rector\Set\ValueObject\SetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
    // get parameters
    $parameters = $containerConfigurator->parameters();

    // Define what rule sets will be applied
    $containerConfigurator->import(SetList::PHP_70);
    $containerConfigurator->import(SetList::PHP_71);

    // get services (needed for register a single rule)
    // $services = $containerConfigurator->services();

    // register a single rule
    // $services->set(\Rector\Php74\Rector\Property\TypedPropertyRector::class);
};

<?php /** @noinspection PhpFullyQualifiedNameUsageInspection */

declare(strict_types=1);

use Rector\Core\Configuration\Option;
use Rector\Set\ValueObject\SetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
    // get parameters
    $parameters = $containerConfigurator->parameters();

    // Define what rule sets will be applied
    $containerConfigurator->import(SetList::PHP_70);
    $containerConfigurator->import(SetList::PHP_71);
    $containerConfigurator->import(SetList::PHP_72);

    // get services (needed for register a single rule)
    // $services = $containerConfigurator->services();

    // register a single rule
    // $services->set(\Rector\Php74\Rector\Property\TypedPropertyRector::class);
};

Add Rector with PHP 7.2

Add Rector with PHP 7.2


<?php
  require_once('backend.php');

  $backend = new Backend();
  $backend->connect('/var/www/config.ini');
  if (!$backend->auth($_POST['username'], $_POST['password'])) {
    header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
    header('Status: 403 Forbidden');
    exit;
  }

  header('Content-Type: application/json');
  echo json_encode($backend->search($_GET['query'],$_GET['limit'],$_GET['offset'], 5))."\n";
?>

<?php
  require_once('backend.php');

  $backend = new Backend();
  $backend->connect('config.ini');
  if (!$backend->auth($_POST['username'], $_POST['password'])) {
    header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
    header('Status: 403 Forbidden');
    exit;
  }

  header('Content-Type: application/json');
  echo json_encode($backend->search($_GET['query'],$_GET['limit'],$_GET['offset'], 5))."\n";
?>

Make it look in the current directory instead of a fixed path for the config file.


<?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\Components\Logo;

use function class_exists;
use Illuminate\Console\Application as Artisan;
use LaravelZero\Framework\Components\AbstractComponentProvider;

/**
 * @internal
 */
final class Provider extends AbstractComponentProvider
{
    /**
     * {@inheritdoc}
     */
    public function isAvailable(): bool
    {
        return class_exists(\Laminas\Text\Figlet\Figlet::class)
            && is_array($this->app['config']->get('logo', false));
    }

    /**
     * {@inheritdoc}
     */
    public function register(): void
    {
        $config = $this->app['config'];

        if ($config->get('logo.enabled', false)) {
            Artisan::starting(
                function ($artisan) use ($config) {
                    $artisan->setName(
                        new FigletString($config->get('app.name'), $config->get('logo', []))
                    );
                }
            );
        }
    }
}

<?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\Components\Logo;

use function class_exists;
use Illuminate\Console\Application as Artisan;
use LaravelZero\Framework\Components\AbstractComponentProvider;

/**
 * @internal
 */
final class Provider extends AbstractComponentProvider
{
    /**
     * {@inheritdoc}
     */
    public function isAvailable(): bool
    {
        return class_exists(\Laminas\Text\Figlet\Figlet::class)
            && is_array($this->app['config']->get('logo', false));
    }

    /**
     * {@inheritdoc}
     */
    public function register(): void
    {
        $config = $this->app['config'];

        if ($config->get('logo.enabled', false)) {
            Artisan::starting(
                function ($artisan) use ($config) {
                    $artisan->setName(
                        (string) new FigletString($config->get('app.name'), $config->get('logo', []))
                    );
                }
            );
        }
    }
}

Fix the logo component in Symfony 5

Fix the logo component in Symfony 5


<?php

// if you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

// this check prevents access to debug front controllers that are deployed by accident to production servers.
// feel free to remove this, extend it, or make something more sophisticated.
if (!in_array(@$_SERVER['REMOTE_ADDR'], array(
    '127.0.0.1',
    '::1',
))) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';

use Symfony\Component\HttpFoundation\Request;

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$kernel->handle(Request::createFromGlobals())->send();

<?php

// if you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

// this check prevents access to debug front controllers that are deployed by accident to production servers.
// feel free to remove this, extend it, or make something more sophisticated.
if (!in_array(@$_SERVER['REMOTE_ADDR'], array(
    '127.0.0.1',
    '::1',
    'fe80::1',
))) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'.$_SERVER['REMOTE_ADDR']);
}

require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';

use Symfony\Component\HttpFoundation\Request;

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$kernel->handle(Request::createFromGlobals())->send();

Include mac ipv6 localhost, server address.


<?php

namespace SymfonyDay\Bundle\BlogBundle\Controller;

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

class DefaultController extends Controller
{
    /**
     * @Route("/blog", name="blog")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $posts = $em->getRepository('SymfonyDayBlogBundle:Post')
            ->createQueryBuilder('p')
            ->where('p.publishedAt IS NULL')
            ->orWhere('p.publishedAt <= :date')
            ->setParameter('date', date('Y-m-d H:i'))
            ->getQuery()
            ->execute()
        ;

        return array('posts' => $posts);
    }

    /**
     * @Route("/blog/{id}", requirements={ "id"="\d+" }, name="post")
     * @Template()
     */
    public function postAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $post = $em->getRepository('SymfonyDayBlogBundle:Post')->find($id);

        if (!$post) {
            throw $this->createNotFoundException(sprintf('The post object identified by #%u does not exist.', $id));
        }

        return array('post' => $post);
    }
}

<?php

namespace SymfonyDay\Bundle\BlogBundle\Controller;

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

class DefaultController extends Controller
{
    /**
     * @Route("/blog", name="blog")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $posts = $em->getRepository('SymfonyDayBlogBundle:Post')
            ->createQueryBuilder('p')
            ->where('p.publishedAt IS NULL')
            ->orWhere('p.publishedAt <= :date')
            ->orderBy('p.publishedAt', 'DESC')
            ->setParameter('date', date('Y-m-d H:i'))
            ->getQuery()
            ->execute()
        ;

        return array('posts' => $posts);
    }

    /**
     * @Route("/blog/{id}", requirements={ "id"="\d+" }, name="post")
     * @Template()
     */
    public function postAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $post = $em->getRepository('SymfonyDayBlogBundle:Post')->find($id);

        if (!$post) {
            throw $this->createNotFoundException(sprintf('The post object identified by #%u does not exist.', $id));
        }

        return array('post' => $post);
    }
}

Sort blog posts by date

Sort blog posts by date


<?php

// nc localhost 4000

use React\Chatroulette\AppInterface;
use React\Chatroulette\LoggingApp;
use React\Chatroulette\PairApp;
use React\Chatroulette\TextApp;

require 'vendor/autoload.php';

$logger = new Monolog\Logger('chatroulette');
$logger->pushHandler(new Monolog\Handler\StreamHandler(STDOUT));

$app = new LoggingApp(
    new TextApp(new PairApp()),
    $logger
);

$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);

$i = 0;

$socket->on('connection', function ($conn) use (&$i, $app) {
    $conn->id = ++$i;
    $app->connect($conn);
});

$socket->listen(4000);
$loop->run();

<?php

// nc localhost 4000

use React\Chatroulette\AppInterface;
use React\Chatroulette\LoggingApp;
use React\Chatroulette\PairApp;
use React\Chatroulette\TextApp;

require 'vendor/autoload.php';

$logger = new Monolog\Logger('chatroulette');
$logger->pushHandler(new Monolog\Handler\StreamHandler(STDOUT));

$app = new LoggingApp(
    new TextApp(new PairApp()),
    $logger
);

$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);

$i = 0;
$names = ['Alice', 'Bob', 'Carol', 'Dave', 'Erin', 'Frank', 'Eve',
          'Mallory', 'Oscar', 'Peggy', 'Trent', 'Walter'];

$socket->on('connection', function ($conn) use (&$i, $names, $app) {
    $conn->id = isset($names[$i]) ? $names[$i] : $i;
    $app->connect($conn);
    $i++;
});

$socket->listen(4000);
$loop->run();

Use real names for connections

Use real names for connections


<?php

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

class CreateBudgetsTable extends Migration {
    public function up() {
        Schema::create('budgets', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('year');
            $table->integer('month');
            $table->float('amount');
        });
    }

    public function down() {
        Schema::dropIfExists('budgets');
    }
}

<?php

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

class CreateBudgetsTable extends Migration {
    public function up() {
        Schema::create('budgets', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('tag_id')->unsigned();
            $table->integer('year');
            $table->integer('month');
            $table->float('amount');
        });
    }

    public function down() {
        Schema::dropIfExists('budgets');
    }
}

Fix bug where tag_id wasn't in budgets migration


<?php
global $_dbName;

if ( 'cli' == PHP_SAPI )
{
	$_dbName = 'dreamfactory';
}
else
{
	$_host = $_SERVER['HTTP_HOST'];

	if ( false === strpos( $_host, '.cloud.dreamfactory.com' ) )
	{
		throw new CHttpException( 401, $_host . ': Not authorized.' );
	}

	$_parts = explode( '.', $_host );
	$_dbName = $_parts[0];
}

return array(
	'connectionString' => 'mysql:host=localhost;port=3306;dbname=' . $_dbName,
	'username'         => $_dbName . '_user',
	'password'         => $_dbName . '_user',
	'emulatePrepare'   => true,
	'charset'          => 'utf8',
);

<?php
global $_dbName;

if ( 'cli' == PHP_SAPI || file_exists( '/var/www/launchpad/current' ) )
{
	$_dbName = 'dreamfactory';
	$_dbUser = 'dsp_user';
}
else
{
	$_host = $_SERVER['HTTP_HOST'];

	if ( false === strpos( $_host, '.cloud.dreamfactory.com' ) )
	{
		throw new CHttpException( 401, $_host . ': Not authorized.' );
	}

	$_parts = explode( '.', $_host );
	$_dbName = $_parts[0];
	$_dbUser = $_dbName . '_user';
}

return array(
	'connectionString' => 'mysql:host=localhost;port=3306;dbname=' . $_dbName,
	'username'         => $_dbUser,
	'password'         => $_dbUser,
	'emulatePrepare'   => true,
	'charset'          => 'utf8',
);

Check for deployed vs. hosted fixed.

Check for deployed vs. hosted fixed.


<?php

/*
 * This file is part of the Incipio package.
 *
 * (c) Florian Lefevre
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Mgate\SuiviBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RepartitionJEHType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('nbrJEH', 'integer', array('required' => true))
                ->add('prixJEH', 'integer', array('required' => true, 'attr' => array('min' => 80, 'max' => 320)));
    }

    public function getName()
    {
        return 'Mgate_suivibundle_RepartitionJEHType';
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Mgate\SuiviBundle\Entity\RepartitionJEH',
            'type' => '',
            'prospect' => '',
            'phases' => '',
        ));
    }
}

<?php

/*
 * This file is part of the Incipio package.
 *
 * (c) Florian Lefevre
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Mgate\SuiviBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RepartitionJEHType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('nbrJEH', 'integer', array('required' => true))
                ->add('prixJEH', 'integer', array('required' => true, 'attr' => array('min' => 80)));
    }

    public function getName()
    {
        return 'Mgate_suivibundle_RepartitionJEHType';
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Mgate\SuiviBundle\Entity\RepartitionJEH',
            'type' => '',
            'prospect' => '',
            'phases' => '',
        ));
    }
}

Remove max amount for jeh in repartitionjehtype


<?php

require_once __DIR__ . '/../bootstrap.php';

$client = new Madcoda\Youtube(['key' => $config->youtube->key]);

$mostRecentVideoDateTime = $db->getRead()->fetchValue(
    "SELECT `datetime` FROM `jpemeric_stream`.`youtube` ORDER BY `datetime` DESC LIMIT 1"
);
$mostRecentVideoDateTime = new DateTime($mostRecentVideoDateTime);

$playlist = $client->getPlaylistItemsByPlaylistId($config->youtube->favorites_playlist, 10);

foreach ($playlist as $playlistItem) {
    $datetime = new DateTime($playlistItem->snippet->publishedAt);
    if ($datetime <= $mostRecentVideoDateTime) {
        break;
    }

    $uniqueVideoCheck = $db->getRead()->fetchValue(
        "SELECT 1 FROM `jpemeric_stream`.`youtube` WHERE `video_id` = :video_id LIMIT 1",
        ['video_id' => $playlistItem->contentDetails->videoId]
    );
    if ($uniqueVideoCheck !== false) {
        continue;
    }

    $datetime->setTimezone(new DateTimeZone('America/Phoenix'));

    $db->getWrite()->perform(
        "INSERT INTO `jpemeric_stream`.`youtube` (`video_id`, `datetime`, `metadata`) " .
        "VALUES (:video_id, :datetime, :metadata)",
        [
            'video_id' => $playlistItem->contentDetails->videoId,
            'datetime' => $datetime->format('Y-m-d H:i:s'),
            'metadata' => json_encode($metadata),
        ]
    );
}

<?php

require_once __DIR__ . '/../bootstrap.php';

$client = new Madcoda\Youtube(['key' => $config->youtube->key]);

$mostRecentVideoDateTime = $db->getRead()->fetchValue(
    "SELECT `datetime` FROM `jpemeric_stream`.`youtube` ORDER BY `datetime` DESC LIMIT 1"
);
$mostRecentVideoDateTime = new DateTime($mostRecentVideoDateTime);

$playlist = $client->getPlaylistItemsByPlaylistId($config->youtube->favorites_playlist, 10);

foreach ($playlist as $playlistItem) {
    $datetime = new DateTime($playlistItem->snippet->publishedAt);
    if ($datetime <= $mostRecentVideoDateTime) {
        break;
    }

    $uniqueVideoCheck = $db->getRead()->fetchValue(
        "SELECT 1 FROM `jpemeric_stream`.`youtube` WHERE `video_id` = :video_id LIMIT 1",
        ['video_id' => $playlistItem->contentDetails->videoId]
    );
    if ($uniqueVideoCheck !== false) {
        continue;
    }

    $datetime->setTimezone(new DateTimeZone('America/Phoenix'));

    $db->getWrite()->perform(
        "INSERT INTO `jpemeric_stream`.`youtube` (`video_id`, `datetime`, `metadata`) " .
        "VALUES (:video_id, :datetime, :metadata)",
        [
            'video_id' => $playlistItem->contentDetails->videoId,
            'datetime' => $datetime->format('Y-m-d H:i:s'),
            'metadata' => json_encode($playlistItem),
        ]
    );
}

Fix broken reference to YouTube metadata