<?php

/**
 * @package         Billing
 * @copyright       Copyright (C) 2012 S.D.O.C. LTD. All rights reserved.
 * @license         GNU General Public License version 2 or later; see LICENSE.txt
 */
class Mongodloid_Cursor implements Iterator
{

	private $_cursor;

	public function __construct(MongoCursor $cursor)
	{
		$this->_cursor = $cursor;
	}

	public function count()
	{
		return $this->_cursor->count();
	}

	public function current()
	{
		return new Mongodloid_Entity($this->_cursor->current());
	}

	public function key()
	{
		return $this->_cursor->key();
	}

	public function next()
	{
		return $this->_cursor->next();
	}

	public function rewind()
	{
		return $this->_cursor->rewind();
	}

	public function valid()
	{
		return $this->_cursor->valid();
	}

	public function sort(array $fields)
	{
		$this->_cursor->sort($fields);
		return $this;
	}

	public function limit(int $limit)
	{
		$this->_cursor->limit($limit);
		return $this;
	}

}

<?php

/**
 * @package         Billing
 * @copyright       Copyright (C) 2012 S.D.O.C. LTD. All rights reserved.
 * @license         GNU General Public License version 2 or later; see LICENSE.txt
 */
class Mongodloid_Cursor implements Iterator
{

	private $_cursor;

	public function __construct(MongoCursor $cursor)
	{
		$this->_cursor = $cursor;
	}

	public function count()
	{
		return $this->_cursor->count();
	}

	public function current()
	{
		return new Mongodloid_Entity($this->_cursor->current());
	}

	public function key()
	{
		return $this->_cursor->key();
	}

	public function next()
	{
		return $this->_cursor->next();
	}

	public function rewind()
	{
		$this->_cursor->rewind();
		return $this;
	}

	public function valid()
	{
		return $this->_cursor->valid();
	}

	public function sort(array $fields)
	{
		$this->_cursor->sort($fields);
		return $this;
	}

	public function limit($limit)
	{
		$this->_cursor->limit(intval($limit));
		return $this;
	}

}

Change Mongoloid cursor to return itself on rewind except of void and also accept any value in limit and then change it to number.


<?php

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

class CreateApplicationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('applications', function (Blueprint $table) {
            $table->uuid('id')->unique();
            $table->primary('id');

            $table->uuid('userid');
            $table->foreign('userid')->references('id')->on('users')->onDelete('cascade');

            $table->uuid('employerid');
            $table->foreign('employerid')->references('id')->on('employers')->onDelete('cascade');

            $table->uuid('jobid');
            $table->foreign('jobid')->references('id')->on('jobs')->onDelete('cascade');

            $table->text('message');

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('applications', function (Blueprint $table) {
            Schema::dropIfExists('applicants');
        });
    }
}

<?php

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

class CreateApplicationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('applications', function (Blueprint $table) {
            $table->uuid('id')->unique();
            $table->primary('id');

            $table->uuid('userid');
            $table->foreign('userid')->references('id')->on('users')->onDelete('cascade');

            $table->uuid('employerid');
            $table->foreign('employerid')->references('id')->on('employers')->onDelete('cascade');

            $table->uuid('jobid');
            $table->foreign('jobid')->references('id')->on('jobs')->onDelete('cascade');

            $table->text('message');
			$table->boolean('rejected')->default(0);

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('applications', function (Blueprint $table) {
            Schema::dropIfExists('applicants');
        });
    }
}

Add input for reject application

Add input for reject application


<?php

class Welcome extends Controller {

	function Welcome()
	{
		parent::Controller();
	}

	function index()
	{
		$this->load->helper('url');
		$this->load->view('welcome_message');
	}
}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */

<?php

class Welcome extends CI_Controller {

	function Welcome()
	{
		parent::Controller();
	}

	function index()
	{
		$this->load->helper('url');
		$this->load->view('welcome_message');
	}
}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */

Extend CI_Controller instead of Controller in CI 2.0


<?php

namespace ScottRobertson\Scrutiny\Reporter;

class Pushover extends Base
{
    private $token;
    private $user;
    public $pushover;

    public function __construct($token, $user, array $subscribe = array('down', 'recovery'))
    {
        // Subscribe to events
        $this->subscribe($subscribe);

        $this->token = $token;
        $this->user = $user;
        $this->pushover = new \Scottymeuk\Pushover\Client(
            array(
                'token' => $this->token
            )
        );
    }

    public function report($service)
    {
        $this->pushover->title = $service->getMessageFromEvent();
        $this->pushover->message = $service->getData('url') . ' returned ' . $service->getData('code');
        $this->pushover->timestamp = $service->getTime();
        $this->pushover->url = $service->getData('url');
        return $this->pushover->push($this->user);
    }
}

<?php

namespace ScottRobertson\Scrutiny\Reporter;

class Pushover extends Base
{
    private $token;
    private $user;
    public $pushover;

    public function __construct($token, $user, array $subscribe = array('down', 'recovery'))
    {
        // Subscribe to events
        $this->subscribe($subscribe);

        $this->token = $token;
        $this->user = $user;
        $this->pushover = new \Scottymeuk\Pushover\Client(
            array(
                'token' => $this->token
            )
        );
    }

    public function report($service)
    {
        $this->pushover->title = $service->getMessageFromEvent();
        $this->pushover->message = $service->getName() . ' returned ' . $service->getData('code');
        $this->pushover->timestamp = $service->getTime();
        $this->pushover->url = $service->getData('url');
        return $this->pushover->push($this->user);
    }
}

Make pushover message more generic

Make pushover message more generic


<?php

namespace CollegeCrazies\Bundle\MainBundle\Entity;

use Doctrine\ORM\EntityRepository;

class LeagueRepository extends EntityRepository
{
    public function findAllPublic()
    {
        return $this->createQueryBuilder('l')
            ->where('l.password IS null OR length(trim(l.password)) = 0')
            ->getQuery()
            ->getResult();
    }

    public function getUsersAndPoints(League $league)
    {
        return $this->getEntityManager()->createQuery('SELECT u, p, l, pk, pg from CollegeCraziesMainBundle:User u
            JOIN u.pickSets p
            JOIN u.leagues l
            JOIN p.picks pk
            JOIN pk.game pg
            WHERE l.id = :leagueId
            ORDER BY pg.id')
            ->setParameter('leagueId', $league->getId())
            ->getResult();
    }

    public function getNumberOfGames()
    {
        return $this->getEntityManager()
            ->createQuery('SELECT COUNT(g.id) FROM CollegeCraziesMainBundle:Game g')
            ->getSingleScalarResult();
    }
}

<?php

namespace CollegeCrazies\Bundle\MainBundle\Entity;

use Doctrine\ORM\EntityRepository;

class LeagueRepository extends EntityRepository
{
    public function findAllPublic()
    {
        return $this->createQueryBuilder('l')
            ->where('l.password IS null OR length(trim(l.password)) = 0')
            ->getQuery()
            ->getResult();
    }

    public function getUsersAndPoints(League $league)
    {
        return $this->getEntityManager()->createQuery('SELECT u, p, l, pk, pg from CollegeCraziesMainBundle:User u
            JOIN u.pickSets p
            JOIN u.leagues l
            JOIN p.picks pk
            JOIN pk.game pg
            WHERE l.id = :leagueId')
            ->setParameter('leagueId', $league->getId())
            ->getResult();
    }

    public function getNumberOfGames()
    {
        return $this->getEntityManager()
            ->createQuery('SELECT COUNT(g.id) FROM CollegeCraziesMainBundle:Game g')
            ->getSingleScalarResult();
    }
}

Remove sort, since we sort client side

Remove sort, since we sort client side


<?php

/** @noinspection DevelopmentDependenciesUsageInspection */

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Set\ValueObject\LevelSetList;
use Rector\Set\ValueObject\SetList;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->paths([
        __DIR__.'/src',
        __DIR__.'/tests',
    ]);

    $rectorConfig->cacheDirectory(__DIR__.'/tools/.rector-cache');

    $rectorConfig->importNames();

    // register a single rule
    // $rectorConfig->rule(InlineConstructorDefaultToPropertyRector::class);

    // define sets of rules
    $rectorConfig->sets([
        SetList::EARLY_RETURN,
        LevelSetList::UP_TO_PHP_74,
    ]);

    $rectorConfig->phpstanConfig(__DIR__.'/phpstan-for-rector.neon.dist');
};

<?php

/** @noinspection DevelopmentDependenciesUsageInspection */

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Set\ValueObject\LevelSetList;
use Rector\Set\ValueObject\SetList;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->paths([
        __DIR__.'/src',
        __DIR__.'/tests',
    ]);

    $rectorConfig->cacheDirectory(__DIR__.'/tools/.rector-cache');

    $rectorConfig->importNames();

    // register a single rule
    // $rectorConfig->rule(InlineConstructorDefaultToPropertyRector::class);

    // define sets of rules
    $rectorConfig->sets([
        SetList::EARLY_RETURN,
        LevelSetList::UP_TO_PHP_81,
    ]);

    $rectorConfig->phpstanConfig(__DIR__.'/phpstan-for-rector.neon.dist');
};

Enable PHP 8.1 features for Rector

Enable PHP 8.1 features for Rector


<?php /** @noinspection PhpFullyQualifiedNameUsageInspection */

declare(strict_types=1);

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

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

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

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

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

<?php /** @noinspection PhpFullyQualifiedNameUsageInspection */

declare(strict_types=1);

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

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

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

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

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

Add Rector with PHP 7.3

Add Rector with PHP 7.3


<?php

class CRM_Speakcivi_APIWrapper implements API_Wrapper {

  public function fromApiInput($apiRequest) {
    return $apiRequest;
  }

  public function toApiOutput($apiRequest, $result) {
    CRM_Core_Error::debug_var('$apiRequest', $apiRequest);
    CRM_Core_Error::debug_var('$result', $result);
    return $result;
  }
}

<?php

class CRM_Speakcivi_APIWrapper implements API_Wrapper {

  public function fromApiInput($apiRequest) {
    return $apiRequest;
  }

  public function toApiOutput($apiRequest, $result) {
    CRM_Core_Error::debug_var('$apiRequest', $apiRequest);
    CRM_Core_Error::debug_var('$result', $result);
    if ($apiRequest['entity'] == 'MailingEventUnsubscribe' && $apiRequest['action'] == 'create') {
      $this->processUnsubscribe($apiRequest);
    }
    return $result;
  }

  private function processUnsubscribe($apiRequest) {
    $eq = new CRM_Mailing_Event_BAO_Queue();
    $eq->id = $apiRequest['params']['event_queue_id'];
    if ($eq->find()) {
      if ($this->contactHasMoreJoinsThanLeaves($eq->contact_id)) {
        $this->addLeave($eq->contact_id);
      }
    }
  }

  private function contactHasMoreJoinsThanLeaves($contactId) {
    $query = "SELECT IF(a.activity_type_id = 57, 1, 0) test
              FROM civicrm_activity a
                JOIN civicrm_activity_contact ac ON ac.activity_id = a.id AND ac.contact_id = %1
              WHERE a.activity_type_id IN (56, 57)
              ORDER BY a.id DESC
              LIMIT 1";
    $params = array(
      1 => array($contactId, 'Integer'),
    );
    return (boolean)CRM_Core_DAO::singleValueQuery($query, $params);
  }

  private function addLeave($contactId) {
    $data = array(
      0 => array(
        'id' => $contactId,
        'subject' => 'unsubscribe',
        'activity_date_time' => date('YmdHis'),
      )
    );
    CRM_Speakcivi_Cleanup_Leave::createActivitiesInBatch($data);
  }
}

Add unsubscribe api wrapper (Leave activity)


<?php

namespace Dara\Origins;

use PDO;
use Dotenv\Dotenv;

class Connection extends PDO
{

    protected static $driver;

    protected static $host;

    protected static $dbname;

    protected static $user;

    protected static $pass;

    /**
     * Get environment values from .env file
     *
     * @return null
     */
    public static function getEnv()
    {
        $dotEnv = new Dotenv($_SERVER['DOCUMENT_ROOT']);
        $dotEnv->load();

        self::$driver  = getenv('P_DRIVER');
        self::$host    = getenv('P_HOST');
        self::$dbname  = getenv('P_DBNAME');
        self::$user    = getenv('P_USER');
        self::$pass    = getenv('P_PASS');
    }

    /**
     * Create PDO connections
     *
     * @return PDO
     */
    public static function connect()
    {
        self::getEnv();
        return new PDO(self::$driver.':host='.self::$host.';dbname='.self::$dbname, self::$user, self::$pass);
    }

}

<?php

namespace Dara\Origins;

use PDO;
use Dotenv\Dotenv;

class Connection extends PDO
{

    protected static $driver;

    protected static $host;

    protected static $dbname;

    protected static $user;

    protected static $pass;

    /**
     * Get environment values from .env file
     *
     * @return null
     */
    public static function getEnv()
    {
        if (!isset(getenv('P_DRIVER'))) {

            $dotEnv = new Dotenv($_SERVER['DOCUMENT_ROOT']);
            $dotEnv->load();
        }

        self::$driver  = getenv('P_DRIVER');
        self::$host    = getenv('P_HOST');
        self::$dbname  = getenv('P_DBNAME');
        self::$user    = getenv('P_USER');
        self::$pass    = getenv('P_PASS');
    }

    /**
     * Create PDO connections
     *
     * @return PDO
     */
    public static function connect()
    {
        self::getEnv();
        return new PDO(self::$driver.':host='.self::$host.';dbname='.self::$dbname, self::$user, self::$pass);
    }

}

Allow loadenv to only run if env variables are not set


<?php
class Kwc_Basic_ImageEnlarge_EnlargeTag_ImagePage_Trl_ContentSender extends Kwf_Component_Abstract_ContentSender_Lightbox
{
    protected function _getOptions()
    {
        $dim = $this->_data->parent->getComponent()->getImageDimensions();
        $options = array(
            'width' => $dim['width'],
            'height' => $dim['height'],
            'style' => 'CenterBox' //TODO get from master
        );
        $options['lightboxUrl'] = $this->_data->url;
        return $options;
    }
}

<?php
class Kwc_Basic_ImageEnlarge_EnlargeTag_ImagePage_Trl_ContentSender extends Kwf_Component_Abstract_ContentSender_Lightbox
{
    protected function _getOptions()
    {
        $dim = $this->_data->parent->getComponent()->getImageDimensions();
        $options = array(
            'width' => $dim['width'],
            'height' => $dim['height'],
            'style' => 'CenterBox' //TODO get from master
        );
        $options['adaptHeight'] = true;
        $options['lightboxUrl'] = $this->_data->url;
        return $options;
    }
}

Add adaptHeight as in master

Add adaptHeight as in master

Should be set for images in lightbox


<?php
require "auth.php";
require "password.php";
check_cors();

if($auth)
{
  if(strlen($pwhash) > 0)
  {
    require_once("../../vendor/qrcode.php");
    $qr = QRCode::getMinimumQRCode($pwhash, QR_ERROR_CORRECT_LEVEL_Q);
    $qr->printHTML("10px");
  }
  else
  {
  ?>
No password set<?php
  }
}
else
{
?>
Not authorized!
<?php
}
?>

<?php
require "auth.php";
require "password.php";
check_cors();

if($auth)
{
  if(strlen($pwhash) > 0)
  {
    require_once("../../vendor/qrcode.php");
    $qr = QRCode::getMinimumQRCode($pwhash, QR_ERROR_CORRECT_LEVEL_Q);
    $qr->printHTML("10px");
    print($pwhash);

  }
  else
  {
  ?>
No password set<?php
  }
}
else
{
?>
Not authorized!
<?php
}
?>

Add API Token in Text

Add API Token in Text


<?php

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

namespace Symfony\Bundle\FrameworkBundle\CacheWarmer;

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

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

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

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

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

<?php

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

namespace Symfony\Bundle\FrameworkBundle\CacheWarmer;

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

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

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

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

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

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

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


<?php namespace Jenssegers\Agent;

use Illuminate\Support\ServiceProvider;

class AgentServiceProvider extends ServiceProvider {

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

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

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

}

<?php namespace Jenssegers\Agent;

use Illuminate\Support\ServiceProvider;

class AgentServiceProvider extends ServiceProvider {

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

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

}

Drop the package registration for L5

Drop the package registration for L5


<?php

namespace Screeenly\Services;

use Screeenly\Entities\Url;
use Screeenly\Entities\Screenshot;
use Spatie\Browsershot\Browsershot;
use Screeenly\Contracts\CanCaptureScreenshot;

class ChromeBrowser extends Browser implements CanCaptureScreenshot
{
    public function capture(Url $url, $storageUrl)
    {
        $browser = Browsershot::url($url->getUrl())
            ->ignoreHttpsErrors()
            ->windowSize($this->width, is_null($this->height) ? 768 : $this->height)
            ->timeout(10)
            ->setDelay($this->delay * 100)
            ->userAgent('screeenly-bot 2.0');

        if (is_null($this->height)) {
            $browser->fullPage();
        }

        $browser->save($storageUrl);

        return new Screenshot($storageUrl);
    }
}

<?php

namespace Screeenly\Services;

use Screeenly\Entities\Url;
use Screeenly\Entities\Screenshot;
use Spatie\Browsershot\Browsershot;
use Screeenly\Contracts\CanCaptureScreenshot;

class ChromeBrowser extends Browser implements CanCaptureScreenshot
{
    public function capture(Url $url, $storageUrl)
    {
        $browser = Browsershot::url($url->getUrl())
            ->ignoreHttpsErrors()
            ->windowSize($this->width, is_null($this->height) ? 768 : $this->height)
            ->timeout(30)
            ->setDelay($this->delay * 100)
            ->userAgent('screeenly-bot 2.0');

        if (is_null($this->height)) {
            $browser->fullPage();
        }

        $browser->save($storageUrl);

        return new Screenshot($storageUrl);
    }
}

Increase Timeout to 30 Seconds

Increase Timeout to 30 Seconds


<?php

namespace Oro\Bundle\TranslationBundle\Tests\Unit\Entity;

use Oro\Bundle\OrganizationBundle\Entity\Organization;
use Oro\Bundle\TranslationBundle\Entity\Language;
use Oro\Bundle\UserBundle\Entity\User;

use Oro\Component\Testing\Unit\EntityTestCaseTrait;

class LanguageTest extends \PHPUnit_Framework_TestCase
{
    use EntityTestCaseTrait;

    public function testAccessors()
    {
        $this->assertPropertyAccessors(new Language(), [
            ['id', 1],
            ['code', 'test_code'],
            ['installedBuildDate', new \DateTime()],
            ['owner', new User()],
            ['organization', new Organization()],
            ['createdAt', new \DateTime()],
            ['updatedAt', new \DateTime()],
        ]);
    }
}

<?php

namespace Oro\Bundle\TranslationBundle\Tests\Unit\Entity;

use Oro\Bundle\OrganizationBundle\Entity\Organization;
use Oro\Bundle\TranslationBundle\Entity\Language;
use Oro\Bundle\UserBundle\Entity\User;

use Oro\Component\Testing\Unit\EntityTestCaseTrait;

class LanguageTest extends \PHPUnit_Framework_TestCase
{
    use EntityTestCaseTrait;

    public function testAccessors()
    {
        $this->assertPropertyAccessors(new Language(), [
            ['id', 1],
            ['code', 'test_code'],
            ['enabled', true],
            ['installedBuildDate', new \DateTime()],
            ['owner', new User()],
            ['organization', new Organization()],
            ['createdAt', new \DateTime()],
            ['updatedAt', new \DateTime()],
        ]);
    }
}

BAP-11409: Create Language entity
- updated unit test


<?php

namespace DesignPatterns\Decorator;

/**
 * Class RenderInXml
 */
class RenderInXml extends Decorator
{
    /**
     * render data as XML
     *
     * @return mixed|string
     */
    public function renderData()
    {
        $output = $this->wrapped->renderData();

        // do some fancy conversion to xml from array ...

        $doc = new \DOMDocument();

        foreach ($output as $key => $val) {
            $doc->appendChild($doc->createElement('foo', 'bar'));
        }

        return $doc->saveXML();
    }
}

<?php

namespace DesignPatterns\Decorator;

/**
 * Class RenderInXml
 */
class RenderInXml extends Decorator
{
    /**
     * render data as XML
     *
     * @return mixed|string
     */
    public function renderData()
    {
        $output = $this->wrapped->renderData();

        // do some fancy conversion to xml from array ...

        $doc = new \DOMDocument();

        foreach ($output as $key => $val) {
            $doc->appendChild($doc->createElement($key, $val));
        }

        return $doc->saveXML();
    }
}

Change Hard code by $key, $val

Change Hard code by $key, $val


<?php

namespace mcordingley\Regression\Algorithm\GradientDescent\Gradient;

final class Linear implements Gradient
{
    /** @var int */
    private $power;

    /**
     * @param int $power
     */
    public function __construct($power = 2)
    {
        $this->power = $power;
    }

    /**
     * @param array $coefficients
     * @param array $features
     * @param float $outcome
     * @return float
     */
    public function cost(array $coefficients, array $features, $outcome)
    {
        return abs(pow($this->predicted($coefficients, $features) - $outcome, $this->power));
    }

    /**
     * @param array $coefficients
     * @param array $features
     * @return float
     */
    private function predicted(array $coefficients, array $features)
    {
        return array_sum(array_map(function ($coefficient, $feature) {
            return $coefficient * $feature;
        }, $coefficients, $features));
    }

    /**
     * @param array $coefficients
     * @param array $features
     * @param float $outcome
     * @return array
     */
    public function gradient(array $coefficients, array $features, $outcome)
    {
        $gradient = [];
        $predicted = $this->predicted($coefficients, $features);

        for ($i = 0; $i < count($features); $i++) {
            $gradient[] = $this->power * abs(pow($predicted - $outcome, $this->power - 1)) * $features[$i];
        }

        return $gradient;
    }
}

<?php

namespace mcordingley\Regression\Algorithm\GradientDescent\Gradient;

final class Linear implements Gradient
{
    /** @var int */
    private $power;

    /**
     * @param int $power
     */
    public function __construct($power = 2)
    {
        $this->power = $power;
    }

    /**
     * @param array $coefficients
     * @param array $features
     * @param float $outcome
     * @return float
     */
    public function cost(array $coefficients, array $features, $outcome)
    {
        return pow(abs($this->predicted($coefficients, $features) - $outcome), $this->power);
    }

    /**
     * @param array $coefficients
     * @param array $features
     * @return float
     */
    private function predicted(array $coefficients, array $features)
    {
        return array_sum(array_map(function ($coefficient, $feature) {
            return $coefficient * $feature;
        }, $coefficients, $features));
    }

    /**
     * @param array $coefficients
     * @param array $features
     * @param float $outcome
     * @return array
     */
    public function gradient(array $coefficients, array $features, $outcome)
    {
        $gradient = [];
        $predicted = $this->predicted($coefficients, $features);

        for ($i = 0; $i < count($features); $i++) {
            $gradient[] = $this->power * pow(abs($predicted - $outcome), $this->power - 1) * $features[$i];
        }

        return $gradient;
    }
}

Normalize in the other direction.

Normalize in the other direction.


<?php
/**
 * Loader
 */
$loader->add('Aura\Router\\', dirname(__DIR__) . DIRECTORY_SEPARATOR . 'src');

/**
 * Services
 */
$di->set('router_map', $di->lazyNew('Aura\Router\Map'));

/**
 * Aura\Router\Map
 */
$di->params['Aura\Router\Map'] = [
    'definition_factory' => $di->lazyNew('Aura\Router\DefinitionFactory'),
    'route_factory' => $di->lazyNew('Aura\Router\RouteFactory'),
];

<?php
/**
 * Loader
 */
$loader->add('Aura\Router\\', dirname(__DIR__) . DIRECTORY_SEPARATOR . 'src');

/**
 * Aura\Router\Map
 */
$di->params['Aura\Router\Map'] = [
    'definition_factory' => $di->lazyNew('Aura\Router\DefinitionFactory'),
    'route_factory' => $di->lazyNew('Aura\Router\RouteFactory'),
];

[CFG] Remove 'router_map' service; leave this for the framework-level config


<?php

namespace App\Classes;

use App\Models\Payment;
use Illuminate\Encryption\Encrypter;
use Config;

/**
 * EtuPay helper
 */
class EtuPay
{
    /*
     * Decrypt and do action according to crypted payload content send by a callback
     * @param $payload crypted payload given by a callback from EtuPay
     * @return Payment object
     */
    public static function readCallback($payload)
    {
        $crypt = new Encrypter(base64_decode(Config::get('services.etupay.key')), 'AES-256-CBC');
        $payload = json_decode($crypt->decrypt($payload));
        if ($payload && is_numeric($payload->service_data)) {
            $paymentId = $payload->service_data;
            $payment = Payment::findOrFail($paymentId);

            switch ($payload->step) {
                case 'INITIALISED':
                    $payment->state = 'returned';
                    break;
                case 'PAID':
                case 'AUTHORISATION':
                    $payment->state = 'paid';
                    break;
                case 'REFUSED':
                case 'CANCELED':
                    $payment->state = 'refused';
                    break;
                case 'REFUNDED':
                    $payment->state = 'refunded';
                    break;
            }
            $payment->informations = ['transaction_id' => $payload->transaction_id];
            $payment->save();

            $payment->user->updateWei();

            return $payment;
        }
        return null;
    }
}

<?php

namespace App\Classes;

use App\Models\Payment;
use Illuminate\Encryption\Encrypter;
use Config;

/**
 * EtuPay helper
 */
class EtuPay
{
    /*
     * Decrypt and do action according to crypted payload content send by a callback
     * @param $payload crypted payload given by a callback from EtuPay
     * @return Payment object
     */
    public static function readCallback($payload)
    {
        $crypt = new Encrypter(base64_decode(Config::get('services.etupay.key')), 'AES-256-CBC');
        $payload = json_decode($crypt->decrypt($payload));
        if ($payload && is_numeric($payload->service_data)) {
            $paymentId = $payload->service_data;
            $payment = Payment::findOrFail($paymentId);

            switch ($payload->step) {
                case 'INITIALISED':
                    $payment->state = 'returned';
                    break;
                case 'PAID':
                case 'AUTHORISATION':
                    $payment->state = 'paid';
                    break;
                case 'REFUSED':
                case 'CANCELED':
                    $payment->state = 'refused';
                    break;
                case 'REFUNDED':
                    $payment->state = 'refunded';
                    break;
            }
            $payment->informations = ['transaction_id' => $payload->transaction_id];
            $payment->save();

            if ($payment->user) {
                $payment->user->updateWei();
            }

            return $payment;
        }
        return null;
    }
}

Fix exception when paiement is not binded to user anymore


<?php
namespace Kregel\Radio\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use Kregel\FormModel\Traits\Formable;
use Kregel\Warden\Traits\Wardenable;

class Notification extends Model
{
    use Formable;

    protected $table = 'radio_notifications';

    protected $fillable = [
        'channel_id', 'user_id', 'is_unread', 'name', 'description' , 'link', 'type'
    ];

    public static function boot()
    {
        Notification::created(function (Notification $notify){
            $data = collect($notify->toArray())->merge([
                'uuid' => $notify->user->channel->uuid,
                'is_unread' => 1
            ]);
            Redis::publish($data['uuid'], collect($data));
        });

    }

    protected $casts = [
        'is_unread' => 'bool'
    ];

    public function user()
    {
        return $this->belongsTo(config('auth.providers.users.model'));
    }
}

<?php
namespace Kregel\Radio\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use Kregel\FormModel\Traits\Formable;
use Kregel\Warden\Traits\Wardenable;

class Notification extends Model
{
    use Formable;

    protected $table = 'radio_notifications';

    protected $fillable = [
        'channel_id', 'user_id', 'is_unread', 'name', 'description', 'link', 'type'
    ];

    public static function boot()
    {
        Notification::created(function (Notification $notify) {
            $data = collect($notify->toArray())->merge([
                'uuid' => $notify->channel->uuid,
                'is_unread' => 1
            ]);
            Redis::publish($data['uuid'], collect($data));
        });

    }

    protected $casts = [
        'is_unread' => 'bool'
    ];

    public function user()
    {
        return $this->belongsTo(config('auth.providers.users.model'));
    }

    public function channel()
    {
        return $this->belongsTo(Channel::class);
    }
}

Update ntofication for channel usage and not user channel usage


<?php
namespace Vivo\View\Helper;

use Vivo\UI\Component;

use Zend\View\Helper\AbstractHelper;

/**
 * View helper for gettting action url
 */
class ActionLink extends AbstractHelper
{
    public function __invoke($action, $body, $params = array(), $reuseMatchedParams = false)
    {
        $model = $this->view->plugin('view_model')->getCurrent();
        $component = $model->getVariable('component');

        $act = $component['path'] . Component::COMPONENT_SEPARATOR . $action;
        $urlHelper = $this->getView()->plugin('url');
        $url = $urlHelper(null,
                array('act' => $act, 'args' => $params), $reuseMatchedParams);
        $link = "$body";
        return $link;
    }
}

Replace ' in href attribute

Replace ' in href attribute


<?php
/**
 * Definition of AuthServiceTestBase.php
 *
 * @copyright  2015-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 */

namespace justso\justauth;

use justso\justapi\testutil\ServiceTestBase;
use justso\justapi\testutil\TestEnvironment;

/**
 * Class AuthServiceTestBase
 */
class AuthServiceTestBase extends ServiceTestBase
{
    /**
     * @param TestEnvironment $env
     * @param int $id
     * @return \PHPUnit_FrameWork_MockObject_MockObject
     */
    protected function getMockUser(TestEnvironment $env, $id)
    {
        $user = $this->mockInterface('\\justso\\justauth', 'UserInterface', $env);
        $user->expects($this->any())->method('getId')->willReturn($id);
        return $user;
    }

    /**
     * @param TestEnvironment $env
     * @param UserInterface $user
     */
    protected function setAuthenticatedUser(TestEnvironment $env, UserInterface $user)
    {
        $env->setDICEntry('Authenticator', 'justso\justauth\EMailAuthenticator');
        $env->getSession()->setValue('user', $user);
    }
}

<?php
/**
 * Definition of AuthServiceTestBase.php
 *
 * @copyright  2015-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 */

namespace justso\justauth;

use justso\justapi\testutil\ServiceTestBase;
use justso\justapi\testutil\TestEnvironment;

/**
 * Class AuthServiceTestBase
 */
class AuthServiceTestBase extends ServiceTestBase
{
    /**
     * @param TestEnvironment $env
     * @param int $id
     * @return \PHPUnit_FrameWork_MockObject_MockObject
     */
    protected function getMockUser(TestEnvironment $env, $id)
    {
        $user = $this->mockInterface('\\justso\\justauth', 'UserInterface', $env);
        $user->expects($this->any())->method('getId')->willReturn($id);
        return $user;
    }

    /**
     * @param TestEnvironment $env
     * @param UserInterface $user
     */
    protected function setAuthenticatedUser(TestEnvironment $env, UserInterface $user)
    {
        $authenticator = $this->getMockForAbstractClass('Authenticator');
        $authenticator->expects($this->any())->method('isAuth')->willReturn(true);
        $authenticator->expects($this->any())->method('getUser')->willReturn($user);
        $authenticator->expects($this->any())->method('getUserId')->willReturn($user->getId());
        $env->setDICEntry('Authenticator', $authenticator);
        $env->getSession()->setValue('user', $user);
    }
}

Use mocked Authenticator instead of an instance of EMailAuthenticator to prevent problems with other ojects used by the latter


<?php

/*
 * This file is part of Cachet.
 *
 * (c) James Brooks <james@cachethq.io>
 * (c) Joseph Cohen <joseph.cohen@dinkbit.com>
 * (c) Graham Campbell <graham@mineuk.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CachetHQ\Cachet\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\RedirectResponse;

class RedirectIfAuthenticated
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param Guard $auth
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->check()) {
            return new RedirectResponse(url('/home'));
        }

        return $next($request);
    }
}

<?php

/*
 * This file is part of Cachet.
 *
 * (c) James Brooks <james@cachethq.io>
 * (c) Joseph Cohen <joseph.cohen@dinkbit.com>
 * (c) Graham Campbell <graham@mineuk.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CachetHQ\Cachet\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\RedirectResponse;

class RedirectIfAuthenticated
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param Guard $auth
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->check()) {
            return new RedirectResponse(route('dashboard'));
        }

        return $next($request);
    }
}

Fix RedirectIfAuthenticate middleware redirecting to wrong location


<?php
	#
	# $Id: login.php,v 1.2 2006-12-17 11:55:53 dan Exp $
	#
	# Copyright (c) 1998-2003 DVL Software Limited
	#

	if (IsSet($_GET['origin'])) $origin = $_GET["origin"];
?>
<form action="<?php echo $_SERVER["PHP_SELF"] . "?origin=$origin" ?>" method="POST" name="l">
      <input type="hidden" name="custom_settings" value="1"><input type="hidden" name="LOGIN" value="1">

User ID:

      <input SIZE="15" NAME="UserID" value="<?php if (IsSet($UserID)) echo htmlentities($UserID) ?>">

Password:

      <input TYPE="PASSWORD" NAME="Password" VALUE = "<?php if (IsSet($Password)) echo htmlentities($Password) ?>" size="20">

<input TYPE="submit" VALUE="Login" name=submit>      <input TYPE="reset" VALUE="reset form">
</form>

<?php
	#
	# $Id: login.php,v 1.3 2010-09-17 14:44:38 dan Exp $
	#
	# Copyright (c) 1998-2003 DVL Software Limited
	#

	if (IsSet($_GET['origin'])) $origin = $_GET["origin"];
?>
<form action="<?php echo $_SERVER["PHP_SELF"] . "?origin=$origin" ?>" method="POST" name="l">
      <input type="hidden" name="custom_settings" value="1"><input type="hidden" name="LOGIN" value="1">

User ID:

      <input SIZE="15" NAME="UserID" value="<?php if (IsSet($UserID)) echo htmlentities($UserID) ?>">

Password:

      <input TYPE="PASSWORD" NAME="Password" VALUE = "<?php if (IsSet($Password)) echo htmlentities($Password) ?>" size="20">

<input TYPE="submit" VALUE="Login" name=submit>

      Forgotten your password?

</form>

Remove reset, we don't need that.
Add link to forgotten password

git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@4327 46e82423-29d8-e211-989e-002590a4cdd4


<?php
/**
 * Zym Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @copyright  Copyright (c) 2008 Zym. (http://www.zym-project.com/)
 * @license http://www.zym-project.com/license New BSD License
 */

/**
 * Project Path
 *
 */
define('PATH_PROJECT', dirname(dirname(__FILE__)) . '/');

/**
 * Include paths
 */
include_once PATH_PROJECT . 'config/paths.php';

/**
 * @see Zym_App
 */
require_once 'Zym/App.php';

/**
 * @see Zend_Controller_Front
 */
require_once 'Zend/Controller/Front.php';

Zym_App::run(PATH_PROJECT . 'config/bootstrap.xml', Zym_App::ENV_DEVELOPMENT);
Zend_Controller_Front::getInstance()->dispatch();

<?php
/**
 * Zym Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @copyright  Copyright (c) 2008 Zym. (http://www.zym-project.com/)
 * @license http://www.zym-project.com/license New BSD License
 */

/**
 * Project Path
 *
 */
define('PATH_PROJECT', dirname(dirname(__FILE__)) . '/');

/**
 * Include paths
 */
include_once PATH_PROJECT . 'config/paths.php';

/**
 * @see Zym_App
 */
require_once 'Zym/App.php';

/**
 * @see Zend_Controller_Front
 */
require_once 'Zend/Controller/Front.php';

Zym_App::run(PATH_PROJECT . 'config/bootstrap.xml', Zym_App::ENV_PRODUCTION);
Zend_Controller_Front::getInstance()->dispatch();

Set default environment to production in the demo.

git-svn-id: d32e76a03a3123f3a7fc632f553a4a003f6b8db0@574 242cd0b0-a150-0410-b6ef-417cb531347b


<?php
namespace App\Repositories;

use App\UGC;
use App\User;
use App\Group;
use App\Category;
use DB;
use Response;

?>

<?php
namespace App\Repositories;

use App\UGC;
use App\User;
use App\Group;
use App\Category;
use DB;
use Response;

class UGCRepository {

}

?>

Create a class for UGC Repository

Create a class for UGC Repository


Test for iframe at homepage

Test for iframe at homepage


<?php
/**
 * Redis Object Cache is installed by Composer but we need a helper to
 * auto-activate this plugin.
 */
require WPMU_PLUGIN_DIR.'/redis-cache/redis-cache.php';

<?php
/*
Plugin Name: Redis Object Cache (MU)
Plugin URI: http://wordpress.org/plugins/redis-cache/
Description: A persistent object cache backend powered by Redis. Supports Predis, PhpRedis, HHVM, replication and clustering.
Version: 1.3.2+
Text Domain: redis-cache
Domain Path: /languages
Author: Till Krüss
Author URI: https://till.im/
License: GPLv3
License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/

/**
 * Redis Object Cache is installed by Composer but we need a helper to
 * auto-activate this plugin.
 */
require WPMU_PLUGIN_DIR.'/redis-cache/redis-cache.php';

Add plugin info to our autoload file

Add plugin info to our autoload file


<?php

namespace System\Helpers;

use Igniter\Flame\Support\Facades\File;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;

class CacheHelper
{
    use \Igniter\Flame\Traits\Singleton;

    /**
     * Execute the console command.
     */
    public static function clear()
    {
        Cache::flush();
        self::clearInternal();
    }

    public static function clearInternal()
    {
        $instance = self::instance();
        $instance->clearCache();
        $instance->clearView();
        $instance->clearTemplates();

        $instance->clearCombiner();

        $instance->clearMeta();
    }

    public function clearView()
    {
        $path = config()->get('view.compiled');
        foreach (File::glob("{$path}/*") as $view) {
            File::delete($view);
        }
    }

    public function clearCombiner()
    {
        $this->clearDirectory('/system/combiner');
    }

    public function clearCache()
    {
        $this->clearDirectory('/system/cache');
    }

    public function clearTemplates()
    {
        $this->clearDirectory('/system/templates');
    }

    public function clearMeta()
    {
        File::delete(App::getCachedClassesPath());
        File::delete(App::getCachedServicesPath());
    }

    public function clearDirectory($path)
    {
        foreach (File::directories(storage_path().$path) as $directory) {
            File::deleteDirectory($directory);
        }
    }
}

<?php

namespace System\Helpers;

use Igniter\Flame\Support\Facades\File;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;

class CacheHelper
{
    use \Igniter\Flame\Traits\Singleton;

    /**
     * Execute the console command.
     */
    public static function clear()
    {
        Cache::flush();
        self::clearInternal();
    }

    public static function clearInternal()
    {
        $instance = self::instance();
        $instance->clearCache();
        $instance->clearView();
        $instance->clearTemplates();

        $instance->clearCombiner();

        $instance->clearMeta();
    }

    public function clearView()
    {
        $path = config()->get('view.compiled');
        foreach (File::glob("{$path}/*") as $view) {
            File::delete($view);
        }
    }

    public function clearCombiner()
    {
        $this->clearDirectory('/system/combiner');
    }

    public function clearCache()
    {
        $this->clearDirectory('/system/cache');
    }

    public function clearTemplates()
    {
        $this->clearDirectory('/system/templates');
    }

    public function clearMeta()
    {
        File::delete(App::getCachedClassesPath());
        File::delete(App::getCachedServicesPath());
    }

    public function clearDirectory($path)
    {
        if (!File::isDirectory(storage_path().$path))
            return;

        foreach (File::directories(storage_path().$path) as $directory) {
            File::deleteDirectory($directory);
        }
    }
}

Fix error with file not found when clearing templates cache

Signed-off-by: Sam Poyigi <ccc2dd82f84c4106203d3b58d5938b70cab9f94a@users.noreply.github.com>


<?php

namespace App\Providers;

use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any application authentication / authorization services.
     *
     * @param  \Illuminate\Contracts\Auth\Access\Gate  $gate
     * @return void
     */
    public function boot(GateContract $gate)
    {
        parent::registerPolicies($gate);

        //
    }
}

<?php

namespace App\Providers;

use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any application authentication / authorization services.
     *
     * @param  \Illuminate\Contracts\Auth\Access\Gate  $gate
     * @return void
     */
    public function boot(GateContract $gate)
    {
        $this->registerPolicies($gate);

        //
    }
}

Use $this instead of parent.

Use $this instead of parent.

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


                {!! Form::open(['route' => 'blog::admin.auth.logout.post']) !!}
                <button type="submit" class="btn btn-link nav-link">Log out</button>
                {!! Form::close() !!}

                {!! Form::open(['route' => 'blog::admin.auth.logout.post']) !!}
                <button type="submit" class="btn-link nav-link">Log out</button>
                {!! Form::close() !!}

Fix log out link spacing

Fix log out link spacing


<?php

class SiteDeployCommand extends Command {
	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'site:deploy';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Deploy the site on live';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{

	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return [];
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return [];
	}
}

<?php

class SiteDeployCommand extends Command {
	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'site:deploy';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Deploy the site on live';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
		SSH::run([
			"php artisan down",
			"git pull origin develop",
			"composer update",
			"php artisan up",
		]);
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return [];
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return [];
	}
}

Add SSH task to deployment

Add SSH task to deployment


<?php
namespace Muffin\Hits\Model\Behavior\Strategy;

use Cake\Database\Expression\QueryExpression;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;

class DefaultStrategy extends AbstractStrategy
{
    protected $_conditions;
    protected $_offset;

    public function __construct(array $conditions = [], $offset = 1)
    {
        $this->_conditions = $conditions;
        $this->$_offset = 1;
    }

    public function increment(Table $table, $counter, $identifier)
    {
        list($alias, $field) = $this->_counterSplit($counter);
        $conditions = [$table->aliasField($table->primaryKey()) => $identifier];
        if ($table->alias() !== $alias) {
            $conditions = [];
            $table = TableRegistry::get($alias);
        }

        $expression = new QueryExpression("$field = $field + " . $this->_offset);
        return $table->updateAll($expression, $conditions + $this->_conditions);
    }
}

<?php
namespace Muffin\Hits\Model\Behavior\Strategy;

use Cake\Database\Expression\QueryExpression;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;

class DefaultStrategy extends AbstractStrategy
{
    protected $_conditions;
    protected $_offset;

    public function __construct(array $conditions = [], $offset = 1)
    {
        $this->_conditions = $conditions;
        $this->$_offset = 1;
    }

    public function increment(Table $table, $counter, $identifier)
    {
        list($alias, $field) = $this->_counterSplit($counter);
        $key = $table->primaryKey();
        if ($table->alias() !== $alias) {
            $key = $table->$alias->bindingKey();
            $table = TableRegistry::get($alias);
        }

        $expression = new QueryExpression("$field = $field + " . $this->_offset);
        $conditions = [$key => $identifier] + $this->_conditions;
        return $table->updateAll($expression, $conditions);
    }
}

Add bindingKey to detached counters conditions


<?php

namespace mcordingley\Regression\Algorithm\GradientDescent;

use mcordingley\Regression\Observations;

final class Stochastic extends GradientDescent
{
    /**
     * @param Observations $observations
     * @param array $coefficients
     * @return array
     */
    protected function calculateGradient(Observations $observations, array $coefficients)
    {
        $observation = $observations->getObservation(mt_rand(0, count($observations) - 1));
        return $this->gradient->gradient($coefficients, $observation->getFeatures(), $observation->getOutcome());
    }
}

<?php

namespace mcordingley\Regression\Algorithm\GradientDescent;

use mcordingley\Regression\Observation;
use mcordingley\Regression\Observations;

final class Stochastic extends GradientDescent
{
    /** @var array */
    private $shuffled;

    /**
     * @param Observations $observations
     * @param array $coefficients
     * @return array
     */
    protected function calculateGradient(Observations $observations, array $coefficients)
    {
        $observation = $this->getObservation($observations);

        return $this->gradient->gradient($coefficients, $observation->getFeatures(), $observation->getOutcome());
    }

    /**
     * @param Observations $observations
     * @return Observation
     */
    private function getObservation(Observations $observations)
    {
        if (!$this->shuffled) {
            $this->shuffled = range(0, count($observations) - 1);
            shuffle($this->shuffled);
        }

        return $observations->getObservation(array_pop($this->shuffled));
    }
}

Modify the SGD to sweep through the training set in random order instead of doing random draws.


<?php

namespace spec\PhpSpec\Wrapper\Subject\Expectation;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

use PhpSpec\Wrapper\Subject\Expectation\ExpectationInterface;

class ConstructorDecoratorSpec extends ObjectBehavior
{
    function let(ExpectationInterface $expectation)
    {
        $this->beConstructedWith($expectation);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('PhpSpec\Wrapper\Subject\Expectation\ExpectationInterface');
    }

}

<?php

namespace spec\PhpSpec\Wrapper\Subject\Expectation;

use PhpSpec\ObjectBehavior;
use PhpSpec\Wrapper\Subject;
use PhpSpec\Wrapper\Subject\WrappedObject;
use Prophecy\Argument;

use PhpSpec\Wrapper\Subject\Expectation\ExpectationInterface;

class ConstructorDecoratorSpec extends ObjectBehavior
{
    function let(ExpectationInterface $expectation)
    {
        $this->beConstructedWith($expectation);
    }

    function it_rethrows_php_errors_as_phpspec_error_exceptions(Subject $subject, WrappedObject $wrapped)
    {
        // calling $subject->getWrappedObject() actually breaks Collaborator
        // as there is a method with that name on it.
        // One of the odds of testing a framework with itself
        $subject->__call('getWrappedObject', array())->willThrow('PhpSpec\Exception\Example\ErrorException');
        $this->shouldThrow('PhpSpec\Exception\Example\ErrorException')->duringMatch('be', $subject, array(), $wrapped);
    }

    function it_ignores_any_other_exception(Subject $subject, WrappedObject $wrapped)
    {
        $subject->__call('getWrappedObject', array())->willThrow('\Exception');
        $wrapped->getClassName()->willReturn('\ArrayObject');
        $this->shouldNotThrow('\Exception')->duringMatch('be', $subject, array(), $wrapped);
    }

}

Add missing specs for constructor decorator


<?php
use Concrete\Core\Support\Facade\Application;

defined('C5_EXECUTE') or die('Access Denied.');

// Arguments
/* @var bool $disableTrackingCode: set to true to avoid including the footer tracking code. */
/* @var bool $display_account_menu: set to true to display the user menu, false to avoid it, null (or not set) to use the default confguration option. */

$app = Application::getFacadeApplication();
$c = Page::getCurrentPage();
$site = $app->make('site')->getSite();
$config = $site->getConfigRepository();

if (is_object($c)) {
    $cp = new Permissions($c);
    View::element('page_controls_footer', ['cp' => $cp, 'c' => $c]);
}

if (empty($disableTrackingCode)) {
    echo $config->get('seo.tracking.code.footer');
}

View::getInstance()->markFooterAssetPosition();

if (!isset($display_account_menu)) {
    $display_account_menu = $config->get('user.display_account_menu');
}
if ($display_account_menu) {
    $dh = $app->make('helper/concrete/dashboard');
    if (!$dh->inDashboard($c)) {
        View::element('account/menu');
    }
}

<?php
use Concrete\Core\Localization\Localization;
use Concrete\Core\Support\Facade\Application;

defined('C5_EXECUTE') or die('Access Denied.');

// Arguments
/* @var bool $disableTrackingCode: set to true to avoid including the footer tracking code. */
/* @var bool $display_account_menu: set to true to display the user menu, false to avoid it, null (or not set) to use the default confguration option. */

$app = Application::getFacadeApplication();
$c = Page::getCurrentPage();
$site = $app->make('site')->getSite();
$config = $site->getConfigRepository();
$localization = Localization::getInstance();

if (is_object($c)) {
    $cp = new Permissions($c);
    $localization->pushActiveContext(Localization::CONTEXT_UI);
    try {
        View::element('page_controls_footer', ['cp' => $cp, 'c' => $c]);
    } finally {
        $localization->popActiveContext();
    }
}

if (empty($disableTrackingCode)) {
    echo $config->get('seo.tracking.code.footer');
}

View::getInstance()->markFooterAssetPosition();

if (!isset($display_account_menu)) {
    $display_account_menu = $config->get('user.display_account_menu');
}
if ($display_account_menu) {
    $dh = $app->make('helper/concrete/dashboard');
    if (!$dh->inDashboard($c)) {
        $localization->pushActiveContext(Localization::CONTEXT_UI);
        try {
            View::element('account/menu');
        } finally {
            $localization->popActiveContext();
        }
    }
}

Use UI localization context in concrete5 toolbar/account menu


<?php

final class PhabricatorAuthProviderOAuthGoogle
  extends PhabricatorAuthProviderOAuth {

  public function getProviderName() {
    return pht('Google');
  }

  public function getConfigurationHelp() {
    $login_uri = PhabricatorEnv::getURI($this->getLoginURI());

    return pht(
      "To configure Google OAuth, create a new 'API Project' here:".
      "\n\n".
      "https://code.google.com/apis/console/".
      "\n\n".
      "You don't need to enable any Services, just go to **API Access**, ".
      "click **Create an OAuth 2.0 client ID...**, and configure these ".
      "settings:".
      "\n\n".
      "  - During initial setup click **More Options** (or after creating ".
      "    the client ID, click **Edit Settings...**), then add this to ".
      "    **Authorized Redirect URIs**: `%s`\n".
      "\n\n".
      "After completing configuration, copy the **Client ID** and ".
      "**Client Secret** to the fields above.",
      $login_uri);
  }

  protected function newOAuthAdapter() {
    return new PhutilAuthAdapterOAuthGoogle();
  }

  protected function getLoginIcon() {
    return 'Google';
  }

  public function getLoginURI() {
    // TODO: Clean this up. See PhabricatorAuthOldOAuthRedirectController.
    return '/oauth/google/login/';
  }

}

<?php

final class PhabricatorAuthProviderOAuthGoogle
  extends PhabricatorAuthProviderOAuth {

  public function getProviderName() {
    return pht('Google');
  }

  public function getConfigurationHelp() {
    $login_uri = PhabricatorEnv::getURI($this->getLoginURI());

    return pht(
      "To configure Google OAuth, create a new 'API Project' here:".
      "\n\n".
      "https://console.developers.google.com/".
      "\n\n".
      "Adjust these configuration settings for your project:".
      "\n\n".
      "  - Under **APIs & auth > APIs**, scroll down the list and enable ".
      "    the **Google+ API**.\n".
      "  - Under **APIs & auth > Credentials**, click **Create New Client".
      "    ID** in the **OAuth** section. Then use these settings:\n".
      "     - **Application Type**: Web Application\n".
      "     - **Authorized Javascript origins**: Leave this empty.\n".
      "     - **Authorized redirect URI**: Set this to `%s`.\n".
      "\n\n".
      "After completing configuration, copy the **Client ID** and ".
      "**Client Secret** from the Google console to the fields above.",
      $login_uri);
  }

  protected function newOAuthAdapter() {
    return new PhutilAuthAdapterOAuthGoogle();
  }

  protected function getLoginIcon() {
    return 'Google';
  }

  public function getLoginURI() {
    // TODO: Clean this up. See PhabricatorAuthOldOAuthRedirectController.
    return '/oauth/google/login/';
  }

}

Update Google auth documentation to discuss "Google+ API" and new console URI

Summary: Fixes T4451. See also D8612.

Test Plan: Viewed panel and read text, saw it matched up with the new console.

Reviewers: btrahan

Reviewed By: btrahan

Subscribers: epriestley

Maniphest Tasks: T4451

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


<?php

namespace oopapi;

class NonInvokableException extends \Exception {
    public function __construct($class) {
        parent::__construct("Class $class does not implement interface Invokable");
    }
}

<?php

namespace oopapi;

class NonInvokableException extends \Exception {
    protected $class;

    public function __construct($class) {
        $this->class = $class;
        parent::__construct("Class $class does not implement interface Invokable");
    }

    public function getClass() {
        return $this->class;
    }
}

Add protected property 'class' and its getter getClass()


<?php

namespace ParserReflection\Stub;

abstract class AbstractClassWithMethods
{
    const TEST = 5;

    public function __construct(){}
    public function __destruct(){}
    public function explicitPublicFunc(){}
    function implicitPublicFunc(){}
    protected function protectedFunc(){}
    private function privateFunc(){}
    static function staticFunc(){}
    abstract function abstractFunc();
    final function finalFunc(){}

    /**
     * @return string
     */
    public function funcWithDocAndBody()
    {
        static $a =5, $test = '1234';

        return 'hello';
    }

    /**
     * @return \Generator
     */
    public function generatorYieldFunc()
    {
        $index = 0;
        while ($index < 1e3) {
            yield $index;
        }
    }

    /**
     * @return int
     */
    public function noGeneratorFunc()
    {
        $gen = function () {
            yield 10;
        };

        return 10;
    }

    private function testParam($a, $b = null, $c = self::class, $d = self::TEST) {}
}

<?php

namespace ParserReflection\Stub;

/**
 * @link https://bugs.php.net/bug.php?id=70957 self::class can not be resolved with reflection for abstract class
 */
abstract class AbstractClassWithMethods
{
    const TEST = 5;

    public function __construct(){}
    public function __destruct(){}
    public function explicitPublicFunc(){}
    function implicitPublicFunc(){}
    protected function protectedFunc(){}
    private function privateFunc(){}
    static function staticFunc(){}
    abstract function abstractFunc();
    final function finalFunc(){}

    /**
     * @return string
     */
    public function funcWithDocAndBody()
    {
        static $a =5, $test = '1234';

        return 'hello';
    }

    /**
     * @return \Generator
     */
    public function generatorYieldFunc()
    {
        $index = 0;
        while ($index < 1e3) {
            yield $index;
        }
    }

    /**
     * @return int
     */
    public function noGeneratorFunc()
    {
        $gen = function () {
            yield 10;
        };

        return 10;
    }

    private function testParam($a, $b = null, $d = self::TEST) {}
}

Exclude a parameter with default value equals to self::class to avoid crash on 5.6

See https://bugs.php.net/bug.php?id=70957 for detail


<?php

namespace Bolt\Extension\Bolt\Members\Oauth2\Handler;

use Symfony\Component\HttpFoundation\Request;

/**
 * OAuth local login provider.
 *
 * Copyright (C) 2014-2016 Gawain Lynch
 *
 * @author    Gawain Lynch <gawain.lynch@gmail.com>
 * @copyright Copyright (c) 2014-2016, Gawain Lynch
 * @license   https://opensource.org/licenses/MIT MIT
 */
class Local extends HandlerBase
{
    /**
     * {@inheritdoc}
     */
    public function login(Request $request)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function process(Request $request, $grantType = 'authorization_code')
    {
    }

    /**
     * {@inheritdoc}
     */
    public function logout(Request $request)
    {
    }
}

<?php

namespace Bolt\Extension\Bolt\Members\Oauth2\Handler;

use Symfony\Component\HttpFoundation\Request;

/**
 * OAuth local login provider.
 *
 * Copyright (C) 2014-2016 Gawain Lynch
 *
 * @author    Gawain Lynch <gawain.lynch@gmail.com>
 * @copyright Copyright (c) 2014-2016, Gawain Lynch
 * @license   https://opensource.org/licenses/MIT MIT
 */
class Local extends HandlerBase
{
    /**
     * {@inheritdoc}
     */
    public function login(Request $request)
    {
        if (parent::login($request)) {
            return;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function process(Request $request, $grantType = 'authorization_code')
    {
        parent::process($request, $grantType);
    }

    /**
     * {@inheritdoc}
     */
    public function logout(Request $request)
    {
        parent::logout($request);
    }
}

Make local provider should call parent methods


<?php
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/Live/Objects/LiveTransmition.php';
$t = LiveTransmition::getValidPlayURL($_GET['playURL']);
if ($t){
   header('location: '.$t);
}else{
    die("Not allow to play this stream on {$_SERVER['HTTP_HOST']}");
}
?>

<?php
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/Live/Objects/LiveTransmition.php';
$t = LiveTransmition::getValidPlayURL($_GET['playURL']);
if ($t){
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header("Cache-Control: no-store, no-cache,must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0",false);
    header("Pragma: no-cache");
    header('Content-type:application/force-download');
    header('Content-Disposition: attachment; filename=YouPHPTube_Stream');
    header('Content-Length: ' . filesize($t));
    header('Content-Type: '.mime_content_type($t));
   echo file_get_contents($t);
}else{
    die("Not allow to play this stream on {$_SERVER['HTTP_HOST']}");
}
?>

Hide Live Stream URL, making it valid for 10 seconds


<?php

define('JAVA_PATH', '/usr/bin/java');
define('FFF_PATH', dirname(dirname(__FILE__)));
define('CLASSPATH', FFF_PATH . '/itext.jar:' . FFF_PATH . '/json-org.jar:' . FFF_PATH . '/');

$template_tmp = isset($_FILES['template']['tmp_name']) ? $_FILES['template']['tmp_name'] : '';
$config_tmp = isset($_FILES['config']['tmp_name']) ? $_FILES['config']['tmp_name'] : '';

$template = tempnam('/tmp', 'FFF');
$config = tempnam('/tmp', 'FFF');
$output = tempnam('/tmp', 'FFF');

// Move uploaded files, otherwise they may be deleted before we call FFF
move_uploaded_file($template_tmp, $template);
move_uploaded_file($config_tmp, $config);

$execstr = JAVA_PATH . ' -classpath ' . CLASSPATH . " FormFillFlatten $config $template $output";

exec($execstr);

echo file_get_contents($output);

?>

<?php

define('JAVA_PATH', '/usr/bin/java');
define('TMP_DIR', '/tmp');
define('FFF_PATH', dirname(dirname(__FILE__)));
define('CLASSPATH', FFF_PATH . '/itext.jar:' . FFF_PATH . '/json-org.jar:' . FFF_PATH . '/');

$template_tmp = isset($_FILES['template']['tmp_name']) ? $_FILES['template']['tmp_name'] : '';
$config_tmp = isset($_FILES['config']['tmp_name']) ? $_FILES['config']['tmp_name'] : '';

$template = tempnam(TMP_DIR, 'FFF');
$config = tempnam(TMP_DIR, 'FFF');
$output = tempnam(TMP_DIR, 'FFF');

// Move uploaded files, otherwise they may be deleted before we call FFF
move_uploaded_file($template_tmp, $template);
move_uploaded_file($config_tmp, $config);

$execstr = JAVA_PATH . ' -classpath ' . CLASSPATH . " FormFillFlatten $config $template $output";

exec($execstr);

echo file_get_contents($output);

?>

Move temporary directory location into a constant


<?php
/**
 * Created by PhpStorm.
 * User: jesper
 * Date: 2015-01-27
 * Time: 15:52
 */

class Billmate_PartPayment_Block_Adminhtml_System_Config_Form_Updateplans extends Mage_Adminhtml_Block_System_Config_Form_Field
{
    protected function _construct()
    {
        parent::_construct();
        $this->setTemplate('billmate/system/config/updateplans.phtml');
    }

    protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
    {
        return $this->_toHtml();
    }

    public function getAjaxCheckUrl()
    {
        return Mage::helper('adminhtml')->getUrl('adminhtml/adminhtml_billmatepartpayment/updateplans');
    }

    public function getButtonHtml()
    {
        $button = $this->getLayout()->createBlock('adminhtml/widget_button')
            ->setData(array(
                'id' => 'partpayment_update',
                'label' => $this->helper('adminhtml')->__('Update'),
                'onclick' => 'javascript:updateplans(); return false'
            ));
        return $button->toHtml();
    }

}

<?php
/**
 * Created by PhpStorm.
 * User: jesper
 * Date: 2015-01-27
 * Time: 15:52
 */

class Billmate_PartPayment_Block_Adminhtml_System_Config_Form_Updateplans extends Mage_Adminhtml_Block_System_Config_Form_Field
{
    protected function _construct()
    {
        parent::_construct();
        $this->setTemplate('billmate/system/config/updateplans.phtml');
    }

    protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
    {
        return $this->_toHtml();
    }

    public function getAjaxCheckUrl()
    {
        return Mage::helper('adminhtml')->getUrl('adminhtml/adminhtml_billmatepartpayment/updateplans',array('_secure' => true));
    }

    public function getButtonHtml()
    {
        $button = $this->getLayout()->createBlock('adminhtml/widget_button')
            ->setData(array(
                'id' => 'partpayment_update',
                'label' => $this->helper('adminhtml')->__('Update'),
                'onclick' => 'javascript:updateplans(); return false'
            ));
        return $button->toHtml();
    }

}

Fix for https ajax request update payment plans


<?php

namespace Moxl\Xec\Action\Disco;

use Moxl\Xec\Action;
use Moxl\Xec\Action\Disco\Request;
use Moxl\Stanza\Disco;

class Items extends Action
{
    private $_to;

    public function request()
    {
        $this->store();
        Disco::items($this->_to);
    }

    public function setTo($to)
    {
        $this->_to = echapJid($to);
        return $this;
    }

    public function handle($stanza, $parent = false) {
        $nd = new \Modl\ItemDAO();

        foreach($stanza->query->item as $item) {
            $n = new \Modl\Item();
            $n->set($item, $this->_to);
            if(substr($n->node, 0, 29) != 'urn:xmpp:microblog:0:comments')
                $nd->set($n, true);

            $r = new Request;
            $r->setTo($n->jid)
              ->request();
        }

        $this->pack($this->_to);
        $this->deliver();
    }

    public function error($error) {
        $this->pack($this->_to);
        $this->deliver();
    }
}

<?php

namespace Moxl\Xec\Action\Disco;

use Moxl\Xec\Action;
use Moxl\Xec\Action\Disco\Request;
use Moxl\Stanza\Disco;

class Items extends Action
{
    private $_to;

    public function request()
    {
        $this->store();
        Disco::items($this->_to);
    }

    public function setTo($to)
    {
        $this->_to = echapJid($to);
        return $this;
    }

    public function handle($stanza, $parent = false) {
        $nd = new \Modl\ItemDAO();

        $jid = null;

        foreach($stanza->query->item as $item) {
            $n = new \Modl\Item();
            $n->set($item, $this->_to);
            if(substr($n->node, 0, 29) != 'urn:xmpp:microblog:0:comments')
                $nd->set($n, true);

            if($n->jid != $jid) {
                $r = new Request;
                $r->setTo($n->jid)
                  ->request();
            }

            $jid = $n->jid;
        }

        $this->pack($this->_to);
        $this->deliver();
    }

    public function error($error) {
        $this->pack($this->_to);
        $this->deliver();
    }
}

Fix a loop issue (doing several time the same request to the server)


<?php

namespace Sellsy\Criteria\Generic;

use Sellsy\Criteria\CriteriaInterface;

/**
 * Class GetListCriteria
 * @package Sellsy\Criteria\Generic
 */
abstract class GetListCriteria implements CriteriaInterface
{
    /**
     * @var array
     */
    protected $tags;

    /**
     * @param string $tag
     * @return $this
     */
    public function addTag($tag)
    {
        $this->tags[] = $tag;
        return $this;
    }

    /**
     * @param array $tags
     * @return $this
     */
    public function setTags(array $tags)
    {
        $this->tags = $tags;
        return $this;
    }

    /**
     * @return $this
     */
    public function clearTags()
    {
        $this->tags = array();
        return $this;
    }

    /**
     * @return array
     */
    public function getTags()
    {
        return $this->tags;
    }
}

<?php

namespace Sellsy\Criteria\Generic;

use Sellsy\Criteria\CriteriaInterface;
use Sellsy\Models\SmartTags\TagInterface;

/**
 * Class GetListCriteria
 * @package Sellsy\Criteria\Generic
 */
abstract class GetListCriteria implements CriteriaInterface
{
    /**
     * @var array
     */
    protected $tags;

    /**
     * @param string $tag
     * @return $this
     */
    public function addTag($tag)
    {
        if ($tag instanceof TagInterface) {
            $tag = $tag->getName();
        }

        $this->tags[] = $tag;
        return $this;
    }

    /**
     * @param array $tags
     * @return $this
     */
    public function setTags(array $tags)
    {
        $this->clearTags();

        foreach($tags as $tag) {
            $this->addTag($tag);
        }

        return $this;
    }

    /**
     * @return $this
     */
    public function clearTags()
    {
        $this->tags = array();
        return $this;
    }

    /**
     * @return array
     */
    public function getTags()
    {
        return $this->tags;
    }
}

Improve tag handling in criteria

Improve tag handling in criteria


<?php

namespace Smartbox\Integration\FrameworkBundle\Core\Processors\ControlFlow;

use Smartbox\CoreBundle\Type\SerializableArray;
use Smartbox\Integration\FrameworkBundle\Core\Exchange;
use Smartbox\Integration\FrameworkBundle\Core\Processors\Exceptions\DelayException;
use Smartbox\Integration\FrameworkBundle\Core\Processors\Exceptions\ThrottledException;
use Smartbox\Integration\FrameworkBundle\Core\Processors\Exceptions\ThrottlingLimitReachedException;
use Smartbox\Integration\FrameworkBundle\Core\Processors\Processor;

class DelayInterceptor extends Processor
{
    protected $delayPeriod = 0;

    /**
     * @return bool
     */
    public function isRuntimeBreakpoint()
    {
        return $this->runtimeBreakpoint;
    }

    /**
     * @param bool $runtimeBreakpoint
     */
    public function setRuntimeBreakpoint($runtimeBreakpoint)
    {
        $this->runtimeBreakpoint = $runtimeBreakpoint;
    }

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

    /**
     * @param int $periodMs
     */
    public function setDelayPeriod(int $delayPeriod)
    {
        $this->delayPeriod = $delayPeriod;
    }

    /**
     * @param Exchange          $exchange
     * @param SerializableArray $processingContext
     *
     * @throws ThrottlingLimitReachedException
     * @throws ThrottledException
     */
    protected function doProcess(Exchange $exchange, SerializableArray $processingContext)
    {
        throw new DelayException();
    }
}

<?php

namespace Smartbox\Integration\FrameworkBundle\Core\Processors\ControlFlow;

use Smartbox\CoreBundle\Type\SerializableArray;
use Smartbox\Integration\FrameworkBundle\Core\Exchange;
use Smartbox\Integration\FrameworkBundle\Core\Processors\Exceptions\DelayException;
use Smartbox\Integration\FrameworkBundle\Core\Processors\Exceptions\ThrottledException;
use Smartbox\Integration\FrameworkBundle\Core\Processors\Exceptions\ThrottlingLimitReachedException;
use Smartbox\Integration\FrameworkBundle\Core\Processors\Processor;

class DelayInterceptor extends Processor
{
    protected $delayPeriod = 0;

    /**
     * @return bool
     */
    public function isRuntimeBreakpoint()
    {
        return $this->runtimeBreakpoint;
    }

    /**
     * @param bool $runtimeBreakpoint
     */
    public function setRuntimeBreakpoint($runtimeBreakpoint)
    {
        $this->runtimeBreakpoint = $runtimeBreakpoint;
    }

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

    /**
     * @param int $periodMs
     */
    public function setDelayPeriod(int $delayPeriod)
    {
        $this->delayPeriod = $delayPeriod;
    }

    /**
     * @param Exchange          $exchange
     * @param SerializableArray $processingContext
     *
     * @throws ThrottlingLimitReachedException
     * @throws ThrottledException
     */
    protected function doProcess(Exchange $exchange, SerializableArray $processingContext)
    {
        if ($this->delayPeriod > 0 || $exchange->getIn()->getHeader('delay') > 0) {
            throw new DelayException();
        }
    }
}

Add logic check to only throw DelayException if required


<?php

declare(strict_types=1);

namespace App\Controller\Api\Stations\Podcasts\Episodes\Media;

use App\Entity;
use App\Flysystem\StationFilesystems;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;

class GetMediaAction
{
    public function __invoke(
        ServerRequest $request,
        Response $response,
        Entity\Repository\PodcastEpisodeRepository $episodeRepo,
        string $episode_id
    ): ResponseInterface {
        set_time_limit(600);

        $station = $request->getStation();
        $episode = $episodeRepo->fetchEpisodeForStation($station, $episode_id);

        if ($episode instanceof Entity\PodcastEpisode) {
            $podcastMedia = $episode->getMedia();

            if ($podcastMedia instanceof Entity\PodcastMedia) {
                $fsPodcasts = (new StationFilesystems($station))->getPodcastsFilesystem();

                $path = $podcastMedia->getPath();

                if ($fsPodcasts->fileExists($path)) {
                    $fileMeta = $fsPodcasts->getMetadata($path);
                    $filename = $podcastMedia->getOriginalName() . '.' . $fileMeta['extension'];

                    return $response->streamFilesystemFile(
                        $fsPodcasts,
                        $path,
                        $filename
                    );
                }
            }
        }

        return $response->withStatus(404)
            ->withJson(new Entity\Api\Error(404, 'Media file not found.'));
    }
}

<?php

declare(strict_types=1);

namespace App\Controller\Api\Stations\Podcasts\Episodes\Media;

use App\Entity;
use App\Flysystem\StationFilesystems;
use App\Http\Response;
use App\Http\ServerRequest;
use Psr\Http\Message\ResponseInterface;

class GetMediaAction
{
    public function __invoke(
        ServerRequest $request,
        Response $response,
        Entity\Repository\PodcastEpisodeRepository $episodeRepo,
        string $episode_id
    ): ResponseInterface {
        set_time_limit(600);

        $station = $request->getStation();
        $episode = $episodeRepo->fetchEpisodeForStation($station, $episode_id);

        if ($episode instanceof Entity\PodcastEpisode) {
            $podcastMedia = $episode->getMedia();

            if ($podcastMedia instanceof Entity\PodcastMedia) {
                $fsPodcasts = (new StationFilesystems($station))->getPodcastsFilesystem();

                $path = $podcastMedia->getPath();

                if ($fsPodcasts->fileExists($path)) {
                    return $response->streamFilesystemFile(
                        $fsPodcasts,
                        $path,
                        $podcastMedia->getOriginalName()
                    );
                }
            }
        }

        return $response->withStatus(404)
            ->withJson(new Entity\Api\Error(404, 'Media file not found.'));
    }
}

Fix double-stacking of file extension in podcast episode download.


<?php
namespace UNL\UCBCN\Calendar;

use UNL\UCBCN\ActiveRecord\Record;

/**
 * Table Definition for subscription
 */
class SubscriptionHasCalendar extends Record
{
    public $id;                              // int(10)  not_null primary_key unsigned auto_increment
    public $subscription_id;                // int(10)  not_null multiple_key unsigned
    public $calendar_id;                     // int(10)  not_null multiple_key unsigned

    public static function getTable()
    {
        return 'subscription_has_calendar';
    }

    function table()
    {
        return array(
            'id'=>129,
            'subscription_id'=>129,
            'calendar_id'=>129
        );
    }

    function keys()
    {
        return array(
            'id',
        );
    }

    function sequenceKey()
    {
        return array('id',true);
    }

    function links()
    {
        return array('calendar_id'    => 'calendar:id',
                     'subscription_id'     => 'subscription:id');
    }
}

<?php
namespace UNL\UCBCN\Calendar;

use UNL\UCBCN\ActiveRecord\Record;

/**
 * Table Definition for subscription
 */
class SubscriptionHasCalendar extends Record
{
    public $id;                              // int(10)  not_null primary_key unsigned auto_increment
    public $subscription_id;                // int(10)  not_null multiple_key unsigned
    public $calendar_id;                     // int(10)  not_null multiple_key unsigned

    public static function getTable()
    {
        return 'subscription_has_calendar';
    }

    function keys()
    {
        return array(
            'id',
        );
    }
}

Remove methods from sub has calendar

Remove methods from sub has calendar


<?php
/*********************
Enqueue the proper CSS
if you use Sass.
*********************/
function reverie_enqueue_style()
{
	// foundation stylesheet
	wp_register_style( 'reverie-foundation-stylesheet', get_template_directory_uri() . '/css/app.css', array(), '' );

	// Register the main style
	wp_register_style( 'reverie-stylesheet', get_template_directory_uri() . '/css/style.css', array(), '', 'all' );

	wp_enqueue_style( 'reverie-foundation-stylesheet' );
	wp_enqueue_style( 'reverie-stylesheet' );

	// Register child theme style if using child theme
	if ( is_child_theme() ) {

		wp_register_style( 'reverie-child-stylesheet', get_stylesheet_directory_uri() . '/style.css', array(), '', 'all' );

		wp_enqueue_style( 'reverie-child-stylesheet' );
	}
}
add_action( 'wp_enqueue_scripts', 'reverie_enqueue_style' );
?>

<?php
/*********************
Enqueue the proper CSS
if you use Sass.
*********************/
function reverie_enqueue_style()
{
	// foundation stylesheet
	wp_register_style( 'reverie-foundation-stylesheet', get_template_directory_uri() . '/css/app.css', array(), '' );

	// Register the main style
	wp_register_style( 'reverie-stylesheet', get_template_directory_uri() . '/css/style.css', array(), '', 'all' );

	wp_enqueue_style( 'reverie-foundation-stylesheet' );
	wp_enqueue_style( 'reverie-stylesheet' );

	// Register child theme style if using child theme
	if ( is_child_theme() ) {

		wp_register_style( 'reverie-child-stylesheet', get_stylesheet_directory_uri() . '/css/style.css', array(), '', 'all' );

		wp_enqueue_style( 'reverie-child-stylesheet' );
	}
}
add_action( 'wp_enqueue_scripts', 'reverie_enqueue_style' );
?>

Update links for child theme

Update links for child theme

To make child theme work better.


<?php
namespace Tev\Tev\Hook;

use Tev\Tev\Url\Cache;

/**
 * Hook for saving pages.
 */
class PageSaveHook
{
    /**
     * After a page is saved, check if it is new or if its RealURL config has
     * been changed.
     *
     * If it has, clear the RealURL config cache.
     *
     * @param  string                                   $status     'new' for new entities, 'update' for existing entities
     * @param  string                                   $table      Database table name being saved
     * @param  int                                      $id         UID of New ID of entity being saved
     * @param  array                                    $fieldArray Array of fields being updated
     * @param  \TYPO3\CMS\Core\DataHandling\DataHandler $pObj
     * @return void
     */
    public function processDatamap_afterDatabaseOperations($status, $table, $id, &$fieldArray, &$pObj)
    {
        if ($table === 'pages') {
            if (($status === 'new') || isset($fieldArray['tx_tev_postvars']) || isset($fieldArray['tx_tev_childpostvars'])) {
                $urlCache = new Cache;
                $urlCache->clear();
            }
        }
    }
}

<?php
namespace Tev\Tev\Hook;

use Tev\Tev\Url\Cache;

/**
 * Hook for saving pages.
 */
class PageSaveHook
{
    /**
     * After a page is saved, check if it is new or if its RealURL config has
     * been changed.
     *
     * If it has, clear the RealURL config cache.
     *
     * @param  string                                   $status     'new' for new entities, 'update' for existing entities
     * @param  string                                   $table      Database table name being saved
     * @param  int                                      $id         UID of New ID of entity being saved
     * @param  array                                    $fieldArray Array of fields being updated
     * @param  \TYPO3\CMS\Core\DataHandling\DataHandler $pObj
     * @return void
     */
    public function processDatamap_afterDatabaseOperations($status, $table, $id, &$fieldArray, &$pObj)
    {
        if ($table === 'pages') {
            if (($status === 'new') ||
                isset($fieldArray['tx_tev_realurl_extbase_extension']) ||
                isset($fieldArray['tx_tev_realurl_extbase_plugin']) ||
                isset($fieldArray['tx_tev_realurl_extbase_inc_controller']) ||
                isset($fieldArray['tx_tev_realurl_extbase_inc_action']) ||
                isset($fieldArray['tx_tev_realurl_extbase_args'])
            ) {
                (new Cache)->clear();
            }
        }
    }
}

Update pagesavehook for new fields

Update pagesavehook for new fields


<?php

require_once 'mediawiki/CSSMin.php';

class OC_Minimizer_CSS extends OC_Minimizer
{
	protected $contentType = 'text/css';

	public function minimizeFiles($files) {
		$css_out = '';
		$webroot = (string) OC::$WEBROOT;
		foreach($files as $file_info) {
			$file = $file_info[0] . '/' . $file_info[2];
			$css_out .= '/* ' . $file . ' */' . "\n";
			$css = file_get_contents($file);

			$in_root = false;
			foreach(OC::$APPSROOTS as $app_root) {
				if(strpos($file, $app_root['path']) === 0) {
					$in_root = rtrim($webroot.$app_root['url'], '/');
					break;
				}
			}
			if ($in_root !== false) {
				$css = str_replace('%appswebroot%', $in_root, $css);
				$css = str_replace('%webroot%', $webroot, $css);
			}
			$remote = $file_info[1];
			$remote .= '/';
			$remote .= dirname($file_info[2]);
			$css_out .= CSSMin::remap($css, dirname($file), $remote, true);
		}
		if (!defined('DEBUG') || !DEBUG){
			$css_out = CSSMin::minify($css_out);
		}
		return $css_out;
	}
}

<?php

require_once 'mediawiki/CSSMin.php';

class OC_Minimizer_CSS extends OC_Minimizer
{
	protected $contentType = 'text/css';

	public function minimizeFiles($files) {
		$css_out = '';
		$webroot = (string) OC::$WEBROOT;
		foreach($files as $file_info) {
			$file = $file_info[0] . '/' . $file_info[2];
			$css_out .= '/* ' . $file . ' */' . "\n";
			$css = file_get_contents($file);

			$in_root = false;
			foreach(OC::$APPSROOTS as $app_root) {
				if(strpos($file, $app_root['path'].'/') === 0) {
					$in_root = rtrim($webroot.$app_root['url'], '/');
					break;
				}
			}
			if ($in_root !== false) {
				$css = str_replace('%appswebroot%', $in_root, $css);
				$css = str_replace('%webroot%', $webroot, $css);
			}
			$remote = $file_info[1];
			$remote .= '/';
			$remote .= dirname($file_info[2]);
			$css_out .= CSSMin::remap($css, dirname($file), $remote, true);
		}
		if (!defined('DEBUG') || !DEBUG){
			$css_out = CSSMin::minify($css_out);
		}
		return $css_out;
	}
}

Add a directory separator to filter app directories with the same
prefix.

Fixes: oc-1663


<?php if (! isset($NOCONTENT)) echo "
"; ?>

 <form method="get" action="http://www.google.com/search" name="search">
 Search Site with Google:

 <input value="mesonet.agron.iastate.edu" name="sitesearch" type="hidden" />
<input type="text" size="15" name="q" /><input type="submit" value="Search" /></form>

Copyright © 2001-<?php echo date("Y"); ?>, Iowa State University of Science and Technology.

All rights reserved.
 <a href="<?php echo $rooturl; ?>/help/abbreviations.php">abbreviations
 · <a href="<?php echo $rooturl; ?>/info/contacts.php">contact us
 · development
 · <a href="<?php echo $rooturl; ?>/disclaimer.php">disclaimer

<?php if (! isset($NOCONTENT)) echo "
 "; ?>

Update development link to github, yay...


<?php

namespace FluxBB\Markdown\Node;

class Blockquote extends Container implements NodeAcceptorInterface
{

    public function acceptParagraph(Paragraph $paragraph)
    {
        $this->addChild($paragraph);

        return $paragraph;
    }

    public function acceptHeading(Heading $heading)
    {
        $this->addChild($heading);

        return $this;
    }

    public function acceptBlockquote(Blockquote $blockquote)
    {
        $this->merge($blockquote);

        return $this;
    }

    public function acceptBlankLine(BlankLine $blankLine)
    {
        return $this->parent;
    }

    public function visit(NodeVisitorInterface $visitor)
    {
        $visitor->enterBlockquote($this);

        parent::visit($visitor);

        $visitor->leaveBlockquote($this);
    }
}

<?php

namespace FluxBB\Markdown\Node;

class Blockquote extends Container implements NodeAcceptorInterface
{

    public function acceptParagraph(Paragraph $paragraph)
    {
        $this->addChild($paragraph);

        return $paragraph;
    }

    public function acceptBlockquote(Blockquote $blockquote)
    {
        $this->merge($blockquote);

        return $this;
    }

    public function acceptBlankLine(BlankLine $blankLine)
    {
        return $this->parent;
    }

    public function visit(NodeVisitorInterface $visitor)
    {
        $visitor->enterBlockquote($this);

        parent::visit($visitor);

        $visitor->leaveBlockquote($this);
    }
}

Remove duplicate implementation (already done in parent class).


<?php
class RandomIntTest extends PHPUnit_Framework_TestCase
{
    public function testFuncExists()
    {
        $this->assertTrue(function_exists('random_int'));
    }

    public function testOutput()
    {
        $integers = array(
            random_int(0, 1000),
            random_int(1001,2000),
            random_int(-100, -10),
            random_int(-1000, 1000),
            random_int(-PHP_INT_MAX + 1, PHP_INT_MAX)
        );

        $this->assertFalse($integers[0] === $integers[1]);
        $this->assertTrue($integers[0] >= 0 && $integers[0] <= 1000);
        $this->assertTrue($integers[1] >= 1001 && $integers[1] <= 2000);
        $this->assertTrue($integers[2] >= -100 && $integers[2] <= -10);
        $this->assertTrue($integers[3] >= -1000 && $integers[3] <= 1000);
        $this->assertTrue($integers[3] >= -1000 && $integers[3] <= 1000);
        $this->assertTrue($integers[4] >= ~PHP_INT_MAX && $integers[4] <= PHP_INT_MAX);
    }
}

<?php
class RandomIntTest extends PHPUnit_Framework_TestCase
{
    public function testFuncExists()
    {
        $this->assertTrue(function_exists('random_int'));
    }

    public function testOutput()
    {
        $integers = array(
            random_int(0, 1000),
            random_int(1001,2000),
            random_int(-100, -10),
            random_int(-1000, 1000),
            random_int(~PHP_INT_MAX, PHP_INT_MAX)
        );

        $this->assertFalse($integers[0] === $integers[1]);
        $this->assertTrue($integers[0] >= 0 && $integers[0] <= 1000);
        $this->assertTrue($integers[1] >= 1001 && $integers[1] <= 2000);
        $this->assertTrue($integers[2] >= -100 && $integers[2] <= -10);
        $this->assertTrue($integers[3] >= -1000 && $integers[3] <= 1000);
        $this->assertTrue($integers[3] >= -1000 && $integers[3] <= 1000);
        $this->assertTrue($integers[4] >= ~PHP_INT_MAX && $integers[4] <= PHP_INT_MAX);
    }
}

Define range properly in unit test.

Define range properly in unit test.


<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'fly@dronepiggy.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: fly@dronepiggy.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])		||
   empty($_POST['budget'])		||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$budget = $_POST['budget'];

// Create the email and send the message
$to = 'fly@dronepiggy.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message Phone: $phone\n\nBudget:\n$budget"";
$headers = "From: fly@dronepiggy.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

Add budget field to PHP

Add budget field to PHP


<?php

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';

// Enable APC for autoloading to improve performance.
// You should change the ApcClassLoader first argument to a unique prefix
// in order to prevent cache key conflicts with other applications
// also using APC.
/*
$apcLoader = new ApcClassLoader(sha1(__FILE__), $loader);
$loader->unregister();
$apcLoader->register(true);
*/

require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);

// When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter
//Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';

// Enable APC for autoloading to improve performance.
// You should change the ApcClassLoader first argument to a unique prefix
// in order to prevent cache key conflicts with other applications
// also using APC.
/*
$apcLoader = new ApcClassLoader(sha1(__FILE__), $loader);
$loader->unregister();
$apcLoader->register(true);
*/

require_once __DIR__.'/../app/AppKernel.php';
require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', true);
$kernel->loadClassCache();
$kernel = new AppCache($kernel);

// When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter
//Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Enable HTTP Cache on Prod

Enable HTTP Cache on Prod