<?php

if (!function_exists('curl_init')) {
  throw new Exception('Userbin needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
  throw new Exception('Userbin needs the JSON PHP extension.');
}

require(dirname(__FILE__) . '/Userbin/Userbin.php');
require(dirname(__FILE__) . '/Userbin/Errors.php');
require(dirname(__FILE__) . '/Userbin/SessionToken.php');
require(dirname(__FILE__) . '/Userbin/SessionStore.php');
require(dirname(__FILE__) . '/Userbin/Resource.php');
require(dirname(__FILE__) . '/Userbin/Model.php');
require(dirname(__FILE__) . '/Userbin/Models/Challenge.php');
require(dirname(__FILE__) . '/Userbin/Models/Session.php');
require(dirname(__FILE__) . '/Userbin/Models/User.php');
require(dirname(__FILE__) . '/Userbin/JWT.php');
require(dirname(__FILE__) . '/Userbin/CurlTransport.php');
require(dirname(__FILE__) . '/Userbin/Request.php');

<?php

if (!function_exists('curl_init')) {
  throw new Exception('Userbin needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
  throw new Exception('Userbin needs the JSON PHP extension.');
}

if (!function_exists('lcfirst'))
{
  function lcfirst( $str ) {
    $str[0] = strtolower($str[0]);
    return (string)$str;
  }
}

require(dirname(__FILE__) . '/Userbin/Userbin.php');
require(dirname(__FILE__) . '/Userbin/Errors.php');
require(dirname(__FILE__) . '/Userbin/SessionToken.php');
require(dirname(__FILE__) . '/Userbin/SessionStore.php');
require(dirname(__FILE__) . '/Userbin/Resource.php');
require(dirname(__FILE__) . '/Userbin/Model.php');
require(dirname(__FILE__) . '/Userbin/Models/Challenge.php');
require(dirname(__FILE__) . '/Userbin/Models/Session.php');
require(dirname(__FILE__) . '/Userbin/Models/User.php');
require(dirname(__FILE__) . '/Userbin/JWT.php');
require(dirname(__FILE__) . '/Userbin/CurlTransport.php');
require(dirname(__FILE__) . '/Userbin/Request.php');

Implement lcfirst for PHP < 5.3

Implement lcfirst for PHP < 5.3


<?php

namespace Transport\Entity\Schedule;

use Transport\Entity;

/**
 * Connection
 */
class Connection
{
    public $date;

    /**
     * @var Transport\Entity\Schedule\Stop
     */
    public $from;

    /**
     * @var Transport\Entity\Schedule\Stop
     */
    public $to;

    static public function createFromXml(\SimpleXMLElement $xml, Connection $obj = null)
    {
        if (!$obj) {
            $obj = new Connection();
        }
        $obj->date = date('Y-m-d', strtotime((string) $xml->Overview->Date));
        $obj->from = Entity\Schedule\Stop::createFromXml($xml->Overview->Departure->BasicStop);
        $obj->to = Entity\Schedule\Stop::createFromXml($xml->Overview->Arrival->BasicStop);

        return $obj;
    }
}

<?php

namespace Transport\Entity\Schedule;

use Transport\Entity;

/**
 * Connection
 */
class Connection
{
    public $date;

    /**
     * @var Transport\Entity\Schedule\Stop
     */
    public $from;

    /**
     * @var Transport\Entity\Schedule\Stop
     */
    public $to;

    /**
     * @var array of Transport\Entity\Schedule\Stop 's
     */
    public $sections;

    static public function createFromXml(\SimpleXMLElement $xml, Connection $obj = null)
    {
        if (!$obj) {
            $obj = new Connection();
        }
        $obj->date = date('Y-m-d', strtotime((string) $xml->Overview->Date));
        $obj->from = Entity\Schedule\Stop::createFromXml($xml->Overview->Departure->BasicStop);
        $obj->to = Entity\Schedule\Stop::createFromXml($xml->Overview->Arrival->BasicStop);

        foreach ($xml->ConSectionList->ConSection AS $section) {
            $obj->sections[] = array(
                'departure' => Entity\Schedule\Stop::createFromXml($section->Departure->BasicStop),
                'arrival' => Entity\Schedule\Stop::createFromXml($section->Arrival->BasicStop)
            );
        }

        return $obj;
    }
}

Add sections to connection request

Add sections to connection request


Increase items per blog (archive) page.

Increase items per blog (archive) page.


<?php
namespace OGetIt\HarvestReport;

class OGetIt_HarvestReport {

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

	/**
	 * @var integer
	 */
	private $_metal;

	/**
	 * @var integer
	 */
	private $_crystal;

	/**
	 * @param unknown $coordinates Format; 1:100:10
	 * @param integer $metal
	 * @param integer $crystal
	 */
	public function __construct($coordinates, $metal, $crystal) {

		$this->_coordinates = $coordinates;
		$this->_metal = $metal;
		$this->_crystal = $crystal;

	}

	/**
	 * @return string
	 */
	public function getCoordinates() {

		return $this->_coordinates;

	}

	/**
	 * @return integer
	 */
	public function getMetal() {

		return $this->_metal;

	}

	/**
	 * @return integer
	 */
	public function getCrystal() {

		return $this->_crystal;

	}

}

<?php
namespace OGetIt\HarvestReport;

use OGetIt\Common\OGetIt_Resources;
class OGetIt_HarvestReport {

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

	/**
	 * @var OGetIt_Resources
	 */
	private $_resources;

	/**
	 * @param unknown $coordinates Format; 1:100:10
	 * @param integer $metal
	 * @param integer $crystal
	 */
	public function __construct($coordinates, $metal, $crystal) {

		$this->_coordinates = $coordinates;
		$this->_resources = new OGetIt_Resources($metal, $crystal, 0);

	}

	/**
	 * @return string
	 */
	public function getCoordinates() {

		return $this->_coordinates;

	}

	/**
	 * @return integer
	 */
	public function getMetal() {

		return $this->_resources->getMetal();

	}

	/**
	 * @return integer
	 */
	public function getCrystal() {

		return $this->_resources->getCrystal();

	}

	/**
	 * @return OGetIt_Resources
	 */
	public function getResources() {

		return $this->_resources;

	}

}

Use resources for harvest reports

Use resources for harvest reports


<?php
namespace Bolt\Tests\Storage;

use Bolt\Legacy\Storage;
use Bolt\Tests\BoltUnitTest;

/**
 * Class to test src/Storage/Repository and field transforms for load and hydrate
 *
 * @author Ross Riley <riley.ross@gmail.com>
 */
class FieldSetTest extends BoltUnitTest
{
    public function testSetWithNormalValues()
    {
        $app = $this->getApp();
        $this->addSomeContent($app);
        $em = $app['storage'];
        $repo = $em->getRepository('showcases');
        $entity = $repo->create(['title' => 'This is a title']);
        $this->assertEquals('This is a title', $entity->getTitle());
    }

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

        $em = $app['storage'];
        $repo = $em->getRepository('pages');
        $entity = $repo->find(1);
        $entity->setTemplate('extrafields.twig');
        $entity->setTemplateFields([
            'section_1' => 'val1',
            'image'     => ['file' => 'path-to-image.jpg', 'title' => 'An awesome image']
        ]);
        $repo->save($entity);

        $entity2 = $repo->find(1);
        $this->assertEquals('An awesome image', $entity2->templatefields->image['title']);
    }
}

<?php
namespace Bolt\Tests\Storage;

use Bolt\Legacy\Storage;
use Bolt\Tests\BoltUnitTest;

/**
 * Class to test src/Storage/Repository and field transforms for load and hydrate
 *
 * @author Ross Riley <riley.ross@gmail.com>
 */
class FieldSetTest extends BoltUnitTest
{
    public function testSetWithNormalValues()
    {
        $app = $this->getApp();
        $this->addSomeContent($app);
        $em = $app['storage'];
        $repo = $em->getRepository('showcases');
        $entity = $repo->create(['title' => 'This is a title']);
        $this->assertEquals('This is a title', $entity->getTitle());
    }

    public function testSetWithUpdatedValues()
    {
        $this->markTestIncomplete('Test dying with: Invalid argument supplied for foreach()');

        $app = $this->getApp();

        $em = $app['storage'];
        $repo = $em->getRepository('pages');
        $entity = $repo->find(1);
        $entity->setTemplate('extrafields.twig');
        $entity->setTemplateFields([
            'section_1' => 'val1',
            'image'     => ['file' => 'path-to-image.jpg', 'title' => 'An awesome image']
        ]);
        $repo->save($entity);

        $entity2 = $repo->find(1);
        $this->assertEquals('An awesome image', $entity2->templatefields->image['title']);
    }
}

Disable template field test for now

[Tests] Disable template field test for now


<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\Downloader;

use Composer\Package\PackageInterface;

/**
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class ZipDownloader extends FileDownloader
{
    protected function extract($file, $path)
    {
        if (!class_exists('ZipArchive')) {
            throw new \UnexpectedValueException('You need the zip extension enabled to use the ZipDownloader');
        }

        $zipArchive = new \ZipArchive();

        if (true !== ($retval = $zipArchive->open($file))) {
            throw new \UnexpectedValueException($file.' is not a valid zip archive, got error code '.$retval);
        }

        $zipArchive->extractTo($path);
        $zipArchive->close();
    }
}

<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\Downloader;

use Composer\Package\PackageInterface;

/**
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class ZipDownloader extends FileDownloader
{
    protected function extract($file, $path)
    {
        if (!class_exists('ZipArchive')) {
            throw new \RuntimeException('You need the zip extension enabled to use the ZipDownloader');
        }

        $zipArchive = new \ZipArchive();

        if (true !== ($retval = $zipArchive->open($file))) {
            throw new \UnexpectedValueException($file.' is not a valid zip archive, got error code '.$retval);
        }

        $zipArchive->extractTo($path);
        $zipArchive->close();
    }
}

Use `RuntimeException` instead of `UnexpectedValueException` when zip extension is not enabled


<?php

namespace TomIrons\Tuxedo\Mailables;

use TomIrons\Tuxedo\Message;
use TomIrons\Tuxedo\TuxedoMailable;

class InvoiceMailable extends TuxedoMailable
{
    use Message;

    /**
     * The view to use for the message.
     *
     * @var string
     */
    public $view = 'tuxedo::templates.invoice';

    public $items = [];

    public function item($name, $price)
    {
        $this->items[] = [
            'name' => $name,
            'price' => $price
        ];

        return $this;
    }
}

<?php

namespace TomIrons\Tuxedo\Mailables;

use TomIrons\Tuxedo\Message;
use TomIrons\Tuxedo\TuxedoMailable;

class InvoiceMailable extends TuxedoMailable
{
    use Message;

    /**
     * The view to use for the message.
     *
     * @var string
     */
    public $view = 'tuxedo::templates.invoice';

    /**
     * The user's name
     *
     * @var string|null
     */
    public $name = null;

    /**
     * The invoice Number
     *
     * @var string|null
     */
    public $invoiceNumber = null;

    /**
     * The invoice date
     *
     * @var string|null
     */
    public $date = null;

    /**
     * The invoice total
     *
     * @var string|null
     */
    public $total = null;

    /**
     * The items that are on the invoice
     *
     * @var array
     */
    public $items = [];

    /**
     * Add an item to the invoice
     *
     * @param string $name
     * @param string|integer $price
     * @return $this
     */
    public function item($name, $price)
    {
        $this->items[] = [
            'name' => $name,
            'price' => $price
        ];

        $this->total += $price;

        return $this;
    }

    /**
     * Set the information for the invoice
     *
     * @param string $name
     * @param string|integer $number
     * @param string $date
     * @return $this
     */
    public function information($name, $number, $date)
    {
        $this->name = $name;
        $this->invoiceNumber = $number;
        $this->date = $date;

        return $this;
    }
}

Add more properties and doc blocks

Add more properties and doc blocks


<?php

namespace AbleCore\Fields\FieldHandlerTypes;

use AbleCore\Fields\FieldValueHandler;
use AbleCore\Fields\FieldValueTypes\EntityReferenceFieldValue;

class EntityReference extends FieldValueHandler
{
	public static $configuration = array(
		'entityreference' => 'reference',
		'node_reference' => 'nodeReference',
		'field_collection' => 'fieldCollection',
	);

	public static function reference($type, $value, $name)
	{
		if (!self::checkFieldValue($value, 'target_id'))
			return null;

		$info = field_info_field($name);

		if (!isset($info['settings']['target_type'])) {
			trigger_error('Target type couldnt be found.', E_USER_WARNING);
			return null;
		}
		$target_type = $info['settings']['target_type'];

		return new EntityReferenceFieldValue($type, $value, $target_type);
	}

	public static function nodeReference($type, $value, $name)
	{
		if (!self::checkFieldValue($value, 'nid'))
			return null;

		return new EntityReferenceFieldValue($type, $value, 'node', 'nid');
	}

	public static function fieldCollection($type, $value, $name)
	{
		if (!self::checkFieldValue($value, 'value'))
			return null;

		return new EntityReferenceFieldValue($type, $value, 'field_collection_item', 'value', 'revision_id');
	}
}

<?php

namespace AbleCore\Fields\FieldHandlerTypes;

use AbleCore\Fields\FieldValueHandler;
use AbleCore\Fields\FieldValueTypes\EntityReferenceFieldValue;

class EntityReference extends FieldValueHandler
{
	public static $configuration = array(
		'entityreference' => 'reference',
		'node_reference' => 'nodeReference',
		'field_collection' => 'fieldCollection',
	);

	public static function reference($type, $value, $name)
	{
		if (!self::checkFieldValue($value, 'target_id'))
			return null;

		$info = field_info_field($name);

		if (!isset($info['settings']['target_type'])) {
			trigger_error('Target type couldnt be found.', E_USER_WARNING);
			return null;
		}
		$target_type = $info['settings']['target_type'];

		return new EntityReferenceFieldValue($type, $value, $target_type);
	}

	public static function nodeReference($type, $value, $name)
	{
		if (!self::checkFieldValue($value, 'nid'))
			return null;

		return new EntityReferenceFieldValue($type, $value, 'node', 'nid');
	}

	public static function fieldCollection($type, $value, $name)
	{
		if (!self::checkFieldValue($value, 'value'))
			return null;

		// TODO: Enable revision support for this when https://www.drupal.org/node/2075325 is fixed.
		return new EntityReferenceFieldValue($type, $value, 'field_collection_item', 'value');
	}
}

Disable revision support for field collection items temporarily.


<?php

namespace Neuron\Net;

use Neuron\Config;

/**
 * Class QueryTrackingParameters
 * @package Neuron\Net
 */
class QueryTrackingParameters
{
	/**
	 * @return QueryTrackingParameters
	 */
	public static function instance()
	{
		static $in;
		if (!isset($in)) {
			$in = new self();

			// Can we set these from config?
            if (Config::get('tracking.queryParameters')) {
                $in->queryParameters = Config::get('tracking.queryParameters');
            }
		}
		return $in;
	}

	public $queryParameters = [
		'utm_abversion',
		'utm_referrer',
		'utm_source',
		'utm_medium',
		'utm_campaign',
		'utm_term',
		'utm_content',
		'_ga',
		'_gac',
		'pk_vid',
        '_gl'
	];
}

<?php

namespace Neuron\Net;

use Neuron\Config;

/**
 * Class QueryTrackingParameters
 * @package Neuron\Net
 */
class QueryTrackingParameters
{
	/**
	 * @return QueryTrackingParameters
	 */
	public static function instance()
	{
		static $in;
		if (!isset($in)) {
			$in = new self();

			// Can we set these from config?
            if (Config::get('tracking.queryParameters')) {
                $in->queryParameters = Config::get('tracking.queryParameters');
            }
		}
		return $in;
	}

	public $queryParameters = [
		'utm_abversion',
		'utm_referrer',
		'utm_source',
		'utm_medium',
		'utm_campaign',
		'utm_term',
		'utm_content',
		'_ga',
		'_gac',
		'pk_vid',
        '_gl',
		'_cc'
	];
}

Add _cc parameter to tracking codes.

Add _cc parameter to tracking codes.


<?php

namespace Omnipay\Gate2shop;

use Omnipay\Common\AbstractGateway;
use Omnipay\Gate2shop\Message\PurchaseRequest;
use Omnipay\Gate2shop\Message\CompletePurchaseRequest;

/**
 * Gate2shop Gateway
 *
 * @link
 */
class Gateway extends AbstractGateway
{
    public function getName()
    {
        return 'Gate2shop';
    }

    public function getDefaultParameters()
    {
        return array(
            'merchantSiteId' => '',
            'merchantId'     => '',
            'secretKey'      => ''
        );
    }

    public function getMerchantSiteId()
    {
        return $this->getParameter('merchantSiteId');
    }

    public function setMerchantSiteId($value)
    {
        return $this->setParameter('merchantSiteId', $value);
    }

    public function getMerchantId()
    {
        return $this->getParameter('merchantId');
    }

    public function setMerchantId($value)
    {
        return $this->setParameter('merchantId', $value);
    }

    public function getSecretKey()
    {
        return $this->getParameter('secretKey');
    }

    public function setSecretKey($value)
    {
        return $this->setParameter('secretKey', $value);
    }

    public function purchase(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\Gate2shop\Message\PurchaseRequest', $parameters);
    }

    public function completePurchase(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\Gate2shop\Message\CompletePurchaseRequest', $parameters);
    }
}

<?php

namespace Omnipay\Gate2shop;

use Omnipay\Common\AbstractGateway;
use Omnipay\Gate2shop\Message\PurchaseRequest;

/**
 * Gate2shop Gateway
 *
 * @link
 */
class Gateway extends AbstractGateway
{
    public function getName()
    {
        return 'Gate2shop';
    }

    public function getDefaultParameters()
    {
        return array(
            'merchantSiteId' => '',
            'merchantId'     => '',
            'secretKey'      => '',
            'customSiteName' => ''
        );
    }

    public function getMerchantSiteId()
    {
        return $this->getParameter('merchantSiteId');
    }

    public function setMerchantSiteId($value)
    {
        return $this->setParameter('merchantSiteId', $value);
    }

    public function getMerchantId()
    {
        return $this->getParameter('merchantId');
    }

    public function setMerchantId($value)
    {
        return $this->setParameter('merchantId', $value);
    }

    public function getSecretKey()
    {
        return $this->getParameter('secretKey');
    }

    public function setSecretKey($value)
    {
        return $this->setParameter('secretKey', $value);
    }

    public function getCustomSiteName()
    {
        return $this->getParameter('customSiteName');
    }

    public function setCustomSiteName($value)
    {
        return $this->setParameter('customSiteName', $value);
    }

    public function purchase(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\Gate2shop\Message\PurchaseRequest', $parameters);
    }
}

Support gateway initialisation of the custom site name. Also remove references to the unused (and unnecessary?) CompletePurchaseRequest.


<?php

/**
 * Overseer modules allow daemons to be externally influenced.
 *
 * See @{class:PhabricatorDaemonOverseerModule} for a concrete example.
 */
abstract class PhutilDaemonOverseerModule extends Phobject {

  /**
   * This method is used to indicate to the overseer that daemons should reload.
   *
   * @return bool  True if the daemons should reload, otherwise false.
   */
  abstract public function shouldReloadDaemons();

  /**
   * Should a hibernating daemon pool be awoken immediately?
   *
   * @return bool True to awaken the pool immediately.
   */
  public function shouldWakePool(PhutilDaemonPool $pool) {
    return false;
  }

  public static function getAllModules() {
    return id(new PhutilClassMapQuery())
      ->setAncestorClass(__CLASS__)
      ->execute();
  }

}

<?php

/**
 * Overseer modules allow daemons to be externally influenced.
 *
 * See @{class:PhabricatorDaemonOverseerModule} for a concrete example.
 */
abstract class PhutilDaemonOverseerModule extends Phobject {

  private $throttles = array();

  /**
   * This method is used to indicate to the overseer that daemons should reload.
   *
   * @return bool  True if the daemons should reload, otherwise false.
   */
  public function shouldReloadDaemons() {
    return false;
  }

  /**
   * Should a hibernating daemon pool be awoken immediately?
   *
   * @return bool True to awaken the pool immediately.
   */
  public function shouldWakePool(PhutilDaemonPool $pool) {
    return false;
  }

  public static function getAllModules() {
    return id(new PhutilClassMapQuery())
      ->setAncestorClass(__CLASS__)
      ->execute();
  }

  /**
   * Throttle checks from executing too often.
   *
   * If you throttle a check like this, it will only execute once every 2.5
   * seconds:
   *
   *   if ($this->shouldThrottle('some.check', 2.5)) {
   *     return;
   *   }
   *
   * @param string Throttle key.
   * @param float Duration in seconds.
   * @return bool True to throttle the check.
   */
  protected function shouldThrottle($name, $duration) {
    $throttle = idx($this->throttles, $name, 0);
    $now = microtime(true);

    // If not enough time has elapsed, throttle the check.
    $elapsed = ($now - $throttle);
    if ($elapsed < $duration) {
      return true;
    }

    // Otherwise, mark the current time as the last time we ran the check,
    // then let it continue.
    $this->throttles[$name] = $now;

    return false;
  }

}

Clean up overseer modules slightly and provide a throttling support method

Summary:
Ref T12298. Make it slightly easier to write overseer modules:

  - You don't need to implement shouldReloadDaemons(), since you can now just implement shouldWakePool() and get useful behavior.
  - It looks like most modules want to do checks only every X seconds, where X is at least somewhat module/use-case dependent, so add a helper for that.

Test Plan: Ran `bin/phd debug pull --trace`, saw config check fire properly every 10 seconds after updating it to use `shouldThrottle()` in the next change.

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T12298

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


<?php

//echo "RUNNING (". __FILE__ .")!!!!\n";

// set the timezone to avoid spurious errors from PHP
date_default_timezone_set("America/Chicago");

if(file_exists(__DIR__ .'/../vendor/autoload.php')) {
	require_once(__DIR__ .'/../vendor/autoload.php');
}
else {
	trigger_error("vendor autoloader not found, unit tests will probably fail -- try running 'composer update'");
}

define('UNITTEST__LOCKFILE', __DIR__ .'/files/rw');

<?php

//echo "RUNNING (". __FILE__ .")!!!!\n";

// set the timezone to avoid spurious errors from PHP
date_default_timezone_set("America/Chicago");

if(file_exists(__DIR__ .'/../vendor/autoload.php')) {
	require_once(__DIR__ .'/../vendor/autoload.php');
}
else {
	trigger_error("vendor autoloader not found, unit tests will probably fail -- try running 'composer update'");
}

if (!defined('PASSWORD_DEFAULT')) {
    define('PASSWORD_BCRYPT', 1);
    define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
}

define('UNITTEST__LOCKFILE', __DIR__ .'/files/rw');

Fix (?) PASSWORD_DEFAULT for PHP < 5.5

Fix (?) PASSWORD_DEFAULT for PHP < 5.5


<?php

class CRM_Logviewer_Page_LogViewer extends CRM_Core_Page {

  public function run() {
    $this->assign('currentTime', date('Y-m-d H:i:s'));
    $file_log = CRM_Core_Error::createDebugLogger();
    $logFileName = $file_log->_filename;
    $file_log->close();
    $this->assign('fileName', $logFileName);
    $entries = array();

    if ($handle = @fopen($logFileName,'r')) {
      $line = 0;
      while (!feof($handle)) {
        $line++;
        $dd = fgets($handle);
        if (strlen($dd) >= 15 && (' ' != $dd[0])) {
          $date = substr($dd,0,15);
          if (preg_match("/^[A-Za-z]{3} [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/",$date)) {
            $entry_url = CRM_Utils_System::url('civicrm/admin/logviewer/logentry', $query = 'lineNumber='.$line);
            $entries[$line] = array('lineNumber' => ''.$line.'', 'dateTime' => $date, 'message' => substr($dd,16));
          }
        }
      }
      fclose($handle);
      krsort($entries);
      $this->assign('logEntries', $entries);
    }
    parent::run();
  }

}

<?php

class CRM_Logviewer_Page_LogViewer extends CRM_Core_Page {

  public function run() {
    $this->assign('currentTime', date('Y-m-d H:i:s'));
    $file_log = CRM_Core_Error::createDebugLogger();
    $logFileName = $file_log->_filename;
    $file_log->close();
    $this->assign('fileName', $logFileName);
    $entries = array();

    if ($handle = @fopen($logFileName,'r')) {
      $line = 0;
      while (!feof($handle)) {
        $line++;
        $dd = fgets($handle);
        if (strlen($dd) >= 15 && (' ' != $dd[0])) {
          // Also support localized dates such as: "fév 14 12:51:13"
          $date = mb_substr($dd,0,15);
          if (preg_match("/^\w{3} [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/u",$date)) {
            $entry_url = CRM_Utils_System::url('civicrm/admin/logviewer/logentry', $query = 'lineNumber='.$line);
            $entries[$line] = array('lineNumber' => ''.$line.'', 'dateTime' => $date, 'message' => substr($dd,16));
          }
        }
      }
      fclose($handle);
      krsort($entries);
      $this->assign('logEntries', $entries);
    }
    parent::run();
  }

}

Fix for localized dates (month names with unicode)


<?php

class IncrementingTest extends RememberTestCase
{
    public function testIncrementingModelsPopsCache()
    {
        $group = Group::create(['id' => static::ID, 'name' => 'counter test', 'counter' => 0]);

        $cached = Group::find(static::ID);

        $group->increment('counter');

        $new = Group::find(static::ID);

        $this->assertNotEquals($cached, $new);

        $this->assertEquals(1, $group->counter);
        $this->assertEquals(1, $new->counter);
    }

    public function testDecrementingModelsPopsCache()
    {
        $group = Group::create(['id' => static::ID, 'name' => 'counter test', 'counter' => 0]);

        $cached = Group::find(static::ID);

        $group->decrement('counter');

        $new = Group::find(static::ID);

        $this->assertNotEquals($cached, $new);

        $this->assertEquals(-1, $group->counter);
        $this->assertEquals(-1, $new->counter);
    }
}

<?php

class IncrementingTest extends RememberTestCase
{
    public function testIncrementingModelsPopsCache()
    {
        $group = Group::create(['id' => static::ID, 'name' => 'counter test', 'counter' => 0]);

        $cached = Group::find(static::ID);

        $group->increment('counter');

        $new = Group::find(static::ID);

        $this->assertNotEquals($cached, $new);

        $this->assertEquals(1, $group->counter);
        $this->assertEquals(1, $new->counter);

        static::$sql = false;

        // check we've properly cached here.
        Group::find(static::ID);
    }

    public function testDecrementingModelsPopsCache()
    {
        $group = Group::create(['id' => static::ID, 'name' => 'counter test', 'counter' => 0]);

        $cached = Group::find(static::ID);

        $group->decrement('counter');

        $new = Group::find(static::ID);

        $this->assertNotEquals($cached, $new);

        $this->assertEquals(-1, $group->counter);
        $this->assertEquals(-1, $new->counter);

        static::$sql = false;

        // check we've properly cached here.
        Group::find(static::ID);
    }
}

Make incrementing tests check the cache was actually used, too


<?php
require 'config.php';

$input = file_get_contents('php://input');
$json = json_decode($input, true);

if(isset($json['accessToken']) && isset($json['clientToken'])) {
	$mysql = new mysqli($CONFIG['host'], $CONFIG['user'], $CONFIG['pass'], $CONFIG['database']);
	$result = $mysql->query('SELECT * FROM ' . $CONFIG['table'] . ' WHERE accesstoken="' . $mysql->real_escape_string($json['accessToken']) . '" AND clientoken="' . $mysql->real_escape_string($json['clientToken']) . '"');
	if($result->num_rows === 1) {
		echo json_encode();
	}
	else if($CONFIG['onlineauth']) {
		echo file_get_contents('https://authserver.mojang.com/validate', false, stream_context_create(array(
			'http' => array(
				'method' => 'POST',
				'header' => 'Content-Type: application/json',
				'content' => $input
			)
		)));
	}
	else {
		echo json_encode(array(
			'error' => 'ForbiddenOperationException',
			'errorMessage' => 'Invalid token.'
		));
	}

	$result->close();
	$mysql->close();
}
else {
	echo $CONFIG['message'];
}
?>

<?php
require 'config.php';

$input = file_get_contents('php://input');
$json = json_decode($input, true);

if(isset($json['accessToken'])) {
	$mysql = new mysqli($CONFIG['host'], $CONFIG['user'], $CONFIG['pass'], $CONFIG['database']);
	$result = $mysql->query('SELECT * FROM ' . $CONFIG['table'] . ' WHERE accesstoken="' . $mysql->real_escape_string($json['accessToken']) . '"');
	if($result->num_rows === 1) {
		echo json_encode();
	}
	else if($CONFIG['onlineauth']) {
		echo file_get_contents('https://authserver.mojang.com/validate', false, stream_context_create(array(
			'http' => array(
				'method' => 'POST',
				'header' => 'Content-Type: application/json',
				'content' => $input
			)
		)));
	}
	else {
		echo json_encode(array(
			'error' => 'ForbiddenOperationException',
			'errorMessage' => 'Invalid token.'
		));
	}

	$result->close();
	$mysql->close();
}
else {
	echo $CONFIG['message'];
}
?>

Validate does not need clientToken

Validate does not need clientToken


@extends('layout.master')

@section('description', trans('cachet.meta.description.subscribe', ['app' => $site_title]))

@section('content')

@include('dashboard.partials.errors')

{{ trans('cachet.subscriber.subscribe') }}

                <form action="{{ cachet_route('subscribe', [], 'post') }}" method="POST" class="form">
                    <input type="hidden" name="_token" value="{{ csrf_token() }}">

                        <input class="form-control" type="email" name="email" placeholder="email@example.com">

                    <button type="submit" class="btn btn-success">{{ trans('cachet.subscriber.button') }}</button>
                </form>

@stop

@extends('layout.master')

@section('title',  trans('cachet.subscriber.subscribe'). " | ". $site_title))

@section('description', trans('cachet.meta.description.subscribe', ['app' => $site_title]))

@section('content')

@include('dashboard.partials.errors')

{{ trans('cachet.subscriber.subscribe') }}

                <form action="{{ cachet_route('subscribe', [], 'post') }}" method="POST" class="form">
                    <input type="hidden" name="_token" value="{{ csrf_token() }}">

                        <input class="form-control" type="email" name="email" placeholder="email@example.com">

                    <button type="submit" class="btn btn-success">{{ trans('cachet.subscriber.button') }}</button>
                </form>

@stop

Configure a title for the subscribe page


<?php
namespace Repositories;

class ItemCache extends Item
{
  const CACHE_KEY = "itemSearch";
  public function where($text)
  {
    $text = str_replace("_", " ", $text);
    $key = self::CACHE_KEY.":".str_replace(" ", "_", $text);
    $expiration = \Config::get("cataclysm.searchCacheExpiration");
    $items = \Cache::remember($key, $expiration, function () use ($text) {
      return array_map(function ($item) {
        return $item->id;
      }, parent::where($text));
      return $result;
    });

    return array_map(function ($item) {
      return $this->find($item);
    }, $items);

  }
}

<?php
namespace Repositories;

class ItemCache extends Item
{
  const CACHE_KEY = "itemSearch";
  public function where($text)
  {
    $text = str_replace("_", " ", $text);
    $key = self::CACHE_KEY.":".str_replace(" ", "_", $text);
    $expiration = \Config::get("cataclysm.searchCacheExpiration");
    $items = \Cache::remember($key, $expiration, function () use ($text) {
      $items = parent::where($text);
      array_walk($items, function (&$item) {
        $item = $item->id;
      });
      return $items;
    });

    array_walk($items, function (&$item) {
      $item = $this->find($item);
    });
    return $items;

  }
}

Use array_walk instead of array_map it's faster, as it avoids copying the arrays.


<?php

/*
 * This file is part of SwiftMailer.
 * (c) 2011 Fabien Potencier
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Stores all sent emails for further usage.
 *
 * @author Fabien Potencier
 */
class Swift_Plugins_MessageLogger implements Swift_Events_SendListener
{
    /**
     * @var array
     */
    private $messages;

    public function __construct()
    {
        $this->messages = array();
    }

    /**
     * Get the message list.
     *
     * @return array
     */
    public function getMessages()
    {
        return $this->messages;
    }

    /**
     * Get the message count.
     *
     * @return int count
     */
    public function countMessages()
    {
        return count($this->messages);
    }

    /**
     * Empty the message list.
     */
    public function clear()
    {
        $this->messages = array();
    }

    /**
     * Invoked immediately before the Message is sent.
     *
     * @param Swift_Events_SendEvent $evt
     */
    public function beforeSendPerformed(Swift_Events_SendEvent $evt)
    {
        $this->messages[] = clone $evt->getMessage();
    }

    /**
     * Invoked immediately after the Message is sent.
     *
     * @param Swift_Events_SendEvent $evt
     */
    public function sendPerformed(Swift_Events_SendEvent $evt)
    {
    }
}

<?php

/*
 * This file is part of SwiftMailer.
 * (c) 2011 Fabien Potencier
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Stores all sent emails for further usage.
 *
 * @author Fabien Potencier
 */
class Swift_Plugins_MessageLogger implements Swift_Events_SendListener
{
    /**
     * @var Swift_Mime_Message[]
     */
    private $messages;

    public function __construct()
    {
        $this->messages = array();
    }

    /**
     * Get the message list.
     *
     * @return Swift_Mime_Message[]
     */
    public function getMessages()
    {
        return $this->messages;
    }

    /**
     * Get the message count.
     *
     * @return int count
     */
    public function countMessages()
    {
        return count($this->messages);
    }

    /**
     * Empty the message list.
     */
    public function clear()
    {
        $this->messages = array();
    }

    /**
     * Invoked immediately before the Message is sent.
     *
     * @param Swift_Events_SendEvent $evt
     */
    public function beforeSendPerformed(Swift_Events_SendEvent $evt)
    {
        $this->messages[] = clone $evt->getMessage();
    }

    /**
     * Invoked immediately after the Message is sent.
     *
     * @param Swift_Events_SendEvent $evt
     */
    public function sendPerformed(Swift_Events_SendEvent $evt)
    {
    }
}

Fix phpdoc return tag in logger pluggin

Fix phpdoc return tag in logger pluggin


<?php
declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
$whitelistClasses = [
    'PHPUnit\*',
    'SebastianBergmann\CodeCoverage\*',
    'PharIo\*',
    'PHP_Token*',
];

return [
    'whitelist' => $whitelistClasses,
];

<?php
declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
$whitelistClasses = [
    'PHPUnit\*',
    'SebastianBergmann\CodeCoverage\*',
    'PharIo\*',
    'PHP_Token*',
    'Prophecy\*',
];

return [
    'whitelist' => $whitelistClasses,
];

Add 'Prophecy' namespace to the scoping whitelist

In oder to setup or check test doubles with Prophecy it has to be
part of the public API of PHPUnit, even it not provided by PHPUnit
itself.

Issues:
- #3578 - Scoped PHAR Prophecy issue


<?php
// vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker:
// +-------------------------------------------------------------------------+
// | Author: Armen Baghumian <armen@OpenSourceClub.org>                      |
// +-------------------------------------------------------------------------+
// | Smarty {arag_load_script} function plugin                               |
// |                                                                         |
// | Type:    function                                                       |
// | Name:    arag_load_script                                               |
// | Purpose: load a scrip                                                   |
// +-------------------------------------------------------------------------+
// $Id$
// ---------------------------------------------------------------------------

static $_loaded = Array();

function smarty_function_arag_load_script($params, &$smarty)
{
    if (is_array($params) && count($params)) {
        foreach ($params as $_key => $_val) {
            switch ($_key) {
                case 'src':
                    $$_key = (string)$_val;
                    break;

                default:
                    $smarty->trigger_error("arag_function_arag_load_script: Unknown attribute '$_key'");
            }
        }
    }

    if (!isset($src)) {
        $smarty->trigger_error("arag_function_arag_load_script: You have to set 'src' attribute.");
    }

    global $_loaded;

    if (!isset($_loaded[sha1($src)])) {
        $_loaded[sha1($src)] = True;
        return html::script($src);
    }

    return Null;
}

<?php
// vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker:
// +-------------------------------------------------------------------------+
// | Author: Armen Baghumian <armen@OpenSourceClub.org>                      |
// +-------------------------------------------------------------------------+
// | Smarty {arag_load_script} function plugin                               |
// |                                                                         |
// | Type:    function                                                       |
// | Name:    arag_load_script                                               |
// | Purpose: load a scrip                                                   |
// +-------------------------------------------------------------------------+
// $Id$
// ---------------------------------------------------------------------------

static $_loaded = Array();

function smarty_function_arag_load_script($params, &$smarty)
{
    if (is_array($params) && count($params)) {
        foreach ($params as $_key => $_val) {
            switch ($_key) {
                case 'src':
                    $$_key = (string)$_val;
                    break;

                default:
                    $smarty->trigger_error("arag_function_arag_load_script: Unknown attribute '$_key'");
            }
        }
    }

    if (!isset($src)) {
        $smarty->trigger_error("arag_function_arag_load_script: You have to set 'src' attribute.");
    }

    global $_loaded;

    if (!isset($_loaded[sha1($src)])) {
        $_loaded[sha1($src)]  = True;
        $GLOBALS['headers'][] = html::script($src);
    }

    return Null;
}

Load script will put scripts in header

Load script will put scripts in header


<?php

namespace TCG\Voyager\Tests;

use TCG\Voyager\Models\Page;
use Illuminate\Support\Facades\Auth;

class PageTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->install();
    }

    /** @test */
    public function can_create_a_page_with_logged_in_user_auto_assigned()
    {
    	// Arrange
    	$user = Auth::loginUsingId(1);

    	$page = new Page;

    	$page->fill([
    		'slug' => 'test-slug',
    		'title' => 'Test Title',
    		'excerpt' => 'Test Excerpt',
    		'body' => 'Test Body',
    		'meta_description' => 'Test Description',
    		'meta_keywords' => 'Test Meta Keywords',
		]);

    	// Act
    	$page->save();

    	// Assert
    	$this->assertEquals(1, $page->author_id);
    	$this->assertEquals('test-slug', $page->slug);
    	$this->assertEquals('Test Title', $page->title);
    	$this->assertEquals('Test Excerpt', $page->excerpt);
    	$this->assertEquals('Test Body', $page->body);
    	$this->assertEquals('Test Description', $page->meta_description);
    	$this->assertEquals('Test Meta Keywords', $page->meta_keywords);

    }
}

<?php

namespace TCG\Voyager\Tests;

use Illuminate\Support\Facades\Auth;
use TCG\Voyager\Models\Page;

class PageTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->install();
    }

    /** @test */
    public function can_create_a_page_with_logged_in_user_auto_assigned()
    {
        // Arrange
        $user = Auth::loginUsingId(1);

        $page = new Page();

        $page->fill([
            'slug'             => 'test-slug',
            'title'            => 'Test Title',
            'excerpt'          => 'Test Excerpt',
            'body'             => 'Test Body',
            'meta_description' => 'Test Description',
            'meta_keywords'    => 'Test Meta Keywords',
        ]);

        // Act
        $page->save();

        // Assert
        $this->assertEquals(1, $page->author_id);
        $this->assertEquals('test-slug', $page->slug);
        $this->assertEquals('Test Title', $page->title);
        $this->assertEquals('Test Excerpt', $page->excerpt);
        $this->assertEquals('Test Body', $page->body);
        $this->assertEquals('Test Description', $page->meta_description);
        $this->assertEquals('Test Meta Keywords', $page->meta_keywords);
    }
}

Apply Style CI Path for Changes.

Apply Style CI Path for Changes.


<?php
/**
 * Copyright (c) 2014 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace OCA\Files_Sharing\External;

class Scanner extends \OC\Files\Cache\Scanner {
	/**
	 * @var \OCA\Files_Sharing\External\Storage
	 */
	protected $storage;

	public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1) {
		$this->scanAll();
	}

	public function scanAll() {
		$data = $this->storage->getShareInfo();
		if ($data['status'] === 'success') {
			$this->addResult($data['data'], '');
		} else {
			throw new \Exception('Error while scanning remote share');
		}
	}

	private function addResult($data, $path) {
		$this->cache->put($path, $data);
		if (isset($data['children'])) {
			foreach ($data['children'] as $child) {
				$this->addResult($child, ltrim($path . '/' . $child['name'], '/'));
			}
		}
	}
}

<?php
/**
 * Copyright (c) 2014 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace OCA\Files_Sharing\External;

class Scanner extends \OC\Files\Cache\Scanner {
	/**
	 * @var \OCA\Files_Sharing\External\Storage
	 */
	protected $storage;

	public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1) {
		$this->scanAll();
	}

	public function scanAll() {
		$data = $this->storage->getShareInfo();
		if ($data['status'] === 'success') {
			$this->addResult($data['data'], '');
		} else {
			throw new \Exception('Error while scanning remote share');
		}
	}

	private function addResult($data, $path) {
		$id = $this->cache->put($path, $data);
		if (isset($data['children'])) {
			$children = array();
			foreach ($data['children'] as $child) {
				$children[$child['name']] = true;
				$this->addResult($child, ltrim($path . '/' . $child['name'], '/'));
			}

			$existingCache = $this->cache->getFolderContentsById($id);
			foreach ($existingCache as $existingChild) {
				// if an existing child is not in the new data, remove it
				if (!isset($children[$existingChild['name']])) {
					$this->cache->remove(ltrim($path . '/' . $existingChild['name'], '/'));
				}
			}
		}
	}
}

Remove no longer existing files from the cache when scanning external storage


<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace Imbo\Image\Loader;

/**
 * Basic image loader / fallback image loader
 *
 * @author Mats Lindh <mats@lindh.no>
 * @package Image\Loaders
 */
class Basic implements LoaderInterface {
    public function getMimeTypeCallbacks() {
        return [
            'image/png' => [
                'extension' => 'png',
                'callback' => [$this, 'load'],
            ],
            'image/jpeg' => [
                'extension' => 'jpg',
                'callback' => [$this, 'load'],
            ],
            'image/gif' => [
                'extension' => 'gif',
                'callback' => [$this, 'load'],
            ],
        ];
    }

    public function load($blob) {
        $imagick = new \Imagick();
        $imagick->readImageBlob($blob);
        return $imagick;
    }
}

<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace Imbo\Image\Loader;

/**
 * Basic image loader / fallback image loader
 *
 * @author Mats Lindh <mats@lindh.no>
 * @package Image\Loaders
 */
class Basic implements LoaderInterface {
    public function getMimeTypeCallbacks() {
        return [
            'image/png' => [
                'extension' => 'png',
                'callback' => [$this, 'load'],
            ],
            'image/jpeg' => [
                'extension' => 'jpg',
                'callback' => [$this, 'load'],
            ],
            'image/gif' => [
                'extension' => 'gif',
                'callback' => [$this, 'load'],
            ],
        ];
    }

    public function load($imagick, $blob) {
        $imagick->readImageBlob($blob);
        return $imagick;
    }
}

Use injected Imagick instance for loading


<?php

namespace Oro\Component\Layout\Tests\Unit;

class AbstractDataProviderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \BadMethodCallException
     * @expectedExceptionMessage Not implemented
     */
    public function testGetIdentifier()
    {
        /** @var AbstractDataProvider $dataProvider */
        $dataProvider = $this->getMockForAbstractClass('Oro\Component\Layout\AbstractDataProvider');
        $dataProvider->getIdentifier();
    }
}

<?php

namespace Oro\Component\Layout\Tests\Unit;

class AbstractDataProviderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \BadMethodCallException
     * @expectedExceptionMessage Not implemented
     */
    public function testGetIdentifier()
    {
        $dataProvider = $this->getMockForAbstractClass('Oro\Component\Layout\AbstractDataProvider');
        $dataProvider->getIdentifier();
    }
}

BB-2140: Improve DataProviders
- removed useless comment


<?php
/**
 * Default hero template file.
 *
 * This is the default hero image for page templates, called
 * 'block'. Strictly air specific.
 *
 * @package air-light
 */

// Block settings
if ( is_front_page() ) :
	$block_class = ' block-front';
else :
	$block_class = ' block-' . get_post_type();
endif;

// Featured image
if ( has_post_thumbnail() ) :
	$featured_image = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
else :
	$featured_image = get_theme_file_uri( 'images/default.jpg' );
endif;
?>

<div class="block<?php echo esc_attr( $block_class ); ?>" style="background-image: url('<?php echo esc_url( $featured_image ); ?>');">

<?php
/**
 * Default hero template file.
 *
 * This is the default hero image for page templates, called
 * 'block'. Strictly air specific.
 *
 * @package air-light
 */

// Block settings
if ( is_front_page() ) {
	$block_class = ' block-front';
} else {
	$block_class = ' block-' . get_post_type();
}

// Featured image
if ( has_post_thumbnail() ) {
	$featured_image = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
} else {
	$featured_image = get_theme_file_uri( 'images/default.jpg' );
}
?>

<div class="block<?php echo esc_attr( $block_class ); ?>" style="background-image: url('<?php echo esc_url( $featured_image ); ?>');">

Change PHP-only to curly brackets format


<?php

class GroupedProduct_CatalogueProduct extends DataExtension {

    private static $has_one = array(
        "ProductGroup" => "Product"
    );

    public function updateCMSFields(FieldList $fields) {
        $fields->addFieldToTab(
            "Root.Settings",
            DropdownField::create(
                "ProductGroupID",
                _t("GroupedProduct.AddToGroup", "Add this product to a group"),
                Product::get()
                    ->filter("ClassName", "GroupedProduct")
                    ->map()
            )->setEmptyString(_t("GroupedProduct.SelectProduct", "Select a Product"))
        );

        // If this is a child product, remove some fields we don't need
        if($this->owner->ProductGroupID) {
            $fields->removeByName("Content");
            $fields->removeByName("Metadata");
            $fields->removeByName("Related");
            $fields->removeByName("Categories");
            $fields->removeByName("TaxRate");
        }
    }

    public function onBeforeWrite() {
        if($this->owner->ProductGroupID && !$this->owner->BasePrice)
            $this->owner->BasePrice = $this->owner->ProductGroup()->BasePrice;
    }

}

<?php

class GroupedProduct_CatalogueProduct extends DataExtension {

    private static $has_one = array(
        "ProductGroup" => "Product"
    );

    public function updateCMSFields(FieldList $fields) {
        $fields->addFieldToTab(
            "Root.Settings",
            DropdownField::create(
                "ProductGroupID",
                _t("GroupedProduct.AddToGroup", "Add this product to a group"),
                Product::get()
                    ->filter("ClassName", "GroupedProduct")
                    ->map()
            )->setEmptyString(_t("GroupedProduct.SelectProduct", "Select a Product"))
        );

        // If this is a child product, remove some fields we don't need
        if($this->owner->ProductGroupID) {
            $fields->removeByName("Content");
            $fields->removeByName("Metadata");
            $fields->removeByName("Related");
            $fields->removeByName("Categories");
            $fields->removeByName("TaxRate");
        }
    }

    public function onBeforeWrite() {
        if($this->owner->ProductGroupID) {
            $group = $this->owner->ProductGroup();

            // Set the URL for this product to include the parent URL
            $this->owner->URLSegment = $group->URLSegment . "-" . Convert::raw2url($this->owner->Title);

            // Set the base price
            if(!$this->owner->BasePrice)
                $this->owner->BasePrice = $group->BasePrice;
        }
    }

}

Add url rewrite for if a product is added below a grouped product


<?php

use Psr7Middlewares\Middleware;

class HttpsTest extends Base
{
    public function HttpsProvider()
    {
        return [
            ['http://localhost', true, 301, 'https://localhost', ''],
            ['https://localhost', false, 200, '', 'max-age=31536000'],
            ['https://localhost', true, 200, '', 'max-age=31536000;includeSubDomains'],
        ];
    }

    /**
     * @dataProvider HttpsProvider
     */
    public function testHttps($url, $includeSubdomains, $status, $location, $hsts)
    {
        $response = $this->execute(
            [
                Middleware::Https()->includeSubdomains($includeSubdomains),
            ],
            $url
        );

        $this->assertEquals($status, $response->getStatusCode());
        $this->assertEquals($location, $response->getHeaderLine('Location'));
        $this->assertEquals($hsts, $response->getHeaderLine('Strict-Transport-Security'));
    }
}

<?php

use Psr7Middlewares\Middleware;

class HttpsTest extends Base
{
    public function HttpsProvider()
    {
        return [
            ['http://localhost', true, 301, 'https://localhost', ''],
            ['https://localhost', false, 200, '', 'max-age=31536000'],
            ['https://localhost', true, 200, '', 'max-age=31536000;includeSubDomains'],
        ];
    }

    /**
     * @dataProvider HttpsProvider
     */
    public function testHttps($url, $includeSubdomains, $status, $location, $hsts)
    {
        $response = $this->execute(
            [
                Middleware::Https()->includeSubdomains($includeSubdomains),
            ],
            $url
        );

        $this->assertEquals($status, $response->getStatusCode());
        $this->assertEquals($location, $response->getHeaderLine('Location'));
        $this->assertEquals($hsts, $response->getHeaderLine('Strict-Transport-Security'));
    }
    public function testRedirectSchemeMatchesPort()
    {
        $url = 'http://domain.com:80';

        $response = $this->execute(
            [
                Middleware::Https()->includeSubdomains(false),
            ],
            $url
        );
        $expectedLocation = 'https://domain.com';
        $location = $response->getHeaderLine('Location');
        $this->assertEquals($expectedLocation,$location);
    }
}

Add unit test to verify properly returned Location


<?php

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

namespace Symfony\Component\DependencyInjection\Extension;

use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * ExtensionInterface is the interface implemented by container extension classes.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface ExtensionInterface
{
    /**
     * Loads a specific configuration.
     *
     * @throws \InvalidArgumentException When provided tag is not defined in this extension
     */
    public function load(array $configs, ContainerBuilder $container);

    /**
     * Returns the namespace to be used for this extension (XML namespace).
     *
     * @return string The XML namespace
     */
    public function getNamespace();

    /**
     * Returns the base path for the XSD files.
     *
     * @return string|false
     */
    public function getXsdValidationBasePath();

    /**
     * Returns the recommended alias to use in XML.
     *
     * This alias is also the mandatory prefix to use when using YAML.
     *
     * @return string The alias
     */
    public function getAlias(): string;
}

<?php

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

namespace Symfony\Component\DependencyInjection\Extension;

use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * ExtensionInterface is the interface implemented by container extension classes.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface ExtensionInterface
{
    /**
     * Loads a specific configuration.
     *
     * @throws \InvalidArgumentException When provided tag is not defined in this extension
     */
    public function load(array $configs, ContainerBuilder $container);

    /**
     * Returns the namespace to be used for this extension (XML namespace).
     *
     * @return string The XML namespace
     */
    public function getNamespace();

    /**
     * Returns the base path for the XSD files.
     *
     * @return string|false
     */
    public function getXsdValidationBasePath();

    /**
     * Returns the recommended alias to use in XML.
     *
     * This alias is also the mandatory prefix to use when using YAML.
     *
     * @return string The alias
     */
    public function getAlias();
}

Add return types - batch 6/n

Add return types - batch 6/n


<?php

require_once dirname(__DIR__) . '/library/CM/Bootloader.php';
define('DIR_TESTS', __DIR__ . DIRECTORY_SEPARATOR);
define('DIR_TEST_DATA', DIR_TESTS . 'data' . DIRECTORY_SEPARATOR);

$bootloader = new CM_Bootloader(dirname(__DIR__) . '/', null);
$bootloader->setEnvironment('test');
$bootloader->load(array('autoloader', 'constants', 'exceptionHandler', 'errorHandler', 'defaults'));

!is_dir(DIR_TMP) ? mkdir(DIR_TMP) : null;
!is_dir(DIR_DATA) ? mkdir(DIR_DATA) : null;
!is_dir(DIR_USERFILES) ? mkdir(DIR_USERFILES) : null;

CMTest_TH::init();

<?php

require_once dirname(__DIR__) . '/vendor/autoload.php';
define('DIR_TESTS', __DIR__ . DIRECTORY_SEPARATOR);
define('DIR_TEST_DATA', DIR_TESTS . 'data' . DIRECTORY_SEPARATOR);

$bootloader = new CM_Bootloader(dirname(__DIR__) . '/', null);
$bootloader->setEnvironment('test');
$bootloader->load(array('autoloader', 'constants', 'exceptionHandler', 'errorHandler', 'defaults'));

!is_dir(DIR_TMP) ? mkdir(DIR_TMP) : null;
!is_dir(DIR_DATA) ? mkdir(DIR_DATA) : null;
!is_dir(DIR_USERFILES) ? mkdir(DIR_USERFILES) : null;

CMTest_TH::init();

Use composer autoload for tests

Use composer autoload for tests


<?php

/**
 * A (quick and dirty) scanner to scanning all (linked) pages of an https-enabled website for Mixed Content
 * @author Bramus! <bramus@bram.us>
 * @version 1.0
 *
 * NO NEED TO TOUCH THIS FILE ... PLEASE REFER TO THE README.MD FILE ;-)
 */

// Error settings
error_reporting(E_ERROR);
ini_set('display_errors', 'on');

// Check if we're at the CLI
if (php_sapi_name() != 'cli') exit('Please run this file on the command line. E.g. `php bin/scanner.php $url`' . PHP_EOL);

// Check arguments (simple)
if ($argc != 2 || !parse_url($argv[1])) exit('Please use a valid URL you wish to scan as a parameter to this script. Eg. `php bin/scanner.php https://www.bram.us/`' . PHP_EOL);

// Require needed Scanner class
require __DIR__ . '/../vendor/autoload.php';

// Get ignorepatterns
$ignorePatterns = include __DIR__ . '/../conf/ignorePatterns.php';

// Go for it!
$scanner = new \Bramus\MCS\Scanner($argv[1], (array) $ignorePatterns);
$scanner->scan();

<?php

/**
 * A (quick and dirty) scanner to scanning all (linked) pages of an https-enabled website for Mixed Content
 * @author Bramus! <bramus@bram.us>
 * @version 1.0
 *
 * NO NEED TO TOUCH THIS FILE ... PLEASE REFER TO THE README.MD FILE ;-)
 */

// Error settings
error_reporting(E_ERROR);
ini_set('display_errors', 'on');

// Check if we're at the CLI
if (php_sapi_name() != 'cli') exit('Please run this file on the command line. E.g. `php bin/scanner.php $url`' . PHP_EOL);

// Require autoloader
if (!file_exists(__DIR__ . '/../vendor/autoload.php')) exit('Make sure you run `composer install` first, before running this scanner');
require __DIR__ . '/../vendor/autoload.php';

// Check arguments (simple)
if ($argc != 2 || !parse_url($argv[1])) exit('Please use a valid URL you wish to scan as a parameter to this script. Eg. `php bin/scanner.php https://www.bram.us/`' . PHP_EOL);

// Get ignorepatterns
$ignorePatterns = include __DIR__ . '/../conf/ignorePatterns.php';

// Go for it!
$scanner = new \Bramus\MCS\Scanner($argv[1], (array) $ignorePatterns);
$scanner->scan();

Check for autoloader file before trying to include it


<?php

namespace WBB\BarBundle\Repository;

use WBB\BarBundle\Entity\Ad;
use WBB\CoreBundle\Repository\EntityRepository;

/**
 * AdRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class AdRepository extends EntityRepository
{
    public function findOneByPositionAndCountry($position = Ad::WBB_ADS_HP_300X250, $country = null)
    {
        $qb = $this->createQuerybuilder($this->getAlias());

        $qb
            ->select($this->getAlias())
            ->where($qb->expr()->eq($this->getAlias().'.position', $qb->expr()->literal($position)))
            ->andWhere($qb->expr()->gte($qb->expr()->literal(date('Y-m-d')), $this->getAlias().'.beginAt'))
            ->andWhere($qb->expr()->lte($qb->expr()->literal(date('Y-m-d')), $this->getAlias().'.endAt'))
            ->orderBy($this->getAlias().'.createdAt', 'DESC')
            ->setMaxResults(1);
        ;

        if($country){
            $qb
                ->leftJoin($this->getAlias().'.countries', 'c')
                ->andWhere($qb->expr()->eq($this->getAlias().'.country', $country->getId()))
            ;
        }

        return $qb->getQuery()->getOneOrNullResult();
    }
}

<?php

namespace WBB\BarBundle\Repository;

use WBB\BarBundle\Entity\Ad;
use WBB\CoreBundle\Repository\EntityRepository;

/**
 * AdRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class AdRepository extends EntityRepository
{
    public function findOneByPositionAndCountry($position = Ad::WBB_ADS_HP_300X250, $country = null)
    {
        $qb = $this->createQuerybuilder($this->getAlias());

        $qb
            ->select($this->getAlias())
            ->where($qb->expr()->eq($this->getAlias().'.position', $qb->expr()->literal($position)))
            ->andWhere($qb->expr()->gte($qb->expr()->literal(date('Y-m-d')), $this->getAlias().'.beginAt'))
            ->andWhere($qb->expr()->lte($qb->expr()->literal(date('Y-m-d')), $this->getAlias().'.endAt'))
            ->orderBy($this->getAlias().'.createdAt', 'DESC')
            ->setMaxResults(1);
        ;

        if($country){
            $qb
                ->leftJoin($this->getAlias().'.countries', 'c')
                ->andWhere($qb->expr()->eq('c.id', $country->getId()))
            ;
        }

        return $qb->getQuery()->getOneOrNullResult();
    }
}

Fix bug on country joint

Fix bug on country joint


<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Org;
use App\User;

class DataTest extends TestCase
{
    use DatabaseTransactions;

    /**
     * Test dashboard gets orgs.
     *
     * @return void
     */
    public function testDashboard()
    {
        $user = factory(User::class)->create();
        $orgs = factory(Org::class, 5)->create([
          'userid' => $user->id,
        ]);
        $response = $this->actingAs($user)
                         ->get('dashboard');

        $response->assertStatus(200)
                 ->assertViewHas('orgs', Org::where('userid', '=', $user->id)->paginate(15));
    }

    /**
     * Test organization settings page gets orgs.
     *
     * @return void
     */
    public function testOrg()
    {
        $user = factory(User::class)->create();
        $org = factory(Org::class)->create([
          'userid' => $user->id,
        ]);
        $response = $this->actingAs($user)
                         ->get('org/'.$org->id);
        $response->assertStatus(200)
                 ->assertViewHas('org');
    }
}

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Org;
use App\User;

class DataTest extends TestCase
{
    use DatabaseTransactions;

    /**
     * Test dashboard gets orgs.
     *
     * @return void
     */
    public function testDashboard()
    {
        $user = factory(User::class)->create();
        $orgs = factory(Org::class, 5)->create([
          'userid' => $user->id,
        ]);
        $response = $this->actingAs($user)
                         ->get('dashboard');

        $response->assertStatus(200)
                 ->assertViewHas('orgs', Org::where('userid', '=', $user->id)->paginate(15));
    }

    /**
     * Test organization settings page gets org.
     *
     * @return void
     */
    public function testOrg()
    {
        $user = factory(User::class)->create();
        $org = factory(Org::class)->create([
          'userid' => $user->id,
        ]);
        $response = $this->actingAs($user)
                         ->get('org/'.$org->id);
        $response->assertStatus(200)
                 ->assertViewHas('org');
    }

    /**
     * Test teams page gets org.
     *
     * @return void
     */
    public function testTeams()
    {
        $user = factory(User::class)->create();
        $org = factory(Org::class)->create([
          'userid' => $user->id,
        ]);
        $response = $this->actingAs($user)
                         ->get('org/'.$org->id.'/teams');
        $response->assertStatus(200)
                 ->assertViewHas('org');
    }
}

Add a test for teams page data

:white_check_mark: Add a test for teams page data


<!DOCTYPE html>

        Course
        Student ID
        Student Name
        Student E-mail
        Enrollment Date

    @foreach($enrollments as $enrollment)

        {{ $enrollment->course->id }}
        {{ $enrollment->course->name }}
        {{ $enrollment->student->student_number }}
        {{ $enrollment->student->user->name }}
        {{ $enrollment->student->user->email }}
        {{ $enrollment->student->created_at }}

    @endforeach

<!DOCTYPE html>

        Course ID
        Course
        Student ID
        Student Name
        Student E-mail
        Enrollment Date

    @foreach($enrollments as $enrollment)

        {{ $enrollment->course->id }}
        {{ $enrollment->course->name }}
        {{ $enrollment->student->student_number }}
        {{ $enrollment->student->user->name }}
        {{ $enrollment->student->user->email }}
        {{ $enrollment->student->created_at }}

    @endforeach

Add field name to the enrollments export list


@extends('app')

@section('content')

					@if(\Auth::user()->isOwner($business))
						{!! Icon::star() !!} {!! link_to(route('manager.businesses.show', $business->id), $business->name) !!}
					@else
						{{ $business->name }}
					@endif

@endsection

@extends('app')

@section('content')

					@if(\Auth::user()->isOwner($business))
						{!! Icon::star() !!} {!! link_to(route('manager.businesses.show', $business->id), $business->name) !!}
					@else
						{{ $business->name }}
					@endif

					{!! Button::normal(trans('user.appointments.btn.book'))->asLinkTo( route('user.booking.book') ) !!}

@endsection

Add book appointment User button

Add book appointment User button


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

		<?php UI::PrintHeader() ?>

			<?php UIFolder::PrintFolders() ?>

			<?php
				foreach (UIFolder::getItems() as &$item) {
					if ($item->isDirectory()) continue;
					echo 'getURL().'?thumbnail=true" alt="'.$item->getName().'" />';
				}
			?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

		<?php UI::PrintHeader() ?>

			<?php UIFolder::PrintFolders() ?>

			<?php
				foreach (UIFolder::getItems() as &$item) {
					if ($item->isDirectory()) continue;
					echo 'getURL().'">getURL().'?thumbnail=true" alt="'.$item->getName().'" />';
				}
			?>

Add links to single image view

Add links to single image view


<?php

use Phinx\Migration\AbstractMigration;

class CreateCookieTokens extends AbstractMigration{
		public function change(){
			try {
				$sql = '';
				$sql = $sql.'CREATE TABLE `cookie_tokens` (';
				$sql = $sql.'  `id` integer(11) not null UNSIGNED AUTO_INCREMENT,';
				$sql = $sql.'  `selector` char(12),';
				$sql = $sql.'  `hashedValidator` char(64),';
				$sql = $sql.'  `user_id` integer(11) not null UNSIGNED,';
				$sql = $sql.'  `expires` datetime,';
				$sql = $sql.'  PRIMARY KEY (`id`)';
				$sql = $sql.') ENGINE=InnoDB DEFAULT CHARSET=utf8;';
				$row = $this->fetchRow($sql);
			}catch(Exception $e){

			}
		}
}

<?php

use Phinx\Migration\AbstractMigration;

class CreateCookieTokens extends AbstractMigration{
		public function change(){
			try {
				$sql = '';
				$sql = $sql.'CREATE TABLE `cookie_tokens` (';
				$sql = $sql.'  `id` integer(11) UNSIGNED NOT NULL AUTO_INCREMENT,';
				$sql = $sql.'  `selector` char(12),';
				$sql = $sql.'  `hashedValidator` char(64),';
				$sql = $sql.'  `user_id` integer(11) UNSIGNED NOT NULL UNSIGNED,';
				$sql = $sql.'  `expires` datetime,';
				$sql = $sql.'  PRIMARY KEY (`id`)';
				$sql = $sql.') ENGINE=InnoDB DEFAULT CHARSET=utf8;';
				$row = $this->fetchRow($sql);
			}catch(Exception $e){

			}
		}
}

Fix migration to create cookie token table


{{ $interest_form->firstname }} {{ $interest_form->lastname }} is interested
in joining the {{ $interest_form->vision ? ' Vision ' : "" }}
{{ $interest_form->vision_team && $interest_form->regional_statistician_team ? " and " : "Team" }}
{{$interest_form->regional_statistician_team ? " Regional Statistician Team " : "" }}

Summary

{{ $interest_form->firstname }} {{ $interest_form->lastname }}

{{ $interest_form->email }}

{{ $interest_form->phone }}

{{ $interest_form->team }}

Best,

The Vision Team

{{ $interest_form->firstname }} {{ $interest_form->lastname }} is interested
in joining the {{ $interest_form->vision_team ? ' Vision ' : "" }}
{{ $interest_form->vision_team && $interest_form->regional_statistician_team ? " and " : "Team" }}
{{$interest_form->regional_statistician_team ? " Regional Statistician Team " : "" }}

Summary

{{ $interest_form->firstname }} {{ $interest_form->lastname }}

{{ $interest_form->email }}

{{ $interest_form->phone }}

{{ $interest_form->team }}

Best,

The Vision Team

Add Interest Form For Weekend

Add Interest Form For Weekend

+ fix email body and subject


<?php

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

namespace Tests\Models\UserStatistics;

use App\Exceptions\ClassNotFoundException;
use App\Models\Beatmap;
use App\Models\UserStatistics\Model;
use Tests\TestCase;

class ModelTest extends TestCase
{
    public function testGetClass()
    {
        $modes = array_keys(Beatmap::MODES);
        foreach ($modes as $mode) {
            $class = Model::getClass($mode);
            $this->assertInstanceOf(Model::class, new $class);
        }
    }

    /**
     * @dataProvider modes
     */
    public function testGetClassByThrowsExceptionIfModeDoesNotExist($mode)
    {
        $this->expectException(ClassNotFoundException::class);
        Model::getClass($mode);
    }

    public function modes()
    {
        return [
            ['does'],
            ['not exist'],
            ['not_real'],
            ['best\\_osu'],
        ];
    }
}

<?php

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

namespace Tests\Models\UserStatistics;

use App\Exceptions\ClassNotFoundException;
use App\Models\Beatmap;
use App\Models\UserStatistics\Model;
use Tests\TestCase;

class ModelTest extends TestCase
{
    /**
     * @dataProvider validModes
     */
    public function testGetClass($mode, $variant)
    {
        $class = Model::getClass($mode, $variant);
        $this->assertInstanceOf(Model::class, new $class);
    }

    /**
     * @dataProvider invalidModes
     */
    public function testGetClassByThrowsExceptionIfModeDoesNotExist($mode, $variant)
    {
        $this->expectException(ClassNotFoundException::class);
        Model::getClass($mode, $variant);
    }

    public function invalidModes()
    {
        return [
            ['does', null],
            ['not exist', null],
            ['not_real', null],
            ['best\\_osu', null],
            ['osu', '4k'],
        ];
    }

    public function validModes()
    {
        $modes = [];

        foreach (Beatmap::MODES as $mode => $_modeInt) {
            $modes[] = [$mode, null];

            foreach (Beatmap::VARIANTS[$mode] ?? [] as $variant) {
                $modes[] = [$mode, $variant];
            }
        }

        return $modes;
    }
}

Update model test to include variants

Update model test to include variants


<?php
/**
 * HTTP request object factory
 *
 * This factory should be used in index.php for request object initialization.
 * Example:
 *
 * $validator = (new Validator)->setAdapter(new PhpFilters);
 * $request = RequestFactory::create($_SERVER['CONTENT_TYPE'])->setValidator($validator);
 *
 * @file      RequestFactory.php
 *
 * PHP version 5.6+
 *
 * @author    Yancharuk Alexander <alex at itvault dot info>
 * @copyright © 2012-2017 Alexander Yancharuk <alex at itvault at info>
 * @date      2017-04-23 16:12
 * @license   The BSD 3-Clause License
 *            <https://tldrlegal.com/license/bsd-3-clause-license-(revised)>
 */

namespace Veles\Request;

class RequestFactory
{
	/**
	 * Create HTTP-request object depending on Content-type HTTP-header
	 *
	 * @param string $type Value of Content-type HTTP-header
	 *
	 * @return HttpRequestAbstract
	 */
	public static function create($type)
	{
		if (!isset($type) or 0 === strpos($type, 'text/html')) {
			return new HttpGetRequest;
		}

		return new HttpPostRequest;
	}
}

<?php
/**
 * HTTP request object factory
 *
 * This factory should be used in index.php for request object initialization.
 * Example:
 *
 * $validator = (new Validator)->setAdapter(new PhpFilters);
 * $request = RequestFactory::create($_SERVER['CONTENT_TYPE'])->setValidator($validator);
 *
 * @file      RequestFactory.php
 *
 * PHP version 5.6+
 *
 * @author    Yancharuk Alexander <alex at itvault dot info>
 * @copyright © 2012-2017 Alexander Yancharuk <alex at itvault at info>
 * @date      2017-04-23 16:12
 * @license   The BSD 3-Clause License
 *            <https://tldrlegal.com/license/bsd-3-clause-license-(revised)>
 */

namespace Veles\Request;

class RequestFactory
{
	/**
	 * Create HTTP-request object depending on Content-type HTTP-header
	 *
	 * @param string $type Value of Content-type HTTP-header
	 *
	 * @return HttpRequestAbstract
	 */
	public static function create($type)
	{
		if (empty($type) || 0 === strpos($type, 'text/html')) {
			return new HttpGetRequest;
		}

		return new HttpPostRequest;
	}
}

Fix issue with empty content type header in request builder


<?php
/**
 * PEAR2_Pyrus_ChannelRegistry_ParseException
 *
 * PHP version 5
 *
 * @category  PEAR2
 * @package   PEAR2_Pyrus
 * @author    Greg Beaver <cellog@php.net>
 * @copyright 2008 The PEAR Group
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @version   SVN: $Id$
 * @link      http://svn.pear.php.net/wsvn/PEARSVN/Pyrus/
 */

/**
 * Base class for Exceptions when parsing channel registry.
 *
 * @category  PEAR2
 * @package   PEAR2_Pyrus
 * @author    Greg Beaver <cellog@php.net>
 * @copyright 2008 The PEAR Group
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @link      http://svn.pear.php.net/wsvn/PEARSVN/Pyrus/
 */
class PEAR2_Pyrus_ChannelRegistry_Exception extends PEAR2_Exception
{
}

<?php
/**
 * PEAR2_Pyrus_ChannelRegistry_ParseException
 *
 * PHP version 5
 *
 * @category  PEAR2
 * @package   PEAR2_Pyrus
 * @author    Greg Beaver <cellog@php.net>
 * @copyright 2008 The PEAR Group
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @version   SVN: $Id$
 * @link      http://svn.pear.php.net/wsvn/PEARSVN/Pyrus/
 */

/**
 * Base class for Exceptions when parsing channel registry.
 *
 * @category  PEAR2
 * @package   PEAR2_Pyrus
 * @author    Greg Beaver <cellog@php.net>
 * @copyright 2008 The PEAR Group
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @link      http://svn.pear.php.net/wsvn/PEARSVN/Pyrus/
 */
class PEAR2_Pyrus_ChannelRegistry_ParseException extends PEAR2_Exception
{
    public $why;

    function __construct($message, $why)
    {
        $this->why = $why;
        parent::__construct($message);
    }
}

Add $why var for parse exceptions.

Add $why var for parse exceptions.

git-svn-id: 71b65f7ff3646a85e1ba76c778efde6466075005@285075 c90b9560-bf6c-de11-be94-00142212c4b1


<?php
namespace CI\UI\Controller;

class HookController
{
    public function hook(\Silex\Application $app)
    {
    	$client= new \GearmanClient();
		$client->addServer('127.0.0.1', 4730);
		$test_id = $client->doBackground('create_test', $app['request']->get('id'));

		return $app->json(array(
			'success' => true
		));
    }
}

<?php
namespace CI\UI\Controller;

class HookController
{
    public function hook(\Silex\Application $app)
    {
    	$client= new \GearmanClient();
		$client->addServer('127.0.0.1', 4730);
		$test_id = $client->doNormal('create_test', $app['request']->get('id'));

        if ($app['request']->get('redirect'))
        {
            return $app->redirect('/project/' . $app['request']->get('id'));
        }

		return $app->json(array(
			'success' => true
		));
    }
}

Allow hook controller to redirect

Allow hook controller to redirect


<?php
if (is_a($context->output,'UNL_UCBCN_EventListing')) {
    if ($dt = strtotime($context->query)) {
        echo '
Search results for events dated '.date('F jS',$dt).'url.'">(link)
';
    } else {
        echo '
Search results for "'.htmlentities($context->query).'"url.'">(link)
';
    }
    echo '
'.count($context->output->events).' results
';
}
echo $savvy->render($context->output);

echo '

            url,array('format'=>'ics')).'">ics format for search results
            url,array('format'=>'rss')).'">rss format for search results

';

?>

        <?php
        if ($dt = strtotime($context->search_query) && ($context->search_query != 'art')) {
            echo 'Search results for events dated '.date('F jS',$dt).'getURL().'">(link)';
        } else {
            echo 'Search results for "'.htmlentities($context->search_query).'"';
        }
        ?>

    <?php

    echo ''.$context->count().' results.  getURL().'">(link)';
    echo $savvy->render($context, 'EventListing.tpl.php');
    ?>

        <a id="icsformat" title="ics format for search results" href="<?php echo $context->getURL()?>?format=ics">ics format for search results
        <a id="rssformat" title="rss format for search results" href="<?php echo $context->getURL()?>?format=rss">rss format for search results

Clean up the code a little

Clean up the code a little


<?php

return [
    'route'             => [
        'prefix' => 'authorization',
    ],

    'database'          => [
        'connection' => config('database.default'),
    ],

    'users'             => [
        'table' => 'users',
        'model' => Arcanesoft\Auth\Models\User::class,
    ],

    'roles'             => [
        'table' => 'roles',
        'model' => Arcanesoft\Auth\Models\Role::class,
    ],

    'permissions'       => [
        'table' => 'permissions',
        'model' => Arcanesoft\Auth\Models\Permission::class,
    ],

    'user-confirmation' => [
        'enabled'   => false,
        'length'    => 30,
    ],

    'throttles'         => [
        'enabled' => true,
        'table'   => 'throttles',
    ],

    'slug-separator'    => '.',

    'seeds'             => [
        'users' => [
            [
                'username'   => 'admin',
                'email'      => env('ADMIN_USER_EMAIL', 'admin@email.com'),
                'password'   => env('ADMIN_USER_PASSWORD', 'password'),
            ],
        ],
    ],
];

<?php

return [
    'route'             => [
        'prefix' => 'authorization',
    ],

    'database'          => [
        'connection' => config('database.default'),
    ],

    'users'             => [
        'table' => 'users',
        'model' => Arcanesoft\Auth\Models\User::class,
    ],

    'roles'             => [
        'table' => 'roles',
        'model' => Arcanesoft\Auth\Models\Role::class,
    ],

    'permissions'       => [
        'table' => 'permissions',
        'model' => Arcanesoft\Auth\Models\Permission::class,
    ],

    'user-confirmation' => [
        'enabled'   => true,
        'length'    => 30,
    ],

    'throttles'         => [
        'enabled' => true,
        'table'   => 'throttles',
    ],

    'slug-separator'    => '.',

    'seeds'             => [
        'users' => [
            [
                'username'   => 'admin',
                'email'      => env('ADMIN_USER_EMAIL', 'admin@email.com'),
                'password'   => env('ADMIN_USER_PASSWORD', 'password'),
            ],
        ],
    ],
];

Enable the user confirmation by default

Enable the user confirmation by default


<?php

/* Libre.fm -- a free network service for sharing your music listening habits

   Copyright (C) 2009 Libre.fm Project

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

require_once('config.php');

$session = curl_init($submissions_url);

$post_vars = '';
foreach($_POST as $key => $element) {
	if (is_array($element)) {
		$i = 0;
		foreach($element as $e) {
			$post_vars .= $key . "[" . $i . "] = " . $e . "&";
			$i++;
		}
	} else {
		$post_vars .= $key.'='.$element.'&';
	}
}
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, $post_vars);

$response = curl_exec($session);
echo $response;

curl_close($session);
?>

<?php

/* Libre.fm -- a free network service for sharing your music listening habits

   Copyright (C) 2009 Libre.fm Project

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

require_once('config.php');

$session = curl_init($submissions_url);

$post_vars = '';
foreach($_POST as $key => $element) {
	if (is_array($element)) {
		$i = 0;
		foreach($element as $e) {
			$post_vars .= $key . "[" . $i . "]=" . $e . "&";
			$i++;
		}
	} else {
		$post_vars .= $key.'='.$element.'&';
	}
}
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, $post_vars);

$response = curl_exec($session);
echo $response;

curl_close($session);
?>

Fix spaces inserted by scrobble proxy

Fix spaces inserted by scrobble proxy


<?php

class BaseController extends Controller {

	/**
	 * Retrieve the current theme's identifier.
	 *
	 * @return string
	 */
	protected function getTheme()
	{
		// TODO: check database access, DJ column will have theme
		return "default";
	}

	/**
	 * Setup the layout used by the controller.
	 * Also adds a few required variables.
	 *
	 * @return void
	 */
	protected function setupLayout()
	{
		if ( ! is_null($this->layout))
		{
			// TODO: dynamic source for the themes
			$this->layout = View::make($this->layout)
				->with("base", Config::get("app.base", ""))
				->with("theme", $this->getTheme());
		}
	}

}

<?php

class BaseController extends Controller {

	public function __construct() {

		// Auth, naturally.
		//$this->beforeFilter('auth');

		// ALL POST/PUT/DELETE REQUIRE CSRF TOKENS.
		$this->beforeFilter('csrf', ['on' => ['post', 'put', 'delete']]);

	}

	/**
	 * Retrieve the current theme's identifier.
	 *
	 * @return string
	 */
	protected function getTheme()
	{
		// TODO: check database access, DJ column will have theme
		return "default";
	}

	/**
	 * Setup the layout used by the controller.
	 * Also adds a few required variables.
	 *
	 * @return void
	 */
	protected function setupLayout()
	{
		if ( ! is_null($this->layout))
		{
			// TODO: dynamic source for the themes
			$this->layout = View::make($this->layout)
				->with("base", Config::get("app.base", ""))
				->with("theme", $this->getTheme());
		}
	}

}

Add CSRF protection as default in all routes.


<?php

/*
 * This file is part of the CSBillCoreBundle package.
 *
 * (c) Pierre du Plessis <info@customscripts.co.za>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CSBill\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller as Base;

abstract class BaseController extends Base
{
    /**
     * Return a instance of the doctrine entity manager
     *
     * @return \Doctrine\Common\Persistence\ObjectManager
     */
    public function getEm()
    {
        return $this->get('doctrine')->getManager();
    }

    /**
     * Get a doctrine repository
     *
     * @param  string                                        $repository
     * @return \Doctrine\Common\Persistence\ObjectRepository
     */
    public function getRepository($repository)
    {
        return $this->getEm()->getRepository($repository);
    }

    /**
     * Adds a message to the session flash
     *
     * @param string $message The message to add to the session flash
     * @param string $type    The flash message type (notice, success, error etc)
     *
     * @return $this
     */
    public function flash($message, $type = 'notice')
    {
        $this->get('session')->getFlashBag()->add($type, $message);

        return $this;
    }

    /**
     * Translates a message
     *
     * @param  string $message
     * @return string
     */
    public function trans($message)
    {
        return $this->get('translator')->trans($message);
    }
}

<?php

/*
 * This file is part of the CSBillCoreBundle package.
 *
 * (c) Pierre du Plessis <info@customscripts.co.za>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CSBill\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller as Base;

abstract class BaseController extends Base
{
    /**
     * Return a instance of the doctrine entity manager
     *
     * @return \Doctrine\Common\Persistence\ObjectManager
     */
    public function getEm()
    {
        return $this->getDoctrine()->getManager();
    }

    /**
     * Get a doctrine repository
     *
     * @param  string                                        $repository
     * @return \Doctrine\Common\Persistence\ObjectRepository
     */
    public function getRepository($repository)
    {
        return $this->getEm()->getRepository($repository);
    }

    /**
     * Adds a message to the session flash
     *
     * @param string $message The message to add to the session flash
     * @param string $type    The flash message type (notice, success, error etc)
     *
     * @return $this
     */
    public function flash($message, $type = 'notice')
    {
        $this->get('session')->getFlashBag()->add($type, $message);

        return $this;
    }

    /**
     * Translates a message
     *
     * @param  string $message
     * @return string
     */
    public function trans($message)
    {
        return $this->get('translator')->trans($message);
    }
}

[CoreBundle] Update getEm function in the core controller to use the getDoctrine function instead


<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class AccountDeleteRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'password' => [ 'required', 'min:6' ],
        ];
    }
}

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class AccountDeleteRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'password' => [ 'required' ],
        ];
    }
}

Remove password minimum length limit

Remove password minimum length limit


<?php namespace Torann\MediaSort\Disks;

use File;
use Config;
use Storage;
use Exception;

abstract class AbstractDisk {

    /**
     * The current media object being processed.
     *
     * @var \Torann\MediaSort\Manager
     */
    public $media;

    /**
     * Storage configurations.
     *
     * @var array
     */
    public $config;

    /**
     * Constructor method
     *
     * @param \Torann\MediaSort\Manager $media
     */
    function __construct($media)
    {
        $this->media  = $media;
        $this->config = Config::get('filesystems.disks.' . $this->media->disk);
    }

    /**
     * Remove an attached file.
     *
     * @param array $files
     */
    public function remove($files)
    {
        foreach ($files as $file)
        {
            try {
                Storage::deleteDirectory($file);
            }
            // Ignore not found exceptions
            catch (Exception $e) {}
        }
    }

    /**
     * Move an uploaded file to it's intended target.
     *
     * @param  string $source
     * @param  string $target
     * @return void
     */
    public function move($source, $target)
    {
        // Save file
        Storage::put(
            $target,
            File::get($source),
            $this->media->visibility
        );
    }
}

<?php namespace Torann\MediaSort\Disks;

use File;
use Config;
use Storage;
use Exception;

abstract class AbstractDisk {

    /**
     * The current media object being processed.
     *
     * @var \Torann\MediaSort\Manager
     */
    public $media;

    /**
     * Storage configurations.
     *
     * @var array
     */
    public $config;

    /**
     * Constructor method
     *
     * @param \Torann\MediaSort\Manager $media
     */
    function __construct($media)
    {
        $this->media  = $media;
        $this->config = Config::get('filesystems.disks.' . $this->media->disk);
    }

    /**
     * Remove an attached file.
     *
     * @param array $files
     */
    public function remove($files)
    {
        foreach ($files as $file)
        {
            try {
                Storage::delete($file);
            }
            // Ignore not found exceptions
            catch (Exception $e) {}
        }
    }

    /**
     * Move an uploaded file to it's intended target.
     *
     * @param  string $source
     * @param  string $target
     * @return void
     */
    public function move($source, $target)
    {
        // Save file
        Storage::put(
            $target,
            File::get($source),
            $this->media->visibility
        );
    }
}

Fix old media from not being removed

Fix old media from not being removed


<?php

namespace HWI\Bundle\OAuthBundle\OAuth\ResourceOwner;

use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class DiscogsResourceOwner extends GenericOAuth1ResourceOwner
{
    /**
     * {@inheritDoc}
     */
    protected $paths = array(
        'identifier'     => 'id',
        'nickname'       => 'username'
    );

    /**
     * {@inheritDoc}
     */
    protected function configureOptions(OptionsResolverInterface $resolver)
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults(array(
            'authorization_url' => 'http://www.discogs.com/oauth/authorize',
            'request_token_url' => 'http://api.discogs.com/oauth/request_token',
            'access_token_url'  => 'http://api.discogs.com/oauth/access_token',
            'infos_url'         => 'http://api.discogs.com/oauth/identity',
        ));
    }
}

<?php

namespace HWI\Bundle\OAuthBundle\OAuth\ResourceOwner;

use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class DiscogsResourceOwner extends GenericOAuth1ResourceOwner
{
    /**
     * {@inheritDoc}
     */
    protected $paths = array(
        'identifier'     => 'id',
        'nickname'       => 'username'
    );

    /**
     * {@inheritDoc}
     */
    protected function configureOptions(OptionsResolverInterface $resolver)
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults(array(
            'authorization_url' => 'https://www.discogs.com/oauth/authorize',
            'request_token_url' => 'https://api.discogs.com/oauth/request_token',
            'access_token_url'  => 'https://api.discogs.com/oauth/access_token',
            'infos_url'         => 'https://api.discogs.com/oauth/identity',
        ));
    }
}

Change Discogs URL from http to https

Change Discogs URL from http to https


<?
include '../scat.php';

$term= $_REQUEST['term'];

$products= array();

if (!$term) {
  die_jsonp([ 'error' => "Need to supply some search terms.",
              'results' => [] ]);
}

$products= Model::factory('Product')
             ->select("product.*")
             ->select("department.name", "department_name")
             ->select("department.slug", "department_slug")
             ->select("brand.name", "brand_name")
             ->select_expr('(SELECT slug
                               FROM department AS parent
                              WHERE department.parent_id = parent.id)',
                           'parent_slug')
             ->join('brand', array('product.brand_id', '=', 'brand.id'))
             ->join('department', array('product.department_id', '=',
                                        'department.id'))
             ->where_raw('MATCH(product.name, product.description)
                          AGAINST (? IN NATURAL LANGUAGE MODE)',
                          array($term))
             ->where('active', 1)
             ->find_array();

/* Select2 */
if ($_REQUEST['_type'] == 'query') {
  $data= [ 'results' => [], 'pagination' => [ 'more' => false ]];

  foreach ($products as $product) {
    $data['results'][]= [ 'id' => $product['id'], 'text' => $product['name'] ];
  }

  echo jsonp($data);
  exit;
}

/* Other queries */
echo jsonp($products);

<?
include '../scat.php';

$term= $_REQUEST['term'];

$products= array();

if (!$term) {
  die_jsonp([ 'error' => "Need to supply some search terms.",
              'results' => [] ]);
}

$products= Model::factory('Product')
             ->select("product.*")
             ->select("department.name", "department_name")
             ->select("department.slug", "department_slug")
             ->select("brand.name", "brand_name")
             ->select_expr('(SELECT slug
                               FROM department AS parent
                              WHERE department.parent_id = parent.id)',
                           'parent_slug')
             ->join('brand', array('product.brand_id', '=', 'brand.id'))
             ->join('department', array('product.department_id', '=',
                                        'department.id'))
             ->where_raw('MATCH(product.name, product.description)
                          AGAINST (? IN NATURAL LANGUAGE MODE)',
                          array($term))
             ->where('active', 1)
             ->find_array();

/* Select2 */
if ($_REQUEST['_type'] == 'query') {
  $data= [ 'results' => [], 'pagination' => [ 'more' => false ]];

  foreach ($products as $product) {
    $data['results'][]= [ 'id' => $product['id'],
                          'text' => $product['name'] . ' / ' .
                                    $product['brand_name'] ];
  }

  echo jsonp($data);
  exit;
}

/* Other queries */
echo jsonp($products);

Include brand name when finding product

Include brand name when finding product