<?php

	function sql_open() {
		global $pdo;
		if($pdo) return true;

		$dsn = DB_TYPE . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE;
		if(!empty(DB_DSN))
			$dsn .= ';' . DB_DSN;
		try {
			return $pdo = new PDO($dsn, DB_USER, DB_PASSWORD);
		} catch(PDOException $e) {
			$message = $e->getMessage();

			// Remove any sensitive information
			$message = str_replace(DB_USER, 'hidden', $message);
			$message = str_replace(DB_PASSWORD, 'hidden', $message);

			// Print error
			error('Database error: ' . $message);
		}
	}

	function sql_close() {
		global $pdo;
		$pdo = NULL;
	}

	function prepare($query) {
		global $pdo;
		return $pdo->prepare($query);
	}

	function query($query) {
		global $pdo;
		return $pdo->query($query);
	}

	function db_error($PDOStatement=null) {
		global $pdo;
		if(isset($PDOStatement)) {
			$err = $PDOStatement->errorInfo();
			return $err[2];
		} else {
			$err = $pdo->errorInfo();
			return $err[2];
		}
	}
?>

<?php

	function sql_open() {
		global $pdo;
		if($pdo) return true;

		$dsn = DB_TYPE . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE;
		if((bool)DB_DSN) // empty() doesn't work on constants
			$dsn .= ';' . DB_DSN;
		try {
			return $pdo = new PDO($dsn, DB_USER, DB_PASSWORD);
		} catch(PDOException $e) {
			$message = $e->getMessage();

			// Remove any sensitive information
			$message = str_replace(DB_USER, 'hidden', $message);
			$message = str_replace(DB_PASSWORD, 'hidden', $message);

			// Print error
			error('Database error: ' . $message);
		}
	}

	function sql_close() {
		global $pdo;
		$pdo = NULL;
	}

	function prepare($query) {
		global $pdo;
		return $pdo->prepare($query);
	}

	function query($query) {
		global $pdo;
		return $pdo->query($query);
	}

	function db_error($PDOStatement=null) {
		global $pdo;
		if(isset($PDOStatement)) {
			$err = $PDOStatement->errorInfo();
			return $err[2];
		} else {
			$err = $pdo->errorInfo();
			return $err[2];
		}
	}
?>

Fix for empty() on a constant

Fix for empty() on a constant


<?php

namespace Yajra\Auditable;

use Illuminate\Database\Eloquent\Model;

class AuditableTraitObserver
{
    /**
     * Model's creating event hook.
     *
     * @param Model $model
     */
    public function creating(Model $model)
    {
        if (! $model->created_by) {
            $model->created_by = $this->getAuthenticatedUserId();
        }

        if (! $model->updated_by) {
            $model->updated_by = $this->getAuthenticatedUserId();
        }
    }

    /**
     * Get authenticated user id depending on model's auth guard.
     *
     * @return int
     */
    protected function getAuthenticatedUserId()
    {
        return auth()->check() ? auth()->id() : 0;
    }

    /**
     * Model's updating event hook.
     *
     * @param Model $model
     */
    public function updating(Model $model)
    {
        if (! $model->isDirty('updated_by')) {
            $model->updated_by = $this->getAuthenticatedUserId();
        }
    }

    /**
     * Model's deleting event hook
     *
     * @param Model $model
     */
    public function deleting(Model $model)
    {
        if (! $model->deleted_by) {
            $model->deleted_by = $this->getAuthenticatedUserId();
        }
    }
}

<?php

namespace Yajra\Auditable;

use Illuminate\Database\Eloquent\Model;

class AuditableTraitObserver
{
    /**
     * Model's creating event hook.
     *
     * @param Model $model
     */
    public function creating(Model $model)
    {
        if (! $model->created_by) {
            $model->created_by = $this->getAuthenticatedUserId();
        }

        if (! $model->updated_by) {
            $model->updated_by = $this->getAuthenticatedUserId();
        }
    }

    /**
     * Get authenticated user id depending on model's auth guard.
     *
     * @return int
     */
    protected function getAuthenticatedUserId()
    {
        return auth()->check() ? auth()->id() : null;
    }

    /**
     * Model's updating event hook.
     *
     * @param Model $model
     */
    public function updating(Model $model)
    {
        if (! $model->isDirty('updated_by')) {
            $model->updated_by = $this->getAuthenticatedUserId();
        }
    }

    /**
     * Model's deleting event hook
     *
     * @param Model $model
     */
    public function deleting(Model $model)
    {
        if (! $model->deleted_by) {
            $model->deleted_by = $this->getAuthenticatedUserId();
        }
    }
}

Use null user by default instead of 0

Use null user by default instead of 0


<?php
namespace Loct\Pinger;

use \JJG\Ping;

/**
 * Factory to create new JJG\Ping
 *
 * @author herloct <herloct@gmail.com>
 */
class PingFactory
{
    /**
     * Create new JJG\Ping
     *
     * @params string  $host Host
     * @params integer $ttl  Ping ttl
     * @return \JJG\Ping
     */
    public function createPing($host)
    {
        return new Ping($host);
    }
}

Add newline character on last line

Add newline character on last line


<?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.

abstract class WebDriverSingleKeyAction
    extends WebDriverKeysRelatedAction
    implements WebDriverAction {

  private $keys;

  public function __construct(
      WebDriverKeyboard $keyboard,
      WebDriverMouse $mouse,
      WebDriverLocatable $location_provider = null,
      $key = null) {
    parent::__construct($keyboard, $mouse, $location_provider);
    $this->key = $key;
  }
}

<?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.

abstract class WebDriverSingleKeyAction
    extends WebDriverKeysRelatedAction
    implements WebDriverAction {

  protected $key;

  public function __construct(
      WebDriverKeyboard $keyboard,
      WebDriverMouse $mouse,
      WebDriverLocatable $location_provider = null,
      $key = null) {
    parent::__construct($keyboard, $mouse, $location_provider);
    $this->key = $key;
  }
}

Fix private property name and visibility


<?php

declare(strict_types=1);

namespace GrumPHP\Process;

use GrumPHP\Collection\ProcessArgumentsCollection;
use Symfony\Component\Process\Process;

/**
 * @internal
 */
final class ProcessFactory
{
    public static function fromArguments(ProcessArgumentsCollection $arguments): Process
    {
        // @todo Remove backward compatibility layer as soon as Symfony Process accepts an array (3.3+).
        //       From then on, you can simply pass `$arguments->getValues()` directly as the first constructor argument.
        $commandlineArgs = array_map(function ($argument) {
            return ProcessUtils::escapeArgument((string) $argument);
        }, $arguments->getValues());

        $commandline = implode(' ', $commandlineArgs);

        return new Process($commandline);
    }
}

<?php

declare(strict_types=1);

namespace GrumPHP\Process;

use GrumPHP\Collection\ProcessArgumentsCollection;
use Symfony\Component\Process\Process;

/**
 * @internal
 */
final class ProcessFactory
{
    public static function fromArguments(ProcessArgumentsCollection $arguments): Process
    {
        return new Process($arguments->getValues());
    }
}

Remove Old Compatibility Layer for Pre-5.x Symfony Process


<?php defined('SYSPATH') or die('No direct script access.');
/**
 * @since 1.0
 * @author Ando Roots <ando@roots.ee>
 */
class ACL_Model_Role extends Model_Auth_Role
{
	// Basic Role constants
	const LOGIN = 1; // Allow login
	const ADMIN = 2; // Never-ever give this role to daily system users! Only for developers.

	protected $_has_many = [
		'permissions' => ['through' => 'permissions_roles'],
		'users'       => ['through' => 'roles_users']
	];

	/**
	 * Check whether the current role can do some action.
	 *
	 * @since 1.0
	 * @param int $permission Either an instance of ACL_Model_Permission or a numeric Permission ID
	 * @return bool True if the action is authorized for this role
	 */
	public function can($permission)
	{
		if (! $this->loaded()) {
			return false;
		}

		// The ADMIN role is all-powerful
		if ($this->pk() === self::ADMIN) {
			return true;
		}

		return $this->has('permissions', $permission);
	}
}

<?php defined('SYSPATH') or die('No direct script access.');
/**
 * @since 1.0
 * @author Ando Roots <ando@roots.ee>
 */
class ACL_Model_Role extends Model_Auth_Role
{
	// Basic Role constants
	const LOGIN = 1; // Allow login
	const ADMIN = 2; // Never-ever give this role to daily system users! Only for developers.

	protected $_has_many = [
		'permissions' => ['through' => 'permissions_roles'],
		'users'       => ['through' => 'roles_users']
	];

	/**
	 * Check whether the current role can do some action.
	 *
	 * @since 1.0
	 * @param int $permission Either an instance of ACL_Model_Permission or a numeric Permission ID
	 * @return bool True if the action is authorized for this role
	 */
	public function can($permission)
	{
		if (! $this->loaded()) {
			return false;
		}

		// The ADMIN role is all-powerful
		if ($this->pk() == self::ADMIN) {
			return true;
		}

		return $this->has('permissions', $permission);
	}
}

Fix type bug: ORM::pk returns a string, not an integer


<?php

namespace WyriHaximus\Ratchet\View\Helper;

use Cake\View\Helper;

class WampHelper extends Helper
{
    public $helpers = [
        'Html',
    ];

    public function beforeLayout()
    {
        $this->_View->append('script', $this->Html->script('WyriHaximus/Ratchet.client'));
    }

    public function client($realm)
    {
        $this->_View->append(
            'script',
            $this->_View->element(
                'WyriHaximus/Ratchet.client',
                [
                    'realm' => $realm,
                ]
            )
        );

        return '';
    }
}

<?php

namespace WyriHaximus\Ratchet\View\Helper;

use Cake\View\Helper;

class WampHelper extends Helper
{
    public $helpers = [
        'Html',
    ];

    public function beforeLayout()
    {
        $this->_View->prepend('script', $this->Html->script('WyriHaximus/Ratchet.client'));
    }

    public function client($realm)
    {
        $this->_View->append(
            'script',
            $this->_View->element(
                'WyriHaximus/Ratchet.client',
                [
                    'realm' => $realm,
                ]
            )
        );

        return '';
    }
}

Prepend WAMP client to script block instead of putting it somewhere in between


<?php
// @codingStandardsIgnoreFile
// @codeCoverageIgnoreStart
// this is an autogenerated file - do not edit
spl_autoload_register(
    function($class) {
        static $classes = null;
        if ($classes === null) {
            $classes = array(
                'theseer\\fdom\\fdomdocument' => '/src/fDOMDocument.php',
                'theseer\\fdom\\fdomdocumentfragment' => '/src/fDOMDocumentFragment.php',
                'theseer\\fdom\\fdomelement' => '/src/fDOMElement.php',
                'theseer\\fdom\\fdomexception' => '/src/fDOMException.php',
                'theseer\\fdom\\fdomnode' => '/src/fDOMNode.php',
                'theseer\\fdom\\fdomnodeinterface' => '/src/fDOMNodeInterface.php',
                'theseer\\fdom\\fdomxpath' => '/src/fDOMXPath.php',
                'theseer\\fdom\\xpathquery' => '/src/XPathQuery.php',
                'theseer\\fdom\\xpathqueryexception' => '/src/XPathQueryException.php'
            );
        }
        $cn = strtolower($class);
        if (isset($classes[$cn])) {
            require __DIR__ . $classes[$cn];
        }
    }
);
// @codeCoverageIgnoreEnd

<?php
// @codingStandardsIgnoreFile
// @codeCoverageIgnoreStart
// this is an autogenerated file - do not edit
spl_autoload_register(
    function($class) {
        static $classes = null;
        if ($classes === null) {
            $classes = array(
                'theseer\\fdom\\fdomdocument' => '/src/fDOMDocument.php',
                'theseer\\fdom\\fdomdocumentfragment' => '/src/fDOMDocumentFragment.php',
                'theseer\\fdom\\fdomelement' => '/src/fDOMElement.php',
                'theseer\\fdom\\fdomexception' => '/src/fDOMException.php',
                'theseer\\fdom\\fdomnode' => '/src/fDOMNode.php',
                'theseer\\fdom\\fdomxpath' => '/src/fDOMXPath.php',
                'theseer\\fdom\\xpathquery' => '/src/XPathQuery.php',
                'theseer\\fdom\\xpathqueryexception' => '/src/XPathQueryException.php'
            );
        }
        $cn = strtolower($class);
        if (isset($classes[$cn])) {
            require __DIR__ . $classes[$cn];
        }
    }
);
// @codeCoverageIgnoreEnd

Remove unused interface from repository

Remove unused interface from repository


<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Newsletter / Config
 */

namespace PH7;

defined('PH7') or exit('Restricted access');

use PH7\Framework\Layout\Html\Design;
use PH7\Framework\Mvc\Router\Uri;
use PH7\Framework\Url\Header;

class Permission extends PermissionCore
{
    public function __construct()
    {
        parent::__construct();

        if (UserCore::auth() && $this->registry->controller === 'HomeController') {
            // Newsletter subscription is only for visitors, not for members since they can subscribe into their account
            Header::redirect(Uri::get('user', 'main', 'index'));
        }

        if (!AdminCore::auth() && $this->registry->controller === 'AdminController') {
            // For security reasons, we don't redirect the user to the admin panel URL
            Header::redirect(
                Uri::get('user', 'main', 'login'),
                $this->adminSignInMsg(),
                Design::ERROR_TYPE
            );
        }
    }
}

<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Newsletter / Config
 */

namespace PH7;

defined('PH7') or exit('Restricted access');

use PH7\Framework\Layout\Html\Design;
use PH7\Framework\Mvc\Router\Uri;
use PH7\Framework\Url\Header;

class Permission extends PermissionCore
{
    public function __construct()
    {
        parent::__construct();

        if (UserCore::auth() && $this->registry->controller === 'HomeController') {
            // Newsletter subscription is only for visitors, not for members since they can subscribe into their account
            Header::redirect(
                Uri::get('user', 'main', 'index')
            );
        }

        if (!AdminCore::auth() && $this->registry->controller === 'AdminController') {
            // For security reasons, we don't redirect the user to the admin panel URL
            Header::redirect(
                Uri::get('user', 'main', 'login'),
                $this->adminSignInMsg(),
                Design::ERROR_TYPE
            );
        }
    }
}

Fix indentation in Header::redirect( arg


<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
class UsersController extends Controller{
    public function actionIndex(){
        $this->render("index", array(

        ));
    }

    public function actionView(){

    }
}

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
class UsersController extends Controller{
    public function actionIndex(){
        $this->render("index", array(

        ));
    }

    public function actionView(){

    }
    public function actionCreate(){
        $this->render("create", array(

        ));
    }
}

Create berita index, models, and views

Create berita index, models, and views


<?php
namespace EdpMarkdown\View\Helper;

use Zend\View\Helper\AbstractHelper;

class Markdown extends AbstractHelper
{
    protected $parser;

    public function __construct($parser)
    {
        $this->setParser($parser);
    }

    public function setParser($parser)
    {
        $this->parser = $parser;
    }

    public function __invoke($string = null)
    {
        if (null === $this->parser) {
            return $string;
        }
        if ($string === null) {
            return $this;
        }

        return $this->parser->transform($string);
    }

    public function start()
    {
        ob_start();
    }

    public function end()
    {
        echo $this->parser->transform(ob_get_clean());
    }
}

<?php
namespace EdpMarkdown\View\Helper;

use Zend\View\Helper\AbstractHelper;

class Markdown extends AbstractHelper
{
    protected $parser;

    public function __construct()
    {
    }

    public function setParser($parser)
    {
        $this->parser = $parser;
    }

    public function __invoke($string = null)
    {
        if (null === $this->parser) {
            return $string;
        }
        if ($string === null) {
            return $this;
        }

        return $this->parser->transform($string);
    }

    public function start()
    {
        ob_start();
    }

    public function end()
    {
        echo $this->parser->transform(ob_get_clean());
    }
}

Revert "Make parser parameter required in the constructor as it is a hard dep"

Doing this will break the fallback PluginBroker behavior, as it tries to
instantiate the helper with no parameters to the constructor.

This reverts commit f368725d5742906cb0bf4130c290327adae1b08f.


<?php

namespace Illuminate\Database\Eloquent\Factories;

use Countable;

class Sequence implements Countable
{
    /**
     * The sequence of return values.
     *
     * @var array
     */
    protected $sequence;

    /**
     * The count of the sequence items.
     *
     * @var int
     */
    public $count;

    /**
     * The current index of the sequence iteration.
     *
     * @var int
     */
    public $index = 0;

    /**
     * Create a new sequence instance.
     *
     * @param  array  $sequence
     * @return void
     */
    public function __construct(...$sequence)
    {
        $this->sequence = $sequence;
        $this->count = count($sequence);
    }

    /**
     * Get the current count of the sequence items.
     *
     * @return int
     */
    public function count()
    {
        return $this->count;
    }

    /**
     * Get the next value in the sequence.
     *
     * @return mixed
     */
    public function __invoke()
    {
        return tap(value($this->sequence[$this->index % $this->count], $this), function () {
            $this->index = $this->index + 1;
        });
    }
}

<?php

namespace Illuminate\Database\Eloquent\Factories;

use Countable;

class Sequence implements Countable
{
    /**
     * The sequence of return values.
     *
     * @var array
     */
    protected $sequence;

    /**
     * The count of the sequence items.
     *
     * @var int
     */
    public $count;

    /**
     * The current index of the sequence iteration.
     *
     * @var int
     */
    public $index = 0;

    /**
     * Create a new sequence instance.
     *
     * @param  array  $sequence
     * @return void
     */
    public function __construct(...$sequence)
    {
        $this->sequence = $sequence;
        $this->count = count($sequence);
    }

    /**
     * Get the current count of the sequence items.
     *
     * @return int
     */
    #[\ReturnTypeWillChange]
    public function count()
    {
        return $this->count;
    }

    /**
     * Get the next value in the sequence.
     *
     * @return mixed
     */
    public function __invoke()
    {
        return tap(value($this->sequence[$this->index % $this->count], $this), function () {
            $this->index = $this->index + 1;
        });
    }
}

Add ReturnTypeWillChange to count method


<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HTTPServiceProvider extends ServiceProvider {

	/**
	 * Indicates that the loading of this provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = true;

	/**
	 * Bootstrap any HTTP services.
	 *
	 * @return void
	 */
	public function boot()
	{
		//
	}

	/**
	 * Register any HTTP services.
	 *
	 * @return void
	 */
	public function register()
	{
		if (function_exists('curl_version')) {
			$driver = 'cURLService';

		} else if (ini_get('allow_url_fopen')) {
			$driver = 'fopenService';

		} else {
			Log::error('Load the cURL module or enable allow_url_fopen in your PHP configuration.');

		}

		$this->app->singleton('App\Contracts\HTTP', 'App\Services\HTTP\\'.$driver);
	}

	/**
	 * Get the services provided by this provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return ['App\Contracts\HTTP'];
	}

}

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Log;

class HTTPServiceProvider extends ServiceProvider {

	/**
	 * Indicates that the loading of this provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = true;

	/**
	 * Bootstrap any HTTP services.
	 *
	 * @return void
	 */
	public function boot()
	{
		//
	}

	/**
	 * Register any HTTP services.
	 *
	 * @return void
	 */
	public function register()
	{
		if (function_exists('curl_version')) {
			$driver = 'cURLService';

		} else if (ini_get('allow_url_fopen')) {
			$driver = 'fopenService';

		} else {
			Log::error('Load the cURL module or enable allow_url_fopen in your PHP configuration.');

		}

		$this->app->singleton('App\Contracts\HTTP', 'App\Services\HTTP\\'.$driver);
	}

	/**
	 * Get the services provided by this provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return ['App\Contracts\HTTP'];
	}

}

Fix HTTP service error message.

Fix HTTP service error message.


<?php
namespace Bolt\Tests\Provider;

use Bolt\Provider\TwigServiceProvider;
use Bolt\Tests\BoltUnitTest;
use Bolt\Twig\SafeEnvironment;

/**
 * Class to test src/Provider/TwigServiceProvider.
 *
 * @author Ross Riley <riley.ross@gmail.com>
 * @author Carson Full <carsonfull@gmail.com>
 *
 * @covers \Bolt\Provider\TwigServiceProvider
 */
class TwigServiceProviderTest extends BoltUnitTest
{
    public function testProvider()
    {
        $app = $this->getApp();
        $app->register(new TwigServiceProvider());
        $app->boot();

        $this->assertInstanceOf('\Pimple', $app['twig.handlers']);
        $this->assertNotEmpty($app['twig.handlers']->keys());

        $this->assertNotEmpty($app['twig.options']['cache'], 'Cache path was not set');
        $this->assertInstanceOf('\Twig_Environment', $app['twig']);
        $this->assertTrue($app['twig']->hasExtension('Bolt'), 'Bolt\Twig\TwigExtension was not added to twig environment');
        $this->assertContains('bolt', $app['twig.loader.bolt_filesystem']->getNamespaces(), 'bolt namespace was not added to filesystem loader');

        $this->assertInstanceOf(SafeEnvironment::class, $app['safe_twig']);
    }

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

        $app['config']->set('general/caching/templates', false);
        $app->register(new TwigServiceProvider());
        $this->assertArrayNotHasKey('cache', $app['twig.options']);
    }
}

<?php
namespace Bolt\Tests\Provider;

use Bolt\Provider\TwigServiceProvider;
use Bolt\Tests\BoltUnitTest;
use Bolt\Twig\SafeEnvironment;

/**
 * Class to test src/Provider/TwigServiceProvider.
 *
 * @author Ross Riley <riley.ross@gmail.com>
 * @author Carson Full <carsonfull@gmail.com>
 *
 * @covers \Bolt\Provider\TwigServiceProvider
 */
class TwigServiceProviderTest extends BoltUnitTest
{
    public function testProvider()
    {
        $app = $this->getApp();
        $app->register(new TwigServiceProvider());
        $app->boot();

        $this->assertNotEmpty($app['twig.options']['cache'], 'Cache path was not set');
        $this->assertInstanceOf('\Twig_Environment', $app['twig']);
        $this->assertTrue($app['twig']->hasExtension('Bolt'), 'Bolt\Twig\TwigExtension was not added to twig environment');
        $this->assertContains('bolt', $app['twig.loader.bolt_filesystem']->getNamespaces(), 'bolt namespace was not added to filesystem loader');

        $this->assertInstanceOf(SafeEnvironment::class, $app['safe_twig']);
    }

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

        $app['config']->set('general/caching/templates', false);
        $app->register(new TwigServiceProvider());
        $this->assertArrayNotHasKey('cache', $app['twig.options']);
    }
}

Remove handlers from Twig provider test

[Tests] Remove handlers from Twig provider test


<?php
    $pwhash =  parse_ini_file("/etc/pihole/setupVars.conf")['WEBPASSWORD'];

    // Test if password is set
    if(strlen($pwhash) > 0)
    {
        // Password set compare with double hash
        if(hash('sha256',hash('sha256',$_POST["pw"])) == $pwhash || $_GET["auth"] == $pwhash)
        {
            // Password (POST) correct or hash (GET) correct
            $auth = true;
            $pwstring = "auth=".$pwhash;
        }
        else
        {
            // Password or hash wrong
            $auth = false;
            $pwstring = "";
        }
    }
    else
    {
        // No password set
        $auth = true;
        $pwstring = "";
    }
?>

<?php
    $pwhash =  parse_ini_file("/etc/pihole/setupVars.conf")['WEBPASSWORD'];

    // Test if password is set
    if(strlen($pwhash) > 0)
    {
        // Compare doubly hashes password input with saved hash
        if(isset($_POST["pw"]))
        {
            $postinput = hash('sha256',hash('sha256',$_POST["pw"]));
            if($postinput == $pwhash)
                $auth = true;
        }
        // Compare auth hash with saved hash
        else if (isset($_GET["auth"]))
        {
            if($_GET["auth"] == $pwhash)
                $auth = true;
        }
        else
        {
            // Password or hash wrong
            $auth = false;
            $pwstring = "";
        }
        // If authorized, then set the hash that will be
        // passed through using GET
        if($auth)
            $pwstring = "auth=".$pwhash;
    }
    else
    {
        // No password set
        $auth = true;
        $pwstring = "";
    }
?>

Test if POST and GET variables are set before trying to actually access them. This increases code complexity noticable, let's see if codacy complains ...


<?php

if(is_dir(__DIR__ . '/../vendor')) {
    include(__DIR__ . '/../vendor/autoload.php');
} else {
    require __DIR__ . '/../src.php';
}

require __DIR__ . '/TestCase.php';
require __DIR__ . '/DatabaseTestCase.php';

$models = glob(realpath(__DIR__) . '/models/*.php');
foreach($models as $model) {
    include $model;
}

require __DIR__ . '/custom.php';

function d() {
    $debug = debug_backtrace();
    $args = func_get_args();
    $data = array(
        'data' => $args,
        'debug' => array(
            'file' => $debug[0]['file'],
            'line' => $debug[0]['line'],
        )
    );
    if(class_exists('Mindy\Helper\Dumper')) {
        Mindy\Helper\Dumper::dump($data, 10);
    } else {
        var_dump($data);
    }
    die();
}

<?php

if(is_dir(__DIR__ . '/../vendor')) {
    include(__DIR__ . '/../vendor/autoload.php');
} else {
    require __DIR__ . '/../src.php';
}

require __DIR__ . '/TestCase.php';
require __DIR__ . '/DatabaseTestCase.php';

$models = glob(realpath(__DIR__) . '/Models/*.php');
foreach($models as $model) {
    include $model;
}

require __DIR__ . '/custom.php';

function d() {
    $debug = debug_backtrace();
    $args = func_get_args();
    $data = array(
        'data' => $args,
        'debug' => array(
            'file' => $debug[0]['file'],
            'line' => $debug[0]['line'],
        )
    );
    if(class_exists('Mindy\Helper\Dumper')) {
        Mindy\Helper\Dumper::dump($data, 10);
    } else {
        var_dump($data);
    }
    die();
}

Fix models path in tests

Fix models path in tests


<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Title</title>
        @yield('additional_styles')
    </head>
    <body>
        {{-- Nav bar goes here --}}

        <div class="container mainContainer">
            @yield('content')
        </div>

    </body>
</html>

<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Title</title>
        <link rel="stylesheet" href="/css/app.css" />
        @yield('additional_styles')
    </head>
    <body>
        {{-- Nav bar goes here --}}

        <div class="container mainContainer">
            @yield('content')
        </div>

    </body>
</html>

Add css to master template

Add css to master template


<?php

class OC_Search_Provider_News extends OC_Search_Provider{

	function search($query) {
		if (!OCP\App::isEnabled('news')) {
			return array();
		}

		$feedMapper = new OCA\News\FeedMapper(OCP\USER::getUser());
		$results=array();

		if($feedMapper->feedCount() > 0) {
			$allFeeds = $feedMapper->findAll();

			$l = new OC_l10n('news');

			foreach($allFeeds as $feed) {
				if(substr_count(strtolower($feed['title']), strtolower($query)) > 0) {
					$link = OCP\Util::linkTo('news', 'index.php').'&feedid='.urlencode($feed['id']);
					$results[]=new OC_Search_Result($feed['title'], '', $link, (string)$l->t('News'));
				}
			}
		}
		return $results;

	}
}

<?php

class OC_Search_Provider_News extends OC_Search_Provider{

	function search($query) {
		if (!OCP\App::isEnabled('news')) {
			return array();
		}

		$feedMapper = new OCA\News\FeedMapper(OCP\USER::getUser());
		$results=array();

		if($feedMapper->feedCount() > 0) {
			$allFeeds = $feedMapper->findAll();

			$l = new OC_l10n('news');

			foreach($allFeeds as $feed) {
				if(substr_count(strtolower($feed['title']), strtolower($query)) > 0) {
					$link = OCP\Util::linkTo('news', 'index.php').'?feedid='.urlencode($feed['id']);
					$results[]=new OC_Search_Result($feed['title'], '', $link, (string)$l->t('News'));
				}
			}
		}
		return $results;

	}
}

Fix linkTo links for new url format

Fix linkTo links for new url format

fix #176


<?php

namespace OParl\Website\API\Controllers;

use App\Model\Endpoint;
use Illuminate\Http\Request;

class EndpointApiController
{
    /**
     * @SWG\Get(
     *     path="/endpoints",
     *     tags={ "endpoints" },
     *     summary="list endpoints",
     *     @SWG\Response(
     *         response="200",
     *         description="A listing of known OParl endpoints",
     *         @SWG\Schema(
     *              @SWG\Property( property="data", type="array", @SWG\Items( ref="#/definitions/Endpoint" ))
     *         )
     *     )
     * )
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $page = 0;
        $itemsPerPage = 25;

        if ($request->has('page')) {
            $page = intval($request->get('page'));
        }

        $endpoints = Endpoint::with('bodies')->get()->forPage($page, $itemsPerPage);
        $pageCount = floor($endpoints->count() / $itemsPerPage);

        return response()->json([
            'data' => $endpoints,
            'meta' => [
                'page'  => $page,
                'total' => $pageCount,
                'next'  => ($pageCount > $page)
                    ? route('api.endpoints.index', ['page' => ++$page])
                    : null,
            ],
        ]);
    }
}

<?php

namespace OParl\Website\API\Controllers;

use App\Model\Endpoint;
use Illuminate\Http\Request;

class EndpointApiController
{
    /**
     * @SWG\Get(
     *     path="/endpoints",
     *     tags={ "endpoints" },
     *     summary="list endpoints",
     *     @SWG\Response(
     *         response="200",
     *         description="A listing of known OParl endpoints",
     *         @SWG\Schema(
     *              @SWG\Property( property="data", type="array", @SWG\Items( ref="#/definitions/Endpoint" ))
     *         )
     *     )
     * )
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $page = 0;
        $itemsPerPage = 25;

        if ($request->has('page')) {
            $page = intval($request->get('page'));
        }

        $endpoints = Endpoint::with('bodies')->get()->forPage($page, $itemsPerPage);
        $pageCount = floor($endpoints->count() / $itemsPerPage);

        return response()->json([
            'data' => $endpoints,
            'meta' => [
                'page'  => $page,
                'total' => $pageCount,
                'next'  => ($pageCount > $page)
                    ? route('api.endpoints.index', ['page' => ++$page])
                    : null,
            ],
        ], 200, [
            'Content-Type'                => 'application/json',
            'Access-Control-Allow-Origin' => '*',
        ]);
    }
}

Make endpoints api cors friendly

Make endpoints api cors friendly


<?php

namespace League\Glide\Responses;

use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use PHPUnit\Framework\TestCase;

class ZendResponseFactoryTest extends TestCase
{
    public function testCreateInstance()
    {
        $this->assertInstanceOf(
            'League\Glide\Responses\ZendResponseFactory',
            new ZendResponseFactory()
        );
    }

    public function testCreate()
    {
        $cache = new Filesystem(
            new Local(dirname(__DIR__))
        );

        $factory = new ZendResponseFactory();
        $response = $factory->create($cache, 'kayaks.jpg');

        $this->assertInstanceOf('Zend\Diactoros\Response', $response);
        $this->assertEquals('image/jpeg', $response->getHeaderLine('Content-Type'));
        $this->assertEquals('5175', $response->getHeaderLine('Content-Length'));
        $this->assertContains(
            date_create('+1 years')->format('D, d M Y H:i:s') . ' GMT',
            $response->getHeaderLine('Expires')
        );
        $this->assertEquals('max-age=31536000, public', $response->getHeaderLine('Cache-Control'));
    }
}

<?php

namespace League\Glide\Responses;

use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use PHPUnit\Framework\TestCase;

class ZendResponseFactoryTest extends TestCase
{
    public function testCreateInstance()
    {
        $this->assertInstanceOf(
            'League\Glide\Responses\ZendResponseFactory',
            new ZendResponseFactory()
        );
    }

    public function testCreate()
    {
        $cache = new Filesystem(
            new Local(dirname(__DIR__))
        );

        $factory = new ZendResponseFactory();
        $response = $factory->create($cache, 'kayaks.jpg');

        $this->assertInstanceOf('Zend\Diactoros\Response', $response);
        $this->assertEquals('image/jpeg', $response->getHeaderLine('Content-Type'));
        $this->assertEquals('5175', $response->getHeaderLine('Content-Length'));
        $this->assertContains(gmdate('D, d M Y H:i', strtotime('+1 years')), $response->getHeaderLine('Expires'));
        $this->assertEquals('max-age=31536000, public', $response->getHeaderLine('Cache-Control'));
    }
}

Revert "Update a test to reflect a change in league/glide"

This reverts commit 29cc75df4170a2ff902cd9f2bfdd675db0a91684.


<?php

namespace Tests\Unit\Pages\Help;

use Tests\TestCase;
use Tests\CreatesUser;
use Illuminate\Foundation\Testing\RefreshDatabase;

class HelpIndexPageTest extends TestCase
{
    use RefreshDatabase, CreatesUser;

    /** @test */
    public function it_can_refresh_the_user_page()
    {
        Auth::guard('canvas')->login($this->user);
        $this->actingAs($this->user)
            ->visit(route('canvas.admin.help'))
            ->click('Refresh Help');
        $this->assertSessionMissing('errors');
        $this->seePageIs(route('canvas.admin.help'));
    }
}

<?php

namespace Tests\Unit\Pages\Help;

use Tests\TestCase;
use Tests\CreatesUser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class HelpIndexPageTest extends TestCase
{
    use DatabaseMigrations, DatabaseTransactions, CreatesUser;

    /** @test */
    public function it_can_refresh_the_user_page()
    {
        Auth::guard('canvas')->login($this->user);
        $this->actingAs($this->user)
            ->visit(route('canvas.admin.help'))
            ->click('Refresh Help');
        $this->assertSessionMissing('errors');
        $this->seePageIs(route('canvas.admin.help'));
    }
}

Use migrations inside test class

Use migrations inside test class


<?php

class GridRowsExtension extends DataExtension {

  /*
  If you are laying out using some form of grid, e.g. HTML table (ugh) or bootstraps span classes it is useful
  to have the DataSet split by row.  This is what this method does.

  To execute this code from a template, do something like the following:

  <% control SplitSetIntoGridRows(Children|4) %>
  YOur template here
  <% end_control %>

  */
  public function SplitSetIntoGridRows($itemsInGridMethod,$numberOfCols) {
    error_log("GRID ROWS");
    $itemsInGrid = $this->owner->$itemsInGridMethod();
    $position = 1;
    $columns = new ArrayList();
    $result = new ArrayList();
    foreach ($itemsInGrid as $key => $item) {
      $columns->push($item);
      error_log("Comparing position $position > number of cols $numberOfCols");
      if (($position) >= $numberOfCols) {
        error_log("NEW ROW");
        $position = 1;
        $row = new ArrayList();
        $row->Columns = $columns;
        $result->push($row);
        $columns = new ArrayList();
      } else {
        $position = $position + 1;
      }
    }

    if ($columns->Count() > 0) {
      $row = new ArrayList();
      $row->Columns = $columns;
      $result->push($row);
    }

    // FIXME add padding?

    return $result;
    //$result = new DataObjectSet();

  }

}
?>

<?php

class GridRowsExtension extends DataExtension {

  /*
  If you are laying out using some form of grid, e.g. HTML table (ugh) or bootstraps span classes it is useful
  to have the DataSet split by row.  This is what this method does.

  To execute this code from a template, do something like the following:

  <% control SplitSetIntoGridRows(Children|4) %>
  YOur template here
  <% end_control %>

  */
  public function SplitDataListIntoGridRows($itemsInGridMethod,$numberOfCols) {
    $itemsInGrid = $this->owner->$itemsInGridMethod();
    $position = 1;
    $columns = new ArrayList();
    $result = new ArrayList();
    foreach ($itemsInGrid as $key => $item) {
      $columns->push($item);
      if (($position) >= $numberOfCols) {
        $position = 1;
        $row = new ArrayList();
        $row->Columns = $columns;
        $result->push($row);
        $columns = new ArrayList();
      } else {
        $position = $position + 1;
      }
    }

    if ($columns->Count() > 0) {
      $row = new ArrayList();
      $row->Columns = $columns;
      $result->push($row);
    }

    return $result;
  }

}

FIX: Revert name of extension method and remove debugging


<?php
	function insert($map_id)
	{
		//Standard SQL connection stuff
		$linkID = mysql_connect("localhost", "root", "") or die ("Could not connect to database!");
		mysql_select_db("agora", $linkID) or die ("Could not find database");
		$whereclause = mysql_real_escape_string("$mapID");

		//Set up the basics of the XML.
		header("Content-type: text/xml");
		$xmlstr = "<?xml version='1.0' ?>\n<map></map>";
		$xml = new SimpleXMLElement($xmlstr);
	}
	$map_id = $_REQUEST['map_id'];  //TODO: Change this back to a GET when all testing is done.
	$xml = $_REQUEST['xml']; //TODO: Change this back to a GET when all testing is done.
	$output = insert($map_id);
	print($output->asXML());
?>

<?php
	function insert($xml)
	{
		//Standard SQL connection stuff
		$linkID = mysql_connect("localhost", "root", "") or die ("Could not connect to database!");
		mysql_select_db("agora", $linkID) or die ("Could not find database");

		//Dig the Map ID out of the XML

		//Check to see if the map already exists
		//$mapClause = mysql_real_escape_string("$mapID");

		//If not, create it!

		//Validate nodes
		//Validate textboxes
		//Validate nodetext
		//Validate arguments
		//Validate connections

		//Insert/update everything

		//Set up the basics of the output XML.
		header("Content-type: text/xml");
		$xmlstr = "<?xml version='1.0' ?>\n<map></map>";
		$output = new SimpleXMLElement($xmlstr);
		return $output;
	}
	$xml = $_REQUEST['xml']; //TODO: Change this back to a GET when all testing is done.
	$output = insert($xml);
	print($output->asXML());
?>

Define our plan of action for the code

Define our plan of action for the code


<?php
	/**
	 * @package content
	 */
	/**
	 * The AjaxTranslate page is used for translating strings on the fly
	 * that are used in Symphony's javascript
	 */
	Class contentAjaxTranslate extends AjaxPage{

		public function handleFailedAuthorisation(){
			$this->_status = self::STATUS_UNAUTHORISED;
			$this->_Result = json_encode(array('status' => __('You are not authorised to access this page.')));
		}

		public function view(){
			$strings = $_GET['strings'];
			$namespace = (empty($_GET['namespace']) ? null : $_GET['namespace']);

			$new = array();
			foreach($strings as $key => $value) {

				// Check value
				$value = urldecode($value);
				if(empty($value)) {
					$value = urldecode($key);
				}

				// Translate
				$new[$value] = Lang::translate($value, null, $namespace);
			}
			$this->_Result = json_encode($new);
		}

		public function generate(){
			header('Content-Type: application/json');
			echo $this->_Result;
			exit;
		}

	}

<?php
	/**
	 * @package content
	 */
	/**
	 * The AjaxTranslate page is used for translating strings on the fly
	 * that are used in Symphony's javascript
	 */
	Class contentAjaxTranslate extends AjaxPage{

		public function handleFailedAuthorisation(){
			$this->_status = self::STATUS_UNAUTHORISED;
			$this->_Result = json_encode(array('status' => __('You are not authorised to access this page.')));
		}

		public function view(){
			$strings = $_GET['strings'];
			$namespace = (empty($_GET['namespace']) ? null : $_GET['namespace']);

			$new = array();
			foreach($strings as $key => $value) {

				// Check value
				if(empty($value) || $value = 'false') {
					$value = $key;
				}

				// Translate
				$new[$value] = Lang::translate(urldecode($value), null, $namespace);
			}
			$this->_Result = json_encode($new);
		}

		public function generate(){
			header('Content-Type: application/json');
			echo $this->_Result;
			exit;
		}

	}

Check if values are set or not

Check if values are set or not


<?php

$router->get([
    'route' => '/name/(name)',
    'object' => 'Example@getName',
    'require' => function() {
        return 1 + 1 == 2;
    }
]);

$router->post([
    'route' => '/name/(name)',
    'function' => ['functionExample', 'postName'],
    'require' => function() {
        return 1 + 1 == 2;
    }
]);

<?php

return function($router)
{

    $router->get([
        'route' => '/name/(name)',
        'object' => 'Example@getName',
        'require' => function() {
            return 1 + 1 == 2;
        }
    ]);

    $router->post([
        'route' => '/name/(name)',
        'function' => ['functionExample', 'postName'],
        'require' => function() {
            return 1 + 1 == 2;
        }
    ]);

};

Move routing into a separate function

Move routing into a separate function


<?php

namespace notamedia\relation;

use yii\base\Exception;

/**
 * Exception for throw when relation errors occured
 */
class RelationException extends Exception
{
    /**
     * @return string the user-friendly name of this exception
     */
    public function getName()
    {
        return 'Relation exception';
    }
}

<?php

namespace notamedia\relation;

use yii\base\Exception;

/**
 * Exception for throw when relation errors occured
 */
class RelationException extends Exception
{
    /**
     * @return string the user-friendly name of this exception
     */
    public function getName()
    {
        return 'Relation exception';
    }

    /**
     * Returns the fully qualified name of this class.
     * @return string the fully qualified name of this class.
     */
    public static function className()
    {
        return get_called_class();
    }
}

Fix RelationBehavior load many-to-many test. Set required php 5.6.0


<?php
defined('mnminclude') or die();

$query = '
    FROM comments, links
    WHERE (
        comment_user_id = "'.(int)$user->id.'"
        AND link_id = comment_link_id
    )
';

$comments = $db->get_results('
    SELECT comment_id, link_id, comment_type
    '.$query.'
    ORDER BY comment_date DESC
    LIMIT '.(int)$offset.', '.(int)$limit.';
');

if (empty($comments)) {
    return Haanga::Load('user/empty.html');
}

require __DIR__.'/libs-comments.php';

print_comment_list($comments, $user);

do_pages($count, $limit);

<?php
defined('mnminclude') or die();

$query = '
    FROM comments, links
    WHERE (
        comment_user_id = "'.(int)$user->id.'"
        AND link_id = comment_link_id
    )
';

$comments = $db->get_results('
    SELECT comment_id, link_id, comment_type
    '.$query.'
    ORDER BY comment_date DESC
    LIMIT '.(int)$offset.', '.(int)$limit.';
');

if (empty($comments)) {
    return Haanga::Load('user/empty.html');
}

require __DIR__.'/libs-comments.php';

print_comment_list($comments, $user);

do_pages(-1, $limit);

Enable pagination on comment list in user profile


	<?php foreach ($ingredients as $key => $ingredient) { ?>

<?php echo $ingredient['name']; ?>

					Compatible Ingredients
					Price

				<?php foreach ($ingredient['secondary'] as $secondary) { ?>

							<a href="<?php echo site_url("ingredients/view/".$secondary['id']); ?>">
								<?php echo $secondary['name']; ?>

							<?php echo $secondary['price']; ?>

				<?php } ?>

	<?php } ?>

	<?php foreach ($ingredients as $key => $ingredient) { ?>
		<?php foreach ($ingredient['secondary'] as $secondary) { ?>

<?php echo $ingredient['name']; ?> + <?php echo $secondary['name']; ?>

						Ingredients
						Price

					<?php foreach ($secondary['tertiary'] as $tertiary) { ?>

								<?php echo $tertiary['name']; ?>

								<?php echo $tertiary['price']; ?>

					<?php } ?>

		<?php } ?>
	<?php } ?>

Fix view to loop to all ingredients level


<?php
namespace Slack;

/**
 * A serializable model object that stores its data in a hash.
 */
abstract class DataObject implements \JsonSerializable
{
    /**
     * @var array The object's data cache.
     */
    public $data = [];

    /**
     * Creates a data object from an array of data.
     *
     * @param array $data The array containing object data.
     *
     * @return self A new object instance.
     */
    public static function fromData(array $data)
    {
        $reflection = new \ReflectionClass(static::class);
        $instance = $reflection->newInstanceWithoutConstructor();
        $instance->data = $data;
        return $instance;
    }

    /**
     * Returns scalar data to be serialized.
     *
     * @return array
     */
    public function jsonSerialize()
    {
        return $this->data;
    }
}

<?php
namespace Slack;

/**
 * A serializable model object that stores its data in a hash.
 */
abstract class DataObject implements \JsonSerializable
{
    /**
     * @var array The object's data cache.
     */
    public $data = [];

    /**
     * Creates a data object from an array of data.
     *
     * @param array $data The array containing object data.
     *
     * @return self A new object instance.
     */
    public static function fromData(array $data)
    {
        $reflection = new \ReflectionClass(static::class);
        $instance = $reflection->newInstanceWithoutConstructor();
        $instance->data = $data;
        $instance->jsonUnserialize($data);
        return $instance;
    }

    /**
     * Returns scalar data to be serialized.
     *
     * @return array
     */
    public function jsonSerialize()
    {
        return $this->data;
    }

    /**
     * Re-initializes the object when unserialized or created from a data array.
     *
     * @param array $data The object data.
     */
    public function jsonUnserialize(array $data)
    {
    }
}

Add unserialize handler for data objects


<?hh // strict

namespace HackPack\HackUnit\Event;

use HackPack\HackUnit\Util\TraceItem;

class Skip
{
    public function __construct(private TraceItem $callSite)
    {
    }

    public function testMethod() : ?string
    {
        return $this->callSite['function'] === '' ?
            null :
            $this->callSite['function'];
    }

    public function testClass() : ?string
    {
        return $this->callSite['class'] === '' ?
            null :
            $this->callSite['class'];
    }

    public function testFile() : ?string
    {
        return $this->callSite['file'] === '' ?
            null :
            $this->callSite['file'];
    }

    public function assertionLine() : ?int
    {
        return $this->callSite['line'] === -1 ?
            null :
            $this->callSite['line'];
    }
}

<?hh // strict

namespace HackPack\HackUnit\Event;

use HackPack\HackUnit\Util\TraceItem;

class Skip
{
    public function __construct(private TraceItem $callSite)
    {
    }

    public function assertionLine() : ?int
    {
        return $this->callSite['line'] === -1 ?
            null :
            $this->callSite['line'];
    }

    public function testMethod() : ?string
    {
        return $this->callSite['function'] === '' ?
            null :
            $this->callSite['function'];
    }

    public function testClass() : ?string
    {
        return $this->callSite['class'] === '' ?
            null :
            $this->callSite['class'];
    }

    public function testFile() : ?string
    {
        return $this->callSite['file'] === '' ?
            null :
            $this->callSite['file'];
    }
}

Order methods line -> function -> class -> file.


<?php

namespace App\Handler\Framework;

use App\Command\Framework\CopyFrameworkCommand;
use App\Event\CommandEvent;
use App\Handler\BaseDoctrineHandler;
use App\Entity\Framework\LsDoc;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class CloneFrameworkHandler extends BaseDoctrineHandler
{
    public function __construct(ValidatorInterface $validator, EntityManagerInterface $entityManager)
    {
        parent::__construct($validator, $entityManager);
    }

    public function handle(CommandEvent $event, string $eventName, EventDispatcherInterface $dispatcher): void
    {
        /** @var CopyFrameworkCommand $command */
        $command = $event->getCommand();
        $this->validate($command, $command);

        /** @var LsDoc $doc */
        $doc = $command->getDoc();

        $newDoc = clone $doc;
        $newDoc->setTitle('Clone '.$newDoc->getTitle());
        $this->em->persist($newDoc);
    }
}

<?php

namespace App\Handler\Framework;

use App\Command\Framework\CopyFrameworkCommand;
use App\Event\CommandEvent;
use App\Handler\BaseDoctrineHandler;
use App\Entity\Framework\LsDoc;
use App\Repository\Framework\LsDocRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class CloneFrameworkHandler extends BaseDoctrineHandler
{
    private $repository;
    public function __construct(ValidatorInterface $validator, EntityManagerInterface $entityManager, LsDocRepository $repository)
    {
        $this->repository = $repository;
        parent::__construct($validator, $entityManager);
    }

    public function handle(CommandEvent $event, string $eventName, EventDispatcherInterface $dispatcher): void
    {
        /** @var CopyFrameworkCommand $command */
        $command = $event->getCommand();
        $this->validate($command, $command);
        $newDoc->setFrameworkType(null);

        $this->repository->copyDocumentContentToDoc($doc, $newDoc, false);

        /** @var LsDoc $doc */
        $doc = $command->getDoc();

        $newDoc = clone $doc;
        $newDoc->setTitle('Clone '.$newDoc->getTitle());
        $this->em->persist($newDoc);
    }
}

Add code back to clone items.

Add code back to clone items.


<?php
$uploadDirectory = 'resourceUploads/';
$temp = explode ( '.', $_FILES [ 'fileToUpload' ] [ 'name' ] );
$extension = end ( $temp );

if ( $extension !== 'pdf' )
    die ( 'Invalid extension' );

if ( $_FILES [ 'fileToUpload' ] [ 'error' ] > 0 )
{
	die ( 'Error code: ' . $_FILES [ 'fileToUpload' ] [ 'error' ] );
}
else
{
	$resourceFilename = $_FILES [ 'fileToUpload' ] [ 'name' ];
	$resourcePath = $uploadDirectory . $resourceFilename;
	move_uploaded_file ( $_FILES [ 'fileToUpload' ] [ 'tmp_name' ], $resourcePath );

	require_once ( 'database.php' );

	$connection = OpenDatabase();

	QueryDatabase ( $connection, 'BEGIN' );

	$oid = pg_lo_import ( $connection, 'C:\\Program Files (x86)\\PostgreSQL\\EnterpriseDB-ApachePHP\\apache\\www\\theta\\' . $resourcePath );

	QueryDatabase ( $connection, 'COMMIT' );

	CloseDatabase ( $connection );

	unlink ( $resourcePath );

	die ( "OK$oid" );
}
?>

<?php
$temp = explode ( '.', $_FILES [ 'fileToUpload' ] [ 'name' ] );
$extension = end ( $temp );

if ( $extension !== 'pdf' )
    die ( 'Invalid extension' );

if ( $_FILES [ 'fileToUpload' ] [ 'error' ] > 0 )
{
	die ( 'Error code: ' . $_FILES [ 'fileToUpload' ] [ 'error' ] );
}
else
{
	require_once ( 'database.php' );

	$connection = OpenDatabase();

	QueryDatabase ( $connection, 'BEGIN' );

	$oid = pg_locreate ( $connection );

	$handle = pg_loopen ( $connection, $oid, 'w' );
	$fp = fopen (  $_FILES [ 'fileToUpload' ] [ 'tmp_name' ], 'r' );

	while ( !feof ( $fp ) )
		pg_lowrite ( $handle, fread ( $fp, 4096 ) );

	fclose ( $fp );

	pg_loclose ( $handle );

	QueryDatabase ( $connection, 'COMMIT' );

	CloseDatabase ( $connection );

	unlink ( $resourcePath );

	die ( "OK$oid" );
}
?>

Use pg_lowrite for writing resource to PostgreSQL

Use pg_lowwrite instead of pg_import for writing resource to PostgreSQL database.


<?php

namespace vv201830;

class AddBootswatchSettings extends \AbstractUpdatableMigration {

    function innerUp($hesk_settings) {
        $this->executeQuery("INSERT INTO `" . hesk_dbEscape($hesk_settings['db_pfix']) . "settings` (`Key`, `Value`) VALUES ('use_bootswatch_theme', '0')");
        $this->executeQuery("INSERT INTO `" . hesk_dbEscape($hesk_settings['db_pfix']) . "settings` (`Key`, `Value`) VALUES ('bootswatch_theme', ''");

    }

    function innerDown($hesk_settings) {
        $this->executeQuery("DELETE FROM `" . hesk_dbEscape($hesk_settings['db_pfix']) . "settings` WHERE `Key` IN ('use_bootswatch_theme', 'bootswatch_theme')");
    }
}

<?php

namespace vv201830;

class AddBootswatchSettings extends \AbstractUpdatableMigration {

    function innerUp($hesk_settings) {
        $this->executeQuery("INSERT INTO `" . hesk_dbEscape($hesk_settings['db_pfix']) . "settings` (`Key`, `Value`) VALUES ('use_bootswatch_theme', '0')");
        $this->executeQuery("INSERT INTO `" . hesk_dbEscape($hesk_settings['db_pfix']) . "settings` (`Key`, `Value`) VALUES ('bootswatch_theme', '')");

    }

    function innerDown($hesk_settings) {
        $this->executeQuery("DELETE FROM `" . hesk_dbEscape($hesk_settings['db_pfix']) . "settings` WHERE `Key` IN ('use_bootswatch_theme', 'bootswatch_theme')");
    }
}

Fix SQL error in migration 181

Fix SQL error in migration 181


<?php

/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\Bundle\DemoBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
class InspectionAdmin extends Admin
{
    /**
     * {@inheritdoc}
     */
    protected function configureDatagridFilters(DatagridMapper $filter)
    {
        $filter
            ->add('date')
            ->add('car')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureListFields(ListMapper $list)
    {
        $list
            ->addIdentifier('date')
            ->add('car')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        if (!$this->hasParentFieldDescription()) {
            $formMapper->add('car', null, array('constraints' => new Assert\NotNull()));
        }

        $formMapper->add('date', null, ['widget' => 'single_text']);
    }
}

<?php

/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\Bundle\DemoBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
class InspectionAdmin extends Admin
{
    /**
     * {@inheritdoc}
     */
    protected function configureDatagridFilters(DatagridMapper $filter)
    {
        $filter
            ->add('date')
            ->add('car')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureListFields(ListMapper $list)
    {
        $list
            ->addIdentifier('date')
            ->add('car')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        if (!$this->hasParentFieldDescription()) {
            $formMapper->add('car', null, array('constraints' => new Assert\NotNull()));
        }

        $formMapper->add('date', null, array('widget' => 'single_text'));
    }
}

Replace php 5.4 array notation

Replace php 5.4 array notation


<?php

namespace Ochenta;

/** @throws InvalidArgumentException */
function resource_of($resource) {
    if (is_null($resource)) {
        return null;
    }

    if (is_scalar($resource)) {
        $stream = fopen('php://temp', 'r+');
        if (!empty($resource)) {
            fwrite($stream, $resource);
            fseek($stream, 0);
        }
        return $stream;
    }

    if (is_resource($resource)) {
        return $resource;
    }

    throw new \InvalidArgumentException('Invalid resource');
}

/** @throws RuntimeException */
function mimetype_of($resource, $filename=null) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    if ($finfo === false) {
        throw new \RuntimeException('Fileinfo database is not available');
    }

    $mimetype = false;
    if (is_file($filename) && file_exists($filename)) {
        $mimetype = finfo_file($finfo, $filename);
    }

    if ($mimetype === false) {
        $contents = false;

        if (is_string($resource)) {
            $contents = $resource;
        } elseif (is_resource($resource)) {
            $contents = stream_get_contents($resource, -1, 0);
        }

        if ($contents !== false) {
            $mimetype = finfo_buffer($finfo, $contents);
        }
    }
    finfo_close($finfo);

    if ($mimetype === false) {
        throw new \RuntimeException('Couldn\'t detect mime type from resource');
    }

    return $mimetype;
}

<?php

namespace Ochenta;

/** @throws InvalidArgumentException */
function resource_of($resource) {
    if (is_null($resource)) {
        return null;
    }

    if (is_scalar($resource)) {
        $stream = fopen('php://temp', 'r+');
        if (!empty($resource)) {
            fwrite($stream, $resource);
            fseek($stream, 0);
        }
        return $stream;
    }

    if (is_resource($resource)) {
        return $resource;
    }

    throw new \InvalidArgumentException('Invalid resource');
}

/** @throws RuntimeException */
function mimetype_of($resource, $filename=null) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    if ($finfo === false) {
        throw new \RuntimeException('Fileinfo database is not available');
    }

    $mimetype = false;
    if (is_file($filename) && is_readable($filename)) {
        $mimetype = finfo_file($finfo, $filename);
    }

    if ($mimetype === false) {
        $contents = false;

        if (is_string($resource)) {
            $contents = $resource;
        } elseif (is_resource($resource)) {
            $contents = stream_get_contents($resource, -1, 0);
        }

        if ($contents !== false) {
            $mimetype = finfo_buffer($finfo, $contents);
        }
    }
    finfo_close($finfo);

    if ($mimetype === false) {
        throw new \RuntimeException('Couldn\'t detect mime type from resource');
    }

    return $mimetype;
}

Use is_readable instead of file_exists

Use is_readable instead of file_exists


<?php

return [
    'client_id' => env('TWITCH_KEY', ''),
    'client_secret' => env('TWITCH_SECRET', ''),
    'redirect_url' => env('TWITCH_REDIRECT_URI', ''),
    'scopes' => [
        'user_read',
        'user_blocks_edit',
        'user_blocks_read',
        'user_follows_edit',
        'channel_read',
        'channel_editor',
        'channel_commercial',
        'channel_stream',
        'channel_subscriptions',
        'user_subscriptions',
        'channel_check_subscription',
        'chat_login',
    ],
];

<?php

return [
    'client_id' => env('TWITCH_KEY', ''),
    'client_secret' => env('TWITCH_SECRET', ''),
    'redirect_url' => env('TWITCH_REDIRECT_URI', ''),
    'scopes' => [
        'channel_check_subscription',
        'channel_commercial',
        'channel_editor',
        'channel_feed_edit',
        'channel_feed_read',
        'channel_read',
        'channel_stream',
        'channel_subscriptions',
        'chat_login',
        'collections_edit',
        'communities_edit',
        'communities_moderate',
        'openid',
        'user_blocks_edit',
        'user_blocks_read',
        'user_follows_edit',
        'user_read',
        'user_subscriptions',
        'viewing_activity_read'
    ],
];

Add Additional Scopes to Vendor Config

Add Additional Scopes to Vendor Config

Newly added scopes were missing from vendor config file. These scopes have been added.


<?php

/**
 * Lazy Images for Contao Open Source CMS
 *
 * @copyright  DerHaeuptling 2016
 * @author     Martin Schwenzer <mail@derhaeuptling.com>
 * @author     Sebastijan Ribarić <sebastijan.ribaric@media-8.org>
 * @author     Kamil Kuzminski <kamil.kuzminski@codefog.pl>
 * @package    Lazy Images
 * @license    http://opensource.org/licenses/lgpl-3.0.html
 */

/**
 * Register the classes
 */
ClassLoader::addClasses(array
(
	// Classes
	'Contao\LazySizes'            => 'system/modules/zz_LazyLoad/library/DerHaeuptling/classes/LazySizes.php',

	// Elements
	'Contao\LazyContentText'            => 'system/modules/zz_lazy-images/elements/LazyContentText.php',
	'Contao\LazyContentImage'           => 'system/modules/zz_lazy-images/elements/LazyContentImage.php',
	//'Contao\LazyContentGallery'         => 'system/modules/zz_lazy-images/elements/LazyContentGallery.php',
));

/**
 * Register the templates
*/
TemplateLoader::addFiles(array
(
	'picture_lazy'      => 'system/modules/zz_lazy-images/templates'

));

<?php

/**
 * Lazy Images for Contao Open Source CMS
 *
 * @copyright  DerHaeuptling 2016
 * @author     Martin Schwenzer <mail@derhaeuptling.com>
 * @author     Sebastijan Ribarić <sebastijan.ribaric@media-8.org>
 * @author     Kamil Kuzminski <kamil.kuzminski@codefog.pl>
 * @package    Lazy Images
 * @license    http://opensource.org/licenses/lgpl-3.0.html
 */

/**
 * Register the classes
 */
ClassLoader::addClasses(array
(
	// Classes
	'Contao\LazySizes'            => 'system/modules/zz_lazy-images/library/DerHaeuptling/classes/LazySizes.php',

	// Elements
	'Contao\LazyContentText'            => 'system/modules/zz_lazy-images/elements/LazyContentText.php',
	'Contao\LazyContentImage'           => 'system/modules/zz_lazy-images/elements/LazyContentImage.php',
	//'Contao\LazyContentGallery'         => 'system/modules/zz_lazy-images/elements/LazyContentGallery.php',
));

/**
 * Register the templates
*/
TemplateLoader::addFiles(array
(
	'picture_lazy'      => 'system/modules/zz_lazy-images/templates'

));

Fix for main class not found

Fix for main class not found


<?php

namespace SumoCoders\FrameworkMultiUserBundle\Security;

use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidPasswordResetTokenException;
use SumoCoders\FrameworkMultiUserBundle\User\UserInterface;

class PasswordResetToken
{
    /**
     * @var string
     */
    private $token;

    /**
     * PasswordResetToken constructor.
     *
     * @param string|null $token
     */
    public function __construct($token)
    {
        $this->token = $token;
    }

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

    /**
     * @param UserInterface $user
     * @param $token
     *
     * @throws InvalidPasswordResetTokenException
     *
     * @return bool
     */
    public static function validateToken(UserInterface $user, PasswordResetToken $token)
    {
        if ($user->getPasswordResetToken()->equals($token)) {
            return true;
        }

        throw new InvalidPasswordResetTokenException('The given token is not valid.');
    }

    /**
     * Generates a PasswordToken
     *
     * @return PasswordResetToken
     */
    public static function generate()
    {
        $token = time() . base64_encode(random_bytes(10));

        return new self($token);
    }

    /**
     * Check if a token is equal to a different token.
     *
     * @param PasswordResetToken $token
     *
     * @return bool
     */
    public function equals(PasswordResetToken $token)
    {
        return $token->token === $this->token;
    }
}

<?php

namespace SumoCoders\FrameworkMultiUserBundle\Security;

use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidPasswordResetTokenException;
use SumoCoders\FrameworkMultiUserBundle\User\UserInterface;

class PasswordResetToken
{
    /**
     * @var string
     */
    private $token;

    /**
     * PasswordResetToken constructor.
     *
     * @param string $token
     */
    public function __construct($token)
    {
        $this->token = $token;
    }

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

    /**
     * @param UserInterface $user
     * @param $token
     *
     * @throws InvalidPasswordResetTokenException
     *
     * @return bool
     */
    public static function validateToken(UserInterface $user, PasswordResetToken $token)
    {
        if ($user->getPasswordResetToken()->equals($token)) {
            return true;
        }

        throw new InvalidPasswordResetTokenException('The given token is not valid.');
    }

    /**
     * Generates a PasswordToken
     *
     * @return PasswordResetToken
     */
    public static function generate()
    {
        $token = time() . base64_encode(random_bytes(10));

        return new self($token);
    }

    /**
     * Check if a token is equal to a different token.
     *
     * @param PasswordResetToken $token
     *
     * @return bool
     */
    public function equals(PasswordResetToken $token)
    {
        return $token->token === $this->token;
    }
}

Update phpdoc constructor parameter can't be null


<?php
/**
 * Created by PhpStorm.
 * User: Nabeel
 * Date: 2015-10-15
 * Time: 6:40 PM
 */

namespace ShortCirquit\LinkoScopeApi\Models;

class UserProfile extends BaseModel
{
    public $id;
    public $username;
}

<?php
/**
 * Created by PhpStorm.
 * User: Nabeel
 * Date: 2015-10-15
 * Time: 6:40 PM
 */

namespace ShortCirquit\LinkoScopeApi\Models;

class UserProfile extends BaseModel
{
    public $id;
    public $name;
    public $username;
    public $url;
}

Add new fields to user profile information


<?php

namespace Codeception\PHPUnit;

abstract class TestCase extends \PHPUnit\Framework\TestCase
{

    protected function setUp(): void
    {
        if (method_exists($this, '_setUp')) {
            $this->_setUp();
        }
    }

    protected function tearDown(): void
    {
        if (method_exists($this, '_tearDown')) {
            $this->_tearDown();
        }
    }

    public static function setUpBeforeClass(): void
    {
        if (method_exists(get_called_class(), '_setUpBeforeClass')) {
            static::_setUpBeforeClass();
        }
    }

    public static function tearDownAfterClass(): void
    {
        if (method_exists(get_called_class(), '_tearDownAfterClass')) {
            static::_tearDownAfterClass();
        }
    }

    public function expectExceptionMessageRegExp(string $regularExpression): void
    {
        $this->expectExceptionMessageMatches($regularExpression);
    }
}

<?php

namespace Codeception\PHPUnit;

abstract class TestCase extends \PHPUnit\Framework\TestCase
{

    protected function setUp(): void
    {
        if (method_exists($this, '_setUp')) {
            $this->_setUp();
        }
    }

    protected function tearDown(): void
    {
        if (method_exists($this, '_tearDown')) {
            $this->_tearDown();
        }
    }

    public static function setUpBeforeClass(): void
    {
        if (method_exists(get_called_class(), '_setUpBeforeClass')) {
            static::_setUpBeforeClass();
        }
    }

    public static function tearDownAfterClass(): void
    {
        if (method_exists(get_called_class(), '_tearDownAfterClass')) {
            static::_tearDownAfterClass();
        }
    }

    public function expectExceptionMessageRegExp(string $regularExpression): void
    {
        $this->expectExceptionMessageMatches($regularExpression);
    }

    public static function assertRegExp(string $pattern, string $string, string $message = ''): void
    {
        parent::assertMatchesRegularExpression($pattern, $string, $message);
    }

    public static function assertNotRegExp(string $pattern, string $string, string $message = ''): void
    {
        parent::assertDoesNotMatchRegularExpression($pattern, $string, $message);
    }

    public static function assertFileNotExists(string $filename, string $message = ''): void
    {
        parent::assertFileDoesNotExist($filename, $message);
    }
}

Create wrapper for methods deprecated in PHPUnit 9


<?php
/**
 * Core Configurations.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       Cake.Config
 * @since         CakePHP(tm) v 1.1.11.4062
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
$versionFile = file(CAKE . 'VERSION.txt');
return $config['Cake.version'] = trim(array_pop($versionFile));

<?php
/**
 * Core Configurations.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       Cake.Config
 * @since         CakePHP(tm) v 1.1.11.4062
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
$versionFile = file(CAKE . 'VERSION.txt');
$config['Cake.version'] = trim(array_pop($versionFile));
return $config;

Fix failing test in App.

Fix failing test in App.


<?php
namespace Veles\DataBase\ConnectionPools;

use Veles\DataBase\Connections\PdoConnection;

/**
 * Class ConnectionPool
 *
 * @author  Alexander Yancharuk <alex at itvault dot info>
 */
class ConnectionPool
{
	/** @var array */
	protected $pool;
	/** @var  string */
	protected $default_connection_name;

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

	/**
	 * Add connection to connection pool
	 *
	 * @param PdoConnection $conn
	 * @param bool $default Flag is this connection default or not
	 * @return $this
	 * @see DbConnection
	 */
	public function addConnection(PdoConnection $conn, $default = false)
	{
		$this->pool[$conn->getName()] = $conn;

		if ($default) {
			$this->default_connection_name = $conn->getName();
		}
		return $this;
	}

	/**
	 * Get connection class by name
	 *
	 * @param string $name Connection name
	 * @return PdoConnection|null
	 * @see DbConnection
	 */
	public function getConnection($name)
	{
		return isset($this->pool[$name]) ? $this->pool[$name] : null;
	}
}

<?php
namespace Veles\DataBase\ConnectionPools;

use Veles\DataBase\Connections\PdoConnection;

/**
 * Class ConnectionPool
 *
 * @author  Alexander Yancharuk <alex at itvault dot info>
 */
class ConnectionPool
{
	/** @var array */
	protected $pool;
	/** @var  string */
	protected $conn_name;

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

	/**
	 * Add connection to connection pool
	 *
	 * @param PdoConnection $conn
	 * @param bool $default Flag is this connection default or not
	 * @return $this
	 * @see DbConnection
	 */
	public function addConnection(PdoConnection $conn, $default = false)
	{
		$this->pool[$conn->getName()] = $conn;

		if ($default) {
			$this->conn_name = $conn->getName();
		}
		return $this;
	}

	/**
	 * Get connection class by name
	 *
	 * @param string $name Connection name
	 * @return PdoConnection|null
	 * @see DbConnection
	 */
	public function getConnection($name)
	{
		return isset($this->pool[$name]) ? $this->pool[$name] : null;
	}
}

Rename default connection name property

Rename default connection name property


<?php

namespace SecucardConnect\Product\Payment;

use SecucardConnect\Client\ProductService;

/**
 * Operations for the payment/customers resource.
 * @package SecucardConnect\Product\Payment
 */
class CustomersService extends ProductService
{

}

<?php

namespace SecucardConnect\Product\Payment;

use SecucardConnect\Client\ProductService;
use SecucardConnect\Client\RequestOptions;
use SecucardConnect\Event\AbstractEventHandler;
use SecucardConnect\Product\Common\Model\BaseCollection;
use SecucardConnect\Product\General\Model\Event;
use SecucardConnect\Product\Payment\Model\Customer;

/**
 * Operations for the payment/customers resource.
 * @package SecucardConnect\Product\Payment
 */
class CustomersService extends ProductService
{
    /**
     * Set a callback to be notified when a customer has changed. Pass null to remove a previous setting.
     * @param $fn callable|null Any function which accepts a Customer class argument.
     *
     */
    public function onCustomerChanged($fn)
    {
        $this->registerEventHandler('h2k0sh6lm1w',
            $fn === null ? null : new CustChange($this->resourceMetadata->resourceId, Event::TYPE_CHANGED, $fn, $this));
    }

    /**
     * {@inheritDoc}
     */
    protected function getRequestOptions()
    {
        return [
            RequestOptions::RESULT_PROCESSING => function (&$value) {
                if ($value instanceof BaseCollection) {
                    $results = $value->items;
                } elseif ($value instanceof Customer) {
                    $results[] = $value;
                } else {
                    return;
                }

                foreach ($results as $result) {
                    $this->process($result);
                }
            }
        ];
    }

    /**
     * Handles proper picture object initialization after retrieval of a customer.
     * @param Customer $customer
     */
    private function process(Customer &$customer)
    {
        if (isset($customer->contact) && isset($customer->contact->picture)) {
            $customer->contact->pictureObject = $this->initMediaResource($customer->contact->picture);
        }
    }
}

/**
 * Internal class to handle a customer change event.
 * @package SecucardConnect\Product\Payment
 */
class CustChange extends AbstractEventHandler
{
    /**
     * @var CustomersService
     */
    private $service;

    /**
     * CustomerChangedHandler constructor.
     * @param null|string $eventTarget
     * @param null|string $eventType
     * @param callable $callback
     * @param $service CustomersService
     */
    public function __construct($eventTarget, $eventType, callable $callback, $service)
    {
        parent::__construct($eventTarget, $eventType, $callback);
        $this->service = $service;
    }

    function handle($event)
    {
        if ($this->accept($event)) {
            if (!empty($event->data) && count($event->data) != 0) {
                call_user_func($this->callback, $this->service->get($event->data[0]['id']));
            }
            return true;
        }

        return false;
    }
}

New: Add change event handler to payment customers.


<?php namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Laravel\Lumen\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        //
    }
}

<?php namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Laravel\Lumen\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \Hexcores\Api\Console\ApiKeyGenerate::class
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        //
    }
}

Add api key generator command.

Add api key generator command.


@extends('layout')

@section('body')

            @if ($errors->any())
                @foreach ($errors->all() as $error)

{{ $error }}

                @endforeach
            @endif

Register

                <form method="POST">
                    {{ csrf_field() }}
                    Name
                    <input type="text" name="name" />
                    E-mail
                    <input type="email" name="email" />
                    Password
                    <input type="password" name="password" />
                    Currency
                    <select name="currency">
                        @foreach ($currencies as $currency)
                            <option value="{{ $currency->id }}">{{ $currency->symbol }} · {{ $currency->name }}</option>
                        @endforeach
                    </select>

                            <input type="submit" value="Register" />

                            Log in

                </form>

@endsection

@extends('layout')

@section('body')

Register

                <form method="POST">
                    {{ csrf_field() }}
                    Name
                    <input type="text" name="name" />
                    @if ($errors->has('name'))

{{ $errors->first('name') }}

                    @endif
                    E-mail
                    <input type="email" name="email" />
                    @if ($errors->has('email'))

{{ $errors->first('email') }}

                    @endif
                    Password
                    <input type="password" name="password" />
                    @if ($errors->has('password'))

{{ $errors->first('password') }}

                    @endif
                    Currency
                    <select name="currency">
                        @foreach ($currencies as $currency)
                            <option value="{{ $currency->id }}">{{ $currency->symbol }} · {{ $currency->name }}</option>
                        @endforeach
                    </select>
                    @if ($errors->has('currency_id'))

{{ $errors->first('currency_id') }}

                    @endif

                            <input type="submit" value="Register" />

                            Log in

                </form>

@endsection

Replace big alerts with inline alerts for register view


<?php

namespace Illuminate\Foundation\Bootstrap;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Foundation\PackageAssetLoader;
use Illuminate\Contracts\Foundation\Application;

class RegisterPackageProviders
{
    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Application $app)
    {
        $assetLoader = new PackageAssetLoader(new Filesystem, base_path('vendor'), $app->getCachedPackagesPath());

        foreach ($assetLoader->get('providers') as $provider) {
            $app->register($provider);
        }
    }
}

<?php

namespace Illuminate\Foundation\Bootstrap;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Foundation\PackageAssetLoader;
use Illuminate\Contracts\Foundation\Application;

class RegisterPackageProviders
{
    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Application $app)
    {
        if (! $app->make('config')->get('app.autoload_package_providers', true)) {
            return;
        }

        $assetLoader = new PackageAssetLoader(new Filesystem, base_path('vendor'), $app->getCachedPackagesPath());

        foreach ($assetLoader->get('providers') as $provider) {
            $app->register($provider);
        }
    }
}

Allow users to disable package autoloading


<?php

namespace Politix\PolitikportalBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
// use Politix\PolitikportalBundle\Model;

class SourcesController extends Controller {

    public function indexAction($name) {

		$out['items'] = $this->getSource('tagesschau');
		$out['name'] = $name;

        return $this->render('PolitikportalBundle:Default:items.html.twig', $out);

    }

    function getSourceAction($source) {

    	$out['source'] = $source;

    	$sql = 'SELECT * FROM rss_items WHERE source LIKE "' . $source . '" ORDER BY pubDate DESC LIMIT 0,10';
    	$out['items'] = $this->getDB($sql);

        return $this->render('PolitikportalBundle:Default:items.html.twig', $out);

    }

    function getSourcesAction() {

    	require ('/var/www/vhosts/politikportal.eu/subdomains/new/httpdocs/politix/src/Politix/PolitikportalBundle/Model/SourceModel.php');
    	$db = new SourceModel();
    	$out['sources'] = $db->getSources;

    	return $this->render('PolitikportalBundle:Default:sources.html.twig', $out);

    }

    function getDB($sql) {

    	$conn = $this->container->get('database_connection');
		return $conn->query($sql);

    }

}

<?php

namespace Politix\PolitikportalBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
// use Politix\PolitikportalBundle\Model;

class SourcesController extends Controller {

    public function indexAction($name) {

		$out['items'] = $this->getSource('tagesschau');
		$out['name'] = $name;

        return $this->render('PolitikportalBundle:Default:items.html.twig', $out);

    }

    function getSourceAction($source) {

    	$out['source'] = $source;

    	$sql = 'SELECT * FROM rss_items WHERE source LIKE "' . $source . '" ORDER BY pubDate DESC LIMIT 0,10';
    	$out['items'] = $this->getDB($sql);

        return $this->render('PolitikportalBundle:Default:items.html.twig', $out);

    }

    function getSourcesAction() {

    	require ('/var/www/vhosts/politikportal.eu/subdomains/new/httpdocs/politix/src/Politix/PolitikportalBundle/Model/SourceModel.php');
    	$db = new Politix\PolitikportalBundle\Model\SourceModel();
    	$out['sources'] = $db->getSources;

    	return $this->render('PolitikportalBundle:Default:sources.html.twig', $out);

    }

    function getDB($sql) {

    	$conn = $this->container->get('database_connection');
		return $conn->query($sql);

    }

}

Add path when calling object

Add path when calling object


<?php
/**
 * The story editor.
 *
 * @package AMP
 */

// don't load directly.
if ( ! defined( 'ABSPATH' ) ) {
	die( '-1' );
}

require_once ABSPATH . 'wp-admin/admin-header.php';

AMP_Story_Legacy_Post_Type::enqueue_block_editor_scripts();

global $post, $post_type;

$config = [];

$config['api'] = [
	'stories' => sprintf( '/wp/v2/%s', $post_type ),
	'media' => '/wp/v2/media',
];

if ( ! empty( $post ) ) {
	$config['storyId'] = $post->ID;
}

?>

<div id="edit-story" data-config="<?php echo esc_attr( wp_json_encode( $config ) ); ?>">

Please wait...

<?php
/**
 * The story editor.
 *
 * @package AMP
 */

// don't load directly.
if ( ! defined( 'ABSPATH' ) ) {
	die( '-1' );
}

require_once ABSPATH . 'wp-admin/admin-header.php';

?>

<?php esc_html_e( 'Please wait...', 'amp' ); ?>

Add new custom post type and add new setting.


<?php

/*
 * This file is part of the EmharCqrsInfrastructure bundle.
 *
 * (c) Emmanuel Harleaux
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Emhar\CqrsInfrastructureBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration.
 *
 * @link http://symfony.com/doc/current/cookbook/bundles/extension.html
 */
class EmharCqrsInfrastructureExtension extends Extension
{
    /**
     * {@inheritdoc}
     * @throws \Exception
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.yml');
        if ($container->getParameter('kernel.debug')) {
            $loader->load('datacollector.yml');
            $loader->load('commands.yml');
        }
    }
}

<?php

/*
 * This file is part of the EmharCqrsInfrastructure bundle.
 *
 * (c) Emmanuel Harleaux
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Emhar\CqrsInfrastructureBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration.
 *
 * @link http://symfony.com/doc/current/cookbook/bundles/extension.html
 */
class EmharCqrsInfrastructureExtension extends Extension
{
    /**
     * {@inheritdoc}
     * @throws \Exception
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.yml');
        $loader->load('commands.yml');
        if ($container->getParameter('kernel.debug')) {
            $loader->load('datacollector.yml');
        }
    }
}

Fix config file loading in prod

Fix config file loading in prod


<?php
declare(strict_types=1);

/**
 * This file is part of the Carbon package.
 *
 * (c) Brian Nesbitt <brian@nesbot.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Tests\Language;

use Carbon\Translator;
use Tests\AbstractTestCase;

class TranslatorTest extends AbstractTestCase
{
    public function testSetLocale()
    {
        $currentLocale = setlocale(LC_TIME, '0');
        $currentLocaleAll = setlocale(LC_ALL, '0');

        $translator = new Translator('en_FooBar');
        $translator->setLocale('auto');

        $this->assertSame('en', $translator->getLocale());

        $translator = new Translator('en');
        $translator->setLocale('en_iso');

        $this->assertSame('en_ISO', $translator->getLocale());

        $translator = new Translator('fr');
        setlocale(LC_ALL, 'en_US', 'en_GB', 'en');
        setlocale(LC_TIME, 'en_US', 'en_GB', 'en');
        $translator->setLocale('auto');

        $this->assertStringStartsWith('en_US', $translator->getLocale());

        setlocale(LC_ALL, $currentLocaleAll);
        setlocale(LC_TIME, $currentLocale);
    }
}

<?php
declare(strict_types=1);

/**
 * This file is part of the Carbon package.
 *
 * (c) Brian Nesbitt <brian@nesbot.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace Tests\Language;

use Carbon\Translator;
use Tests\AbstractTestCase;

class TranslatorTest extends AbstractTestCase
{
    public function testSetLocale()
    {
        $currentLocale = setlocale(LC_TIME, '0');
        $currentLocaleAll = setlocale(LC_ALL, '0');

        $translator = new Translator('en_FooBar');
        $translator->setLocale('auto');

        $this->assertSame('en', $translator->getLocale());

        $translator = new Translator('en');
        $translator->setLocale('en_iso');

        $this->assertSame('en_ISO', $translator->getLocale());

        $translator = new Translator('fr');
        setlocale(LC_ALL, 'en_US.UTF-8', 'en_US.utf8', 'en_US', 'en_GB', 'en');
        setlocale(LC_TIME, 'en_US.UTF-8', 'en_US.utf8', 'en_US', 'en_GB', 'en');
        $translator->setLocale('auto');

        $this->assertStringStartsWith('en_US', $translator->getLocale());

        setlocale(LC_ALL, $currentLocaleAll);
        setlocale(LC_TIME, $currentLocale);
    }
}

Fix Translator tests for Travis

Fix Translator tests for Travis


<?php

/**
 * @author marcus
 */
class AssetUrlConversionFilter implements RequestFilter {

    private $convertUrls = false;

    public function setConvertUrls($v) {
        $this->convertUrls = $v;
    }

    public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model) {
        if ($this->convertUrls) {
            $body = $response->getBody();

            if (preg_match_all('/data-cdnfileid="(\d+)"/', $body, $matches)) {
                $files = CdnImage::get()->filter('ID', $matches[1]);
                foreach ($files as $file) {
                    $url = $file->getUrl();
                    $filename = $file->Filename;
                    $body = str_replace("src=\"$filename\"", "src=\"$url\"", $body);
                }
                $response->setBody($body);
            }
        }
    }

    public function preRequest(\SS_HTTPRequest $request, \Session $session, \DataModel $model) {

    }

}

<?php

/**
 * @author marcus
 */
class AssetUrlConversionFilter implements RequestFilter {

    private $convertUrls = false;

    public function setConvertUrls($v) {
        $this->convertUrls = $v;
    }

    public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model) {
        if ($this->convertUrls) {
            $body = $response->getBody();

//            if (preg_match_all('{(src|href)="/?(assets/.*?)"}', $body, $matches)) {
//                $names = $matches[2];
//                $files =
//            }
            // find urls inserted in content
            if (preg_match_all('/data-cdnfileid="(\d+)"/', $body, $matches)) {
                $files = CdnImage::get()->filter('ID', $matches[1]);
                foreach ($files as $file) {
                    $url = $file->getUrl();
                    $filename = $file->Filename;
                    $body = str_replace("src=\"$filename\"", "src=\"$url\"", $body);
                }
                $response->setBody($body);
            }
        }
    }

    public function preRequest(\SS_HTTPRequest $request, \Session $session, \DataModel $model) {

    }

}

FIX If no image found for the given conversion, skip adding data- attribute


<?php
namespace App\EventListener;

use App\Service\Config;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

use function Sentry\init as sentryInit;
use function Sentry\captureException as sentryCaptureException;

/**
 * Sends errors to symfony
 */
class SentryCaptureListener
{
    /**
     * @var bool
     */
    protected $errorCaptureEnabled;

    public function __construct(
        Config $config,
        string $sentryDSN
    ) {
        $this->errorCaptureEnabled = $config->get('errorCaptureEnabled');
        if ($this->errorCaptureEnabled) {
            sentryInit(['dsn' => $sentryDSN]);
        }
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if ($this->errorCaptureEnabled) {
            sentryCaptureException($event->getException());
        }
    }
}

<?php
namespace App\EventListener;

use App\Service\Config;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use function Sentry\init as sentryInit;
use function Sentry\captureException as sentryCaptureException;

/**
 * Sends errors to symfony
 */
class SentryCaptureListener
{
    /**
     * @var bool
     */
    protected $errorCaptureEnabled;

    public function __construct(
        Config $config,
        string $sentryDSN
    ) {
        $this->errorCaptureEnabled = $config->get('errorCaptureEnabled');
        if ($this->errorCaptureEnabled) {
            sentryInit(['dsn' => $sentryDSN]);
        }
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if ($this->errorCaptureEnabled) {
            $exception = $event->getException();
            //don't report 404s to Sentry
            if ($exception instanceof NotFoundHttpException) {
                return;
            }
            sentryCaptureException($exception);
        }
    }
}

Stop reporting 404 errors to sentry

Stop reporting 404 errors to sentry

We get lots of these and they are all crawlers or bad actors. We should
just ignore them.


<?php

/**
 * Copyright 2016 SURFnet B.V.
 *
 * 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 Surfnet\SamlBundle\SAML2\Attribute;

use SAML2_Assertion;

interface AttributeSetFactory
{
    /**
     * @param SAML2_Assertion $assertion
     * @param AttributeDictionary $attributeDictionary
     * @return AttributeSetInterface
     *
     * @deprecated Will be replaced with different creation implementation
     */
    public static function createFrom(SAML2_Assertion $assertion, AttributeDictionary $attributeDictionary);

    /**
     * @param Attribute[] $attributes
     * @return AttributeSetInterface
     *
     * @deprecated Will be replaced with different creation implementation
     */
    public static function create(array $attributes);
}

<?php

/**
 * Copyright 2016 SURFnet B.V.
 *
 * 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 Surfnet\SamlBundle\SAML2\Attribute;

use SAML2_Assertion;

interface AttributeSetFactory
{
    /**
     * @param SAML2_Assertion $assertion
     * @param AttributeDictionary $attributeDictionary
     * @return AttributeSet
     *
     * @deprecated Will be replaced with different creation implementation
     */
    public static function createFrom(SAML2_Assertion $assertion, AttributeDictionary $attributeDictionary);

    /**
     * @param Attribute[] $attributes
     * @return AttributeSet
     *
     * @deprecated Will be replaced with different creation implementation
     */
    public static function create(array $attributes);
}

Make doc blocks bc compliant

Make doc blocks bc compliant