<?php

/**
 * The Tsugi variant of a Silex Application
 *
 * This needs the session started before it is called
 *
 */

namespace Tsugi\Silex;

use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;

class Application extends \Silex\Application {

    function __construct($launch, array $values = array()) {
        global $CFG;
        parent::__construct($values);
        $this['tsugi'] = $launch;
        $launch->output->buffer = true;  // Buffer output

        $session = new Session(new PhpBridgeSessionStorage());
        $session->start();
        $this['session'] = $session;

        $yourNewPath = $CFG->dirroot . '/vendor/tsugi/lib/src/Templates';
        // $loader = new \Twig_Loader_Filesystem(array('templates', $yourNewPath) );
        $loader = new \Twig_Loader_Filesystem('templates');
        $loader->addPath($yourNewPath, 'Tsugi');

        //$loader = new \Tsugi\Twig\Twig_Loader_Class();
        $this->register(new \Silex\Provider\TwigServiceProvider(), array(
            'twig.loader' => $loader
        ));
    }
}

<?php

/**
 * The Tsugi variant of a Silex Application
 *
 * This needs the session started before it is called
 *
 */

namespace Tsugi\Silex;

use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;

class Application extends \Silex\Application {

    function __construct($launch, array $values = array()) {
        global $CFG;
        parent::__construct($values);
        if ( ! isset($CFG->loader) ) {
            echo("<pre>\n".'Please fix your config.php to set $CFG->loader as follows:'."\n");
            echo('$loader = require_once($dirroot."/vendor/autoload.php");'."\n");
            echo("...\n".'$CFG = ...'."\n...\n");
            echo('$CFG->loader = $loader;'."\n");
            echo("Please see config-dist.php for sample code.\n</pre>\n");
            die('Need to set $CFG->loader');
        }
        $this['tsugi'] = $launch;
        $launch->output->buffer = true;  // Buffer output

        $session = new Session(new PhpBridgeSessionStorage());
        $session->start();
        $this['session'] = $session;

        $loader = new \Twig_Loader_Filesystem('templates');
        $yourNewPath = $CFG->dirroot . '/vendor/tsugi/lib/src/Templates';
        $loader->addPath($yourNewPath, 'Tsugi');
        $yourNewPath = $CFG->dirroot . '/vendor/koseu/lib/src/Templates';
        if ( file_exists($yourNewPath) ) {
            $loader->addPath($yourNewPath, 'Koseu');
        }
        $CFG->loader->addPsr4('AppBundle\\', 'src/AppBundle');

        //$loader = new \Tsugi\Twig\Twig_Loader_Class();
        $this->register(new \Silex\Provider\TwigServiceProvider(), array(
            'twig.loader' => $loader
        ));
    }
}

Add PSR4 loader for AppBundle

Add PSR4 loader for AppBundle


<?php

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

namespace Packagist\WebBundle\Controller;

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

/**
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class Controller extends BaseController
{
    protected function getPackagesMetadata($packages)
    {
        $metadata = null;
        try {
            $dlKeys = array();
            foreach ($packages as $package) {
                $id = $package instanceof \Solarium_Document_ReadOnly ? $package->id : $package->getId();
                $dlKeys[$id] = 'dl:'.$id;
            }
            $res = $this->get('snc_redis.default')->mget(array_values($dlKeys));

            $metadata = array(
                'downloads' => array_combine(array_keys($dlKeys), $res),
                'favers' => $this->get('packagist.favorite_manager')->getFaverCounts(array_keys($dlKeys)),
            );
        } catch (\Predis\Network\ConnectionException $e) {}

        return $metadata;
    }
}

<?php

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

namespace Packagist\WebBundle\Controller;

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

/**
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class Controller extends BaseController
{
    protected function getPackagesMetadata($packages)
    {
        $metadata = null;
        try {
            $dlKeys = array();
            foreach ($packages as $package) {
                $id = $package instanceof \Solarium_Document_ReadOnly ? $package->id : $package->getId();
                $dlKeys[$id] = 'dl:'.$id;
            }
            if (!$dlKeys) {
                return $metadata;
            }
            $res = $this->get('snc_redis.default')->mget(array_values($dlKeys));

            $metadata = array(
                'downloads' => array_combine(array_keys($dlKeys), $res),
                'favers' => $this->get('packagist.favorite_manager')->getFaverCounts(array_keys($dlKeys)),
            );
        } catch (\Predis\Network\ConnectionException $e) {}

        return $metadata;
    }
}

Fix metadata addition when the results are empty


<?php

namespace DesignPatterns\Structural\Proxy\Tests;

use DesignPatterns\Structural\Proxy\RecordProxy;

class ProxyTest extends \PHPUnit_Framework_TestCase
{
    public function testWillSetDirtyFlagInProxy()
    {
        $recordProxy = new RecordProxy([]);
        $recordProxy->username = 'baz';

        $this->assertTrue($recordProxy->isDirty());
    }

    public function testProxyIsInstanceOfRecord()
    {
        $recordProxy = new RecordProxy([]);
        $recordProxy->username = 'baz';

        $this->assertInstanceOf('DesignPatterns\Structural\Proxy\Record', $recordProxy);
    }
}

<?php

namespace DesignPatterns\Structural\Proxy\Tests;

use DesignPatterns\Structural\Proxy\RecordProxy;

class ProxyTest extends \PHPUnit_Framework_TestCase
{
    public function testWillSetDirtyFlagInProxy()
    {
        $recordProxy = new RecordProxy([]);
        $recordProxy->username = 'baz';

        $this->assertTrue($recordProxy->isDirty());
    }

    public function testProxyIsInstanceOfRecord()
    {
        $recordProxy = new RecordProxy([]);
        $recordProxy->username = 'baz';

        $this->assertInstanceOf(RecordProxy::class, $recordProxy);
    }
}

Use class constant instead of hardcoded namespace


<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use App\Business;
use App\Contact;
use Route;

class AlterContactRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return $this->contact === null || \Auth::user()->contacts->contains($this->contact);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [  'firstname' => 'required|min:3',
                    'lastname' => 'required|min:3',
                    'gender' => 'required|max:1',
                    'mobile_country' => 'required_with:mobile|size:2',
                    'mobile' => 'phone',
                    'email' => 'email'
                ];

        switch ($this->method()) {
            case 'PATCH':
            case 'PUT':
            case 'POST':
                return $rules;
                break;
            default:
                return [];
                break;
        }
    }
}

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use App\Business;
use App\Contact;
use Route;

class AlterContactRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return $this->contact === null || \Auth::user()->contacts->contains($this->contact);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [  'firstname' => 'required|min:3',
                    'lastname' => 'required|min:2',
                    'gender' => 'required|max:1',
                    'mobile_country' => 'required_with:mobile|size:2',
                    'mobile' => 'phone',
                    'email' => 'email'
                ];

        switch ($this->method()) {
            case 'PATCH':
            case 'PUT':
            case 'POST':
                return $rules;
                break;
            default:
                return [];
                break;
        }
    }
}

Make min length of lastname =2

Make min length of lastname =2


<?php

namespace App\Model\Query;

use App\Model\Entity\Song;
use Kdyby\Doctrine\QueryBuilder;
use Kdyby\Doctrine\QueryObject;
use Kdyby\Persistence\Queryable;

/**
 * Performs search for public songs which metadata contains search string.
 * @author Tomáš Jirásek
 */
class SongPublicSearchQuery extends QueryObject
{

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

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

	/**
	 * @param Queryable $repository
	 * @return QueryBuilder
	 */
	protected function doCreateQuery(Queryable $repository)
	{
		return $repository->createQueryBuilder()
			->select('s')
			->from(Song::class, 's')
            ->orWhere('s.title LIKE :query')
            ->orWhere('s.author LIKE :query')
            ->orWhere('s.originalAuthor LIKE :query')
			->setParameter('query', "%$this->search%")
			->orderBy('s.title');
	}

}

<?php

namespace App\Model\Query;

use App\Model\Entity\Song;
use Kdyby\Doctrine\QueryBuilder;
use Kdyby\Doctrine\QueryObject;
use Kdyby\Persistence\Queryable;

/**
 * Performs search for public songs which metadata contains search string.
 * @author Tomáš Jirásek
 */
class SongPublicSearchQuery extends QueryObject
{

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

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

	/**
	 * @param Queryable $repository
	 * @return QueryBuilder
	 */
	protected function doCreateQuery(Queryable $repository)
	{
		return $repository->createQueryBuilder()
			->select('s')
			->from(Song::class, 's')
            ->orWhere('s.title LIKE :query')
            ->orWhere('s.author LIKE :query')
            ->orWhere('s.originalAuthor LIKE :query')
            ->andWhere('s.public = 1')
			->setParameter('query', "%$this->search%")
			->orderBy('s.title');
	}

}

Fix recommended songs in wishes to public only


<?php
define('COOKIE_SESSION', true);
require_once("../config.php");
session_start();
require_once("gate.php");
if ( $REDIRECTED === true || ! isset($_SESSION["admin"]) ) return;

setcookie("adminmenu","true", 0, "/");

\Tsugi\Core\LTIX::getConnection();

$OUTPUT->header();
$OUTPUT->bodyStart();
$OUTPUT->topNav();
require_once("sanity-db.php");
?>

Welcome Adminstrator

Upgrade Database

Check Nonces

View Contexts

<?php if ( $CFG->providekeys ) { ?>

Manage Access Keys

<?php } ?>

Manage Installed Modules

<?php
$OUTPUT->footer();

<?php
define('COOKIE_SESSION', true);
require_once("../config.php");
session_start();
require_once("gate.php");
if ( $REDIRECTED === true || ! isset($_SESSION["admin"]) ) return;

setcookie("adminmenu","true", 0, "/");

\Tsugi\Core\LTIX::getConnection();

$OUTPUT->header();
$OUTPUT->bodyStart();
$OUTPUT->topNav();
require_once("sanity-db.php");
?>

   <iframe name="iframe-frame" style="height:400px" id="iframe-frame"
    src="<?= $OUTPUT->getSpinnerUrl() ?>">

Welcome Adminstrator

  Ugrade Database

  Check Nonces

View Contexts

<?php if ( $CFG->providekeys ) { ?>

Manage Access Keys

<?php } ?>

Manage Installed Modules

<?php
$OUTPUT->footer();

Put database and nonces in modals

Put database and nonces in modals


<?php if ( ! defined('BASEPATH')) exit('Direct script access is not permitted.');

/**
 * OmniLog module.
 *
 * @author          Stephen Lewis (http://github.com/experience/)
 * @copyright       Experience Internet
 * @package         Omnilog
 */

class Omnilog {

    private $_ee;
    private $_model;
    public $return_data = '';

    /* --------------------------------------------------------------
     * PUBLIC METHODS
     * ------------------------------------------------------------ */

    /**
     * Constructor.
     *
     * @access  public
     * @return  void
     */
    public function __construct()
    {
        $this->_ee =& get_instance();
        $this->_ee->load->model('omnilog_model');
        $this->_model = $this->_ee->omnilog_model;
    }

    /* --------------------------------------------------------------
     * ACTION METHODS
     * ------------------------------------------------------------ */

    /**
     *
     *
     * @access  public
     * @return  void
     */
    public function ()
    {
        error_log('Running the  action.');
    }

    /* --------------------------------------------------------------
     * TEMPLATE TAG METHODS
     * ------------------------------------------------------------ */

    /**
     *
     *
     * @access  public
     * @return  string
     */
    public function ()
    {
        return $this->return_data = 'exp:omnilog: output';
    }

}

/* End of file      : mod.omnilog.php */
/* File location    : third_party/omnilog/mod.omnilog.php */

<?php if ( ! defined('BASEPATH')) exit('Direct script access is not permitted.');

/**
 * OmniLog module.
 *
 * @author          Stephen Lewis (http://github.com/experience/)
 * @copyright       Experience Internet
 * @package         Omnilog
 */

class Omnilog {

    private $_ee;
    private $_model;
    public $return_data = '';

    /* --------------------------------------------------------------
     * PUBLIC METHODS
     * ------------------------------------------------------------ */

    /**
     * Constructor.
     *
     * @access  public
     * @return  void
     */
    public function __construct()
    {
        $this->_ee =& get_instance();
        $this->_ee->load->model('omnilog_model');
        $this->_model = $this->_ee->omnilog_model;
    }

}

/* End of file      : mod.omnilog.php */
/* File location    : third_party/omnilog/mod.omnilog.php */

Remove obsolete 'action' and 'template tag' methods.

Unnamed methods added as a result of a bug in Addonis.


<?php

/**
 * @author kylekatarnls
 */

class Jade {

    protected $CI;
    protected $jade;
    protected $view_path;

    public function __construct(array $options = array()) {

        if(isset($options['view_path'])) {
            $this->view_path = $options['view_path'];
            unset($options['view_path']);
        } else {
            $this->view_path = APPPATH . 'views';
        }
        if(isset($options['cache'])) {
            if($options['cache'] === TRUE) {
                $options['cache'] = __DIR__ . '/../cache/jade';
            }
            if(! file_exists($options['cache']) && ! mkdir($options['cache'], 0777, TRUE)) {
                throw new Exception("Cache folder does not exists and cannot be created.", 1);
            }
        }
        $this->CI =& get_instance();
        $this->jade = new Jade\Jade($options);
    }

    public function view($view, array $data = array(), $return = false) {

        $view = $this->view_path . DIRECTORY_SEPARATOR . $view . '.jade';
        $data = array_merge($this->CI->load->get_vars(), $data);
        if($return) {
            return $this->jade->render($view, $data);
        } else {
            echo $this->jade->render($view, $data);
        }
    }
}

<?php

/**
 * @author kylekatarnls
 */

trait Jade {

    protected $jade;
    protected $jade_view_path;

    public function settings(array $options = array()) {

        if(isset($options['view_path'])) {
            $this->jade_view_path = $options['view_path'];
            unset($options['view_path']);
        } else {
            $this->jade_view_path = APPPATH . 'views';
        }
        if(isset($options['cache'])) {
            if($options['cache'] === TRUE) {
                $options['cache'] = APPPATH . 'cache/jade';
            }
            if(! file_exists($options['cache']) && ! mkdir($options['cache'], 0777, TRUE)) {
                throw new Exception("Cache folder does not exists and cannot be created.", 1);
            }
        }
        $this->jade = new Jade\Jade($options);
        return $this;
    }

    public function view($view, array $data = array(), $return = false) {

        if(! $this->jade) {
            $this->settings();
        }
        $view = $this->jade_view_path . DIRECTORY_SEPARATOR . $view . '.jade';
        $data = array_merge($this->load->get_vars(), $data);
        if($return) {
            return $this->jade->render($view, $data);
        } else {
            echo $this->jade->render($view, $data);
            return $this;
        }
    }
}

Implement with trait in controller

Implement with trait in controller


@extends('layouts.master')

@section('content')

takas.lk

ICMD

kapruka.com

@endsection

@extends('layouts.master')

@section('content')

takas.lk

ICMD

@endsection

Remove kapruka link from online donation list


<?php
$sochEndpoint = 'http://kulturarvsdata.se/';

function sochQueryRequest($queryString, $sochEndpoint) {
  $url = $sochEndpoint . $queryString;
  $content = file_get_contents($url);

  foreach ($http_response_header as $header) {
    header($header);
  }

  header('Access-Control-Allow-Origin: *');

  echo $content;
}

<?php
$sochEndpoint = 'http://kulturarvsdata.se/';

function sochQueryRequest($queryString, $sochEndpoint) {
  $url = $sochEndpoint . $queryString;

  $incomingHeaders = getallheaders();
  if (array_key_exists('Accept format', $incomingHeaders) && ($incomingHeaders == 'application/json' || 'application/json-ld' || 'application/ld-json')) {
    $opts = array(
      'http' => array(
        'method' => "GET",
        'header' => "Accept format: application/json\r\n"
      )
    );
  } else {
    $opts = array(
      'http' => array(
        'method' => "GET",
        'header' => "Accept format: *\r\n"
      )
    );
  }

  $context = stream_context_create($opts);
  $content = file_get_contents($url, false, $context);

  foreach ($http_response_header as $header) {
    header($header);
  }

  header('Access-Control-Allow-Origin: *');

  echo $content;
}

Support getting JSON-LD from http headers


<?php namespace Dan\Irc\Packets;

use Dan\Contracts\PacketContract;
use Dan\Irc\Connection;

class Packet251 implements PacketContract {

    public function handle(Connection $connection, array $from, array $data)
    {
        foreach($connection->config->get('autorun_commands') as $command)
        {
            $nick = $connection->user->nick();
            $connection->raw(str_replace(['{NICK}'], [$nick], $command));
        }

        if($connection->config->get('user.pass') != '')
        {
            $command    = $connection->config->get('auth_command');
            $password   = $connection->config->get('user.pass');

            $connection->raw(sprintf($command, $password));
        }

        sleep(5);

        foreach($connection->config->get('channels') as $channel)
        {
            $data = explode(':', $channel);

            $connection->joinChannel($data[0], (isset($data[1]) ? $data[1] : null));
        }
    }
}

<?php namespace Dan\Irc\Packets;

use Dan\Contracts\PacketContract;
use Dan\Irc\Connection;

class Packet251 implements PacketContract {

    public function handle(Connection $connection, array $from, array $data)
    {
        foreach($connection->config->get('autorun_commands') as $command)
        {
            $nick = $connection->user->nick();
            $connection->raw(str_replace(['{NICK}'], [$nick], $command));
        }

        if($connection->config->get('user.pass') != '')
        {
            $command    = $connection->config->get('nickserv_auth_command');
            $password   = $connection->config->get('user.pass');

            $connection->raw(sprintf($command, $password));
        }

        sleep(5);

        foreach($connection->config->get('channels') as $channel)
        {
            $data = explode(':', $channel);

            $connection->joinChannel($data[0], (isset($data[1]) ? $data[1] : null));
        }
    }
}

Fix bot not authing against nickserv.

Fix bot not authing against nickserv.


<?php

class ContactNotify {

	public function fire($job, $data)
	{
		Mail::send(['text' => 'emails.contact'], $data, function($m) use ($data) {
			$m->to(Config::get('quill.contact.email'), Config::get('quill.contact.name'))
				->subject("[cnq] Contact from {$data['name']}")
				->from(Config::get('quill.send.email'), Config::get('quill.send.name'))
				->replyTo($data['email']);
		});
	}
}

<?php

class ContactNotify {

	public function fire($job, $data)
	{
		Mail::send(['text' => 'emails.contact'], $data, function($m) use ($data) {
			$reply_to = $data['email'] ?: Config::get('quill.send.email');
			$m->to(Config::get('quill.contact.email'), Config::get('quill.contact.name'))
				->subject("[cnq] Contact from {$data['name']}")
				->from(Config::get('quill.send.email'), Config::get('quill.send.name'))
				->replyTo($reply_to);
		});
	}
}

Handle blank replyTo in contact email

Handle blank replyTo in contact email


Add minor spaces to docblock

Add minor spaces to docblock

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


{!! '<?'.'php' !!}

use function phln\{{$ns}}\{{$name}};
use const phln\{{$ns}}\{{$name}};

class {{ ucfirst("{$name}Test") }} extends \PHPUnit_Framework_TestCase
{
}

{!! '<?'.'php' !!}

use const phln\{{$ns}}\{{$name}};

class {{ ucfirst("{$name}Test") }} extends \Phln\Build\PhpUnit\TestCase
{
    public function getTestedFn(): string
    {
        return {{$name}};
    }

    /** @test */
    public function it_works()
    {
        $this->assertTrue($this->callFn());
    }
}

Update functions unit test template

Update functions unit test template


<?php
$stime = microtime();
include('base/entry.php');
$entry = new \Teadaze\Entry();
include('site/entry.php');
try {
	echo $entry->run();
} catch(exception $e) {
	echo $e;
}
$etime = microtime();
if($config['debug']) {
	echo "
".peak_memory_string()."
";
	echo "
".time_us_ms($etime-$stime)."ms
";
}

<?php
$stime = microtime();
include('base/entry.php');
$entry = new \Teadaze\Entry();
include('site/entry.php');
try {
	echo $entry->run();
} catch(exception $e) {
	echo $e;
}
$etime = microtime();
if($config['debug']) {
	echo "
".Teadaze\peak_memory_string()."
";
	echo "
".Teadaze\time_us_ms($etime-$stime)."ms
";
}

Add correct namespace to metrics

Add correct namespace to metrics


<!DOCTYPE html>

        <title>teodizzo</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="frameworks/bootstrap_dist/css/bootstrap.css" rel="stylesheet" type="text/css"/>

Welcome to Teodizzo

We hope that you enjoy your stay.

We hope that you enjoy your stay.

We hope that you enjoy your stay.

Copy the main paragraph 3x

Copy the main paragraph 3x


<?php

class SV_IntegratedReports_AlertHandler_Report extends XenForo_AlertHandler_Abstract
{
    const ContentType = 'report';
    var $_reportModel = null;

    public function getContentByIds(array $contentIds, $model, $userId, array $viewingUser)
    {
        if (empty($this->_reportModel))
        {
            $this->_reportModel = $model->getModelFromCache('XenForo_Model_Report');
        }
        return $this->_reportModel->getReportsByIds($contentIds);
    }

    public function canViewAlert(array $alert, $content, array $viewingUser)
    {
        return ($viewingUser['is_moderator'] || $viewingUser['is_admin']);
    }

    public function prepareAlert(array $item, array $viewingUser)
    {
    	parent::prepareAlert($item, $viewingUser);

        if (!empty($item['content']['content_info']))
        {
            if (empty($this->_reportModel))
            {
                $this->_reportModel = XenForo_Model::create("XenForo_Model_Report");
            }
            $item['content']['content_info'] = unserialize($item['content']['content_info']);
            $handler = $this->_reportModel->getReportHandler($item['content']['content_type']);
            if (!empty($handler) && !empty($item['content']['content_info']))
            {
                $item['content']['title'] = $handler->getContentTitle($item['content'], $item['content']['content_info']);
            }
        }
        if (!empty($item['extra_data']))
        {
            $item['content']['extra'] = unserialize($item['extra_data']);
            unset($item['extra_data']);
        }
    	return $item;
    }
}

<?php

class SV_IntegratedReports_AlertHandler_Report extends XenForo_AlertHandler_Abstract
{
    const ContentType = 'report';
    var $_reportModel = null;

    public function getContentByIds(array $contentIds, $model, $userId, array $viewingUser)
    {
        if (empty($this->_reportModel))
        {
            $this->_reportModel = $model->getModelFromCache('XenForo_Model_Report');
        }
        return $this->_reportModel->getReportsByIds($contentIds);
    }

    public function canViewAlert(array $alert, $content, array $viewingUser)
    {
        return ($viewingUser['is_moderator'] || $viewingUser['is_admin']);
    }

    public function prepareAlert(array $item, array $viewingUser)
    {
    	parent::prepareAlert($item, $viewingUser);

        if (!empty($item['content']['content_info']))
        {
            if (empty($this->_reportModel))
            {
                $this->_reportModel = XenForo_Model::create("XenForo_Model_Report");
            }
            $handler = $this->_reportModel->getReportHandler($item['content']['content_type']);
            if (!empty($handler))
            {
                $item['content'] = $handler->prepareReport($item['content']);
            }
        }
        if (!empty($item['extra_data']))
        {
            $item['content']['extra'] = unserialize($item['extra_data']);
            unset($item['extra_data']);
        }
    	return $item;
    }
}

Improve prepareAlert for report alerts

Improve prepareAlert for report alerts


<?php
namespace ComplexPie;

class Data extends Extension
{
    protected static $static_ext = array();

    public static function add_static_extension($extpoint, $ext, $priority)
    {
        if ($extpoint === 'get' && !is_callable($ext))
        {
            throw new \InvalidArgumentException("$ext is not callable");
        }
        parent::add_static_extension($extpoint, $ext, $priority);
    }

    public function add_extension($extpoint, $ext, $priority)
    {
        if ($extpoint === 'get' && !is_callable($ext))
        {
            throw new \InvalidArgumentException("$ext is not callable");
        }
        parent::add_extension($extpoint, $ext, $priority);
    }

    public function __get($name)
    {
        $return = array();
        $extensions = $this->get_extensions('get');
        if (method_exists($this, "get_$name"))
        {
            $extensions[] = array($this, "get_$name");
        }

        foreach ($extensions as $extension)
        {
            if (($extreturn = call_user_func($extension, $this->dom, $name)) !== null)
            {
                if (is_array($extreturn))
                {
                    $return = array_merge_recursive($extreturn, $return);
                }
                elseif (!$return)
                {
                    return $extreturn;
                }
            }
        }
        if ($return)
        {
            return $return;
        }
    }
}

Data::add_static_extension_point('get');

<?php
namespace ComplexPie;

class Data extends Extension
{
    protected static $static_ext = array();

    public static function add_static_extension($extpoint, $ext, $priority)
    {
        if ($extpoint === 'get' && !is_callable($ext))
        {
            throw new \InvalidArgumentException("$ext is not callable");
        }
        parent::add_static_extension($extpoint, $ext, $priority);
    }

    public function add_extension($extpoint, $ext, $priority)
    {
        if ($extpoint === 'get' && !is_callable($ext))
        {
            throw new \InvalidArgumentException("$ext is not callable");
        }
        parent::add_extension($extpoint, $ext, $priority);
    }

    public function __get($name)
    {
        $extensions = $this->get_extensions('get');
        if (method_exists($this, "get_$name"))
        {
            $extensions[] = array($this, "get_$name");
        }

        $return = array();
        $returnarray = false;
        foreach ($extensions as $extension)
        {
            if (($extreturn = call_user_func($extension, $this->dom, $name)) !== null)
            {
                if (is_array($extreturn))
                {
                    $returnarray = true;
                    $return = array_merge_recursive($extreturn, $return);
                }
                else
                {
                    $return[] = $extreturn;
                }
            }
        }

        if ($return)
        {
            if ($returnarray)
                return $return;
            else
                return $return[0];
        }
    }
}

Data::add_static_extension_point('get');

Check whether any getter returns an array before returning a non-array type in Data.


<?php

namespace GtfsMerger\Merger;

use League\Flysystem\ZipArchive\ZipArchiveAdapter;
use Nette\Caching\Cache;
use Nette\InvalidStateException;

class StopTimeLimitations implements MergerInterface
{
    /** @var Cache */
    private $tripsIdsCache;

    /** @var Cache */
    private $stopsIdsCache;

    function __construct(
        Cache $tripsIdsCache,
        Cache $stopsIdsCache
    )
    {
        $this->tripsIdsCache = $tripsIdsCache;
        $this->stopsIdsCache = $stopsIdsCache;
    }

    /**
     * @param resource $stream
     * @return array
     */
    public function merge($stream)
    {
        $items = [];
        $header = fgetcsv($stream);
        while(($data = fgetcsv($stream)) !== false) {
            $data = array_combine($header, $data);

            $currentId = $data['trip_id'];
            $newId = $this->tripsIdsCache->load($currentId);
            if ($newId === null) {
                throw new InvalidStateException('Unknown trip ID: ' . $currentId);
            }
            $data['trip_id'] = $newId;

            $currentId = $data['stop_id'];
            $newId = $this->stopsIdsCache->load($currentId);
            if ($newId === null) {
                throw new InvalidStateException('Unknown stop ID: ' . $currentId);
            }
            $data['stop_id'] = $newId;

            $items[] = $data;
        }
        return $items;
    }
}

<?php

namespace GtfsMerger\Merger;

use League\Flysystem\ZipArchive\ZipArchiveAdapter;
use Nette\Caching\Cache;
use Nette\InvalidStateException;

class StopTimeLimitations implements MergerInterface
{
    /** @var Cache */
    private $tripsIdsCache;

    /** @var Cache */
    private $stopsIdsCache;

    function __construct(
        Cache $tripsIdsCache,
        Cache $stopsIdsCache
    )
    {
        $this->tripsIdsCache = $tripsIdsCache;
        $this->stopsIdsCache = $stopsIdsCache;
    }

    /**
     * @param resource $stream
     * @return array
     */
    public function merge($stream)
    {
        $items = [];
        $header = fgetcsv($stream);
        while(($data = fgetcsv($stream)) !== false) {
            $data = array_combine($header, $data);

            $currentId = $data['trip_id'] ?? null;
            $newId = $this->tripsIdsCache->load($currentId);
            if ($newId === null) {
                throw new InvalidStateException('Unknown trip ID: ' . $currentId);
            }
            $data['trip_id'] = $newId;

            $currentId = $data['stop_id'] ?? null;
            $newId = $this->stopsIdsCache->load($currentId);
            if ($newId === null) {
                throw new InvalidStateException('Unknown stop ID: ' . $currentId);
            }
            $data['stop_id'] = $newId;

            $items[] = $data;
        }
        return $items;
    }
}

Check for wrong or non-existing stop or trip id


<?php

namespace ProjectRena\Model;

use ProjectRena\RenaApp;

/**
 * Class Config.
 */
class Config
{
    private $app;
    private $db;

    function __construct(RenaApp $app)
    {
        $this->app = $app;
        $this->db = $app->Db;
    }

    /**
     * @param $key
     *
     * @return string
     */
    public function get($key)
    {
        $dbResult = $this->db->queryField('SELECT value FROM configuration WHERE `key` = :key', 'value', array(':key' => $key));

        return $dbResult;
    }

    /**
     * @param $key
     * @param $value
     *
     * @return mixed
     */
    public function set($key, $value)
    {
        return $this->db->execute('INSERT INTO configuration (`key`, value) VALUES (:key, :value)', array(':key' => $key,
            ':value' => $value,
        ));
    }
}

<?php

namespace ProjectRena\Model\Database\Site;

use ProjectRena\RenaApp;

/**
 * Class Config.
 */
class Config
{
    private $app;
    private $db;

    function __construct(RenaApp $app)
    {
        $this->app = $app;
        $this->db = $app->Db;
    }

    /**
     * @param $key
     *
     * @return string
     */
    public function get($key)
    {
        $dbResult = $this->db->queryField('SELECT value FROM configuration WHERE `key` = :key', 'value', array(':key' => $key));

        return $dbResult;
    }

    /**
     * @param $key
     * @param $value
     *
     * @return mixed
     */
    public function set($key, $value)
    {
        return $this->db->execute('INSERT INTO configuration (`key`, value) VALUES (:key, :value)', array(':key' => $key,
            ':value' => $value,
        ));
    }
}

Use the proper namespace for config

Use the proper namespace for config


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

namespace Flarum\Foundation;

use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Foundation\Application;

abstract class AbstractServiceProvider extends ServiceProvider
{
    /**
     * @var Application
     */
    protected $app;

    /**
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        parent::__construct($app);
    }

    /**
     * {@inheritdoc}
     */
    public function register()
    {
    }
}

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

namespace Flarum\Foundation;

use Illuminate\Support\ServiceProvider;

abstract class AbstractServiceProvider extends ServiceProvider
{
    /**
     * @var Application
     */
    protected $app;

    /**
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        parent::__construct($app);
    }

    /**
     * {@inheritdoc}
     */
    public function register()
    {
    }
}

Revert "typehint fix, opening for implementation"


@section('title')
{{{$item->rawName}}} (construction) - Cataclysm: Dark Days Ahead
@endsection
@include('items.menu', array('active'=>'construction'))

  {{$item->symbol}} $item->id)) }}">{{ $item->name }} construction.

@include("world._constructionList", array("data"=>$item->constructionUses))

Increase the width of the construction table in the item view.


@extends('layout.master')

@section('content')

@include('dashboard.partials.errors')

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

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

                        <input class="form-control" type="email" name="email">

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

@stop

@extends('layout.master')

@section('content')

@include('dashboard.partials.errors')

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

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

                        <input class="form-control" type="email" name="email">

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

@stop

Tidy up the subscribe page

Tidy up the subscribe page


<?php

namespace OpenCFP;

trait ContainerAware
{
    /**
     * @var \Silex\Application
     */
    public $app;

    public function setApplication(Application $application)
    {
        $this->app = $application;
    }

    protected function service($slug)
    {
        return $this->app[$slug];
    }
}

<?php

namespace OpenCFP;

trait ContainerAware
{
    /**
     * @var \Silex\Application
     */
    protected $app;

    public function setApplication(Application $application)
    {
        $this->app = $application;
    }

    protected function service($slug)
    {
        return $this->app[$slug];
    }
}

Fix: Reduce visibility from public to protected


<?php

// This check prevents access to debug front controllers that are deployed by
// accident to production servers. Feel free to remove this, extend it or make
// something more sophisticated.

$allowedIps = array('127.0.0.1', '::1');
if (false !== $envIp = getenv('ATOM_DEBUG_IP'))
{
  $allowedIps[] = $envIp;
}

if (!in_array(@$_SERVER['REMOTE_ADDR'], $allowedIps))
{
  die('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

require_once(dirname(__FILE__).'/config/ProjectConfiguration.class.php');

$configuration = ProjectConfiguration::getApplicationConfiguration('qubit', 'dev', true);
sfContext::createInstance($configuration)->dispatch();

<?php

// This check prevents access to debug front controllers that are deployed by
// accident to production servers. Feel free to remove this, extend it or make
// something more sophisticated.

$allowedIps = array('127.0.0.1', '::1');
if (false !== $envIp = getenv('ATOM_DEBUG_IP'))
{
  $allowedIps = array_merge($allowedIps, array_filter(explode(',', $envIp)));
}

if (!in_array(@$_SERVER['REMOTE_ADDR'], $allowedIps))
{
  die('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

require_once(dirname(__FILE__).'/config/ProjectConfiguration.class.php');

$configuration = ProjectConfiguration::getApplicationConfiguration('qubit', 'dev', true);
sfContext::createInstance($configuration)->dispatch();

Allow multiple IPs in ATOM_DEBUG_IP

Allow multiple IPs in ATOM_DEBUG_IP


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

namespace Darvin\ContentBundle\Widget;

/**
 * Widget
 */
interface WidgetInterface
{
    /**
     * @return string
     */
    public function getContent();

    /**
     * @return string
     */
    public function getPlaceholder();
}

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

namespace Darvin\ContentBundle\Widget;

/**
 * Widget
 */
interface WidgetInterface
{
    /**
     * @return string
     */
    public function getContent();

    /**
     * @return string
     */
    public function getPlaceholder();

    /**
     * @return string
     */
    public function getName();
}

Implement custom CKEditor form type.

Implement custom CKEditor form type.


<?php
/**
 * Defines the StaffFolder page type
 */
class StaffFolder extends Page {
   static $db = array(
   );
   static $has_one = array(
   );

   static $allowed_children = array('Staff');
}

class StaffFolder_Controller extends Page_Controller {
  public function StaffFolderCacheKey() {
    $start = isset( $_GET['start'] ) ? (int)( Convert::raw2sql( $_GET['start'] ) ) : 0;
    return implode( '_', array(
        'StaffFolders',
        $this->Locale,
        $this->Aggregate( 'Staff' )->Max( 'LastEdited' ),
        $this->Aggregate( 'StaffFolder' )->Max( 'LastEdited' ),
        '_',
        $start
      ) );
  }
}

?>

<?php
/**
 * Defines the StaffFolder page type
 */
class StaffFolder extends Page implements RenderableAsPortlet {
  static $db = array(
  );
  static $has_one = array(
    'MainImage' => 'Image'
  );

  static $allowed_children = array( 'Staff' );

  function getCMSFields() {
    $fields = parent::getCMSFields();
    $fields->addFieldToTab( 'Root.Content.Image', new ImageField( 'MainImage' ) );

    return $fields;
  }

  public function getPortletTitle() {
    return $this->Title;
  }

  // FIXME - make this more efficient
  public function getPortletImage() {
    if ( $this->MainImageID ) {
      return DataObject::get_by_id( 'Image', $this->MainImageID );
    } else {
      return null;
    }

  }

  public function getPortletCaption() {
    return '';
  }

}

class StaffFolder_Controller extends Page_Controller {
  public function StaffFolderCacheKey() {
    $start = isset( $_GET['start'] ) ? (int)( Convert::raw2sql( $_GET['start'] ) ) : 0;
    return implode( '_', array(
        'StaffFolders',
        $this->Locale,
        $this->Aggregate( 'Staff' )->Max( 'LastEdited' ),
        '_',
        $this->ID,
        '_',
        $this->Aggregate( 'StaffFolder' )->Max( 'LastEdited' ),
        '_',
        $start
      ) );
  }
}

?>

Reformat code, fix cache bug

BUGFIX: Reformat code, fix cache bug


<?php

/**
 * Model for CSV
 *
 */
class CSVDRM extends BaseCSVDRM {

    public function __construct() {
        $this->type = "CSVDRM";
        parent::__construct();
    }

    public function getFileContent() {
        return file_get_contents($this->getAttachmentUri($this->getFileName()));
    }

    public function getFileName() {
        return 'import_edi_' . $this->identifiant . '_' . $this->periode . '.csv';
    }

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

    public function addErreur($erreur) {
        $erreurNode = $this->erreurs->getOrAdd($erreur->num_ligne);
        $erreurNode->num_ligne = $erreur->num_ligne;
        $erreurNode->csv_erreur = $erreur->erreur_csv;
        $erreurNode->diagnostic = $erreur->raison;
        return $erreurNode;
    }

    public function clearErreurs() {
        $this->remove('erreurs');
        $this->add('erreurs');
        $this->statut = null;
    }

}

<?php

/**
 * Model for CSV
 *
 */
class CSVDRM extends BaseCSVDRM {

    public function __construct() {
        parent::__construct();
        $this->type = "CSVDRM";
    }

    public function getFileContent() {
        return file_get_contents($this->getAttachmentUri($this->getFileName()));
    }

    public function getFileName() {
        return 'import_edi_' . $this->identifiant . '_' . $this->periode . '.csv';
    }

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

    public function addErreur($erreur) {
        $erreurNode = $this->erreurs->getOrAdd($erreur->num_ligne);
        $erreurNode->num_ligne = $erreur->num_ligne;
        $erreurNode->csv_erreur = $erreur->erreur_csv;
        $erreurNode->diagnostic = $erreur->raison;
        return $erreurNode;
    }

    public function clearErreurs() {
        $this->remove('erreurs');
        $this->add('erreurs');
        $this->statut = null;
    }

}

Set type après le construct

Set type après le construct


<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    public const VERSION = '0.8.7';
}

<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    public const VERSION = '0.8.8';
}

Set release version to 0.8.8

Set release version to 0.8.8


<?php

use Symfony\Component\Dotenv\Dotenv;

require dirname(__DIR__).'/vendor/autoload.php';

// Load cached env vars if the .env.local.php file exists
// Run "composer dump-env prod" to create it (requires symfony/flex >=1.2)
if (is_array($env = @include dirname(__DIR__).'/.env.local.php')) {
    $_SERVER += $env;
    $_ENV += $env;
} elseif (!class_exists(Dotenv::class)) {
    throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
} else {
    // load all the .env files
    (new Dotenv())->loadEnv(dirname(__DIR__).'/.env');
}

$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev';
$_SERVER['APP_DEBUG'] = $_SERVER['APP_DEBUG'] ?? $_ENV['APP_DEBUG'] ?? 'prod' !== $_SERVER['APP_ENV'];
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int) $_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';

<?php

use Symfony\Component\Dotenv\Dotenv;

require dirname(__DIR__).'/vendor/autoload.php';

// Load cached env vars if the .env.local.php file exists
// Run "composer dump-env prod" to create it (requires symfony/flex >=1.2)
if (is_array($env = @include dirname(__DIR__).'/.env.local.php')) {
    $_SERVER += $env;
    $_ENV += $env;
} elseif (!class_exists(Dotenv::class)) {
    throw new RuntimeException(
        'Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.'
    );
} else {
    // load all the .env files
    (new Dotenv())->loadEnv(dirname(__DIR__).'/.env');
}

$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev';
$_SERVER['APP_DEBUG'] = $_SERVER['APP_DEBUG'] ?? $_ENV['APP_DEBUG'] ?? 'prod' !== $_SERVER['APP_ENV'];
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int) $_SERVER['APP_DEBUG'] ||
    filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';

Fix line length for code style check

Fix line length for code style check


<?php

namespace Orbt\StyleMirror\Css;

use Orbt\StyleMirror\Resource\SingleUseQueue;
use Orbt\ResourceMirror\Resource\GenericResource;

/**
 * Scans a stylesheet for resources.
 */
class ResourceScanner
{
    protected $queue;

    public function __construct(SingleUseQueue $queue)
    {
        $this->queue = $queue;
    }

    /**
     * Scans CSS content for resources.
     *
     * @param GenericResource $resource
     * @param string $content
     */
    public function scan(GenericResource $resource, $content)
    {
        // Match all URL references.
        preg_match_all('!url\(\s*[\'"]?([^\'"):/]+(?:/[^\'"):/]+)*)[\'"]?\s*\)!i', $content, $matches);
        foreach ($matches[1] as $path) {
            $this->queue->add(new GenericResource($resource->resolvePath($path)));
        }
    }
}

<?php

namespace Orbt\StyleMirror\Css;

use Orbt\StyleMirror\Resource\SingleUseQueue;
use Orbt\ResourceMirror\Resource\GenericResource;

/**
 * Scans a stylesheet for resources.
 */
class ResourceScanner
{
    /**
     * Scanner queue.
     * @var SingleUseQueue
     */
    protected $queue;

    public function __construct(SingleUseQueue $queue)
    {
        $this->queue = $queue;
    }

    /**
     * Returns the queue used by this scanner.
     */
    public function getQueue()
    {
        return $this->queue;
    }

    /**
     * Scans CSS content for resources.
     *
     * @param GenericResource $resource
     * @param string $content
     */
    public function scan(GenericResource $resource, $content)
    {
        // Match all URL references.
        preg_match_all('!url\(\s*[\'"]?([^\'"):/]+(?:/[^\'"):/]+)*)[\'"]?\s*\)!i', $content, $matches);
        foreach ($matches[1] as $path) {
            $this->queue->add(new GenericResource($resource->resolvePath($path)));
        }
    }
}

Add getter method for scanner queue.

Add getter method for scanner queue.


<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'task',
        '/task'
        //
    ];
}

Add Test case with delete Feature

Add Test case with delete Feature


<?php

/*
 * This file is part of the Manalize project.
 *
 * (c) Manala <contact@manala.io>
 *
 * For the full copyright and license information, please refer to the LICENSE
 * file that was distributed with this source code.
 */

namespace Manala\Manalize;

use Symfony\Component\Console\Application as BaseApplication;

/**
 * @author Robin Chalas <robin.chalas@gmail.com>
 */
final class Application extends BaseApplication
{
    const VERSION = '0.5.1-DEV';
    const REPOSITORY_NAME = 'manala/manalize';

    public function __construct()
    {
        parent::__construct('Manalize', self::VERSION);

        $this->addCommands([
            new Command\Setup(),
            new Command\Diff(),
            new Command\CheckRequirements(),
            new Command\SelfUpdate(),
        ]);
    }
}

<?php

/*
 * This file is part of the Manalize project.
 *
 * (c) Manala <contact@manala.io>
 *
 * For the full copyright and license information, please refer to the LICENSE
 * file that was distributed with this source code.
 */

namespace Manala\Manalize;

use Symfony\Component\Console\Application as BaseApplication;

/**
 * @author Robin Chalas <robin.chalas@gmail.com>
 */
final class Application extends BaseApplication
{
    const VERSION = '0.5.1';
    const REPOSITORY_NAME = 'manala/manalize';

    public function __construct()
    {
        parent::__construct('Manalize', self::VERSION);

        $this->addCommands([
            new Command\Setup(),
            new Command\Diff(),
            new Command\CheckRequirements(),
            new Command\SelfUpdate(),
        ]);
    }
}

Bump version to 0.5.1 stable

Bump version to 0.5.1 stable


<?php

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

class CreateNotificationsTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('seat_notifications', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('type')->default('system');
            $table->string('title');
            $table->string('text');
            $table->integer('read')->default(0);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('seat_notifications');
    }

}

<?php

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

class CreateNotifications extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('seat_notifications', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('type')->default('system');
            $table->string('title');
            $table->string('text');
            $table->integer('read')->default(0);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('seat_notifications');
    }

}

Fix class name to be psr compliant else the migration will fail to find the class


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

namespace Facebook\WebDriver\Remote;

class WebDriverCommandTest extends \PHPUnit_Framework_TestCase
{
    public function testShouldSetOptionsUsingConstructot()
    {
        $command = new WebDriverCommand('session-id-123', 'bar-baz-name', array('foo' => 'bar'));

        $this->assertSame('session-id-123', $command->getSessionID());
        $this->assertSame('bar-baz-name', $command->getName());
        $this->assertSame(array('foo' => 'bar'), $command->getParameters());
    }
}

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

namespace Facebook\WebDriver\Remote;

class WebDriverCommandTest extends \PHPUnit_Framework_TestCase
{
    public function testShouldSetOptionsUsingConstructor()
    {
        $command = new WebDriverCommand('session-id-123', 'bar-baz-name', array('foo' => 'bar'));

        $this->assertSame('session-id-123', $command->getSessionID());
        $this->assertSame('bar-baz-name', $command->getName());
        $this->assertSame(array('foo' => 'bar'), $command->getParameters());
    }
}

Fix typo in test method name.

Fix typo in test method name.


<?php

namespace Core\GameSessionBundle\Form\Type;

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

class CreateGameSessiontype extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('description', 'textarea', array('attr' => array('rows' => '5', 'cols' => '30')))
            ->add('save', 'submit')
            ->getForm()
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Core\GameSessionBundle\Entity\GameSession',
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'core_gamesessionbundle_createGameSession';
    }
}

<?php

namespace Core\GameSessionBundle\Form\Type;

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

class CreateGameSessionType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('description', 'textarea', array('attr' => array('rows' => '5', 'cols' => '30')))
            ->add('save', 'submit')
            ->getForm()
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Core\GameSessionBundle\Entity\GameSession',
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'core_gamesessionbundle_createGameSession';
    }
}

Fix typo... type to Type

Fix typo... type to Type


<?php

namespace Intracto\SecretSantaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Intracto\SecretSantaBundle\Entity\Pool;
use Intracto\SecretSantaBundle\Entity\Entry;
use Symfony\Component\HttpFoundation\Request;

class ReportController extends Controller
{
    /**
     * @Route("/report", name="report")
     * @Template()
     */
    public function reportAction(Request $request)
    {
        $reportingServices = $this->get('intracto_secret_santa.report.reporting');

        $current_year = $request->get('year');

        if ($request->get('year') != NULL && $request->get('year') != 'all') {
            $dataPool = $reportingServices->getPullReport($current_year);
        } else {
            $dataPool = $reportingServices->getFullPullReport();
        }

        return $data = [
            'current_year' => $current_year,
            'dataPool' => $dataPool
        ];
    }
}

<?php

namespace Intracto\SecretSantaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Intracto\SecretSantaBundle\Entity\Pool;
use Intracto\SecretSantaBundle\Entity\Entry;
use Symfony\Component\HttpFoundation\Request;

class ReportController extends Controller
{
    /**
     * @Route("/report", name="report")
     * @Template()
     */
    public function reportAction(Request $request)
    {
        $reportingServices = $this->get('intracto_secret_santa.report.reporting');

        $current_year = $request->get('year');

        if ($current_year != NULL && $current_year != 'all') {
            $dataPool = $reportingServices->getPullReport($current_year);

            $featured_years = [];
            foreach ($dataPool['featured_years'] as $d) {
                array_push($featured_years, $d['featured_year']);
            }

            if (!in_array($current_year, $featured_years)) {
                throw $this->createNotFoundException('Data over dit jaartal zijn niet beschikbaar');
            }
        } else {
            $dataPool = $reportingServices->getFullPullReport();
        }

        return $data = [
            'current_year' => $current_year,
            'dataPool' => $dataPool
        ];
    }
}

Throw exception if no data of year is available


<?php

namespace App\Console\Commands\Search;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ScoutImportAll extends BaseCommand
{

    protected $signature = 'scout:import-all';

    protected $description = 'Import all models into the search index';

    public function handle()
    {

        ini_set("memory_limit", "-1");

        $models = app('Search')->getSearchableModels();

        foreach( $models as $model ) {

            $this->call("scout:import", ['model' => $model]);

        }

    }

}

<?php

namespace App\Console\Commands\Search;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ScoutImportAll extends BaseCommand
{

    protected $signature = 'scout:import-all';

    protected $description = 'Import all models into the search index';

    private $excludeModels = [
        // 'App\\Models\\Collections\\Artwork',
        // 'App\\Models\\Collections\\Image',
    ];

    public function handle()
    {

        ini_set("memory_limit", "-1");

        $models = app('Search')->getSearchableModels();

        $models = array_diff($models, $this->excludeModels);

        foreach( $models as $model ) {

            $this->call("scout:import", ['model' => $model]);

        }

    }

}

Allow exclusion of models from scout:import-all


<?php

namespace User\Form;

use Zend\Form\Form;

class UserForm extends Form
{
    public function __construct($name = null)
    {
        parent::__construct('user');
        $this->setAttribute('method', 'post');

        $this->add(array(
            'name' => 'id',
            'type' => 'Hidden',
        ));

        $this->add(array(
            'name' => 'username',
            'type' => 'Text',
            'attributes' => array(
                'class' => 'form-control',
            ),
        ));

        $this->add(array(
            'name' => 'email',
            'type' => 'Email',
            'attributes' => array(
                'class' => 'form-control',
            ),
        ));

        $this->add(array(
            'name' => 'full_name',
            'type' => 'Text',
            'attributes' => array(
                'class' => 'form-control',
            ),
        ));

        $this->add(array(
            'name' => 'password',
            'type' => 'Password',
            'attributes' => array(
                'class' => 'form-control',
            ),
        ));

        $this->add(array(
            'name' => 'submit',
            'type' => 'Submit',
            'attributes' => array(
                'value' => 'Submit',
                'id' => 'submit-btn',
                'class' => 'btn btn-primary',
            ),
        ));
    }
}

<?php

namespace User\Form;

use Zend\Form\Form;

class UserForm extends Form
{
    public function __construct($name = null)
    {
        parent::__construct('user');
        $this->setAttribute('method', 'post');

        $this->add(array(
            'name' => 'id',
            'type' => 'Hidden',
        ));

        $this->add(array(
            'name' => 'username',
            'type' => 'Text',
            'attributes' => array(
                'class' => 'form-control',
            ),
        ));

        $this->add(array(
            'name' => 'email',
            'type' => 'Email',
            'attributes' => array(
                'class' => 'form-control',
            ),
        ));

        $this->add(array(
            'name' => 'full_name',
            'type' => 'Text',
            'attributes' => array(
                'class' => 'form-control',
            ),
        ));

        $this->add(array(
            'name' => 'password',
            'type' => 'Password',
            'attributes' => array(
                'class' => 'form-control',
            ),
        ));

        $this->add(array(
            'name' => 'confirm_password',
            'type' => 'Password',
            'attributes' => array(
                'class' => 'form-control',
            ),
        ));

        $this->add(array(
            'name' => 'remember_me',
            'type' => 'checkbox',
        ));

        $this->add(array(
            'name' => 'submit',
            'type' => 'Submit',
            'attributes' => array(
                'value' => 'Submit',
                'id' => 'submit-btn',
                'class' => 'btn btn-primary',
            ),
        ));
    }
}

Add field `confirm_password` and `remember_me` to form


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

namespace Darvin\Utils\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;

/**
 * Anti-spam form type
 */
class AntiSpamType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'label'       => false,
            'attr'        => [
                'class' => 'title_field',
            ],
            'constraints' => new Blank(),
            'mapped'      => false,
            'required'    => false,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return TextType::class;
    }
}

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

namespace Darvin\Utils\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;

/**
 * Anti-spam form type
 */
class AntiSpamType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'label'       => false,
            'attr'        => [
                'class' => 'title_field',
            ],
            'constraints' => new Blank(),
            'mapped'      => false,
            'required'    => false,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getParent(): string
    {
        return TextType::class;
    }

    /**
     * {@inheritDoc}
     */
    public function getBlockPrefix(): string
    {
        return 'darvin_utils_anti_spam';
    }
}

Configure block prefix of anti spam form.


<?php
/*
 * The configuration of SURFconext Service Registry package
 */

$config = array (
    'meta_refresh_cron_tags'      => array('hourly'),
    'validate_entity_certificate_cron_tags' => array('daily'),
    'validate_entity_endpoints_cron_tags' => array('daily'),
    'ca_bundle_file' => '/etc/pki/tls/certs/ca-bundle.pem',
);

<?php
/*
 * The configuration of SURFconext Service Registry package
 */

$config = array (
    'meta_refresh_cron_tags'      => array('hourly'),
    'validate_entity_certificate_cron_tags' => array('daily'),
    'validate_entity_endpoints_cron_tags' => array('daily'),
    'ca_bundle_file' => '/etc/pki/tls/certs/ca-bundle.crt',
);

Use .crt file instead of custom .pem file for Root CAs

git-svn-id: fac53d8b196e0ef1c2775236b39a8c3227ab71b5@511 528793b8-127e-4309-9901-b74759c7208d


<?php
require_once("../lib/Helper.php");
require_once("../lib/Deployer.php");
require_once("../lib/Api.php");

$data = (file_get_contents('php://input'));
$api = new Api($data);

<?php
require_once("../resources/lib/Helper.php");
require_once("../resources/lib/Deployer.php");
require_once("../resources/lib/Api.php");

$data = (file_get_contents('php://input'));
$api = new Api($data);

Change wrong path in rest-api

Change wrong path in rest-api


<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Setups\Customizer\Posts\Controls;

use GrottoPress\Jentil\Setups\Customizer\Posts\AbstractSection;

final class Image extends AbstractControl
{
    public function __construct(AbstractSection $section)
    {
        parent::__construct($section);

        $this->id = $secion->settings['Image']->id;

        $this->args['label'] = \esc_html__('Image size', 'jentil');
        $this->args['type'] = 'select';
        $this->args['choices'] = $this->customizer->app
            ->utilities->page->posts->imageSizes();
    }
}

<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Setups\Customizer\Posts\Controls;

use GrottoPress\Jentil\Setups\Customizer\Posts\AbstractSection;

final class Image extends AbstractControl
{
    public function __construct(AbstractSection $section)
    {
        parent::__construct($section);

        $this->id = $section->settings['Image']->id;

        $this->args['label'] = \esc_html__('Image size', 'jentil');
        $this->args['type'] = 'select';
        $this->args['choices'] = $this->customizer->app
            ->utilities->page->posts->imageSizes();
    }
}

Fix PHP Notice: `Undefined variable: secion`


<?php namespace EngineWorks\DBAL\Sqlite;

use EngineWorks\DBAL\Abstracts\SettingsMap;

/**
 * Settings for a sqlite connection
 *
 * - filename: database resource
 * - prefix: tables prefix
 * - flags: null
 * - dump: '' => nothing, 'info' => '-- info messages',  'debug' => SELECT... + info
 *
 * @package EngineWorks\DBAL\Sqlite
 */
class Settings extends SettingsMap
{
    protected $map = [
        'filename' => '',
        'prefix' => '',
        'flags' => null,
        'dump' => '',
    ];
}

<?php namespace EngineWorks\DBAL\Sqlite;

use EngineWorks\DBAL\Abstracts\SettingsMap;

/**
 * Settings for a sqlite connection
 *
 * - filename: database resource
 * - enable-exceptions: sqlite will throw \Exceptions instead of errors
 * - prefix: tables prefix
 * - flags: 6 => SQLITE3_OPEN_CREATE + SQLITE3_OPEN_READWRITE
 * - dump: '' => nothing, 'info' => '-- info messages',  'debug' => SELECT... + info
 *
 * @package EngineWorks\DBAL\Sqlite
 */
class Settings extends SettingsMap
{
    protected $map = [
        'filename' => '',
        'enable-exceptions' => false,
        'prefix' => '',
        'flags' => SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE,
        'dump' => '',
    ];
}

Set default flags and document enable-exceptions


<?php
namespace Neilime\AssetsBundle\Service\Filter;
class CssFilter implements \Neilime\AssetsBundle\Service\Filter\FilterInterface{

	/**
	 * @param string $sContent
	 * @see \Neilime\AssetsBundle\Service\Filter\FilterInterface::run()
	 * @throws \Exception
	 * @return string
	 */
	public function run($sContent){
		if(!is_string($sContent))throw new \Exception('Content is not a string : '.gettype($sContent));
		return \CssMin::minify(
			$sContent,
			null,
			array(
				'ConvertHslColors' => true,
				'ConvertRgbColors' => true,
				'ConvertNamedColors' => true,
				'CompressColorValues' => true,
				'CompressUnitValues' => true,
				'CompressExpressionValues' => true
			)
		);
	}
}

<?php
namespace Neilime\AssetsBundle\Service\Filter;
class CssFilter implements \Neilime\AssetsBundle\Service\Filter\FilterInterface{

	/**
	 * @param string $sContent
	 * @see \Neilime\AssetsBundle\Service\Filter\FilterInterface::run()
	 * @throws \Exception
	 * @return string
	 */
	public function run($sContent){
		if(!is_string($sContent))throw new \Exception('Content is not a string : '.gettype($sContent));
		return \CssMin::minify(
			$sContent,
			array(
				'ConvertLevel3AtKeyframes' => array('RemoveSource' => false),
				'ConvertLevel3Properties' => true
			),
			array(
		       	'ConvertFontWeight' => true,
		        'ConvertHslColors' => true,
		        'ConvertRgbColors' => true,
		        'ConvertNamedColors' => true,
		        'CompressColorValues' => true,
		        'CompressUnitValues' => true,
		        'CompressExpressionValues' => true
			)
		);
	}
}

Add support for css Keyframes properties


<?php

namespace MainBundle\Controller;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;
use MainBundle\Entity\Logo;
use MainBundle\Entity\Section;
use MainBundle\Repository\LogoRepository;
use MainBundle\Repository\SectionRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use phpCAS;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use UserBundle\Entity\User;
use UserBundle\Repository\UserRepository;

class RestController extends BaseController
{
    public function logoAction($code_section)
    {
        /** @var EntityManager $em */
        $em = $this->getDoctrine()->getManager();

        /** @var Section $section */
        $section = $em->getRepository('MainBundle:Section')->findOneBy(array("code" => $code_section));

        if (!$section){
            throw $this->createNotFoundException('No section found with this code');
        }

        /** @var Logo $logo */
        $logo = $section->getLogos()->first();

        $baseurl = "http://logoinserter.esnlille.fr";

        return new JsonResponse(
            $baseurl . "/" . $logo->getWebPath()
        );
    }
}

<?php

namespace MainBundle\Controller;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;
use MainBundle\Entity\Logo;
use MainBundle\Entity\Section;
use MainBundle\Repository\LogoRepository;
use MainBundle\Repository\SectionRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use phpCAS;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use UserBundle\Entity\User;
use UserBundle\Repository\UserRepository;

class RestController extends BaseController
{
    public function logoAction($code_section)
    {
        /** @var EntityManager $em */
        $em = $this->getDoctrine()->getManager();

        /** @var Section $section */
        $section = $em->getRepository('MainBundle:Section')->findOneBy(array("code" => $code_section));

        if (!$section){
            throw $this->createNotFoundException('No section found with this code');
        }

        /** @var Logo $logo */
        $logo = $section->getLogos()->first();

        $baseurl = "http://logoinserter.esnlille.fr";

        return new JsonResponse(array(
            "url" => $baseurl . "/" . $logo->getWebPath()
        )
        );
    }
}

Add array return for the rest controller


Fix update version for 0.9.0 -> 0.9.2

Fix update version for 0.9.0 -> 0.9.2


<?php namespace professionalweb\payment\contracts\recurring;

use professionalweb\payment\contracts\PayService;

/**
 * Interface for payment systems have recurring payments
 * @package professionalweb\payment\contracts\recurring
 */
interface RecurringPayment
{
    /**
     * Get payment token
     *
     * @return string
     */
    public function getRecurringPayment(): string;

    /**
     * Initialize recurring payment
     *
     * @param string $token
     * @param float  $amount
     * @param string $description
     * @param string $currency
     *
     * @return bool
     */
    public function initPayment(string $token, float $amount, string $description, string $currency = PayService::CURRENCY_RUR_ISO): bool;

    /**
     * Remember payment fo recurring payments
     *
     * @return RecurringPayment
     */
    public function makeRecurring(): self;

    /**
     * Set user id payment will be assigned
     *
     * @param string $id
     *
     * @return RecurringPayment
     */
    public function setUserId(string $id): self;
}

<?php namespace professionalweb\payment\contracts\recurring;

use professionalweb\payment\contracts\PayService;

/**
 * Interface for payment systems have recurring payments
 * @package professionalweb\payment\contracts\recurring
 */
interface RecurringPayment
{
    /**
     * Get payment token
     *
     * @return string
     */
    public function getRecurringPayment(): string;

    /**
     * Initialize recurring payment
     *
     * @param string $token
     * @param string $accountId
     * @param float  $amount
     * @param string $description
     * @param string $currency
     *
     * @param array  $extraParams
     *
     * @return bool
     */
    public function initPayment(string $token, string $accountId, float $amount, string $description, string $currency = PayService::CURRENCY_RUR_ISO, array $extraParams = []): bool;

    /**
     * Remember payment fo recurring payments
     *
     * @return RecurringPayment
     */
    public function makeRecurring(): self;

    /**
     * Set user id payment will be assigned
     *
     * @param string $id
     *
     * @return RecurringPayment
     */
    public function setUserId(string $id): self;
}

Add params to recurring interface

Add params to recurring interface


<?php

if ( ! defined('COOKIE_SESSION') ) {
    ini_set('session.use_cookies', '0');
    ini_set('session.use_only_cookies',0);
    ini_set('session.use_trans_sid',1);
}

if ( ! isset($CFG) ) die("Please configure this product using config.php");
if ( ! isset($CFG->staticroot) ) die('$CFG->staticroot not defined see https://github.com/csev/webauto/issues/2');
if ( ! isset($CFG->bootstrap) ) die('$CFG->bootstrap not defined in config.php');
if ( ! isset($CFG->timezone) ) die('$CFG->timezone not defined in config.php');
// Set this to the temporary folder
if ( ! isset($CFG->dataroot) ) {
	$tmp = sys_get_temp_dir();
    if (strlen($tmp) > 1 && substr($tmp, -1) == '/') $tmp = substr($tmp,0,-1);
	$CFG->dataroot = $tmp;
}

error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL );
ini_set('display_errors', 1);

date_default_timezone_set($CFG->timezone);

// No trailer

<?php

require_once $CFG->dirroot."/lib/lms_lib.php";  // During transition

if ( ! defined('COOKIE_SESSION') ) {
    ini_set('session.use_cookies', '0');
    ini_set('session.use_only_cookies',0);
    ini_set('session.use_trans_sid',1);
}

if ( ! isset($CFG) ) die("Please configure this product using config.php");
if ( ! isset($CFG->staticroot) ) die('$CFG->staticroot not defined see https://github.com/csev/webauto/issues/2');
if ( ! isset($CFG->bootstrap) ) die('$CFG->bootstrap not defined in config.php');
if ( ! isset($CFG->timezone) ) die('$CFG->timezone not defined in config.php');

// Set this to the temporary folder if not set - dev only
if ( ! isset($CFG->dataroot) ) {
	$tmp = sys_get_temp_dir();
    if (strlen($tmp) > 1 && substr($tmp, -1) == '/') $tmp = substr($tmp,0,-1);
	$CFG->dataroot = $tmp;
}

error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL );
ini_set('display_errors', 1);

date_default_timezone_set($CFG->timezone);

// No trailer

Make sure that lib/lms_lib is included

Make sure that lib/lms_lib is included


<?php
namespace WiContactAPI\V1\Rest\Contact;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="WiContactAPI\V1\Rest\Contact\ContactCollection")
 * @ORM\Table(name="contacts")
 */
class ContactEntity
{

    /**
     *
     * @var int @ORM\Id
     *      @ORM\Column(type="integer")
     *      @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     *
     * @var string @ORM\Column(type="string", nullable=true)
     */
    protected $name;

    /**
     *
     * @return the $id
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     *
     * @return the $name
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     *
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    // @todo: Add phones support
    // @todo: Add Gedmo Annotations support

    /**
     *
     * @see Zend\\Stdlib\\Hydrator\\ArraySerializable::extract expects the provided object to implement getArrayCopy()
     * @return multitype
     */
    public function getArrayCopy()
    {
        return get_object_vars($this);
    }

}

<?php
namespace WiContactAPI\V1\Rest\Contact;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="WiContactAPI\V1\Rest\Contact\ContactCollection")
 * @ORM\Table(name="wi_contacts")
 */
class ContactEntity
{

    /**
     *
     * @var int @ORM\Id
     *      @ORM\Column(type="integer")
     *      @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     *
     * @var string @ORM\Column(type="string", nullable=true)
     */
    protected $name;

    /**
     *
     * @return the $id
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     *
     * @return the $name
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     *
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    // @todo: Add phones support
    // @todo: Add Gedmo Annotations support

    /**
     *
     * @see Zend\\Stdlib\\Hydrator\\ArraySerializable::extract expects the provided object to implement getArrayCopy()
     * @return multitype
     */
    public function getArrayCopy()
    {
        return get_object_vars($this);
    }

}

Add prefix 'wi' to database table name.

Add prefix 'wi' to database table name.


<?php

namespace App\Http\Controllers;

class FootnotesController extends ApiController
{

    protected $model = \App\Models\Dsc\Footnote::class;

    protected $transformer = \App\Http\Transformers\FootnoteTransformer::class;

}

<?php

namespace App\Http\Controllers;

class FootnotesController extends ApiController
{

    protected $model = \App\Models\Dsc\Footnote::class;

    protected $transformer = \App\Http\Transformers\FootnoteTransformer::class;

    /**
     * Validate `id` route or query string param format.
     * Footnotes follow OSCI `id` format, e.g. `fn-429-158`
     *
     * @param mixed $id
     * @return boolean
     */
    protected function validateId( $id )
    {

        return preg_match( '/^fn-[0-9]+-[0-9]+$/', $id );

    }

}

Fix id validation for Footnotes

Fix id validation for Footnotes


<?php
namespace Criterion\UI\Controller;

class HookController
{
    public function github(\Silex\Application $app)
    {
        $payload = json_decode($app['request']->get('payload'), true);
        if ( ! isset($payload['repository']['url']))
        {
            return $app->json(array(
                'success' => false
            ));
        }

        $repo = $payload['repository']['url'];
        // Detect if its an private repository, if so then we need to use SSH
        if ($payload['repository']['private'])
        {
            $repo = \Criterion\Helper\Github::toSSHUrl($repo);
        }

        $project = new \Criterion\Model\Project(array(
            'repo' => $repo
        ));

        if ( ! $project->exists)
        {
            $project->save();
        }

        $test = new \Criterion\Model\Test();
        $test->project_id = $project->id;
        $test->branch = str_replace('refs/heads/', null, $payload['ref']);
        $test->save();

        return $app->json(array(
            'success' => true,
            'test' => (string) $test->id
        ));
    }
}

<?php
namespace Criterion\UI\Controller;

class HookController
{
    public function github(\Silex\Application $app)
    {
        $query_token = $app['request']->query->get('token');

        $token = new \Criterion\Model\Token($query_token);

        if ( ! $token->exists)
        {
            return $app->abort(404, 'Page does not exist');
        }

        $payload = json_decode($app['request']->get('payload'), true);
        if ( ! isset($payload['repository']['url']))
        {
            return $app->json(array(
                'success' => false
            ));
        }

        $repo = $payload['repository']['url'];
        // Detect if its an private repository, if so then we need to use SSH
        if ($payload['repository']['private'])
        {
            $repo = \Criterion\Helper\Github::toSSHUrl($repo);
        }

        $project = new \Criterion\Model\Project(array(
            'repo' => $repo
        ));

        if ( ! $project->exists)
        {
            $project->save();
        }

        $test = new \Criterion\Model\Test();
        $test->project_id = $project->id;
        $test->branch = str_replace('refs/heads/', null, $payload['ref']);
        $test->save();

        return $app->json(array(
            'success' => true,
            'test' => (string) $test->id
        ));
    }
}

Use token in github hook

Use token in github hook


<?php

namespace Metrique\Building\Contracts;

interface PageRepositoryInterface
{
    /**
     * Get all pages.
     * @return Illuminate\Support\Collection
     */
    public function all();

    /**
     * Find a page.
     * @return mixed
     */
    public function find($id);

    /**
     * Create a page from an array.
     * @return mixed
     */
    public function create(array $data);

    /**
     * Create a page from the request object.
     * @return mixed
     */
    public function createWithRequest();

    /**
     * Destroy a page.
     * @param  int $id
     * @return mixed
     */
    public function destroy($id);

    /**
     * Update a page from an array.
     * @return mixed
     */
    public function update($id, array $data);

    /**
     * Create a page from the request object.
     * @return mixed
     */
    public function updateWithRequest($id);

    /**
     * Get the page and meta by slug.
     * @param  strint $slug
     * @return mixed
     */
    public function bySlug($slug);

    /**
     * Get the page and full formatted content by slug.
     * @param  string $slug
     * @return $mixed
     */
    public function contentBySlug($slug);

    /**
     * Get meta data from page meta json.
     * For this to be populated the bySlug($slug) method should be called first.
     * By default this will return a blank string.
     *
     * @param  string
     * @return string
     */
    public function getMeta($key);
}

<?php

namespace Metrique\Building\Contracts;

interface PageRepositoryInterface
{
    /**
     * Get all pages.
     * @return Illuminate\Support\Collection
     */
    public function all();

    /**
     * Find a page.
     * @return mixed
     */
    public function find($id);

    /**
     * Create a page from an array.
     * @return mixed
     */
    public function create(array $data);

    /**
     * Create a page from the request object.
     * @return mixed
     */
    public function createWithRequest();

    /**
     * Destroy a page.
     * @param  int $id
     * @return mixed
     */
    public function destroy($id);

    /**
     * Update a page from an array.
     * @return mixed
     */
    public function update($id, array $data);

    /**
     * Create a page from the request object.
     * @return mixed
     */
    public function updateWithRequest($id);

    /**
     * Get the page and meta by slug.
     * @param  strint $slug
     * @return mixed
     */
    public function bySlug($slug);

    /**
     * Get the page and full formatted content by slug.
     * @param  string $slug
     * @return $mixed
     */
    public function contentBySlug($slug);

    /**
     * Converts a string to slug/url format.
     * Underscore represents a path separator.
     * Dash is used as a word separator.
     *
     * @param  $string
     * @param  string $delimiter
     * @param  string $directorySeparator
     * @return string
     */
    public function slugify($string, $delimiter = '-', $directorySeparator = '_');

    /**
     * Converts a slug back to a path.
     *
     * @param  string $string
     * @return string
     */
    public function unslugify($string, $directorySeparator = '_');
}

Add slugify with / _ support

Add slugify with / _ support


<?php

namespace wcf\action;

use wcf\system\exception\IllegalLinkException;
use wcf\util\JSON;

/**
 * Internal action used to run a test for url rewriting.
 *
 * @author  Alexander Ebert
 * @copyright   2001-2019 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Action
 * @since       3.1
 */
class CoreRewriteTestAction extends AbstractAction
{
    const AVAILABLE_DURING_OFFLINE_MODE = true;

    /**
     * @inheritDoc
     *
     * @throws      IllegalLinkException
     */
    public function readParameters()
    {
        parent::readParameters();

        if (!isset($_GET['uuidHash']) || !\hash_equals(\hash('sha256', WCF_UUID), $_GET['uuidHash'])) {
            throw new IllegalLinkException();
        }
    }

    /**
     * @inheritDoc
     */
    public function execute()
    {
        parent::execute();

        \header('Access-Control-Allow-Origin: *');
        \header('Content-type: application/json; charset=UTF-8');
        echo JSON::encode(['core_rewrite_test' => 'passed']);

        exit;
    }
}

<?php

namespace wcf\action;

use Laminas\Diactoros\Response\JsonResponse;
use wcf\system\exception\IllegalLinkException;

/**
 * Internal action used to run a test for url rewriting.
 *
 * @author  Alexander Ebert
 * @copyright   2001-2019 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Action
 * @since       3.1
 */
class CoreRewriteTestAction extends AbstractAction
{
    const AVAILABLE_DURING_OFFLINE_MODE = true;

    /**
     * @inheritDoc
     *
     * @throws      IllegalLinkException
     */
    public function readParameters()
    {
        parent::readParameters();

        if (!isset($_GET['uuidHash']) || !\hash_equals(\hash('sha256', WCF_UUID), $_GET['uuidHash'])) {
            throw new IllegalLinkException();
        }
    }

    /**
     * @inheritDoc
     */
    public function execute()
    {
        parent::execute();

        return new JsonResponse(
            [
                'core_rewrite_test' => 'passed',
            ],
            200,
            [
                'access-control-allow-origin' => '*',
            ]
        );
    }
}

Use PSR-7 responses in CoreRewriteTestAction


<?php

use Illuminate\Database\Seeder;
use Northstar\Models\Client;

class ApiKeyTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('client')->delete();

        Client::create([
            'client_id' => '456',
            'client_secret' => 'abc4324',
            'scope' => ['admin', 'user'],
        ]);

        Client::create([
            'client_id' => '123',
            'client_secret' => '5464utyrs',
            'scope' => ['user'],
        ]);
    }
}

<?php

use Illuminate\Database\Seeder;
use Northstar\Models\Client;

class ApiKeyTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('clients')->delete();

        Client::create([
            'client_id' => '456',
            'client_secret' => 'abc4324',
            'scope' => ['admin', 'user'],
        ]);

        Client::create([
            'client_id' => '123',
            'client_secret' => '5464utyrs',
            'scope' => ['user'],
        ]);
    }
}

Update table name in seeder.

Update table name in seeder.


<input type="search"
    <?php echo $view['form']->attributes() ?>
    name="<?php echo $view->escape($name) ?>"
    value="<?php echo $view->escape($value) ?>"
    <?php if ($read_only): ?>disabled="disabled"<?php endif ?>
    <?php if ($required): ?>required="required"<?php endif ?>
    <?php if ($max_length): ?>maxlength="<?php echo $max_length ?>"<?php endif ?>
/>

<input type="search"
    <?php echo $view['form']->attributes() ?>
    name="<?php echo $view->escape($full_name) ?>"
    value="<?php echo $view->escape($value) ?>"
    <?php if ($read_only): ?>disabled="disabled"<?php endif ?>
    <?php if ($required): ?>required="required"<?php endif ?>
    <?php if ($max_length): ?>maxlength="<?php echo $max_length ?>"<?php endif ?>
/>

Fix rendering search inputs in PHP

[FrameworkBundle][Form] Fix rendering search inputs in PHP


<?php

require_once __DIR__.'/../../../init.php';

//var_dump($_SERVER);exit;

$configPath = __DIR__.'/../../../config/config.json';
$configService = new Ric_Server_Config($configPath);
$api = new Ric_Server_Api(
    new Ric_Server_Server($configService),
    new Ric_Server_Auth_Service($configService->getConfig()));
$api->handleRequest();

<?php

require_once __DIR__.'/../../../init.php';

$configPath = __DIR__.'/../../../config/config.json';
$configService = new Ric_Server_Config($configPath);
$api = new Ric_Server_Api(
    new Ric_Server_Server($configService),
    new Ric_Server_Auth_Service($configService->getConfig()));
$api->handleRequest();

Remove debug output of _SERVER

Remove debug output of _SERVER


<?php

/**
 *    Copyright 2016 ppy Pty. Ltd.
 *
 *    This file is part of osu!web. osu!web is distributed with the hope of
 *    attracting more community contributions to the core ecosystem of osu!.
 *
 *    osu!web is free software: you can redistribute it and/or modify
 *    it under the terms of the Affero GNU General Public License version 3
 *    as published by the Free Software Foundation.
 *
 *    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
 *    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *    See the GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with osu!web.  If not, see <http://www.gnu.org/licenses/>.
 */
namespace App\Transformers;

use App\Models\ArtistTrack;
use League\Fractal;

class ArtistTrackTransformer extends Fractal\TransformerAbstract
{
    public function transform(ArtistTrack $track)
    {
        return [
            'id' => $track->id,
            'title' => $track->title,
            'length' => format_duration_for_display($track->length),
            'bpm' => $track->bpm,
            'genre' => $track->genre,
            'preview' => $track->preview,
            'cover_url' => $track->cover_url,
            'osz' => $track->osz,
        ];
    }
}

<?php

/**
 *    Copyright 2016 ppy Pty. Ltd.
 *
 *    This file is part of osu!web. osu!web is distributed with the hope of
 *    attracting more community contributions to the core ecosystem of osu!.
 *
 *    osu!web is free software: you can redistribute it and/or modify
 *    it under the terms of the Affero GNU General Public License version 3
 *    as published by the Free Software Foundation.
 *
 *    osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
 *    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *    See the GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with osu!web.  If not, see <http://www.gnu.org/licenses/>.
 */
namespace App\Transformers;

use App\Models\ArtistTrack;
use League\Fractal;

class ArtistTrackTransformer extends Fractal\TransformerAbstract
{
    public function transform(ArtistTrack $track)
    {
        return [
            'id' => $track->id,
            'title' => $track->title,
            'version' => $track->version,
            'length' => format_duration_for_display($track->length),
            'bpm' => $track->bpm,
            'genre' => $track->genre,
            'preview' => $track->preview,
            'cover_url' => $track->cover_url,
            'osz' => $track->osz,
        ];
    }
}

Add track version to transformer

Add track version to transformer


<?php
/* @var $context Exception */
if (false == headers_sent()
    && $code = $context->getCode()) {
    header('HTTP/1.1 '.$code.' '.$context->getMessage());
    header('Status: '.$code.' '.$context->getMessage());
}

$savvy->setReplacementData('pagetitle', 'Sorry, an error occurred.');
$savvy->setReplacementData('sitetitle', 'Sorry, an error occurred');
?>

        Close this notice

Whoops! Sorry, there was an error:

<?php echo $context->getMessage(); ?>

Convert simple error template to Exception template


<?
// Used to redirect to the real callback page in LODO
// TODO: check if we lose any post params!
header("Location: /lodo.php?t=oauth.callback&" . http_build_query($_GET));
?>

<?
// Used to redirect to the real callback page in LODO
// Need to start session here or we lose redirect url and data
session_start();
header("Location: /lodo.php?t=oauth.callback&" . http_build_query($_GET));
?>

Fix loss of parameters set in _SESSION

Fix loss of parameters set in _SESSION


<?php
namespace DanDMartin\LoggerAware\Traits;

use Psr\Log\LoggerInterface as PsrLogger;
use DanDMartin\LoggerAware\Logger\NullLogger;

trait LoggerAware
{
	protected $logger;

	public function setLogger(PsrLogger $l)
	{
		$this->logger = $l;
	}

	public function getLogger()
	{
		if(is_null($this->logger)) {
			$this->logger = new NullLogger();
		}
		return $this->logger;
	}
}

<?php
namespace DanDMartin\LoggerAware\Traits;

use Psr\Log\LoggerInterface as PsrLogger;
use DanDMartin\LoggerAware\Logger\NullLogger;

trait LoggerAware
{
    /**
     * @var PsrLogger
     */
    protected $logger;

    /**
     * @param PsrLogger $l
     * @required
     */
    public function setLogger(PsrLogger $l)
    {
        $this->logger = $l;
    }

    /**
     * @return PsrLogger
     */
    public function getLogger()
    {
        if(is_null($this->logger)) {
            $this->logger = new NullLogger();
        }
        return $this->logger;
    }
}

Add @required tag to setLogger() so that Symfony can autowire it.