<?php namespace Dan\Irc\Packets;

use Dan\Contracts\PacketContract;

class PacketKick implements PacketContract {

    public function handle($from, $data)
    {
        $user = user($from);

        console("[{$data[0]}] {$user->nick()} was kicked from the channel");

        if(!connection()->inChannel($data[0]))
            return;

        $channel = connection()->getChannel($data[0]);

        $channel->removeUser($user);

        event('irc.packets.kick', [
            'user'      => $user,
            'channel'   => $channel
        ]);
    }
}

<?php namespace Dan\Irc\Packets;

use Dan\Contracts\PacketContract;

class PacketKick implements PacketContract {

    public function handle($from, $data)
    {
        $user = user($from);

        console("[{$data[0]}] {$data[1]} was kicked from the channel");

        if(!connection()->inChannel($data[0]))
            return;

        $channel = connection()->getChannel($data[0]);

        $channel->removeUser($data[1]);

        event('irc.packets.kick', [
            'user'      => $user,
            'channel'   => $channel,
            'kicked'    => $data[1],
        ]);
    }
}

Fix kick bug causing crash

Fix kick bug causing crash


<?php namespace Pingpong\Themes;

use Illuminate\Filesystem\Filesystem;
use Pingpong\Modules\Json;
use Symfony\Component\Finder\Finder as SymfonyFinder;

class Finder {

    /**
     * The symfony finder instance.
     *
     * @var SymfonyFinder
     */
    protected $finder;

    /**
     * The constructor.
     *
     * @param $finder SymfonyFinder
     */
    public function __construct(SymfonyFinder $finder = null)
    {
        $this->finder = $finder ?: new SymfonyFinder;
    }

    /**
     * Find the specified theme by searching a 'theme.json' file as identifier.
     *
     * @param  string $path
     * @param  string $filename
     * @return array
     */
    public function find($path, $filename = 'theme.json')
    {
        $themes = [];

        if(is_dir($path))
        {
            $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks();

            foreach ($found as $file) $themes[] = new Theme($this->getInfo($file));
        }

        return $themes;
    }

    /**
     * Get theme info from json file.
     *
     * @param  SplFileInfo $file
     * @return array
     */
    protected function getInfo($file)
    {
        return Json::make($file->getRealPath())->toArray();
    }

}

<?php namespace Pingpong\Themes;

use Illuminate\Filesystem\Filesystem;
use Pingpong\Modules\Json;
use Symfony\Component\Finder\Finder as SymfonyFinder;

class Finder {

    /**
     * The symfony finder instance.
     *
     * @var SymfonyFinder
     */
    protected $finder;

    /**
     * The constructor.
     *
     * @param $finder SymfonyFinder
     */
    public function __construct(SymfonyFinder $finder = null)
    {
        $this->finder = $finder ?: new SymfonyFinder;
    }

    /**
     * Find the specified theme by searching a 'theme.json' file as identifier.
     *
     * @param  string $path
     * @param  string $filename
     * @return array
     */
    public function find($path, $filename = 'theme.json')
    {
        $themes = [];

        if(is_dir($path))
        {
            $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks();

            foreach ($found as $file) $themes[] = new Theme($this->getInfo($file));
        }

        return $themes;
    }

    /**
     * Get theme info from json file.
     *
     * @param  SplFileInfo $file
     * @return array
     */
    protected function getInfo($file)
    {
        $attributes = Json::make($path = $file->getRealPath())->toArray();

        $attributes['path'] = dirname($path);

        return $attributes;
    }

}

Add path to theme attributes

Add path to theme attributes


<?php

namespace Sztyup\Authsch;

use Illuminate\Support\ServiceProvider;

class AuthschServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->make('Sztyup\Authsch\LoginController');

        $this->loadRoutesFrom(__DIR__ . "/../routes/routes.php");

        $this->mergeConfigFrom(
            __DIR__.'/../config/config.php', 'authsch'
        );
    }

    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../config/config.php' => config_path('authsch.php')
        ]);

        $socialite = $this->app->make('Laravel\Socialite\Contracts\Factory');
        $socialite->extend(
            'authsch',
            function ($app) use ($socialite) {
                $config = $app['config']['authsch.driver'];
                return $socialite->buildProvider(SchProvider::class, $config);
            }
        );

    }
}

<?php

namespace Sztyup\Authsch;

use Illuminate\Support\ServiceProvider;

class AuthschServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->make('Sztyup\Authsch\LoginController');

        $this->loadRoutesFrom(__DIR__ . "/../routes/routes.php");

        $this->mergeConfigFrom(
            __DIR__.'/../config/config.php', 'authsch'
        );
    }

    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../config/config.php' => config_path('authsch.php')
        ], 'config');

        $socialite = $this->app->make('Laravel\Socialite\Contracts\Factory');
        $socialite->extend(
            'authsch',
            function ($app) use ($socialite) {
                $config = $app['config']['authsch.driver'];
                return $socialite->buildProvider(SchProvider::class, $config);
            }
        );

    }
}

Add config tag for config publish

Add config tag for config publish


<?php
/*
 * This file is part of the DB Backup utility.
 *
 * (c) Tom Adam <tomadam@instantiate.co.uk>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Instantiate\DatabaseBackup\FileEncrypter;

use Instantiate\DatabaseBackup\Util\Process;

class GpgFileEncrypter extends AbstractFileEncrypter
{
    /**
     * @param string $inputFile
     * @param string $outputFile
     */
    protected function encryptFile($inputFile, $outputFile)
    {
        Process::exec(
            'gpg2 -v --encrypt {sign} --recipient {recipient} --batch --yes {passphrase} --output {output_file} {input_file}',
            [
                '{sign}' => $this->config['sign'] ? '--sign' : '',
                '{recipient}' => $this->config['recipient'],
                '{passphrase}' => $this->config['sign'] && $this->config['key_file']
                    ? '--passphrase-file '.$this->config['key_file']
                    : '',
                '{input_file}' => $inputFile,
                '{output_file}' => $outputFile,
            ],
            [],
            $this->logger
        );
    }

    protected function getEncryptedFilename($inputFile)
    {
        return $inputFile.'.gpg';
    }
}

<?php
/*
 * This file is part of the DB Backup utility.
 *
 * (c) Tom Adam <tomadam@instantiate.co.uk>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Instantiate\DatabaseBackup\FileEncrypter;

use Instantiate\DatabaseBackup\Util\Process;

class GpgFileEncrypter extends AbstractFileEncrypter
{
    /**
     * @param string $inputFile
     * @param string $outputFile
     */
    protected function encryptFile($inputFile, $outputFile)
    {
        Process::exec(
            'gpg2 -v --encrypt {sign} --recipient {recipient} --batch --pinentry-mode loopback --yes {passphrase} --output {output_file} {input_file}',
            [
                '{sign}' => $this->config['sign'] ? '--sign' : '',
                '{recipient}' => $this->config['recipient'],
                '{passphrase}' => $this->config['sign'] && $this->config['key_file']
                    ? '--passphrase-file '.$this->config['key_file']
                    : '',
                '{input_file}' => $inputFile,
                '{output_file}' => $outputFile,
            ],
            [],
            $this->logger
        );
    }

    protected function getEncryptedFilename($inputFile)
    {
        return $inputFile.'.gpg';
    }
}

Add pinentry mode loopback to gpg command


<?php

namespace App\Controllers;

use App\Entities\Lead;
use Core\Controllers\EmailController  as Email;
use Symfony\Component\VarDumper\Dumper\DataDumperInterface;

class LeadController extends BaseController
{
    /**
     * Validations rules to $_POST data
     * @var [array]
     */
    protected $rules = [
            'required' => [
                ['name'],
                ['email'],
            ],
            'lengthMin' => [
                ['name', 3],
            ],

            'email' => 'email',
        ];

    /**
     * Input labels
     * @var array
     */
    protected $labels = [
        'name'  => 'Name',
        'email' => 'Email',
    ];

    public function store($request, $response)
    {
        //$errors = $this->validate($_POST, $this->rules, $this->labels);

       /* if ($errors) {
            return view('home.twig', compact('errors'));
        }*/

        $lead            = new Lead();
        $lead->name      = $request->getParam('name');
        $lead->email     = $request->getParam('email');
        $lead->date      = date('Y-m-d H:i:s');

        if (!$lead->isRegistered($lead->email)) {
            $lead->save();
        }

	    return $response->withRedirect('/thanks', 301);
    }

    /**
     * Route params example
     * if the path has parameters, the $ response parameter is required as the first method argument
     * @param $response
     * @param $name
     */
    public function search($response, $name)
    {
        dd($name);
    }
}

<?php

namespace App\Controllers;

use App\Entities\Lead;

class LeadController extends BaseController
{
    /**
     * Validations rules to $_POST data
     * @var [array]
     */
    protected $rules = [
            'required' => [
                ['name'],
                ['email'],
            ],
            'lengthMin' => [
                ['name', 3],
            ],

            'email' => 'email',
        ];

    /**
     * Input labels
     * @var array
     */
    protected $labels = [
        'name'  => 'Name',
        'email' => 'Email',
    ];

    public function store($request, $response)
    {

        $lead            = new Lead();
        $lead->name      = $request->getParam('name');
        $lead->email     = $request->getParam('email');
        $lead->date      = date('Y-m-d H:i:s');

        if (!$lead->isRegistered($lead->email)) {
            $lead->save();
        }

        sendEmail($lead->email, $lead->name, getenv('LEAD_EMAIL_SUBJECT'), 'lead', $lead);
        sendEmail(getenv('ADMIN_EMAIL'), 'Edwin Ramírez', getenv('LEAD_EMAIL_SUBJECT'), 'admin', $lead);

	    return $response->withRedirect('/thanks', 301);
    }
}

Add support for emails notifications

Add support for emails notifications


<?php

			//Set database login parameters
			define('HOST', 'localhost');
			define('DB_USERNAME', 'my_username');
			define('DB_PASSWORD', 'my_password');
			define('DATABASE_NAME', 'my_database');

			//Set table & column names containing the required information (usernames, email addresses, passwords)
			define('TABLE_OF_USERS', 'my_table_name');
			define('COLUMN_OF_USERS', 'column_name');
			define('COLUMN_OF_EMAILS', 'column_name');
			define('COLUMN_OF_PASSWORDS', 'column_name');

?>

<?php

			//Set database login parameters
			define('HOST', 'localhost');
			define('DB_USERNAME', 'my_username');
			define('DB_PASSWORD', 'my_password');
			define('DATABASE_NAME', 'my_database');

			//Set table & column names containing the required information (usernames, email addresses, passwords)
			define('TABLE_OF_USERS', 'my_table_name');
			define('COLUMN_OF_USERS', 'column_name');
			define('COLUMN_OF_PASSWORDS', 'column_name');

?>

Remove email parameter. The email address will be used to login, $username will be the email address, so no need for a separate $email variable


<?php
$cmd = "wget {$argv[1]} --no-check-certificate --delete-after -q --output-document=/dev/null";

$avg = 0;
$iterations = 10;

for ($i =0; $i < $iterations; $i++) {
  $start = microtime(true);
  shell_exec($cmd);
  $end = microtime(true);
  $avg += ($end - $start);
}

echo number_format(($avg/$iterations), 3).' seconds average time over 10 iterations.';
echo PHP_EOL;

<?php
$cmd = "wget {$argv[1]} --no-check-certificate --delete-after -q --output-document=/dev/null";

$avg = 0;
$iterations = 10;
$max = 0;
$min = null;

for ($i =0; $i < $iterations; $i++) {
  echo '.';
  $start = microtime(true);
  shell_exec($cmd);
  $end = microtime(true);
  $time = ($end - $start);
  $avg += $time;
  $max = $max < $time ? $time : $max;
  $min =  $min == null || $min > $time ? $time : $min;
}

echo PHP_EOL;
echo 'Average: '.number_format(($avg/$iterations)*1000, 0).'ms'.PHP_EOL;
echo 'Max: '.number_format($max*1000, 0).'ms'.PHP_EOL;
echo 'Min: '.number_format($min*1000, 0).'ms'.PHP_EOL;

Add maximum and minimum time.

Add maximum and minimum time.


<?php
/**
 * Plugin Name: Culture Object Sync
 * Plugin URI: http://www.gladdy.co.uk/projects/culture-object-sync
 * Description: A framework as a plugin to enable sync of culture objects into WordPress.
 * Version: 2.0
 * Author: Liam Gladdy / Thirty8 Digital
 * Author URI: https://www.gladdy.uk / http://www.thirty8digital.co.uk
 * License: Apache 2 License
 */

require_once('CultureObject/CultureObject.class.php');
$cos = new \CultureObject\CultureObject();

function cos_get_remapped_field_name($field_key) {
	global $cos;
	return $cos->helper->cos_get_remapped_field_name($field_key);
}

function cos_remapped_field_name($field_key) {
	global $cos;
	return $cos->helper->cos_remapped_field_name($field_key);
}

function cos_get_field($field_key) {
	$id = get_the_ID();
	if (!$id) return false;
	echo get_post_meta($id, $field_key, true);
}

function cos_the_field($field_key) {
	echo cos_get_field($field_key);
}

Add 'cos_get_field' and 'cos_the_field' to mimic ACF's get_field and the_field


<?php
namespace Bolt\Database\Table;

use Doctrine\DBAL\Schema\Schema;

/**
 * Table for taxonomy data.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Taxonomy extends BaseTable
{
    /**
     * {@inheritdoc}
     */
    protected function addColumns()
    {
        // @codingStandardsIgnoreStart
        $this->table->addColumn('id',           'integer', ['autoincrement' => true]);
        $this->table->addColumn('content_id',   'integer', []);
        $this->table->addColumn('contenttype',  'string',  ['length' => 32]);
        $this->table->addColumn('taxonomytype', 'string',  ['length' => 32]);
        $this->table->addColumn('slug',         'string',  ['length' => 64]);
        $this->table->addColumn('name',         'string',  ['length' => 64, 'default' => '']);
        $this->table->addColumn('sortorder',    'integer', ['default' => 0]);
        // @codingStandardsIgnoreEnd
    }

    /**
     * {@inheritdoc}
     */
    protected function addIndexes()
    {
        $this->table->addIndex(['content_id']);
        $this->table->addIndex(['contenttype']);
        $this->table->addIndex(['taxonomytype']);
        $this->table->addIndex(['sortorder']);
    }

    /**
     * {@inheritdoc}
     */
    protected function setPrimaryKey()
    {
        $this->table->setPrimaryKey(['id']);
    }
}

<?php
namespace Bolt\Database\Table;

/**
 * Table for taxonomy data.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class Taxonomy extends BaseTable
{
    /**
     * {@inheritdoc}
     */
    protected function addColumns()
    {
        // @codingStandardsIgnoreStart
        $this->table->addColumn('id',           'integer', ['autoincrement' => true]);
        $this->table->addColumn('content_id',   'integer', []);
        $this->table->addColumn('contenttype',  'string',  ['length' => 32]);
        $this->table->addColumn('taxonomytype', 'string',  ['length' => 32]);
        $this->table->addColumn('slug',         'string',  ['length' => 64]);
        $this->table->addColumn('name',         'string',  ['length' => 64, 'default' => '']);
        $this->table->addColumn('sortorder',    'integer', ['default' => 0]);
        // @codingStandardsIgnoreEnd
    }

    /**
     * {@inheritdoc}
     */
    protected function addIndexes()
    {
        $this->table->addIndex(['content_id']);
        $this->table->addIndex(['contenttype']);
        $this->table->addIndex(['taxonomytype']);
        $this->table->addIndex(['sortorder']);
    }

    /**
     * {@inheritdoc}
     */
    protected function setPrimaryKey()
    {
        $this->table->setPrimaryKey(['id']);
    }
}

Move the taxonomy table definition into a class


<?php

namespace App\Iep\Legacy\Commands;

use File;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldBeQueued;

class RemoveFile extends Job implements SelfHandling, ShouldBeQueued
{
    public $files;

    use InteractsWithQueue, SerializesModels;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($files)
    {
        $this->files = $files;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if ($this->attempts() < 3) {
            if (is_array($this->files)) {
                foreach ($this->files as $file) {
                    File::delete(public_path($file));
                }
            } else {
                File::delete(public_path($file));
            }
        } else {
            $this->delete();
        }
    }
}

<?php

namespace App\Iep\Legacy\Commands;

use File;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class RemoveFile implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public $files;

    /**
     * Create a new job instance.
     * @param $files
     */
    public function __construct($files)
    {
        Log::info('Creating RemoveFile command');
        $this->files = $files;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if ($this->attempts() < 3) {
            if (is_array($this->files)) {
                foreach ($this->files as $file) {
                    Log::info("Deleting file: " . public_path($file));
                    File::delete(public_path($file));
                }
            } else {
                Log::info("Deleting file: " . public_path($this->files));
                File::delete(public_path($this->files));
            }
        } else {
            $this->delete();
        }
    }

    public function failed(Exception $exception)
    {
        Log::info($exception);
    }
}

Update Job to use laravel 5.3's traits

Update Job to use laravel 5.3's traits


<?php
  //URLの引数を見て、適切なphpコードを呼び出す。

  if(isset($_GET['pid']) or isset($_GET['vid']) or isset($_GET['sid'])) {
    //オブジェクト詳細表示
    require_once('idetail.php');
  } elseif(isset($_GET['aid'])) {
    //アルバム
    $_GET['id'] = $_GET['aid'];
    require_once('ialbum.php');
  } elseif(isset($_GET['query'])) {
    //検索
    require_once('isearch.php');
  } elseif(isset($_GET['type'])) {
    require_once('ialbum.php');
  } elseif(isset($_GET['admin'])) {
    // Show Admin page
    require_once('psqlAlbum-admin/iadmin.php');
  } elseif(isset($_GET['login'])) {
    // Show Login page
    require_once('psqlAlbum-admin/ilogin.php');
  } elseif(isset($_GET['logout'])) {
    // Show Logout page
    require_once('psqlAlbum-admin/ilogout.php');
  } elseif(empty($_GET)) {
    //アルバム一覧(トップページ)
    require_once('iindex.php');
  }

<?php
  //URLの引数を見て、適切なphpコードを呼び出す。
  //See URL Parameters and call appropriate code.

  if(isset($_GET['pid']) or isset($_GET['vid']) or isset($_GET['sid'])) {
    // Show object detail
    require_once('idetail.php');
  } elseif(isset($_GET['aid'])) {
    // Show Album
    $_GET['id'] = $_GET['aid'];
    require_once('ialbum.php');
  } elseif(isset($_GET['query'])) {
    // Search
    require_once('isearch.php');
  } elseif(isset($_GET['type'])) {
    require_once('ialbum.php');
  } elseif(isset($_GET['admin'])) {
    // Show Admin page
    require_once('psqlAlbum-admin/iadmin.php');
  } elseif(isset($_GET['login'])) {
    // Show Login page
    require_once('psqlAlbum-admin/ilogin.php');
  } elseif(isset($_GET['logout'])) {
    // Show Logout page
    require_once('psqlAlbum-admin/ilogout.php');
  } elseif(empty($_GET)) {
    // Show album list (top page)
    require_once('iindex.php');
  }

Replace Japanese comment by English

Replace Japanese comment by English


<?php

/**
 * @copyright  Frederic G. Østby
 * @license    http://www.makoframework.com/license
 */

namespace mako\security;

/**
 * Secure comparison.
 *
 * @author  Frederic G. Østby
 */

class Comparer
{
	/**
	 * Protected constructor since this is a static class.
	 *
	 * @access  protected
	 */

	protected function __construct()
	{
		// Nothing here
	}

	/**
	 * Timing attack safe string comparison. Returns TRUE if the two strings a equal and FALSE if not.
	 *
	 * @access  public
	 * @param   string   $string1  String one
	 * @param   string   $string2  String two
	 * @return  boolean
	 */

	public static function compare($string1, $string2)
	{
		$string1 = (string) $string1;
		$string2 = (string) $string2;

		$string1Length = strlen($string1);
		$string2Length = strlen($string2);

		$minLength = min($string1Length, $string2Length);
		$maxLength = max($string1Length, $string2Length);

		$result = $string1Length ^ $string2Length;

		$string1 = str_pad($string1, $maxLength);
		$string2 = str_pad($string2, $maxLength);

		for($i = 0; $i < $maxLength; $i++)
		{
			$result |= ord($string1[$i]) ^ ord($string2[$i]);
		}

		return $result === 0;
	}
}

<?php

/**
 * @copyright  Frederic G. Østby
 * @license    http://www.makoframework.com/license
 */

namespace mako\security;

/**
 * Secure comparison.
 *
 * @author  Frederic G. Østby
 */

class Comparer
{
	/**
	 * Protected constructor since this is a static class.
	 *
	 * @access  protected
	 */

	protected function __construct()
	{
		// Nothing here
	}

	/**
	 * Timing attack safe string comparison. Returns TRUE if the two strings a equal and FALSE if not.
	 *
	 * @access  public
	 * @param   string   $string1  String one
	 * @param   string   $string2  String two
	 * @return  boolean
	 */

	public static function compare($string1, $string2)
	{
		$string1 = (string) $string1;
		$string2 = (string) $string2;

		$string1Length = strlen($string1);
		$string2Length = strlen($string2);

		$minLength = min($string1Length, $string2Length);

		$result = $string1Length ^ $string2Length;

		for($i = 0; $i < $minLength; $i++)
		{
			$result |= ord($string1[$i]) ^ ord($string2[$i]);
		}

		return $result === 0;
	}
}

Revert "Ensure that comparison time isn't affected by different string lengths"

This reverts commit 3b67e0c2c953727b203a9caafb227b62b4b4c39a.


<?php

final class PhabricatorDaemonManagementStatusWorkflow
  extends PhabricatorDaemonManagementWorkflow {

  protected function didConstruct() {
    $this
      ->setName('status')
      ->setSynopsis(pht('Show daemon processes on this host.'));
  }

  public function execute(PhutilArgumentParser $args) {
    $process_refs = $this->getOverseerProcessRefs();

    if (!$process_refs) {
      $instance = $this->getInstance();
      if ($instance !== null) {
        $this->logInfo(
          pht('NO DAEMONS'),
          pht(
            'There are no running daemon processes for the current '.
            'instance ("%s").',
            $instance));
      } else {
        $this->writeInfo(
          pht('NO DAEMONS'),
          pht('There are no running daemon processes.'));
      }

      return 1;
    }

    $table = id(new PhutilConsoleTable())
      ->addColumns(
        array(
          'pid' => array(
            'title' => pht('PID'),
          ),
          'command' => array(
            'title' => pht('Command'),
          ),
        ));

    foreach ($process_refs as $process_ref) {
      $table->addRow(
        array(
          'pid' => $process_ref->getPID(),
          'command' => $process_ref->getCommand(),
        ));
    }

    $table->draw();

    return 0;
  }

}

<?php

final class PhabricatorDaemonManagementStatusWorkflow
  extends PhabricatorDaemonManagementWorkflow {

  protected function didConstruct() {
    $this
      ->setName('status')
      ->setSynopsis(pht('Show daemon processes on this host.'));
  }

  public function execute(PhutilArgumentParser $args) {
    $process_refs = $this->getOverseerProcessRefs();

    if (!$process_refs) {
      $instance = $this->getInstance();
      if ($instance !== null) {
        $this->logInfo(
          pht('NO DAEMONS'),
          pht(
            'There are no running daemon processes for the current '.
            'instance ("%s").',
            $instance));
      } else {
        $this->logInfo(
          pht('NO DAEMONS'),
          pht('There are no running daemon processes.'));
      }

      return 1;
    }

    $table = id(new PhutilConsoleTable())
      ->addColumns(
        array(
          'pid' => array(
            'title' => pht('PID'),
          ),
          'command' => array(
            'title' => pht('Command'),
          ),
        ));

    foreach ($process_refs as $process_ref) {
      $table->addRow(
        array(
          'pid' => $process_ref->getPID(),
          'command' => $process_ref->getCommand(),
        ));
    }

    $table->draw();

    return 0;
  }

}

Fix a bad call to "writeInfo()" in "bin/phd stop" with no PHABRICATOR_INSTANCE defined

Summary: See <https://discourse.phabricator-community.org/t/phd-status-calls-to-undefined-method-when-theres-no-instance/2918>. This call should be `logInfo()`.

Test Plan:
  - Purged `PHABRICATOR_INSTANCE` from my environment. In a Phacility development environment, it comes from loading `services/`.
  - Ran `bin/phd stop` with all daemons already stopped.
    - Before: bad call.
    - After: helpful error.
  - Ran some other `bin/phd start`, `bin/phd status`, etc., to kick the tires.
  - Grepped for remaining `writeInfo()` calls (found none).

Reviewers: amckinley

Reviewed By: amckinley

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


<?php

use Rawebone\Tapped\Comparator;
use Rawebone\Tapped\Extension;
use Rawebone\Tapped\Extensions;
use function Rawebone\Tapped\test;

test('Extensions can be registered and executed', function ($expect) {

    $extension = new class extends Extension
    {
        function boot() { $this->boot = true; }
        function comparisons(Comparator $c) { $this->comparisons = true; }
        function setup() { $this->setup = true; }
        function tearDown() { $this->tearDown = true; }
        function shutdown() { $this->shutdown = true; }
    };

    $extensions = new Extensions;
    $extensions->registerMany([$extension]);
    $extensions->boot();
    $extensions->comparisons(new Comparator);
    $extensions->setup();
    $extensions->tearDown();
    $extensions->shutdown();

    $expect($extension->boot)->toEqual(true)->when('Extensions can be booted');
    $expect($extension->comparisons)->toEqual(true)->when('Extensions can register comparisons');
    $expect($extension->setup)->toEqual(true)->when('Extensions can be setup');
    $expect($extension->tearDown)->toEqual(true)->when('Extensions can be torn down');
    $expect($extension->shutdown)->toEqual(true)->when('Extensions can be shutdown');
});

<?php

use Rawebone\Tapped\Comparator;
use Rawebone\Tapped\Extension;
use Rawebone\Tapped\Extensions;
use function Rawebone\Tapped\test;

test(Extensions::class, function ($expect) {

    $extension = new class extends Extension
    {
        function boot() { $this->boot = true; }
        function comparisons(Comparator $c) { $this->comparisons = true; }
        function setup() { $this->setup = true; }
        function tearDown() { $this->tearDown = true; }
        function shutdown() { $this->shutdown = true; }
    };

    $extensions = new Extensions;
    $extensions->registerMany([$extension]);
    $extensions->boot();
    $extensions->comparisons(new Comparator);
    $extensions->setup();
    $extensions->tearDown();
    $extensions->shutdown();

    $expect($extension->boot)->toEqual(true)->when('Extensions can be booted');
    $expect($extension->comparisons)->toEqual(true)->when('Extensions can register comparisons');
    $expect($extension->setup)->toEqual(true)->when('Extensions can be setup');
    $expect($extension->tearDown)->toEqual(true)->when('Extensions can be torn down');
    $expect($extension->shutdown)->toEqual(true)->when('Extensions can be shutdown');
});

Rename test to use class convention

Rename test to use class convention


<?php
declare(strict_types=1);

namespace Riskio\IdempotencyModule\Container;

use Interop\Container\ContainerInterface;
use Riskio\IdempotencyModule\ModuleOptions;

class ModuleOptionsFactory
{
    public function __invoke(ContainerInterface $container) : ModuleOptions
    {
        $options = $container->get('config');

        return new ModuleOptions($options['idempotency']);
    }
}

<?php
declare(strict_types=1);

namespace Riskio\IdempotencyModule\Container;

use Interop\Container\ContainerInterface;
use Riskio\IdempotencyModule\ModuleOptions;

class ModuleOptionsFactory
{
    public function __invoke(ContainerInterface $container) : ModuleOptions
    {
        $options = $container->get('config');

        return new ModuleOptions($options['riskio_idempotency']);
    }
}

Fix config key in ModuleOptions factory

Fix config key in ModuleOptions factory


<?php
namespace Overflowsith\Firewall;

use Config;
use Str;

class Firewall
{

    public static function isAllowed($ip)
    {
        switch(Config::get('firewall::config.mode')) {
            case 'disabled':
                return true;
                break;
            case 'enforcing':
                return self::isInWhiteList($ip);
                break;
            case 'permissive':
                return !(self::isInBlackList($ip));
                break;
            default:
                return false;
        }
    }

    public static function isInWhiteList($ip)
    {
        return self::check(Config::get('firewall::config.whitelist', []), $ip);
    }

    public static function isInBlackList($ip)
    {
        return self::check(Config::get('firewall::config.blacklist', []), $ip);
    }

    private static function check($source, $ip)
    {
        foreach($source as $pattern) {
            if (Str::is($pattern, $ip)) {
                return true;
            }
        }
        return false;
    }
}

<?php
namespace Overflowsith\Firewall;

use Config;
use Str;

class Firewall
{

    public static function isAllowed($ip)
    {
        switch(Config::get('firewall::config.mode')) {
            case 'disabled':
                return true;
                break;
            case 'enforcing':
                return self::isInWhiteList($ip) && !(self::isInBlackList($ip));
                break;
            case 'permissive':
                return !(self::isInBlackList($ip));
                break;
            default:
                return false;
        }
    }

    public static function isInWhiteList($ip)
    {
        return self::check(Config::get('firewall::config.whitelist', []), $ip);
    }

    public static function isInBlackList($ip)
    {
        return self::check(Config::get('firewall::config.blacklist', []), $ip);
    }

    private static function check($source, $ip)
    {
        foreach($source as $pattern) {
            if (Str::is($pattern, $ip)) {
                return true;
            }
        }
        return false;
    }
}

Check if ip is in whitelist and not in blacklist

This can be useful when we define a subnet as whitelist but we want
to exclude a particular ip, for example:

whitelist 192.168.0.*
blacklist 192.168.0.50


<?php

namespace Raffle;

class RandomService
{
    /**
     * Base URL
     */
    const BASE_URL = 'https://www.random.org/integer-sets/?sets=1&min=%d&max=%d&num=%d&order=random&format=plain&rnd=new';

    /**
     * Retrieve a block of random numbers.
     *
     * @param int $min   Minimum amount.
     * @param int $max   Maximum amount.
     * @return array
     */
    public function getRandomNumbers($min, $max)
    {
        // Construct the URL
        $url = sprintf(self::BASE_URL, $min, $max, $max + 1);

        // Fetch the numbers
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);

        // Decode data and return
        return explode(" ", trim($data));
    }
}

<?php

namespace Raffle;

class RandomService
{
    /**
     * Base URL
     */
    const BASE_URL = 'https://www.random.org/integer-sets/?sets=1&min=%d&max=%d&num=%d&order=random&format=plain&rnd=new';

    /**
     * Retrieve a block of random numbers.
     *
     * @param int $min   Minimum amount.
     * @param int $max   Maximum amount.
     * @return array
     */
    public function getRandomNumbers($min, $max)
    {
        // Construct the URL
        $url = sprintf(self::BASE_URL, $min, $max, $max + 1);

        // Fetch the numbers
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $data = curl_exec($ch);

        // Decode data and return
        return explode(" ", trim($data));
    }
}

Make curl follow redirects to prevent relocation in the future


<?php

/*
 * Copyright 2012 Mo McRoberts.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

require_once(dirname(__FILE__) . '/client.php');

class BarlesquePage extends Page
{
	protected $blq;
	protected $defaultSkin = 'barlesque';

	public function __construct()
	{
		parent::__construct();
		$this->blq = new Barlesque();
	}

	protected function assignTemplate()
	{
		parent::assignTemplate();
		$this->vars['blq'] = $this->blq;
	}
}

<?php

/*
 * Copyright 2012 Mo McRoberts.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

require_once(dirname(__FILE__) . '/client.php');

class BarlesquePage extends Page
{
	protected $blq;
	protected $defaultSkin = 'barlesque';

	public function __construct()
	{
		parent::__construct();
		$this->blq = $this->barlesque();
	}

	protected function barlesque()
	{
		return new Barlesque();
	}

	protected function assignTemplate()
	{
		parent::assignTemplate();
		$this->vars['blq'] = $this->blq;
	}
}

Allow instantiation of the Barlesque object to be overridden.


<?php

use Wedeto\DB\Query\Builder AS QB;
use Wedeto\DB\Schema\Table;
use Wedeto\DB\Schema\Column;
use Wedeto\DB\Schema\Index;

$table = new Table(
    "db_version",
    new Column\TSerial('id'),
    new Column\TVarchar('module', 128),
    new Column\TInt('version'),
    new Column\TDatetime('date_upgraded'),
    new Index(Index::PRIMARY, 'id'),
    new Index(Index::UNIQUE, 'module', 'version')
);

$db->getDriver()->createTable($table);

<?php

use Wedeto\DB\Query\Builder AS QB;
use Wedeto\DB\Schema\Table;
use Wedeto\DB\Schema\Column;
use Wedeto\DB\Schema\Index;

$table = new Table(
    "db_version",
    new Column\Serial('id'),
    new Column\Varchar('module', 128),
    new Column\Integer('version'),
    new Column\Datetime('date_upgraded'),
    new Index(Index::PRIMARY, 'id'),
    new Index(Index::UNIQUE, 'module', 'version')
);

$db->getDriver()->createTable($table);

Rename sql directory to migrations

Rename sql directory to migrations


@extends('layout.app', [
    'title' => $designer->getTranslation()->name . ' - Designer',
    'body_id' => 'designer-page',
    'body_class' => 'designer-page',
])

@section('content')

@if (!Auth::guest())

    id.'/edit') }}"
        id="edit-button" class="btn btn-default pull-right">Edit

@endif

@foreach ($designer->getImages() as $image)

getUrl()) }}"
        data-thumb="{{ url($image->getThumbUrl()) }}"
        style="background-image:url({{ url($image->getThumbUrl()) }})">

@endforeach

id }}" class="designer container">

{{ $designer->getTranslation()->name }}

{!! $designer->getTranslation()->content !!}

@endsection

@extends('layout.app', [
    'title' => $designer->getTranslation()->name . ' - Designer',
    'body_id' => 'designer-page',
    'body_class' => 'designer-page',
])

@section('content')

@if (!Auth::guest())

            id.'/edit') }}"
                id="edit-button" class="btn btn-default pull-right">Edit

@endif

        getMainImage()->getThumbUrl() }}" />

{{ $designer->getTranslation()->name }}

Helsinki, Finland

    @foreach ($designer->getImages() as $image)

getUrl()) }}"
            data-thumb="{{ url($image->getThumbUrl()) }}"
            style="background-image:url({{ url($image->getThumbUrl()) }})">

    @endforeach

id }}" class="designer container">
    {{ $designer->getTranslation()->content }}

@endsection

Add designer photo and location to designer page.


<?php
$pdo = new PDO('mysql:host=localhost;dbname=annahda', 'root', '');

<?php
$pdo = new PDO('mysql:host=mysql.hostinger.co.uk;dbname=u897984522_immo', 'u897984522_asdev', 'RevoK2016I');

Update Tasks - Date : 25/10/2016

Update Tasks - Date : 25/10/2016


<?php
    namespace DB\Driver;

    /**
     * Interface for all database driver. Any database driver must implement
     * this class.
     *
     * @package DB\Driver
     */
    interface IDriver
    {
        /**
         * Connect to selected database host
         *
         * @param  string $host     Database host name
         * @param  string $user     Username for database host
         * @param  string $password Password for database host
         */
        public function connect($host, $user, $password);

        /**
         * Connect to database in the host.
         *
         * @param  string $name         Database name
         * @param  bool   $forceCreate  If set to true, will create database if
         * 								database is not exists
         */
        public function database($name, $forceCreate=false);

        /**
         * Perform Query based on the driver.
         *
         * @param  string $sql SQL that need to be run
         *
         * @return \DB\Result  Database query result
         */
        public function query($sql);

        /**
         * Perform database query by binding the data to query syntax.
         *
         * @param  string $sql  SQL
         * @param  array  $data Data that will be binded to query
         *
         * @return \DB\Result   Database query result
         */
        public function bind($sql, $data=[]);

        public function escape($string);
    }

?>

<?php
    namespace DB\Driver;

    /**
     * Interface for all database driver. Any database driver must implement
     * this class.
     *
     * @package DB\Driver
     */
    interface IDriver
    {
        /**
         * Connect to selected database host
         *
         * @param  string $host     Database host name
         * @param  string $user     Username for database host
         * @param  string $password Password for database host
         */
        public function connect($host, $user, $password);

        /**
         * Connect to database in the host.
         *
         * @param  string $name         Database name
         * @param  bool   $forceCreate  If set to true, will create database if
         * 								database is not exists
         */
        public function database($name, $forceCreate=false);

        /**
         * Perform Query based on the driver.
         *
         * @param  string $sql SQL that need to be run
         *
         * @return \DB\Result  Database query result
         */
        public function query($sql);

        /**
         * Perform database query by binding the data to query syntax.
         *
         * @param  string $sql  SQL
         * @param  array  $data Data that will be binded to query
         *
         * @return \DB\Result   Database query result
         */
        public function bind($sql, $data=[]);

    }

?>

Remove esacpe method at driver (use bind instead)


@extends('layout')

@section('title', __('models.imports'))

@section('body')

{{ __('models.imports') }}

            @if (count($imports))

Name

Type

Status

                @foreach ($imports as $import)

{{ $import->name }}

{{ $import->type }}

{{ $import->status }}

                @endforeach
            @else
                @include('partials.empty_state', ['payload' => 'imports'])
            @endif

@endsection

@extends('layout')

@section('title', __('models.imports'))

@section('body')

{{ __('models.imports') }}

            @if (count($imports))

Name

Status

                @foreach ($imports as $import)

{{ $import->name }}

{{ $import->status }}

                @endforeach
            @else
                @include('partials.empty_state', ['payload' => 'imports'])
            @endif

@endsection

Drop usage of Import model's type field in views


<?php echo $head; ?>

<?php echo _('Facebook login successful!') ?>

 <?php
            echo _('The last step.');
            echo _('You can add a message to your check-in.');
            ?>

            <form class="pure-form">
                <fieldset>
                    <legend><?php echo _('Check In'); ?></legend>
                    <input type="textarea" placeholder="" name="message" id="text_fb_message">
                        <?php echo $suggested_message; ?>
                    </input>
                    <button class="pure-button" id="button_clear_fb_message">
                        <?php echo _('Clear message'); ?>
                    </button>
                    <button type="submit" class="pure-button pure-button-primary" action="<?php echo $post_action; ?>">
                        <?php echo _('Check in to') . $place_name; ?>
                    </button>
                </fieldset>
            </form>

 <?php echo_('If you do not want to check in, you can still use the access code!') ; ?>

            <a href="<?php echo $retry_url; ?>" class="pure-button"><?php echo _('Back to login'); ?>

<?php echo $foot; ?>

<?php echo $head; ?>

<?php echo _('Facebook login successful!') ?>

 <?php
                echo _('The last step.');
                echo ' ';
                echo _('You can add a message to your check-in.');
                echo ' ';
            ?>

            <form class="pure-form">
                <fieldset>
                    <legend><?php echo _('Check In'); ?></legend>
                    <input type="textarea" placeholder="" name="message" id="text_fb_message">
                        <?php echo $suggested_message; ?>
                    </input>
                    <button class="pure-button" id="button_clear_fb_message">
                        <?php echo _('Clear message'); ?>
                    </button>
                    <button type="submit" class="pure-button pure-button-primary" action="<?php echo $post_action; ?>">
                        <?php echo _('Check in to') . $place_name; ?>
                    </button>
                </fieldset>
            </form>

 <?php echo_('If you do not want to check in, you can still use the access code!') ; ?>

            <a href="<?php echo $retry_url; ?>" class="pure-button"><?php echo _('Back to login'); ?>

<?php echo $foot; ?>

Add missing spaces, re-indent HTML

Add missing spaces, re-indent HTML


<?php if ($tests): ?>

<?=form_open($form_action); ?>

<?php foreach ($tests AS $addon): ?>

			<a href="#addon_<?=strtolower($addon->name); ?>"><?=str_replace('%addon_name%', ucfirst($addon->name), lang('addon_anchor')); ?>
			<input type="checkbox" /> <?=ucfirst($addon->name); ?>
				(<?=count($addon->tests) .' ' .(count($addon->tests) === 1 ? lang('test') : lang('tests')); ?>)

			<?php foreach ($addon->tests AS $test): ?>

<?=form_checkbox('tests[]', $test->file_path, FALSE); ?> <?=$test->file_name; ?>

			<?php endforeach; ?>

<?php endforeach; ?>

<?=form_submit(array('name' => 'submit', 'value' => lang('run_tests'), 'class' => 'submit')); ?>

<?=form_close(); ?>

<?php else: ?>

<?=lang('no_tests'); ?>

<?php endif; ?>

<?php if ($tests): ?>

<?=form_open($form_action); ?>

<?php foreach ($tests AS $addon): ?>

			<a href="#addon_<?=strtolower($addon->name); ?>"><?=str_replace('%addon_name%', ucfirst($addon->name), lang('addon_anchor')); ?>
			<?=ucfirst($addon->name); ?>
				(<?=count($addon->tests) .' ' .(count($addon->tests) === 1 ? lang('test') : lang('tests')); ?>)

			<?php foreach ($addon->tests AS $test): ?>

<?=form_radio('test', $test->file_path, FALSE); ?> <?=$test->file_name; ?>

			<?php endforeach; ?>

<?php endforeach; ?>

<?=form_submit(array('name' => 'submit', 'value' => lang('run_tests'), 'class' => 'submit')); ?>

<?=form_close(); ?>

<?php else: ?>

<?=lang('no_tests'); ?>

<?php endif; ?>

Change 'test' checkboxes to radio buttons. Rename form field from 'tests' to 'test'.


<?php

namespace App\Controllers;

class HomeController extends BaseController
{
    public function index($request, $response)
    {
	    return $this->view->render($response, 'home.twig');
    }

    public function test($request, $response, $args)
    {
    	$id = $args['id'];

	    return $this->view->render($response, 'home.twig');
    }
}

<?php

namespace App\Controllers;

class HomeController extends BaseController
{
    public function index($request, $response)
    {
	    return $this->view->render($response, 'home.twig');
    }
}

Remove unnecessary method on Home controller


<?php
/**
 * @license MIT
 * Full license text in LICENSE file
 */

namespace VLibrary\Core\Tool;

interface Photoshopper
{
    /**
     * Sets the source image to manipulate, and the destination to save the result
     *
     * Example:
     * $photoshopper->setup('/tmp/myfile.png', '/home/user/profile.png');
     *
     * @param string $source      The path to the source image file
     * @param string $destination The path of the destination image file. If
     *                            blank, the source file will be overwritten.
     *
     * @return void
     */
    public function setup($source, $destination = NULL);

    /**
     * Returns image width in pixels
     *
     * @return int
     */
    public function get_width();

    /**
     * Resizes an image to a width in pixels, maintaining aspect ratio
     *
     * Example:
     * $photoshopper->resize_to_width(40);
     *
     * @param int $width Width in pixels to resize to
     *
     * @return void
     */
    public function resize_to_width($width);

    /**
     * Blurs the image using the Gaussian algorithm
     *
     * Example:
     * $photoshopper->gaussian_blur(2.5);
     *
     * @param float $sigma The sigma magnitude of the Gaussian blur
     *
     * @return void
     */
    public function gaussian_blur($sigma);
}

<?php
/**
 * @license MIT
 * Full license text in LICENSE file
 */

namespace VLibrary\Core\Tool;

interface Photoshopper
{
    /**
     * Sets the source image to manipulate, and the destination to save the result
     *
     * Example:
     * $photoshopper->setup('/tmp/myfile.png', '/home/user/profile.png');
     *
     * @param string $source      The path to the source image file
     * @param string $destination The path of the destination image file. If
     *                            blank, the source file will be overwritten.
     *
     * @return void
     */
    public function setup($source, $destination = NULL);

    /**
     * Returns image dimensions
     *
     * @return array($width, $height) in pixels
     */
    public function get_dimensions();

    /**
     * Resizes an image to a width in pixels, maintaining aspect ratio
     *
     * Example:
     * $photoshopper->resize_to_width(40);
     *
     * @param int $width Width in pixels to resize to
     *
     * @return void
     */
    public function resize_to_width($width);

    /**
     * Resizes an image to a height in pixels, maintaining aspect ratio
     *
     * Example:
     * $photoshopper->resize_to_height(40);
     *
     * @param int $height height in pixels to resize to
     *
     * @return void
     */
    public function resize_to_height($height);

    /**
     * Blurs the image using the Gaussian algorithm
     *
     * Example:
     * $photoshopper->gaussian_blur(2.5);
     *
     * @param float $sigma The sigma magnitude of the Gaussian blur
     *
     * @return void
     */
    public function gaussian_blur($sigma);
}

Add more photoshopper tool functions

Add more photoshopper tool functions

New function to resize to height
Get dimensions now supported


<?php

class NewsController extends BaseController {

  /**
  * The events implementation.
  *
  * @var Static
  */
  protected $events;

  // protected static $path = "./app/views/news/speakers/";

  /**
  * Set our Events instance.
  *
  * @param Events $events
  * @return void
  */
  public function __construct(Events $events)
  {
    $this->events = $events;
  }

  /**
  * GET -> irexinc.org/ & irexinc.org/news/
  *
  * @return View
  */
  public function index ()
  {
    $meetings = $this->events->getNextMeetings();

    // die(var_dump($meetings));

    foreach ($meetings as $index => $meeting)
    {
      if (file_exists("./app/views/news/speakers/" . $meeting['date'] . ".blade.php"))
      {
        $meetings[$index]['speaker'] = View::make('news.speakers.' . $meeting['date']);
      }

      $meetings[$index]['date'] = strftime("%B %d", strtotime($meeting['date']));
    }

    return View::make('news.index')->with(compact('meetings'));
    // return var_dump($next_meeting);
  }

}

<?php

class NewsController extends BaseController {

  /**
  * The events implementation.
  *
  * @var Static
  */
  protected $events;

  // protected static $path = "./app/views/news/speakers/";

  /**
  * Set our Events instance.
  *
  * @param Events $events
  * @return void
  */
  public function __construct(Events $events)
  {
    $this->events = $events;
  }

  /**
  * GET -> irexinc.org/ & irexinc.org/news/
  *
  * @return View
  */
  public function index ()
  {
    $meetings = $this->events->getNextMeetings();

    // die(var_dump($meetings));

    foreach ($meetings as $index => $meeting)
    {
      if (file_exists(app_path() . "/views/news/speakers/" . $meeting['date'] . ".blade.php"))
      {
        $meetings[$index]['speaker'] = View::make('news.speakers.' . $meeting['date']);
      }

      $meetings[$index]['date'] = strftime("%B %d", strtotime($meeting['date']));
    }

    return View::make('news.index')->with(compact('meetings'));
    // return var_dump($next_meeting);
  }

}

Use Laravel's app_path() to be able to check if a speaker exists instead of absolute path.


<?php

use Doctrine\Common\Annotations\AnnotationRegistry;

if (getenv('IS_JENKINS') === 'true') {
    $jenkinsNeedsThese = array(
        'Stripe' => '/stripe/stripe-php/lib/Stripe.php',
        'ExpressiveDate' => '/jasonlewis/expressive-date/src/ExpressiveDate.php'
    );

    foreach ($jenkinsNeedsThese as $class => $path) {
        if (!class_exists($class)) {
            require_once(realpath(__DIR__ . '/../vendor' . $path));
        }
    }
}

$loader = require __DIR__.'/../vendor/autoload.php';

// intl
if (!function_exists('intl_get_error_code')) {
    require_once __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php';

    $loader->add('', __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs');
}

AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

return $loader;

<?php

use Doctrine\Common\Annotations\AnnotationRegistry;

/**
 * Explicitly include some dependencies that otherwise result in 'class not found'
 * errors when running on Jenkins.
 *
 * Works on local dev environment. Works on live. Works on Travis. Doesn't work on Jenkins.
 */
if (getenv('IS_JENKINS') === 'true') {
    $jenkinsNeedsThese = array(
        'Stripe' => '/stripe/stripe-php/lib/Stripe.php',
        'ExpressiveDate' => '/jasonlewis/expressive-date/src/ExpressiveDate.php'
    );

    foreach ($jenkinsNeedsThese as $class => $path) {
        if (!class_exists($class)) {
            require_once(realpath(__DIR__ . '/../vendor' . $path));
        }
    }
}

$loader = require __DIR__.'/../vendor/autoload.php';

// intl
if (!function_exists('intl_get_error_code')) {
    require_once __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php';

    $loader->add('', __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs');
}

AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

return $loader;

Add explanatory comments regarding odd Jenkins behaviour


<?php

use Illuminate\Routing\Router;

/** @var Router $router */

$router->group(['prefix' =>'/block'], function (Router $router) {
        $router->bind('blocks', function ($id) {
            return app('Modules\Block\Repositories\BlockRepository')->find($id);
        });
        $router->resource('blocks', 'BlockController', ['except' => ['show'], 'names' => [
            'index' => 'admin.block.block.index',
            'create' => 'admin.block.block.create',
            'store' => 'admin.block.block.store',
            'edit' => 'admin.block.block.edit',
            'update' => 'admin.block.block.update',
            'destroy' => 'admin.block.block.destroy',
        ]]);
// append

});

<?php

$router->bind('blocks', function ($id) {
    return app('Modules\Block\Repositories\BlockRepository')->find($id);
});

$router->group(['prefix' =>'/block'], function () {
    get('blocks', ['as' => 'admin.block.block.index', 'uses' => 'BlockController@index']);
    get('blocks/create', ['as' => 'admin.block.block.create', 'uses' => 'BlockController@create']);
    post('blocks', ['as' => 'admin.block.block.store', 'uses' => 'BlockController@store']);
    get('blocks/{blocks}/edit', ['as' => 'admin.block.block.edit', 'uses' => 'BlockController@edit']);
    put('blocks/{blocks}', ['as' => 'admin.block.block.update', 'uses' => 'BlockController@update']);
    delete('blocks/{blocks}', ['as' => 'admin.block.block.destroy', 'uses' => 'BlockController@destroy']);
});

Use manual route definition over the route resource shortcut


<?php
/*
Template Name: Home Template
*/
?>
<?php //get_template_part('templates/page', 'header'); ?>

    <?php get_template_part('templates/content', 'page'); ?>

  <?php get_template_part('templates/row-booking'); ?>
  <?php // get_template_part('templates/row-about'); ?>

<?php get_template_part('templates/row-personal-offers'); ?>

<?php
/*
Template Name: Home Template
*/
?>
<?php //get_template_part('templates/page', 'header'); ?>

    <?php get_template_part('templates/content', 'page'); ?>

  <?php get_template_part('templates/row-booking'); ?>
  <?php get_template_part('templates/row-about'); ?>

<?php get_template_part('templates/row-personal-offers'); ?>

Add About RR to Front-Page

Add About RR to Front-Page


<?php
#
# Retrieves and parses the XML output from gmond. Results stored
# in global variables: $clusters, $hosts, $hosts_down, $metrics.
# Assumes you have already called get_context.php.
#

# If we are in compare_hosts, views and decompose_graph context we shouldn't attempt
# any connections to the gmetad
if ( in_array($context, $SKIP_GMETAD_CONTEXTS) ) {

} else {
   if (! Gmetad($conf['ganglia_ip'], $conf['ganglia_port']) )
      {
         print "
There was an error collecting ganglia data ".
            "(${conf['ganglia_ip']}:${conf['ganglia_port']}): $error
\n";
         exit;
      }

   # If we have no child data sources, assume something is wrong.
   if (!count($grid) and !count($cluster))
      {
         print "
Ganglia cannot find a data source. Is gmond running?
";
         exit;
      }
   # If we only have one cluster source, suppress MetaCluster output.
   if (count($grid) <= 2 and $context=="meta")
      {
         # Lets look for one cluster (the other is our grid).
         foreach($grid as $source)
            if (isset($source['CLUSTER']) and $source['CLUSTER'])
               {
                  $standalone = 1;
                  $context = "cluster";
                  # Need to refresh data with new context.
                  Gmetad($conf['ganglia_ip'], $conf['ganglia_port']);
                  $clustername = $source['NAME'];
               }
      }

}

?>

<?php
#
# Retrieves and parses the XML output from gmond. Results stored
# in global variables: $clusters, $hosts, $hosts_down, $metrics.
# Assumes you have already called get_context.php.
#

# If we are in compare_hosts, views and decompose_graph context we shouldn't attempt
# any connections to the gmetad
if ( in_array($context, $SKIP_GMETAD_CONTEXTS) ) {

} else {
   if (! Gmetad($conf['ganglia_ip'], $conf['ganglia_port']) )
      {
         print "
There was an error collecting ganglia data ".
            "(${conf['ganglia_ip']}:${conf['ganglia_port']}): $error
\n";
         exit;
      }

   # If we have no child data sources, assume something is wrong.
   if (!count($grid) and !count($cluster))
      {
         print "
Ganglia cannot find a data source. Is gmond running?
";
         exit;
      }
   # If we only have one cluster source, suppress MetaCluster output.
   if (count($grid) < 2 and $context=="meta")
      {
         # Lets look for one cluster (the other is our grid).
         foreach($grid as $source)
            if (isset($source['CLUSTER']) and $source['CLUSTER'])
               {
                  $standalone = 1;
                  $context = "cluster";
                  # Need to refresh data with new context.
                  Gmetad($conf['ganglia_ip'], $conf['ganglia_port']);
                  $clustername = $source['NAME'];
               }
      }

}

?>

Fix count check of clusters in $grid

Fix count check of clusters in $grid


<?php

use Upfor\App;

if (!function_exists('app')) {
    /**
     * Get the specified app instance
     *
     * @param  string $name
     * @return \Upfor\App
     */
    function app($name = 'default') {
        return App::getInstance($name);
    }

}

<?php

use Upfor\App;

if (!function_exists('app')) {

    /**
     * Get the specified app instance
     *
     * @param  string $name
     * @return \Upfor\App
     */
    function app($name = null) {
        static $currentApp = 'default';

        if ($name) {
            $currentApp = $name;
        }

        return App::getInstance($currentApp);
    }

}

if (!function_exists('single')) {

    /**
     * Gets a single instance of a class
     *
     * @param  string  $key   The value or object name
     * @param  Closure        The closure that defines the object
     * @return mixed
     */
    function single($key, $value = null) {
        return app()->singleton($key, $value);
    }

}

if (!function_exists('log')) {

    /**
     * Log a debug message to the logs.
     *
     * @param  mixed $level
     * @param  mixed $message
     * @param  array $context
     * @return \Upfor\Exception\Logger|null
     */
    function log($level, $message, $context = []) {
        if (is_null($message)) {
            return single('logger');
        }

        return single('logger')->log($level, $message, $context);
    }

}

Add function `single` and `log`

Add function `single` and `log`


<?php

	class PostgresDbWrapper extends PostgresDb {
		/**
		 * Execute where method with the specified episode and season numbers
		 *
		 * @param string|int|\DB\Episode $s Season, or array with keys season & episode
		 * @param string|int|null        $e Episode, optional if $s is an array
		 *
		 * @return self
		 */
		public function whereEp($s, $e = null){
			if (!isset($e)){
				parent::where('season', $s->season);
				parent::where('episode', $s->episode);
			}
			else {
				parent::where('season', $s);
				parent::where('episode', $e);
			}
			return $this;
		}

		public $query_count = 0;

		private $_nonexistantClassCache = array();

		/**
		 * @param PDOStatement $stmt Statement to execute
		 *
		 * @return bool|array|object[]
		 */
		protected function _execStatement($stmt){
			$className = $this->tableNameToClassName();
			if (isset($className) && empty($this->_nonexistantClassCache[$className])){
				if (!class_exists("\\DB\\$className"))
					$this->_nonexistantClassCache[$className] = true;
				else $this->setClass("\\DB\\$className");
			}

			$this->query_count++;
			return parent::_execStatement($stmt);
		}
	}

<?php

	class PostgresDbWrapper extends PostgresDb {
		/**
		 * Execute where method with the specified episode and season numbers
		 *
		 * @param string|int|\DB\Episode $s Season, or array with keys season & episode
		 * @param string|int|null        $e Episode, optional if $s is an array
		 *
		 * @return self
		 */
		public function whereEp($s, $e = null){
			if (!isset($e)){
				parent::where('season', $s->season);
				parent::where('episode', $s->episode);
			}
			else {
				parent::where('season', $s);
				parent::where('episode', $e);
			}
			return $this;
		}

		public $query_count = 0;

		private $_nonexistantClassCache = array();

		/**
		 * @param PDOStatement $stmt Statement to execute
		 *
		 * @return bool|array|object[]
		 */
		protected function _execStatement($stmt){
			$className = $this->tableNameToClassName();
			if (isset($className) && empty($this->_nonexistantClassCache[$className])){
				try {
					if (!class_exists("\\DB\\$className"))
						throw new Exception();

					$this->setClass("\\DB\\$className");
				}
				catch (Exception $e){ $this->_nonexistantClassCache[$className] = true; }
			}

			$this->query_count++;
			return parent::_execStatement($stmt);
		}
	}

Revert "Speed up non-existent class detection by not using exceptions"

This reverts commit 5f79bf46ceb3644b69bdb100139d537c21b9da85.


<?php
namespace Pux;
use ReflectionClass;
use Closure;

class Compositor
{
    protected $stacks = array();

    protected $app;

    protected $mapApp;

    public function __construct(callable $app = null)
    {
        $this->app = $app;
    }

    public function enable($appClass)
    {
        if ($appClass instanceof Closure) {
            $this->stacks[] = $appClass;
        } else {
            $args = func_get_args();
            array_shift($args);
            $this->stacks[] = [$appClass, $args];
        }
        return $this;
    }

    public function app($app)
    {
        $this->app = $app;
        return $this;
    }

    public function wrap()
    {
        $app = $this->app;

        for ($i = count($this->stacks) - 1; $i > 0; $i--) {
            $stack = $this->stacks[$i];

            // middleware closure
            if ($stack instanceof Closure) {
                $app = $stack($app);
            } else {
                list($appClass, $args) = $stack;
                $refClass = new ReflectionClass($appClass);
                array_unshift($args, $app);
                $app = $refClass->newInstanceArgs($args);
            }

        }
        return $app;
    }

    public function __invoke(array $environment, array $response)
    {
        $app = $this->wrap();
        return $app($environment, $response);
    }

}

<?php
namespace Pux;
use ReflectionClass;
use Closure;

class Compositor
{
    protected $stacks = array();

    protected $app;

    protected $mapApp;

    private $wrappedApp;

    public function __construct(callable $app = null)
    {
        $this->app = $app;
    }

    public function enable($appClass)
    {
        if ($appClass instanceof Closure) {
            $this->stacks[] = $appClass;
        } else {
            $args = func_get_args();
            array_shift($args);
            $this->stacks[] = [$appClass, $args];
        }
        return $this;
    }

    public function app($app)
    {
        $this->app = $app;
        return $this;
    }

    public function wrap()
    {
        $app = $this->app;

        for ($i = count($this->stacks) - 1; $i > 0; $i--) {
            $stack = $this->stacks[$i];

            // middleware closure
            if ($stack instanceof Closure) {
                $app = $stack($app);
            } else {
                list($appClass, $args) = $stack;
                $refClass = new ReflectionClass($appClass);
                array_unshift($args, $app);
                $app = $refClass->newInstanceArgs($args);
            }

        }
        return $app;
    }

    public function __invoke(array $environment, array $response)
    {
        if ($app = $this->wrappedApp) {
            return $app($environment, $response);
        }
        $this->wrappedApp = $app = $this->wrap();
        return $app($environment, $response);
    }

}

Add wrappedApp property to cache wrapped app closure


<?php

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

namespace Symfony\Bundle\FrameworkBundle\Test;

use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;

/**
 * WebTestCase is the base class for functional tests.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
abstract class WebTestCase extends KernelTestCase
{
    /**
     * Creates a KernelBrowser.
     *
     * @param array $options An array of options to pass to the createKernel method
     * @param array $server  An array of server parameters
     *
     * @return KernelBrowser A KernelBrowser instance
     */
    protected static function createClient(array $options = [], array $server = [])
    {
        $kernel = static::bootKernel($options);

        try {
            $client = $kernel->getContainer()->get('test.client');
        } catch (ServiceNotFoundException $e) {
            if (class_exists(Client::class)) {
                throw new \LogicException('You cannot create the client used in functional tests if the "framework.test" config is not set to true.');
            }
            throw new \LogicException('You cannot create the client used in functional tests if the BrowserKit component is not available. Try running "composer require symfony/browser-kit"');
        }

        $client->setServerParameters($server);

        return $client;
    }
}

<?php

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

namespace Symfony\Bundle\FrameworkBundle\Test;

use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;

/**
 * WebTestCase is the base class for functional tests.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
abstract class WebTestCase extends KernelTestCase
{
    /**
     * Creates a KernelBrowser.
     *
     * @param array $options An array of options to pass to the createKernel method
     * @param array $server  An array of server parameters
     *
     * @return KernelBrowser A KernelBrowser instance
     */
    protected static function createClient(array $options = [], array $server = [])
    {
        $kernel = static::bootKernel($options);

        try {
            $client = $kernel->getContainer()->get('test.client');
        } catch (ServiceNotFoundException $e) {
            if (class_exists(KernelBrowser::class)) {
                throw new \LogicException('You cannot create the client used in functional tests if the "framework.test" config is not set to true.');
            }
            throw new \LogicException('You cannot create the client used in functional tests if the BrowserKit component is not available. Try running "composer require symfony/browser-kit"');
        }

        $client->setServerParameters($server);

        return $client;
    }
}

Replace class with new name.

Replace class with new name.


<?php

namespace App\Service;

use App\Classes\ElasticSearchBase;
use App\Entity\User;

class Search extends ElasticSearchBase
{
    /**
     * @param array $params
     * @return array
     * @throws \Exception when the search service isn't setup
     */
    protected function search(array $params) : array
    {
        if (!$this->enabled) {
            throw new \Exception("Search is not configured, isEnabled() should be called before calling this method");
        }
        return $this->client->search($params);
    }

    /**
     * @param string $query
     * @return array
     * @throws \Exception when search is not configured
     */
    public function userIdsQuery(string $query)
    {
        if (!$this->enabled) {
            throw new \Exception("Search is not configured, isEnabled() should be called before calling this method");
        }
        $params = [
            'type' => User::class,
            'index' => self::PRIVATE_INDEX,
            'body' => [
                'query' => [
                    'query_string' => [
                        'query' => "*${query}*",
                    ]
                ],
                "_source" => [
                    '_id'
                ]
            ]
        ];
        $results = $this->search($params);
        return array_map(function (array $arr) {
            return $arr['_id'];
        }, $results['hits']['hits']);
    }
}

<?php

namespace App\Service;

use App\Classes\ElasticSearchBase;
use App\Entity\DTO\UserDTO;

class Search extends ElasticSearchBase
{
    /**
     * @param array $params
     * @return array
     * @throws \Exception when the search service isn't setup
     */
    protected function search(array $params) : array
    {
        if (!$this->enabled) {
            throw new \Exception("Search is not configured, isEnabled() should be called before calling this method");
        }
        return $this->client->search($params);
    }

    /**
     * @param string $query
     * @return array
     * @throws \Exception when search is not configured
     */
    public function userIdsQuery(string $query)
    {
        if (!$this->enabled) {
            throw new \Exception("Search is not configured, isEnabled() should be called before calling this method");
        }
        $params = [
            'type' => UserDTO::class,
            'index' => self::PRIVATE_INDEX,
            'body' => [
                'query' => [
                    'query_string' => [
                        'query' => "*${query}*",
                    ]
                ],
                "_source" => [
                    '_id'
                ]
            ]
        ];
        $results = $this->search($params);
        return array_map(function (array $arr) {
            return $arr['_id'];
        }, $results['hits']['hits']);
    }
}

Use correct UserDTO parameter when searching


<?php

/**
 * Copyright 2016 Bitban Technologies, S.L.
 * Todos los derechos reservados.
 */

namespace Bitban\PhpCodeQualityTools;

class PhpCodeQualityTools
{
    const APP_NAME = 'Bitban Technologies PHP Code Quality Tools';
    const APP_VERSION = '0.9.1';
}

<?php

/**
 * Copyright 2016 Bitban Technologies, S.L.
 * Todos los derechos reservados.
 */

namespace Bitban\PhpCodeQualityTools;

class PhpCodeQualityTools
{
    const APP_NAME = 'Bitban Technologies PHP Code Quality Tools';
    const APP_VERSION = '0.9.2';
}

Update tool version to 0.9.2

Update tool version to 0.9.2


<?php

namespace Spec\PHPSpec\Loader;

use \PHPSpec\Loader\DirectoryLoader,
    \PHPSpec\Util\SpecIterator;

class DescribeDirectoryLoader extends \PHPSpec\Context
{
    function itLoadsAllExampleGroupsUnderADirectory()
    {
        $loader = new DirectoryLoader;
        $examples = $loader->load(__DIR__ . '/_files/Bar');

        $examples = new SpecIterator($examples);

        $i = array('A', 'B', 'C');
        $examples -> withEach ( function ($example) use (&$i) {
            $example->should->beAnInstanceOf('Describe' . current($i));
            next($i);
        });
    }
}

<?php

namespace Spec\PHPSpec\Loader;

use \PHPSpec\Loader\DirectoryLoader,
    \PHPSpec\Util\SpecIterator;

class DescribeDirectoryLoader extends \PHPSpec\Context
{
    function itLoadsAllExampleGroupsUnderADirectory()
    {
        $loader = new DirectoryLoader;
        $examples = $loader->load(__DIR__ . '/_files/Bar');
        $this->spec(count($examples))->should->be(3);

        foreach ($examples as $example) {
            $class = get_class($example);
            if (!in_array($class, array('DescribeA', 'DescribeB', 'DescribeC'))) {
                $this->fail("$class is not meant to be loaded");
            }
        }
    }
}

Fix spec in which order of loading was different in travis server


<?php
namespace Payum\Core\Tests\Mocks\Model;

use Payum\Core\Exception\LogicException;

class Propel2ModelQuery
{
    const MODEL_CLASS = "Payum\\Core\\Tests\\Mocks\\Model\\Propel2Model";

    protected $filters = array();

    protected $modelReflection;

    public function __construct()
    {
        $this->modelReflection = new \ReflectionClass(static::MODEL_CLASS);
    }

    public function filterBy($column, $value)
    {
        if (!$this->modelReflection->hasProperty($column)) {
            throw new LogicException(sprintf(
                "The model doesn't have the column '%s'",
                $column
            ));
        }

        $this->filters[] = [$column, $value];

        return $this;
    }

    public function findOne()
    {
        $model = new Propel2Model();
        $this->applyFilters($model);

        return $model;
    }

    public function findPk($id)
    {
        $model = new Propel2Model();
        $model->setId($id);

        return $model;
    }

    protected function applyFilters(Propel2Model $model)
    {
        foreach ($this->filters as $filter) {
            $propriety = new \ReflectionProperty(static::MODEL_CLASS, $filter[0]);
            $propriety->setAccessible(true);

            $propriety->setValue($model, $filter[1]);
        }
    }
}

<?php
namespace Payum\Core\Tests\Mocks\Model;

use Payum\Core\Exception\LogicException;

class Propel2ModelQuery
{
    const MODEL_CLASS = "Payum\\Core\\Tests\\Mocks\\Model\\Propel2Model";

    protected $filters = array();

    protected $modelReflection;

    public function __construct()
    {
        $this->modelReflection = new \ReflectionClass(static::MODEL_CLASS);
    }

    public function filterBy($column, $value)
    {
        if (!$this->modelReflection->hasProperty($column)) {
            throw new LogicException(sprintf(
                "The model doesn't have the column '%s'",
                $column
            ));
        }

        $this->filters[] = array($column, $value);

        return $this;
    }

    public function findOne()
    {
        $model = new Propel2Model();
        $this->applyFilters($model);

        return $model;
    }

    public function findPk($id)
    {
        $model = new Propel2Model();
        $model->setId($id);

        return $model;
    }

    protected function applyFilters(Propel2Model $model)
    {
        foreach ($this->filters as $filter) {
            $propriety = new \ReflectionProperty(static::MODEL_CLASS, $filter[0]);
            $propriety->setAccessible(true);

            $propriety->setValue($model, $filter[1]);
        }
    }
}

Remove php 5.4 array tags

Remove php 5.4 array tags


<?php

namespace App\Http\Controllers\User;

use Session;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    public function showLoginPage(Request $request){
        return view('user.login');
    }

    public static function isLoggedIn(){
        return Session::has('user_logged_in');
    }
}

<?php

namespace App\Http\Controllers\User;

use Session;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    public function showLoginPage(Request $request){
        return view('user.login');
    }

    public static function isLoggedIn(){
        return (Session::get('user_logged_in') === true);
    }
    }
}

Improve method to check if user is logged in


<?php
/** @var \WEEEOpen\Tarallo\User $user */
/** @var \WEEEOpen\Tarallo\ProductIncomplete|\WEEEOpen\Tarallo\Product|null $base */

$base = $base ?? null;
/** @var int $importedFrom|null */

$this->layout('main', ['title' => 'New product', 'currentPage' => 'product new']);
$this->insert('newProduct', [
    'base' => $base,
	'importedFrom' => $importedFrom,
]);

<?php
/** @var \WEEEOpen\Tarallo\User $user */
/** @var \WEEEOpen\Tarallo\ProductIncomplete|\WEEEOpen\Tarallo\Product|null $base */
$base = $base ?? null;
/** @var int $importedFrom|null */
$importedFrom = $importedFrom ?? null;

$this->layout('main', ['title' => 'New product', 'currentPage' => 'product new']);
$this->insert('newProduct', [
    'base' => $base,
	'importedFrom' => $importedFrom,
]);

Fix undefined variable $importedFrom when splitting a product from an item


<?php
namespace CfdiUtils\Elements\Pagos10;

use CfdiUtils\Elements\Common\AbstractElement;

class Pago extends AbstractElement
{
    public function addDoctoRelacionado(array $attributes = []): DoctoRelacionado
    {
        $doctoRelacionado = new DoctoRelacionado($attributes);
        $this->addChild($doctoRelacionado);
        return $doctoRelacionado;
    }

    public function multiDoctoRelacionado(array ...$elementAttributes): self
    {
        foreach ($elementAttributes as $attributes) {
            $this->addDoctoRelacionado($attributes);
        }
        return $this;
    }

    public function addImpuestos(array $attributes = []): Impuestos
    {
        $impuestos = new Impuestos($attributes);
        $this->addChild($impuestos);
        return $impuestos;
    }

    public function multiImpuestos(array ...$elementAttributes): self
    {
        foreach ($elementAttributes as $attributes) {
            $this->addImpuestos($attributes);
        }
        return $this;
    }

    public function getElementName(): string
    {
        return 'pago10:Pago';
    }

    public function getChildrenOrder(): array
    {
        return ['pago10:DoctoRelacionado', 'pago10:Impuestos'];
    }
}

<?php
namespace CfdiUtils\Elements\Pagos10;

use CfdiUtils\Elements\Common\AbstractElement;

class Pago extends AbstractElement
{
    public function addDoctoRelacionado(array $attributes = []): DoctoRelacionado
    {
        $doctoRelacionado = new DoctoRelacionado($attributes);
        $this->addChild($doctoRelacionado);
        return $doctoRelacionado;
    }

    public function multiDoctoRelacionado(array ...$elementAttributes): self
    {
        foreach ($elementAttributes as $attributes) {
            $this->addDoctoRelacionado($attributes);
        }
        return $this;
    }

    public function addImpuestos(array $attributes = []): Impuestos
    {
        $impuestos = new Impuestos($attributes);
        $this->addChild($impuestos);
        return $impuestos;
    }

    public function getElementName(): string
    {
        return 'pago10:Pago';
    }

    public function getChildrenOrder(): array
    {
        return ['pago10:DoctoRelacionado', 'pago10:Impuestos'];
    }
}

Remove multiImpuestos, it should never exists


<?php
namespace GetOptionKit\ValueType;

abstract class BaseType
{
    public function __construct()
    {
        // code...
    }

    /**
     * Test a value to see if it fit the type
     *
     * @param mixed $value
     */
    abstract public function test($value);
}

<?php
namespace GetOptionKit\ValueType;

abstract class BaseType
{
    public function __construct()
    {
        // code...
    }

    /**
     * Test a value to see if it fit the type
     *
     * @param mixed $value
     */
    abstract public function test($value);

    /**
     * Parse a string value into it's type value
     *
     * @param mixed $value
     */
    abstract public function parse($value);
}

Add abstract parse method to basetype

Add abstract parse method to basetype


<?php

namespace ProcessWire\GraphQL\Type\InterfaceType;

use Youshido\GraphQL\Type\InterfaceType\AbstractInterfaceType;
use ProcessWire\GraphQL\Type\Object\TemplatedPageType;

class PageType extends AbstractInterfaceType {

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

  public function getDescription()
  {
    return 'Base ProcessWire Page interface.';
  }

  public function build($config)
  {
    $pageTypeFieldClassNames = [
      'PageChildField',
      'PageChildrenField',
      'PageCreatedField',
      'PageCreatedUserField',
      'PageFindField',
      'PageHttpUrlField',
      'PageIdField',
      'PageModifiedField',
      'PageModifiedUserField',
      'PageNameField',
      'PageNextField',
      'PageNumChildrenField',
      'PageParentField',
      'PageParentIdField',
      'PageParentsField',
      'PagePathField',
      'PagePrevField',
      'PageRootParentField',
      'PageSiblingsField',
      'PageUrlField',
    ];
    foreach ($pageTypeFieldClassNames as $pageTypeFieldClassName) {
      $className = "ProcessWire\\GraphQL\\Field\\Page\\$pageTypeFieldClassName";
      $config->addField(new $className());
    }
  }

  public function resolveType($page)
  {
    return new TemplatedPageType($page->template);
  }

}

<?php

namespace ProcessWire\GraphQL\Type\InterfaceType;

use Youshido\GraphQL\Type\InterfaceType\AbstractInterfaceType;
use ProcessWire\Field;
use ProcessWire\GraphQL\Type\Object\TemplatedPageType;
use ProcessWire\GraphQL\Settings;

class PageType extends AbstractInterfaceType {

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

  public function getDescription()
  {
    return 'Base ProcessWire Page interface.';
  }

  public function build($config)
  {
    $pageTypeFieldClassNames = [
      'PageChildField',
      'PageChildrenField',
      'PageCreatedField',
      'PageCreatedUserField',
      'PageFindField',
      'PageHttpUrlField',
      'PageIdField',
      'PageModifiedField',
      'PageModifiedUserField',
      'PageNameField',
      'PageNextField',
      'PageNumChildrenField',
      'PageParentField',
      'PageParentIdField',
      'PageParentsField',
      'PagePathField',
      'PagePrevField',
      'PageRootParentField',
      'PageSiblingsField',
      'PageUrlField',
    ];
    foreach ($pageTypeFieldClassNames as $pageTypeFieldClassName) {
      $className = "ProcessWire\\GraphQL\\Field\\Page\\$pageTypeFieldClassName";
      $config->addField(new $className());
    }

    // add global fields too
    $legalFields = Settings::getLegalFields();
    foreach ($legalFields as $field) {
      if ($field->flags & Field::flagGlobal) {
        $className = "\\ProcessWire\\GraphQL\\Field\\Page\\Fieldtype\\" . $field->type->className();
        if (!class_exists($className)) continue;
        $config->addField(new $className($field));
      }
    }
  }

  public function resolveType($page)
  {
    return new TemplatedPageType($page->template);
  }

}

Include global fields to PageInterface.

Include global fields to PageInterface.


<?php

Git::$repositories['xmlseclibs'] = [
    'remote' => 'https://github.com/robrichards/xmlseclibs.git',
    'originBranch' => '1.4',
    'workingBranch' => '1.4',
    'trees' => [
        'php-classes/XMLSecEnc.php' => 'src/XMLSecEnc.php',
        'php-classes/XMLSecurityDSig.php' => 'src/XMLSecurityDSig.php',
        'php-classes/XMLSecurityKey.php' => 'src/XMLSecurityKey.php'
    ]
];

<?php

Git::$repositories['xmlseclibs'] = [
    'remote' => 'https://github.com/robrichards/xmlseclibs.git',
    'originBranch' => 'master',
    'workingBranch' => 'master',
    'trees' => [
        'php-classes/RobRichards/XMLSecLibs' => 'src'
    ]
];

Switch to new namespaced master branch of XMLSecLibs


<?php

namespace Zeropingheroes\Lanager\Requests;

class StoreSlideRequest extends Request
{
    use LaravelValidation;

    /**
     * Whether the request is valid
     *
     * @return bool
     */
    public function valid(): bool
    {
        $this->validationRules = [
            'lan_id'             => ['required', 'numeric', 'exists:lans,id'],
            'name'               => ['required', 'max:255'],
            'content'            => ['required'],
            'position'           => ['integer', 'min:0', 'max:127'],
            'duration'           => ['integer', 'min:0', 'max:32767'],
            'start'              => ['required', 'date_format:Y-m-d H:i:s', 'before:end'],
            'end'                => ['required', 'date_format:Y-m-d H:i:s', 'after:start'],
            'published'          => ['boolean'],
        ];

        if (!$this->laravelValidationPasses()) {
            return $this->setValid(false);
        }

        return $this->setValid(true);
    }
}

<?php

namespace Zeropingheroes\Lanager\Requests;

class StoreSlideRequest extends Request
{
    use LaravelValidation;

    /**
     * Whether the request is valid
     *
     * @return bool
     */
    public function valid(): bool
    {
        $this->validationRules = [
            'lan_id'             => ['required', 'numeric', 'exists:lans,id'],
            'name'               => ['required', 'max:255'],
            'content'            => ['required'],
            'position'           => ['integer', 'min:0', 'max:127'],
            'duration'           => ['integer', 'min:0', 'max:32767'],
            'start'              => ['nullable', 'date_format:Y-m-d H:i:s', 'before:end'],
            'end'                => ['nullable', 'date_format:Y-m-d H:i:s', 'after:start'],
            'published'          => ['boolean'],
        ];

        if (!$this->laravelValidationPasses()) {
            return $this->setValid(false);
        }

        return $this->setValid(true);
    }
}

Make slide start and end optional

Make slide start and end optional


<?php
/**
 * /core/app fixtures for mongodb app collection.
 */

namespace Graviton\I18nBundle\DataFixtures\MongoDB;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Graviton\I18nBundle\Document\Language;

/**
 * Load Language data fixtures into mongodb
 *
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://swisscom.ch
 */
class LoadLanguageData implements FixtureInterface
{
    /**
     * {@inheritDoc}
     *
     * @param ObjectManager $manager Object Manager
     *
     * @return void
     */
    public function load(ObjectManager $manager)
    {
        $lang = new Language;
        $lang->setId('en');
        $lang->setName('English');
        $manager->persist($lang);

        $lang = new Language;
        $lang->setId('de');
        $lang->setName('German');
        $manager->persist($lang);

        $lang = new Language;
        $lang->setId('fr');
        $lang->setName('French');
        $manager->persist($lang);

        $manager->flush();
    }
}

<?php
/**
 * /core/app fixtures for mongodb app collection.
 */

namespace Graviton\I18nBundle\DataFixtures\MongoDB;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Graviton\I18nBundle\Document\Language;

/**
 * Load Language data fixtures into mongodb
 *
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://swisscom.ch
 */
class LoadLanguageData implements FixtureInterface
{
    /**
     * {@inheritDoc}
     *
     * @param ObjectManager $manager Object Manager
     *
     * @return void
     */
    public function load(ObjectManager $manager)
    {
        $enTag = new Language;
        $enTag->setId('en');
        $enTag->setName('English');

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

Revert fixtures changes from 27547f7

Revert fixtures changes from 27547f7


Home

@if (Auth::check())

		Minha conta

@else

		Criar conta/Entrar

@endif

	Status

@if (Auth::check())

		Sair

@endif

Home

@if (Auth::check())

		Minha conta

@else

		Criar conta

		Entrar

@endif

	Status

@if (Auth::check())

		Sair

@endif

Split signup/login into different links

Split signup/login into different links


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

require APPPATH.'/libraries/REST_Controller.php';

/**
 * CodeIgniter Parsing Controller
 *
 * url请求参数解析
 *
 * @package     CodeIgniter
 * @subpackage  Core
 * @category    Core
 * @author      Fire
*/
class Parsing_Controller extends REST_Controller
{

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

        $this->load->helper('kakou');

        $this->gets = $this->_getParams();
    }

    /**
     * 获取ulr请求参数
     *
     * @access private
     * @return void
     */
     private function _getParams()
     {
        $query_str = urldecode(str_replace('+','%2B',$_SERVER["QUERY_STRING"]));
        return h_convertUrlQuery($query_str);
     }

 }

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

require APPPATH.'/libraries/REST_Controller.php';

/**
 * CodeIgniter Parsing Controller
 *
 * url请求参数解析
 *
 * @package     CodeIgniter
 * @subpackage  Core
 * @category    Core
 * @author      Fire
*/
class Parsing_Controller extends REST_Controller
{

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

        $this->load->helper('kakou');

        $this->gets = $this->_getParams();
    }

    /**
     * 获取ulr请求参数
     *
     * @access private
     * @return void
     */
     private function _getParams()
     {
        $query_str = urldecode(str_replace('+', '%2B', $_SERVER["QUERY_STRING"]));
        return h_convertUrlQuery($query_str);
     }

 }

Update core my_controller add blank after ','


<?php
/**
 * HiDev plugin for license generation.
 *
 * @link      https://github.com/hiqdev/hidev-license
 * @package   hidev-license
 * @license   BSD-3-Clause
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
 */

return [
    'controllerMap' => [
        'LICENSE' => [
            'class' => \hidev\license\console\LicenseController::class,
        ],
    ],
    'components' => [
        'license' => [
            'class' => \hidev\license\components\License::class,
        ],
        'view' => [
            'theme' => [
                'pathMap' => [
                    '@hidev/views' => ['@hidev/license/views'],
                ],
            ],
        ],
    ],
];

<?php
/**
 * HiDev plugin for license generation.
 *
 * @link      https://github.com/hiqdev/hidev-license
 * @package   hidev-license
 * @license   BSD-3-Clause
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
 */

return [
    'controllerMap' => [
        'LICENSE' => [
            'class' => \hidev\license\console\LicenseController::class,
        ],
    ],
    'components' => [
        'license' => [
            'class' => \hidev\license\components\License::class,
        ],
        'view' => [
            'theme' => [
                'pathMap' => [
                    '@hidev/views' => ['@hidev/license/views'],
                ],
            ],
        ],
    ],
    'aliases' => [
        '@hidev/license' => dirname(__DIR__) . '/src',
    ],
];

Add forced alias in config

Add forced alias in config


<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        //\App\Http\Middleware\VerifyCsrfToken::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    ];
}

<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];
    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],
        'api' => [
            'throttle:60,1',
        ],
    ];
    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

Update file to version laravel 5.2

Update file to version laravel 5.2


<?php

/**
 * Application configuration for the production environment.
 */

$app['db.options'] = include __DIR__ . '/../../db/prod.php';

//$app['debug'] = true;
$app['monolog.level'] = 'WARNING';

Remove trailing line at end of file

Remove trailing line at end of file


<?php
/**
 * Box packing (3D bin packing, knapsack problem).
 *
 * @author Doug Wright
 */
declare(strict_types=1);

namespace DVDoug\BoxPacker;

/**
 * An item to be packed.
 *
 * @author Doug Wright
 */
interface Item
{
    public const ROTATION_NEVER = 1;

    public const ROTATION_KEEP_FLAT = 2;

    public const ROTATION_BEST_FIT = 6;

    /**
     * Item SKU etc.
     */
    public function getDescription(): string;

    /**
     * Item width in mm.
     */
    public function getWidth(): int;

    /**
     * Item length in mm.
     */
    public function getLength(): int;

    /**
     * Item depth in mm.
     */
    public function getDepth(): int;

    /**
     * Item weight in g.
     */
    public function getWeight(): int;

    /**
     * Possible item rotations allowed. One of the ROTATION_* constants.
     */
    public function getAllowedRotations(): int;
}

<?php
/**
 * Box packing (3D bin packing, knapsack problem).
 *
 * @author Doug Wright
 */
declare(strict_types=1);

namespace DVDoug\BoxPacker;

/**
 * An item to be packed.
 *
 * @author Doug Wright
 */
interface Item
{
    /** @var int must be placed in it's defined orientation only */
    public const ROTATION_NEVER = 1;

    /** @var int can be turned sideways 90°, but cannot be placed *on* it's side e.g. fragile "↑this way up" items */
    public const ROTATION_KEEP_FLAT = 2;

    /** @var int no handling restrictions, item can be placed in any orientation */
    public const ROTATION_BEST_FIT = 6;

    /**
     * Item SKU etc.
     */
    public function getDescription(): string;

    /**
     * Item width in mm.
     */
    public function getWidth(): int;

    /**
     * Item length in mm.
     */
    public function getLength(): int;

    /**
     * Item depth in mm.
     */
    public function getDepth(): int;

    /**
     * Item weight in g.
     */
    public function getWeight(): int;

    /**
     * Possible item rotations allowed. One of the ROTATION_* constants.
     */
    public function getAllowedRotations(): int;
}

Add descriptions for the ROTATION_* constants


<?php

class CM_Db_Query_CountTest extends CMTest_TestCase {

	public function testAll() {
		$query = new CM_Db_Query_Count('t`est', array('foo' => 'foo1', 'bar' => 'bar1'));
		$this->assertSame('SELECT COUNT(*) FROM `t``est` WHERE `foo` = ? AND `bar` = ?', $query->getSqlTemplate());
		$this->assertEquals(array('foo1', 'bar1'), $query->getParameters());
	}

	public function testWithoutWhere() {
		$query = new CM_Db_Query_Count('test');
		$this->assertSame('SELECT COUNT(*) FROM `test`', $query->getSqlTemplate());
	}
}

<?php

class CM_Db_Query_CountTest extends CMTest_TestCase {

	public function testAll() {
		$query = new CM_Db_Query_Count('t`est', array('foo' => 'foo1', 'bar' => 'bar1'));
		$this->assertSame('SELECT COUNT(*) FROM `t``est` WHERE `foo` = ? AND `bar` = ?', $query->getSqlTemplate());
		$this->assertEquals(array('foo1', 'bar1'), $query->getParameters());
	}
}

DONE: Drop testWithoutWhere because already tested in CM_Db_Query_AbstractTest


<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;

/**
 * @var ClassLoader $loader
 */
$loader = require __DIR__.'/../vendor/autoload.php';

AnnotationRegistry::registerLoader([$loader, 'loadClass']);

return $loader;

<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;

/**
 * @var ClassLoader $loader
 */
$loader = require __DIR__.'/../vendor/autoload.php';

$loader->addClassMap([
    'Puli\\GeneratedPuliFactory' => __DIR__.'/../.puli/GeneratedPuliFactory.php',
]);

AnnotationRegistry::registerLoader([$loader, 'loadClass']);

return $loader;

Fix temporary problem with GeneratedPuliFactory