<?php

	namespace MikeVrind\Deployer\Controllers;

	use Illuminate\Routing\Controller;
	use MikeVrind\Deployer\Deployer;

	class DeployController extends Controller
	{

		/**
		 * Parse the incoming webhook to the deployer
		 *
		 * @param Deployer $deployer
		 * @return mixed
		 */
		public function handle( Deployer $deployer )
		{

			if( $deployer->deploy() )
			{

				return response( [
					'status'  => 200,
					'message' => 'deployment successful'
				], 200 );

			}
			else
			{
				return response( [
					'status'  => 503,
					'message' => $deployer->getErrorMessage()
				], 503 );

			}

		}

	}

<?php

	namespace MikeVrind\Deployer\Controllers;

	use Illuminate\Routing\Controller;
	use MikeVrind\Deployer\Deployer;

	class DeployController extends Controller
	{

		/**
		 * Parse the incoming webhook to the deployer
		 *
		 * @param Deployer $deployer
		 * @return mixed
		 */
		public function handle( Deployer $deployer )
		{

			if( $deployer->deploy() )
			{

				return response()->json( [
					'status'  => 200,
					'message' => 'Deployment successful'
				], 200 );

			}
			else
			{
				return response()->json( [
					'status'  => 503,
					'message' => $deployer->getErrorMessage()
				], 503 );

			}

		}

	}

Return actual json to fix webhook testing showing a potential debugbar


<?php
// If blog posts configured for front page, pass on handling
if ( 'posts' == get_option( 'show_on_front' ) ) {
		include( get_home_template() );
		return;
}
?>
<?php get_header(); ?>

			<?php
			if ( is_active_sidebar( 'frontpage' ) ) {
				dynamic_sidebar( 'frontpage' );
			} elseif ( have_posts() ) {
				while ( have_posts() ) {
					the_post();
			?>

			<div <?php post_class( 'card post-wrapper' ); ?>>
				<?php get_template_part( 'template-parts/content', get_post_format() ); ?>

			<?php
				}
				seabadgermd_pagination();
			}
			?>

		<?php get_sidebar(); ?>

<?php get_footer(); ?>

<?php
// If blog posts configured for front page, pass on handling
if ( 'posts' == get_option( 'show_on_front' ) ) {
		load_template( get_home_template() );
		return;
}
?>
<?php get_header(); ?>

			<?php
			if ( is_active_sidebar( 'frontpage' ) ) {
				dynamic_sidebar( 'frontpage' );
			} elseif ( have_posts() ) {
				while ( have_posts() ) {
					the_post();
			?>

			<div <?php post_class( 'card post-wrapper' ); ?>>
				<?php get_template_part( 'template-parts/content', get_post_format() ); ?>

			<?php
				}
				seabadgermd_pagination();
			}
			?>

		<?php get_sidebar(); ?>

<?php get_footer(); ?>

Load homepage template instead of including


<?php namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider {

	/**
	 * This namespace is applied to the controller routes in your routes file.
	 *
	 * In addition, it is set as the URL generator's root namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'App\Http\Controllers';

	/**
	 * Define your route model bindings, pattern filters, etc.
	 *
	 * @param  \Illuminate\Routing\Router  $router
	 * @return void
	 */
	public function boot(Router $router)
	{
		parent::boot($router);

		//
	}

	/**
	 * Define the routes for the application.
	 *
	 * @param  \Illuminate\Routing\Router  $router
	 * @return void
	 */
	public function map(Router $router)
	{
		$router->group(['namespace' => $this->namespace], function($router)
		{
			require app_path('Http/routes.php');
		});
	}

}

<?php namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider {

	/**
	 * This namespace is applied to the controller routes in your routes file.
	 *
	 * In addition, it is set as the URL generator's root namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'App\Http\Controllers';

	/**
	 * Define your route model bindings, pattern filters, etc.
	 *
	 * @param  \Illuminate\Routing\Router  $router
	 * @return void
	 */
	public function boot(Router $router)
	{
		parent::boot($router);

		$router->pattern('id', '[0-9]+');
	}

	/**
	 * Define the routes for the application.
	 *
	 * @param  \Illuminate\Routing\Router  $router
	 * @return void
	 */
	public function map(Router $router)
	{
		$router->group(['namespace' => $this->namespace], function($router)
		{
			require app_path('Http/routes.php');
		});
	}

}

Use the pattern method to contrain the route parameter by a given regular expression.


<?php

class Denkmal_Paging_ScraperSource_All extends CM_Paging_Abstract {

    public function __construct() {
        $scraperList = array(
            new Denkmal_Scraper_Source_Kaschemme(),
            new Denkmal_Scraper_Source_Programmzeitung(),
            new Denkmal_Scraper_Source_Hinterhof(),
            new Denkmal_Scraper_Source_Fingerzeig(),
            new Denkmal_Scraper_Source_Lastfm(),
        );

        $source = new CM_PagingSource_Array($scraperList);
        parent::__construct($source);
    }
}

<?php

class Denkmal_Paging_ScraperSource_All extends CM_Paging_Abstract {

    public function __construct() {
        $scraperList = array(
            new Denkmal_Scraper_Source_Kaschemme(),
            new Denkmal_Scraper_Source_Programmzeitung(),
            new Denkmal_Scraper_Source_Hinterhof(),
            new Denkmal_Scraper_Source_Fingerzeig(),
            new Denkmal_Scraper_Source_Lastfm(),
            new Denkmal_Scraper_Source_Saali(),
        );

        $source = new CM_PagingSource_Array($scraperList);
        parent::__construct($source);
    }
}

Add sääli scraper to paging

Add sääli scraper to paging


<?php

namespace App\Http\Controllers;

use App\Url;
use Illuminate\Http\Request;
use Illuminate\Session\Store;
use Illuminate\Validation\Factory as Validator;
use Zenapply\Shortener\Facades\Shortener;

class UrlController extends Controller
{
    public function manageUrl(Request $request, Store $session, Validator $validator)
    {
        if ($request->isMethod('post')) {
            if ($request->has('url')) {
                $url = new Url();
                $url->original_url = $request->input('url');
                $url->shortened_url = Shortener::shorten($request->input('url'));
                $url->save();
                \Session::flash('message', 'Record saved');
            }

            return redirect('/view-urls');
        }

        return view('url.manage', []);
    }

    public function viewUrls()
    {
        $urls = Url::all();

        return view('url.view', [
            'urls' => $urls,
            'message' => \Session::get('message')
        ]);
    }
}

<?php

namespace App\Http\Controllers;

use App\Url;
use Illuminate\Http\Request;
use Illuminate\Session\Store;
use Illuminate\Validation\Factory as Validator;
use Zenapply\Shortener\Shortener;

class UrlController extends Controller
{
    public function manageUrl(Request $request, Store $session, Validator $validator)
    {
        if ($request->isMethod('post')) {
            if ($request->has('url')) {
                $this->validate($request, [
                    'url' => 'required|url|unique:urls,original_url',
                ]);

                $this->saveAndFlash($request, $session, $shortener);
            }
        }

        return view('url.manage', []);
    }

    public function viewUrls()
    {
        $urls = Url::all();

        return view('url.view', [
            'urls' => $urls,
            'message' => \Session::get('message')
        ]);
    }

    /**
     * Persist the Url/Route object
     *
     * @param Request   $request
     * @param Shortener $shortener
     *
     * @return bool
     */
    private function save(Request $request, Shortener $shortener)
    {
        $url = new Url();
        $url->original_url = $request->input('url');
        $url->shortened_url = $shortener->shorten($request->input('url'));

        return $url->saveOrFail();
    }

    /**
     * Attempt to persist the record and store an appropriate flash message
     *
     * @param Request   $request
     * @param Store     $session
     * @param Shortener $shortener
     */
    private function saveAndFlash(Request $request, Store $session, Shortener $shortener)
    {
        $message = $this->save($request, $shortener) ? 'Record saved' : 'Record NOT saved';
        $session->flash('message', $message);
    }
}

Add utility methods for saving a Url

Add utility methods for saving a Url

Whilst everything could be added in the manageUrl method, that doesn't
aid readability. So I've split out that functionality in to separate
methods.


<?php

/**
 * Hackwork v2.0.0-beta (http://git.io/hackwork)
 * Licensed under the MIT License.
 */

/*
 * Paths
 *
 * Omit trailing slashes here.
 */

// Root
define('ROOT', $_SERVER['DOCUMENT_ROOT']);
define('PATH', ROOT);

// Core
define('CORE', PATH . '/core');
define('HELPERS', CORE . '/helpers');

// Layouts
define('LAYOUTS', PATH . '/layouts');

// Data
define('DATA', PATH . '/data');

// Assets
define('ASSETS', '/assets');
define('CSS', ASSETS . '/css');
define('JS', ASSETS . '/js');
define('FONTS', ASSETS . '/fonts');
define('IMG', ASSETS . '/img');

/*
 * Helpers
 */

$helpers = array(
  'http',
  'errors',
  'layout',
  'config'
);

foreach ($helpers as $helper) {
  require_once HELPERS . "/$helper.php";
}

<?php

/**
 * Hackwork v2.0.0-beta (http://git.io/hackwork)
 * Licensed under the MIT License.
 */

/*
 * Paths
 *
 * Omit trailing slashes here.
 */

// Root
define('ROOT', $_SERVER['DOCUMENT_ROOT']);
define('PATH', ROOT);

// Core
define('CORE', PATH . '/core');
define('HELPERS', CORE . '/helpers');

// Layouts
define('LAYOUTS', PATH . '/layouts');

// Data
define('DATA', PATH . '/data');

// Assets
define('ASSETS', '/assets');
define('CSS', ASSETS . '/css');
define('JS', ASSETS . '/js');
define('FONTS', ASSETS . '/fonts');
define('IMG', ASSETS . '/img');

/*
 * Helpers
 */

$helpers = array(
  'http',
  'errors',
  'layout',
  'config'
);

foreach ($helpers as $helper) {
  $helper = HELPERS . "/$helper.php";

  if (file_exists($helper)) {
    require_once $helper;
  }
}

Fix errors if helper doesn't exist

Fix errors if helper doesn't exist


<?php

declare(strict_types=1);

namespace muqsit\playervaults;

use Ds\Set;
use pocketmine\Player;
use pocketmine\utils\Config;

final class PermissionManager{

	/** @var Set<string>[] */
	private $grouping = [];

	public function __construct(Config $config){
		if($config->get("enabled", false)){
			foreach($config->get("permissions") as $permission => $vaults){
				$this->registerGroup($permission, $vaults);
			}
		}
	}

	public function registerGroup(string $permission, int $vaults) : void{
		if(!isset($this->grouping[$vaults])){
			$this->grouping[$vaults] = new Set();
			ksort($this->grouping);
		}

		$this->grouping[$vaults]->add($permission);
	}

	public function hasPermission(Player $player, int $vault) : bool{
		if($player->hasPermission("playervaults.vault.{$vault}")){
			return true;
		}

		foreach($this->grouping as $max_vaults => $permissions){
			if($max_vaults < $vault){
				break;
			}
			foreach($permissions as $permission){
				if($player->hasPermission($permission)){
					return true;
				}
			}
		}
		return false;
	}
}

<?php

declare(strict_types=1);

namespace muqsit\playervaults;

use Ds\Set;
use pocketmine\Player;
use pocketmine\utils\Config;

final class PermissionManager{

	/** @var Set<string>[] */
	private $grouping = [];

	public function __construct(Config $config){
		if($config->get("enabled", false)){
			foreach($config->get("permissions") as $permission => $vaults){
				$this->registerGroup($permission, $vaults);
			}
		}
	}

	public function registerGroup(string $permission, int $vaults) : void{
		if(!isset($this->grouping[$vaults])){
			$this->grouping[$vaults] = new Set();
			krsort($this->grouping);
		}

		$this->grouping[$vaults]->add($permission);
	}

	public function hasPermission(Player $player, int $vault) : bool{
		if($player->hasPermission("playervaults.vault.{$vault}")){
			return true;
		}

		foreach($this->grouping as $max_vaults => $permissions){
			if($max_vaults < $vault){
				break;
			}
			foreach($permissions as $permission){
				if($player->hasPermission($permission)){
					return true;
				}
			}
		}
		return false;
	}
}

Fix permission grouping bug resulting in incorrect permission checking


<?php

namespace My\BlogBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/hello/Fabien');

        $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
    }
}

<?php

namespace My\BlogBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
//    public function testIndex()
//    {
//        $client = static::createClient();
//        $crawler = $client->request('GET', '/hello/Fabien');
//        $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
//        $arr = array('a','b');
//        $this->assertTrue(count($arr) === 2);

//    }

    public function test一覧画面が表示される()
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/blog/');
        $this->assertTrue($client->getResponse()->isSuccessful());
    }

    public function test詳細画面が表示される()
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/blog/5/show');
        $this->assertTrue($client->getResponse()->isSuccessful());
    }

    public function test登録ができる()
    {
/*
        $client = static::createClient();
        $crawler = $client->request('GET', 'blog/new');

        $this->assertTrue($client->getResponse()->isSuccessful());
        $form = $crawler->selectButton('Save Post')->form();

        $form['form[title]'] = 'title';
        $form['form[body]'] = 'bodybodybody';

        $crawler = $client->submit($form);
        $crawler = $client->followRedirect();
        $this->assertTrue($client->getResponse()->isSuccessful());
*/
       $client = static::createClient();
        $crawler = $client->request('GET', '/blog/new');
        $this->assertTrue($client->getResponse()->isSuccessful());
        $form = $crawler->selectButton('Save Post')->form();//var_dump($form);
        $form['form["title"]'] = 'title';
        $form['form["body"]'] = 'bodybodybody';
        $crawler = $client->submit($form);
        $crawler = $client->followRedirect();
        $this->assertTrue($client->getResponse()->isSuccessful());

        //データベースを参照して登録されているか確認
        $kernel = static::createKernel();
        $kernel->boot();
        $em = $kernel->getContainer()->get('doctrine.orm.entity_manager');
        $dql = 'SELECT p FROM My\BlogBundle\Entity\Post p ORDER BY p.id DESC';
        $query = $em->createQuery($dql);
        $query->setMaxResults(1);
        $posts = $query->execute();
        $post = $posts[0];var_dump($post);
        $this->assertSame('title', $post->getTitle());
        $this->assertSame('bodybodybody', $post->getBody());

    }

}

Add basic unit test code

Add basic unit test code


<?php

if (CM_Db_Db::existsIndex('denkmal_push_subscription', 'subscriptionId-endpoint')) {
    CM_Db_Db::exec("DROP INDEX `subscriptionId-endpoint` ON denkmal_push_subscription;");
    CM_Db_Db::exec("CREATE UNIQUE INDEX `endpoint` ON denkmal_push_subscription (endpoint);");
}

if (CM_Db_Db::existsColumn('denkmal_push_subscription', 'subscriptionId')) {
    CM_Db_Db::exec("ALTER TABLE denkmal_push_subscription DROP COLUMN `subscriptionId`;");
}

<?php

CM_Db_Db::delete('denkmal_push_subscription');

if (CM_Db_Db::existsIndex('denkmal_push_subscription', 'subscriptionId-endpoint')) {
    CM_Db_Db::exec("DROP INDEX `subscriptionId-endpoint` ON denkmal_push_subscription;");
    CM_Db_Db::exec("CREATE UNIQUE INDEX `endpoint` ON denkmal_push_subscription (endpoint);");
}

if (CM_Db_Db::existsColumn('denkmal_push_subscription', 'subscriptionId')) {
    CM_Db_Db::exec("ALTER TABLE denkmal_push_subscription DROP COLUMN `subscriptionId`;");
}

Delete all existing push subscriptions

Delete all existing push subscriptions


<?php

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

class CreateTwoFactorAuthsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('two_factor_auths', function (Blueprint $table) {
            $table->string('id')->nullable();
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

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

<?php

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

class CreateTwoFactorAuthsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('two_factor_auths', function (Blueprint $table) {
            $table->string('id')->nullable();
            $table->bigIncrements('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

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

Change from increments to bigIncrements (unsure if this is adviseable...)


<?php

if(!empty($_GET["set"]) && file_exists("include/themes/" . $_GET["set"])) {
	setcookie("advancedban-panel_theme", $_GET["set"], time( ) + (30 * 60 * 60 * 24), "/");
} elseif(isset($_GET["default"])) {
	setcookie("advancedban-panel_theme", "", time( ) - (30 * 60 * 60 * 24), "/");
}

header("Location: ../../" . (isset($_GET["redirect"]) ? $_GET["redirect"] : "")); die("Redirecting...");

<?php

if(!empty($_GET["set"]) && file_exists("include/themes/" . $_GET["set"])) {
	setcookie("advancedban-panel_theme", $_GET["set"], time( ) + (30 * 60 * 60 * 24), "/");
} elseif(isset($_GET["default"])) {
	setcookie("advancedban-panel_theme", "", time( ) - (30 * 60 * 60 * 24), "/");
}

header("Location: " . ($__public["mod_rewrite"] === true ? "../../" : "./")); die("Redirecting...");

Fix redirecting with mod_rewrite disabled


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

$q= $_GET['q'];
if (!$q) exit;

$options= 0;
if ($_REQUEST['all']) $options+= FIND_ALL;
if ($_REQUEST['or']) $options+= FIND_OR;
if ($_REQUEST['sales']) $options+= FIND_SALES;

$items= item_find($db, $q, $options);

echo jsonp($items);

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

$q= $_GET['q'];
if (!$q) exit;

$options= 0;
if ($_REQUEST['all']) $options+= FIND_ALL;
if ($_REQUEST['or']) $options+= FIND_OR;
if ($_REQUEST['sales']) $options+= FIND_SALES;

$items= item_find($db, $q, $options);

echo jsonp(array('items' => $items));

Return a little more structure for items that are found


<?php namespace App\Data;

use UserPresenter;
use App\Authorization;
use Illuminate\Notifications\Notifiable;
use Laracasts\Presenter\PresentableTrait;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
	use Authorizable, Authorization, Notifiable, PresentableTrait;

	protected $connection = 'users';
	protected $fillable = ['points'];
	protected $hidden = ['password', 'remember_token'];
	protected $dates = ['created_at', 'updated_at', 'deleted_at'];
	protected $presenter = UserPresenter::class;

	//--------------------------------------------------------------------------
	// Relationships
	//--------------------------------------------------------------------------

	public function discussions()
	{
		return $this->hasMany(Discussion::class)->latest();
	}

	public function replies()
	{
		return $this->hasMany(Reply::class);
	}

	//--------------------------------------------------------------------------
	// Model Scopes
	//--------------------------------------------------------------------------

	public function scopeUsername($query, $username)
	{
		$query->where('username', $username);
	}

	//--------------------------------------------------------------------------
	// Model Methods
	//--------------------------------------------------------------------------

	public function getRouteKeyName()
	{
		return 'username';
	}
}

<?php namespace App\Data;

use UserPresenter;
use App\Authorization;
use Illuminate\Notifications\Notifiable;
use Laracasts\Presenter\PresentableTrait;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
	use Authorizable, Authorization, Notifiable, PresentableTrait;

	protected $connection = 'users';
	protected $fillable = ['points', 'signature'];
	protected $hidden = ['password', 'remember_token'];
	protected $dates = ['created_at', 'updated_at', 'deleted_at'];
	protected $presenter = UserPresenter::class;

	//--------------------------------------------------------------------------
	// Relationships
	//--------------------------------------------------------------------------

	public function discussions()
	{
		return $this->hasMany(Discussion::class)->latest();
	}

	public function replies()
	{
		return $this->hasMany(Reply::class);
	}

	//--------------------------------------------------------------------------
	// Model Scopes
	//--------------------------------------------------------------------------

	public function scopeUsername($query, $username)
	{
		$query->where('username', $username);
	}

	//--------------------------------------------------------------------------
	// Model Methods
	//--------------------------------------------------------------------------

	public function getRouteKeyName()
	{
		return 'username';
	}
}

Make sure users can edit their signature


<?php

use Orchestra\Support\Facades\Asset; ?>

© 2012 Orchestra Platform

<?php

$asset = Asset::container('orchestra/foundation::footer');

$asset->script('bootstrap', 'packages/orchestra/foundation/vendor/bootstrap/js/bootstrap.min.js');
$asset->script('jquery-ui', 'packages/orchestra/foundation/vendor/jquery.ui.js');
$asset->script('orchestra', 'packages/orchestra/foundation/js/script.min.js', array('bootstrap', 'jquery-ui'));
$asset->script('jui-toggleSwitch', 'packages/orchestra/foundation/vendor/delta/js/jquery-ui.toggleSwitch.js', array('jquery-ui'));
$asset->script('select2', 'packages/orchestra/foundation/vendor/select2/select2.min.js');

echo $asset->styles();
echo $asset->scripts(); ?>

@placeholder("orchestra.layout: footer")

<?php

use Illuminate\Support\Facades\Request;
use Orchestra\Support\Facades\Asset; ?>

© 2012 Orchestra Platform

<?php

$asset = Asset::container('orchestra/foundation::footer');

$asset->script('bootstrap', 'packages/orchestra/foundation/vendor/bootstrap/js/bootstrap.min.js');
$asset->script('jquery-ui', 'packages/orchestra/foundation/vendor/jquery.ui.js');
$asset->script('orchestra', 'packages/orchestra/foundation/js/script.min.js', array('bootstrap', 'jquery-ui'));
$asset->script('jui-toggleSwitch', 'packages/orchestra/foundation/vendor/delta/js/jquery-ui.toggleSwitch.js', array('jquery-ui'));
$asset->script('select2', 'packages/orchestra/foundation/vendor/select2/select2.min.js');

echo $asset->styles();
echo $asset->scripts(); ?>

@placeholder("orchestra.layout: footer")

Add JS event for each page load.

Add JS event for each page load.

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


<?php

namespace Config;

use CodeIgniter\View\View as BaseView;

class View extends BaseView
{
	/**
	 * When false, the view method will clear the data between each
	 * call. This keeps your data safe and ensures there is no accidental
	 * leaking between calls, so you would need to explicitly pass the data
	 * to each view. You might prefer to have the data stick around between
	 * calls so that it is available to all views. If that is the case,
	 * set $saveData to true.
	 *
	 * @var boolean
	 */
	public $saveData = true;

	/**
	 * Parser Filters map a filter name with any PHP callable. When the
	 * Parser prepares a variable for display, it will chain it
	 * through the filters in the order defined, inserting any parameters.
	 * To prevent potential abuse, all filters MUST be defined here
	 * in order for them to be available for use within the Parser.
	 *
	 * Examples:
	 *  { title|esc(js) }
	 *  { created_on|date(Y-m-d)|esc(attr) }
	 *
	 * @var array
	 */
	public $filters = [];

	/**
	 * Parser Plugins provide a way to extend the functionality provided
	 * by the core Parser by creating aliases that will be replaced with
	 * any callable. Can be single or tag pair.
	 *
	 * @var array
	 */
	public $plugins = [];
}

<?php

namespace Config;

use CodeIgniter\Config\View as BaseView;

class View extends BaseView
{
	/**
	 * When false, the view method will clear the data between each
	 * call. This keeps your data safe and ensures there is no accidental
	 * leaking between calls, so you would need to explicitly pass the data
	 * to each view. You might prefer to have the data stick around between
	 * calls so that it is available to all views. If that is the case,
	 * set $saveData to true.
	 *
	 * @var boolean
	 */
	public $saveData = true;

	/**
	 * Parser Filters map a filter name with any PHP callable. When the
	 * Parser prepares a variable for display, it will chain it
	 * through the filters in the order defined, inserting any parameters.
	 * To prevent potential abuse, all filters MUST be defined here
	 * in order for them to be available for use within the Parser.
	 *
	 * Examples:
	 *  { title|esc(js) }
	 *  { created_on|date(Y-m-d)|esc(attr) }
	 *
	 * @var array
	 */
	public $filters = [];

	/**
	 * Parser Plugins provide a way to extend the functionality provided
	 * by the core Parser by creating aliases that will be replaced with
	 * any callable. Can be single or tag pair.
	 *
	 * @var array
	 */
	public $plugins = [];
}

Fix wrong view config parent

Fix wrong view config parent


<?php

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

class CreateLikeableTables extends Migration {

	public function up() {

		Schema::create('likeable_likes', function(Blueprint $table) {
			$table->increments('id');
			$table->string('likable_id', 36);
			$table->string('likable_type', 255);
			$table->string('user_id', 36)->index();
			$table->timestamps();
			$table->unique(['likable_id', 'likable_type', 'user_id'], 'likeable_likes_unique');
		});

		Schema::create('likeable_like_counters', function(Blueprint $table) {
			$table->increments('id');
			$table->string('likable_id', 36);
			$table->string('likable_type', 255);
			$table->integer('count')->unsigned()->default(0);
			$table->unique(['likable_id', 'likable_type'], 'likeable_counts');
		});

	}

	public function down() {
		Schema::drop('likeable_likes');
		Schema::drop('likeable_like_counters');
	}
}

<?php

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

class CreateLikeableTables extends Migration {

	public function up() {

		Schema::create('likeable_likes', function(Blueprint $table) {
			$table->increments('id');
			$table->string('likable_id', 36);
			$table->string('likable_type', 255);
			$table->string('user_id', 36)->index();
			$table->timestamps();
			$table->unique(['likable_id', 'likable_type', 'user_id'], 'likeable_likes_unique');
		});

		Schema::create('likeable_like_counters', function(Blueprint $table) {
			$table->increments('id');
			$table->string('likable_id', 36);
			$table->string('likable_type', 255);
			$table->unsignedInteger('count')->default(0);
			$table->unique(['likable_id', 'likable_type'], 'likeable_counts');
		});

	}

	public function down() {
		Schema::drop('likeable_likes');
		Schema::drop('likeable_like_counters');
	}
}

Use the shortcut method for unsigned integer


<?php

require 'vendor/autoload.php';

$_SERVER['REQUEST_URI'] = '/test/slugifiedtext/123';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['HTTP_HOST'] = 'example.com';

class TestController
{
    public function indexAction($slug, $id)
    {
    }
}

$bench = new \KM\Benchmark();
$bench
    ->execute(
       'Saffron',
        function () {
            require 'test/saffron.php';
        }
    )
    ->execute(
       'Saffron (e)',
        function () {
            require 'test/saffron.execute.php';
        }
    )
    ->execute(
        'Pux',
        function () {
            require 'test/pux.php';
        }
    )
    ->execute(
        'Symfony',
        function () {
            require 'test/symfony.php';
        }
    )
    ->execute(
        'Klein (e)',
        function () {
            require 'test/klein.php';
        }
    )
    ->execute(
        'Aura',
        function () {
            require 'test/aura.php';
        }
    )
    ->summary();

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

class TestController
{
    public function indexAction($slug, $id)
    {
    }
}

$_SERVER['REQUEST_URI'] = '/test/slugifiedtext/123';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['HTTP_HOST'] = 'example.com';

// Clear cache
array_map('unlink', glob(__DIR__ . '/cache/*.php'));

$bench = new \KM\Benchmark();
$bench
    ->execute(
       'Saffron',
        function () {
            require 'test/saffron.php';
        }
    )
    ->execute(
       'Saffron (e)',
        function () {
            require 'test/saffron.execute.php';
        }
    )
    ->execute(
        'Pux',
        function () {
            require 'test/pux.php';
        }
    )
    ->execute(
        'Symfony',
        function () {
            require 'test/symfony.php';
        }
    )
    ->execute(
        'Klein (e)',
        function () {
            require 'test/klein.php';
        }
    )
    ->execute(
        'Aura',
        function () {
            require 'test/aura.php';
        }
    )
    ->summary();

Clean cache before doing benchmark + copyright


<?php

namespace SerendipityHQ\Library\PHPUnit_Profiler;

use Symfony\Component\Stopwatch\Stopwatch;

class Profiler extends \PHPUnit_Framework_BaseTestListener
{
    private $stopwatch;

    public function __construct()
    {
        $this->stopwatch = new Stopwatch();
    }

    protected function getStopwatch()
    {
        return $this->stopwatch;
    }
}

<?php

namespace SerendipityHQ\Library\PHPUnit_Profiler;

use Symfony\Component\Stopwatch\Stopwatch;

class Profiler extends \PHPUnit_Framework_BaseTestListener
{
    private $stopwatch;

    public function __construct($options = [])
    {
        $this->stopwatch = new Stopwatch();
    }

    protected function getStopwatch()
    {
        return $this->stopwatch;
    }
}

Add `$options` argument to constructor.

Add `$options` argument to constructor.


<?php

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

class CreateTopicsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('topics', function(Blueprint $table)
		{
			$table->increments('id');
			$table->timestamps();
		});
	}

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

}

<?php

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

class CreateTopicsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('topics', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('title')->index();
			$table->text('body');
			$table->integer('user_id')->index();
			$table->integer('node_id')->index();
			$table->boolean('excellent')->default(false)->index();
			$table->boolean('blocked')->default(false)->index();
			$table->integer('reply_count')->default(0)->index();
			$table->integer('view_count')->default(0)->index();
			$table->integer('favorite_count')->default(0)->index();
			$table->integer('vote_count')->default(0)->index();
			$table->integer('last_reply_user_id')->default(0)->index();
			$table->softDeletes();
			$table->timestamps();
		});
	}

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

}

Add some fields to the topics migration files.


<?php

namespace jorenvanhocht\Blogify\Commands;

use Illuminate\Console\Command;

class BlogifyMigrateCommand extends Command
{

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'blogify:migrate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run the migrations for the Blogify package';

    /**
     * @var array
     */
    protected $paths;

    /**
     * Construct the class
     */
    public function __construct()
    {
        parent::__construct();

        $this->paths = [
            'packages/jorenvanhocht/blogify/database/Migrations',
            'vendor/jorenvanhocht/tracert/database/Migrations',
        ];
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        foreach ($this->paths as $path) {
            $this->call('migrate', ['--path' => $path]);
        }
    }

}

<?php

namespace jorenvanhocht\Blogify\Commands;

use Illuminate\Console\Command;

class BlogifyMigrateCommand extends Command
{

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'blogify:migrate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run the migrations for the Blogify package';

    /**
     * @var array
     */
    protected $paths;

    /**
     * Construct the class
     */
    public function __construct()
    {
        parent::__construct();

        $this->paths = [
            'vendor/jorenvanhocht/blogify/database/Migrations',
            'vendor/jorenvanhocht/tracert/database/Migrations',
        ];
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        foreach ($this->paths as $path) {
            $this->call('migrate', ['--path' => $path]);
        }
    }

}

Set migrate command settings back to production


<?php

/*
 * 이 컨트롤러를 상속받아 구현하는 컨트롤러는 application/json 타입의 리턴을 기본으로 하고, 로그인 체크를 하지 않음
 */

class API_Controller extends CI_Controller {

    public $result;

    public function __construct() {
        parent::__construct();
        $this->output->set_content_type('application/json');
        $this->result = ['result' => false, 'errorCode' => null, 'body' => null];
    }

    public function set_success_response($body) {
        $this->result['result'] = true;
        $this->result['body'] = $body;
    }

    public function set_fail_response($error_code, $body) {
        $this->result['result'] = false;
        $this->result['errorCode'] = $error_code;
        $this->result['body'] = $body;
    }
}

<?php

/*
 * 이 컨트롤러를 상속받아 구현하는 컨트롤러는 application/json 타입의 리턴을 기본으로 하고, 로그인 체크를 하지 않음
 */

class API_Controller extends CI_Controller {

    public $result;

    public function __construct() {
        parent::__construct();
        $this->output->set_content_type('application/json');
        $this->result = ['result' => false, 'errorCode' => null, 'body' => null];
    }

    /**
     * @deprecated return_success_response 쓰는 방식으로 변경해주세요.
     */
    public function set_success_response($body) {
        $this->result['result'] = true;
        $this->result['body'] = $body;
    }

    public function return_success_response($body) {
        $this->set_success_response($body);
        $this->return_response();
    }

    /**
     * @deprecated return_fail_response 쓰는 방식으로 변경해주세요.
     */
    public function set_fail_response($error_code, $body) {
        $this->result['result'] = false;
        $this->result['errorCode'] = $error_code;
        $this->result['body'] = $body;
    }

    public function return_fail_response($error_code, $body) {
        $this->set_fail_response($error_code, $body);
        $this->return_response();
    }

    public function return_response() {
        return $this->output->set_output(json_encode($this->result));
        die;
    }
}

Add a function to return response and die


<?php namespace TightenCo\Jigsaw;

class BasicOutputPathResolver
{
    public function link($path, $name, $type, $page = 1)
    {
        if ($page > 1) {
            return $this->clean('/' . $path . '/' . $page . '/' . $name . '.' . $type);
        }
        return $this->clean('/' . $path . '/' . $name . '.' . $type);
    }

    public function path($path, $name, $type, $page = 1)
    {
        return $this->link($path, $name, $type, $page);
    }

    public function directory($path, $name, $type, $page = 1)
    {
        if ($page > 1) {
            return $this->clean($path . '/' . $page);
        }
        return $this->clean($path);
    }

    private function clean($path)
    {
        return str_replace('//', '/', $path);
    }
}

<?php namespace TightenCo\Jigsaw;

class BasicOutputPathResolver
{
    public function link($path, $name, $type, $page = 1)
    {
        $extension = $type ? '.' . $type : '';
        $name = basename($name, $extension);

        return $page > 1 ?
            $this->clean('/' . $path . '/' . $page . '/' . $name . $extension) :
            $this->clean('/' . $path . '/' . $name . $extension);
    }

    public function path($path, $name, $type, $page = 1)
    {
        return $this->link($path, $name, $type, $page);
    }

    public function directory($path, $name, $type, $page = 1)
    {
        return $page > 1 ?
            $this->clean($path . '/' . $page) :
            $this->clean($path);
    }

    private function clean($path)
    {
        return str_replace('//', '/', $path);
    }
}

Fix double extension bug for nested files with non-pretty-URL


<?php

namespace Interop\Amqp;

use Interop\Queue\PsrConsumer;

/**
 * @method AmqpMessage|null receiveNoWait()
 * @method AmqpMessage|null receive(int $timeout)
 * @method AmqpQueue getQueue()
 * @method void acknowledge(AmqpMessage $message)
 * @method void reject(AmqpMessage $message, bool $requeue)
 */
interface AmqpConsumer extends PsrConsumer
{
    const FLAG_NOPARAM = 0;
    const FLAG_NOLOCAL = 1;
    const FLAG_NOACK = 2;
    const FLAG_EXCLUSIVE = 4;
    const FLAG_NOWAIT = 8;

    /**
     * @param string $consumerTag
     */
    public function setConsumerTag($consumerTag);

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

    public function clearFlags();

    /**
     * @param int $flag
     */
    public function addFlag($flag);

    /**
     * @return int
     */
    public function getFlags();

    /**
     * @param int $flags
     */
    public function setFlags($flags);
}

<?php

namespace Interop\Amqp;

use Interop\Queue\PsrConsumer;

/**
 * @method AmqpMessage|null receiveNoWait()
 * @method AmqpMessage|null receive(int $timeout = 0)
 * @method AmqpQueue getQueue()
 * @method void acknowledge(AmqpMessage $message)
 * @method void reject(AmqpMessage $message, bool $requeue)
 */
interface AmqpConsumer extends PsrConsumer
{
    const FLAG_NOPARAM = 0;
    const FLAG_NOLOCAL = 1;
    const FLAG_NOACK = 2;
    const FLAG_EXCLUSIVE = 4;
    const FLAG_NOWAIT = 8;

    /**
     * @param string $consumerTag
     */
    public function setConsumerTag($consumerTag);

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

    public function clearFlags();

    /**
     * @param int $flag
     */
    public function addFlag($flag);

    /**
     * @return int
     */
    public function getFlags();

    /**
     * @param int $flags
     */
    public function setFlags($flags);
}

Include default timeout value from interface

Both the interface (`Interop\Queue\PsrConsumer`) and the implementation (for example `Enqueue\AmqpBunny\AmqpConsumer`) seem to have a default value for the `receive()` method's first and only parameter `$timeout`. This default value (`0`) isn't included in the `@method` annotation in `Interop\Queue\PsrConsumer\AmqpConsumer` which makes code completion in an IDE give a false positive when leaving out the (optional) parameter.

Including this default value in the annotation fixes this problem. There is no effect on the actual functionality or operation of this interop library or any of it's decendants.


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class SMSInboundController extends Controller
{
	public function indexAction(Request $request = NULL)
	{
		return new Response('OK', 200);
	}
}

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class SMSInboundController extends Controller
{
	public function indexAction(Request $request = NULL)
	{
		$query = $request->query;
		$msisdn = $query->msisdn;

		return new Response('OK', 200);
	}

	public function callbackAction(Request $request = NULL)
	{
		$query = $request->query;
		$msisdn = $query->msisdn;

		return new Response('OK', 200);
	}
}

Add callback for sms inbound

Add callback for sms inbound


<?php

namespace SimpleBus\DoctrineORMBridge\MessageBus;

use Doctrine\ORM\EntityManager;
use Doctrine\Persistence\ManagerRegistry;
use SimpleBus\Message\Bus\Middleware\MessageBusMiddleware;
use Throwable;

class WrapsMessageHandlingInTransaction implements MessageBusMiddleware
{
    /**
     * @var ManagerRegistry
     */
    private $managerRegistry;

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

    /**
     * @param string $entityManagerName
     */
    public function __construct(ManagerRegistry $managerRegistry, $entityManagerName)
    {
        $this->managerRegistry = $managerRegistry;
        $this->entityManagerName = $entityManagerName;
    }

    public function handle($message, callable $next)
    {
        $entityManager = $this->managerRegistry->getManager($this->entityManagerName);
        /* @var $entityManager EntityManager */

        try {
            $entityManager->transactional(
                function () use ($message, $next) {
                    $next($message);
                }
            );
        } catch (Throwable $error) {
            $this->managerRegistry->resetManager($this->entityManagerName);

            throw $error;
        }
    }
}

<?php

namespace SimpleBus\DoctrineORMBridge\MessageBus;

use Doctrine\ORM\EntityManager;
use Doctrine\Persistence\ManagerRegistry;
use SimpleBus\Message\Bus\Middleware\MessageBusMiddleware;
use Throwable;

class WrapsMessageHandlingInTransaction implements MessageBusMiddleware
{
    /**
     * @var ManagerRegistry
     */
    private $managerRegistry;

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

    /**
     * @param string $entityManagerName
     */
    public function __construct(ManagerRegistry $managerRegistry, $entityManagerName)
    {
        $this->managerRegistry = $managerRegistry;
        $this->entityManagerName = $entityManagerName;
    }

    public function handle($message, callable $next)
    {
        /** @var $entityManager EntityManager */
        $entityManager = $this->managerRegistry->getManager($this->entityManagerName);

        try {
            $entityManager->transactional(
                function () use ($message, $next) {
                    $next($message);
                }
            );
        } catch (Throwable $error) {
            $this->managerRegistry->resetManager($this->entityManagerName);

            throw $error;
        }
    }
}

Move the `/* @var` syntax above

Move the `/* @var` syntax above


<?php namespace GeneaLabs\LaravelGovernor\Policies;

use GeneaLabs\LaravelGovernor\Permission;

class LaravelGovernorPolicy
{
    protected $permissions;

    public function __construct()
    {
        $this->permissions = Permission::with('role')->get();
    }

    protected function validatePermissions($user, $action, $entity, $entityCreatorId)
    {
        if (! $user->roles->count()) {
            return false;
        }

        $user->load('roles');
        $ownership = 'other';

        if ($user->id === $entityCreatorId) {
            $ownership = 'own';
        }

        $filteredPermissions = $this->filterPermissions($action, $entity, $ownership);

        foreach ($filteredPermissions as $permission) {
            if ($user->roles->contains($permission->role)) {
                return true;
            }
        }

        return false;
    }

    protected function filterPermissions($action, $entity, $ownership)
    {
        $filteredPermissions = $this->permissions->filter(function ($permission) use ($action, $entity, $ownership) {
            return ($permission->action_key === $action
                && $permission->entity_key === $entity
                && in_array($permission->ownership_key, [$ownership, 'any']));
        });

        return $filteredPermissions;
    }
}

<?php namespace GeneaLabs\LaravelGovernor\Policies;

use GeneaLabs\LaravelGovernor\Permission;

class LaravelGovernorPolicy
{
    protected $permissions;

    public function __construct()
    {
        $this->permissions = Permission::with('role')->get();
    }

    protected function validatePermissions($user, $action, $entity, $entityCreatorId)
    {
        if (! $user->roles) {
            return false;
        }

        $user->load('roles');
        $ownership = 'other';

        if ($user->id === $entityCreatorId) {
            $ownership = 'own';
        }

        $filteredPermissions = $this->filterPermissions($action, $entity, $ownership);

        foreach ($filteredPermissions as $permission) {
            if ($user->roles->contains($permission->role)) {
                return true;
            }
        }

        return false;
    }

    protected function filterPermissions($action, $entity, $ownership)
    {
        $filteredPermissions = $this->permissions->filter(function ($permission) use ($action, $entity, $ownership) {
            return ($permission->action_key === $action
                && $permission->entity_key === $entity
                && in_array($permission->ownership_key, [$ownership, 'any']));
        });

        return $filteredPermissions;
    }
}

Fix roles check if no roles present

Fix roles check if no roles present


<?php
/**
 * Unitest (PHP Unit Test)
 *
 * @version 1.0.0
 * @author franckysolo <franckysolo@gmail.com>
 */
namespace Unitest;

/**
 * @category PHP Unit Test - Simple Unit Test for PHP
 * @version 1.0.0
 * @author franckysolo <franckysolo@gmail.com>
 * @license http://creativecommons.org/licenses/by-sa/3.0/  CC BY-SA 3.0
 * @package Unitest
 * @filesource  Series.php
 */
class Series
{
    /**
     * The array of test cases
     *
     * @var array
     */
    protected $cases = array();

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

    /**
     * Run all test cases
     */
    public function run() {

        $report = new Report();

        foreach ($this->cases as $case) {

            $result = $report->newResult($case);

            ob_start();

            try {

                $unitest = new $case($result);

                // Init the test (config)
                $unitest->init();

                // Run it
                $unitest->run();

            } catch (\Exception $e) {
                $result->setException($e);
            }

            $result->setOutput(ob_get_clean());
        }

        return $report;
    }
}

<?php
/**
 * Unitest (PHP Unit Test)
 *
 * @version 1.0.0
 * @author franckysolo <franckysolo@gmail.com>
 */
namespace Unitest;

/**
 * @category PHP Unit Test - Simple Unit Test for PHP
 * @version 1.0.0
 * @author franckysolo <franckysolo@gmail.com>
 * @license http://creativecommons.org/licenses/by-sa/3.0/  CC BY-SA 3.0
 * @package Unitest
 * @filesource  Series.php
 */
class Series
{
    /**
     * The array of test cases
     *
     * @var array
     */
    protected $cases = array();

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

    /**
     * Run all test cases
     *
     * @return Report
     */
    public function run() {

        $report = new Report();

        foreach ($this->cases as $case) {

            $result = $report->newResult($case);

            ob_start();

            try {

                $unitest = new $case($result);

                // Init the test (config)
                $unitest->init();

                // Run it
                $unitest->run();

            } catch (\Exception $e) {
                $result->setException($e);
            }

            $result->setOutput(ob_get_clean());
        }

        return $report;
    }
}

Add @return to run method

Add @return to run method

Signed-off-by: franckysolo <a6b137401235e3a76c6d3fec9a271303e5d76274@gmail.com>


<?php
/**
 * This file parses the configuration and connection details for the catalog database.
 *
 * @package UNL_UCBCN
 * @author bbieber
 */

function autoload($class)
{
    $class = str_replace(array('_', '\\'), '/', $class);
    include $class . '.php';
}

spl_autoload_register('autoload');

set_include_path(
    __DIR__ . '/src' . PATH_SEPARATOR
  . __DIR__ . '/backend/src' . PATH_SEPARATOR
  . __DIR__ . '/vendor/php'
);

ini_set('display_errors', true);
error_reporting(E_ALL);

UNL\UCBCN\Frontend\Controller::$url = '/workspace/UNL_UCBCN_Frontend/www/';

UNL\UCBCN\ActiveRecord\Database::setDbSettings(
    array(
    'host'     => 'localhost',
    'user'     => 'events',
    'password' => 'events',
    'dbname'   => 'events',
));

<?php
/**
 * This file parses the configuration and connection details for the catalog database.
 *
 * @package UNL_UCBCN
 * @author bbieber
 */

function autoload($class)
{
    $class = str_replace(array('_', '\\'), '/', $class);
    include $class . '.php';
}

spl_autoload_register('autoload');

set_include_path(
    __DIR__ . '/src' . PATH_SEPARATOR
    . __DIR__ . '/backend/src' . PATH_SEPARATOR
    . __DIR__ . '/vendor/php' . PATH_SEPARATOR
    . __DIR__ . '/vendor/unl_submodules/RegExpRouter/src'
);

ini_set('display_errors', true);
error_reporting(E_ALL);

UNL\UCBCN\Frontend\Controller::$url = '/workspace/UNL_UCBCN_Frontend/www/';

UNL\UCBCN\ActiveRecord\Database::setDbSettings(
    array(
    'host'     => 'localhost',
    'user'     => 'events',
    'password' => 'events',
    'dbname'   => 'events',
));

Add the RegExpRouter to the include path


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

class Welcome extends MY_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		$this->load->view('welcome_message');
	}
}

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

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

class Welcome extends MY_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
    $this->template->build('welcome_message');
	}
}

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

Use template instead of default view generator


<?php

declare(strict_types=1);

/**
 * This file is part of Laravel Zero.
 *
 * (c) Nuno Maduro <enunomaduro@gmail.com>
 *
 *  For the full copyright and license information, please view the LICENSE
 *  file that was distributed with this source code.
 */

namespace LaravelZero\Framework\Providers\GitVersion;

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Symfony\Component\Process\Process;

/**
 * @codeCoverageIgnore
 * @internal
 */
final class GitVersionServiceProvider extends ServiceProvider
{
    /**
     * {@inheritdoc}
     */
    public function register(): void
    {
        $this->app->bind(
            'git.version',
            function (Application $app) {
                $lastRevisionTag = '$(git rev-list --tags --max-count=1)';

                if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                    $taskGetLastRevisionTag = 'git rev-list --tags --max-count=1';

                    $process = tap(new Process($taskGetLastRevisionTag, $app->basePath()))->run();

                    $lastRevisionTag = trim($process->getOutput()) ?: 'unreleased';

                    if ($lastRevisionTag === 'unreleased') {
                        return 'unreleased';
                    }
                }
                $task = "git describe --tags $lastRevisionTag";

                $process = tap(new Process($task, $app->basePath()))->run();

                return trim($process->getOutput()) ?: 'unreleased';
            }
        );
    }
}

<?php

declare(strict_types=1);

/**
 * This file is part of Laravel Zero.
 *
 * (c) Nuno Maduro <enunomaduro@gmail.com>
 *
 *  For the full copyright and license information, please view the LICENSE
 *  file that was distributed with this source code.
 */

namespace LaravelZero\Framework\Providers\GitVersion;

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Symfony\Component\Process\Process;

/**
 * @codeCoverageIgnore
 * @internal
 */
final class GitVersionServiceProvider extends ServiceProvider
{
    /**
     * {@inheritdoc}
     */
    public function register(): void
    {
        $this->app->bind(
            'git.version',
            function (Application $app) {
                $lastRevisionTag = '$(git rev-list --tags --max-count=1)';

                if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                    $taskGetLastRevisionTag = ['git', 'rev-list', '--tags', '--max-count=1'];

                    $process = tap(new Process($taskGetLastRevisionTag, $app->basePath()))->run();

                    $lastRevisionTag = trim($process->getOutput()) ?: 'unreleased';

                    if ($lastRevisionTag === 'unreleased') {
                        return 'unreleased';
                    }
                }
                $task = ['git', 'describe', '--tags', $lastRevisionTag];

                $process = tap(new Process($task, $app->basePath()))->run();

                return trim($process->getOutput()) ?: 'unreleased';
            }
        );
    }
}

Update GitVersion provider to use Process array


<link rel="shortcut icon" href="<?php echo get_template_directory_uri(); ?>/favicon.ico" />
<?php
$template_dir = get_template_directory_uri();
$sizes = array(
  '',
  '57x57',
  '72x72',
  '76x76',
  '114x114',
  '120x120',
  '144x144',
  '152x152',
);
foreach($sizes as $size) {
  $sizes_attr = (strlen($size))
    ? 'sizes="'.$size.'"'
    : null;
  $size_suffix = (strlen($size))
    ? '-'.$size
    : null;
  echo sprintf(
    '<link rel="apple-touch-icon" %s href="%s/img/apple-touch-icon%s.png" />',
    $sizes_attr,
    $template_dir,
    $size_suffix
  );
}
?>

<link rel="shortcut icon" href="<?php echo get_template_directory_uri(); ?>/favicon.ico">
<?php
$template_dir = get_template_directory_uri();
$sizes = array(
  '', // 57 x 57
  '57x57',
  '72x72',
  '76x76',
  '114x114',
  '120x120',
  '144x144',
  '152x152',
);
foreach($sizes as $size) {
  $sizes_attr = (strlen($size))
    ? 'sizes="'.$size.'"'
    : null;
  $size_suffix = (strlen($size))
    ? '-'.$size
    : null;
  echo sprintf(
    '<link rel="apple-touch-icon" %s href="%s/img/apple-touch-icon%s.png%s">',
    $sizes_attr,
    $template_dir,
    $size_suffix,
    THEME_SUFFIX
  );
}
?>

Add theme version number to favicons

Add theme version number to favicons


<?php
namespace Codception\Command;

class MyCustomCommandTest extends \PHPUnit_Framework_TestCase
{
    public static function setUpBeforeClass()
    {
        require_once \Codeception\Configuration::dataDir() . 'register_command/examples/MyCustomCommand.php';
    }

    public function testHasCodeceptionCustomCommandInterface()
    {
        $command = new \Codeception\Command\MyCustomCommand('commandName');
        $this->assertInstanceOf('Codeception\CustomCommandInterface', $command);
    }

    public function testHasCommandName()
    {
        $commandName = \Codeception\Command\MyCustomCommand::getCommandName();
        $this->assertEquals('myProject:myCommand', $commandName);
    }
}

<?php
namespace Project\Command;

class MyCustomCommandTest extends \PHPUnit_Framework_TestCase
{
    public static function setUpBeforeClass()
    {
        require_once \Codeception\Configuration::dataDir() . 'register_command/examples/MyCustomCommand.php';
    }

    public function testHasCodeceptionCustomCommandInterface()
    {
        $command = new MyCustomCommand('commandName');
        $this->assertInstanceOf('Codeception\CustomCommandInterface', $command);
    }

    public function testHasCommandName()
    {
        $commandName = MyCustomCommand::getCommandName();
        $this->assertEquals('myProject:myCommand', $commandName);
    }
}

Change the namespace for the example command, too.


{{ trans('releases.label') }}

{{ trans('releases.none') }}

                    {{ trans('releases.name') }}
                    {{ trans('app.actions') }}

@push('templates')

@endpush

Add an entry for deploying

Add an entry for deploying


<?php

namespace ATPComic\Controller;

class IndexController extends \ATPCore\Controller\AbstractController
{
	public function init()
	{
	}

	public function pageAction()
	{
		$this->init();

		//Get the current arc
		$arc = new \ATPComic\Model\Arc();
		$arc->loadByUrl($this->params('arc'));

		//Get the current page
		$page = new \ATPComic\Model\Page();
		$page->loadByUrl($this->params('pageUrl'));

		//Get the arc/page node
		$node = new \ATPComic\Model\Node($arc, $page);

		return new \Zend\View\Model\ViewModel(array(
			'arc' => $arc,
			'page' => $page,
			'node' => $node,
		));
	}

	public function archivesAction()
	{
		$this->init();

		$arcUrl = $this->params('arc');

		$arc = new \ATPComic\Model\Arc();
		$arcs = $arc->loadMultiple(array(
			'where' => !empty($arcUrl) ? "url = ?" : null,
			'data' =>!empty($arcUrl) ? array($arcUrl) : array()
		));

		return new \Zend\View\Model\ViewModel(array(
			'arcs' => $arcs
		));
	}
}

<?php

namespace ATPComic\Controller;

class IndexController extends \ATPCore\Controller\AbstractController
{
	public function init()
	{
	}

	public function pageAction()
	{
		$this->init();

		//Get the current arc
		$arc = new \ATPComic\Model\Arc();
		$arc->loadByUrl($this->params('arc'));

		//Get the current page
		$page = new \ATPComic\Model\Page();
		$page->loadByUrl($this->params('pageUrl'));

		//Get the arc/page node
		$node = new \ATPComic\Model\Node($arc, $page);

		$view = new \Zend\View\Model\ViewModel(array(
			'arc' => $arc,
			'page' => $page,
			'node' => $node,
		));

		//Add patreon link
		$this->layout()->addChild(new \ATPSocial\View\Widget\PatreonLink($this->siteParam('Patreon Name')), 'patreonLink');

		return $view;
	}

	public function archivesAction()
	{
		$this->init();

		$arcUrl = $this->params('arc');

		$arc = new \ATPComic\Model\Arc();
		$arcs = $arc->loadMultiple(array(
			'where' => !empty($arcUrl) ? "url = ?" : null,
			'data' =>!empty($arcUrl) ? array($arcUrl) : array()
		));

		return new \Zend\View\Model\ViewModel(array(
			'arcs' => $arcs
		));
	}
}

Add patreon link to right sidebar

Add patreon link to right sidebar


<?php
/**
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
 * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com)
 */

namespace ZF\ContentValidation;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ContentValidationListenerFactory implements FactoryInterface
{
    /**
     * @param ServiceLocatorInterface $services
     * @return ContentValidationListener
     */
    public function createService(ServiceLocatorInterface $services)
    {
        $config = [];
        if ($services->has('Config')) {
            $allConfig = $services->get('Config');
            if (isset($allConfig['zf-content-validation'])) {
                $config = $allConfig['zf-content-validation'];
            }
        }
        return new ContentValidationListener($config, $services);
    }
}

<?php
/**
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
 * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com)
 */

namespace ZF\ContentValidation;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ContentValidationListenerFactory implements FactoryInterface
{
    /**
     * @param ServiceLocatorInterface $services
     * @return ContentValidationListener
     */
    public function createService(ServiceLocatorInterface $services)
    {
        $config = array();
        if ($services->has('Config')) {
            $allConfig = $services->get('Config');
            if (isset($allConfig['zf-content-validation'])) {
                $config = $allConfig['zf-content-validation'];
            }
        }
        return new ContentValidationListener($config, $services);
    }
}

Change minimimum required PHP version to 5.3.23

- Remove [] array notation


<?php
namespace Datenknoten\LigiBundle\Entity;

use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @Gedmo\Uploadable(pathMethod="getDefaultPath", filenameGenerator="SHA1", allowOverwrite=true, appendNumber=true)
 */
class File
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @ORM\Column(name="path", type="string")
     * @Gedmo\UploadableFilePath
     */
    private $path;

    /**
     * @ORM\Column(name="name", type="string")
     * @Gedmo\UploadableFileName
     */
    private $name;

    /**
     * @ORM\Column(name="mime_type", type="string")
     * @Gedmo\UploadableFileMimeType
     */
    private $mimeType;

    /**
     * @ORM\Column(name="size", type="decimal")
     * @Gedmo\UploadableFileSize
     */
    private $size;

    public function getDefaultPath()
    {
        return realpath(__DIR__ . '/../../../../media');
    }

    public function getId()
    {
        return $this->id;
    }

    public function getPath()
    {
        return $this->path;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getMimeType()
    {
        return $this->mimeType;
    }
}

<?php
namespace Datenknoten\LigiBundle\Entity;

use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @Gedmo\Uploadable(pathMethod="getDefaultPath", filenameGenerator="SHA1", allowOverwrite=true, appendNumber=true)
 */
class File
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @ORM\Column(name="path", type="string")
     * @Gedmo\UploadableFilePath
     */
    private $path;

    /**
     * @ORM\Column(name="name", type="string")
     * @Gedmo\UploadableFileName
     */
    private $name;

    /**
     * @ORM\Column(name="mime_type", type="string")
     * @Gedmo\UploadableFileMimeType
     */
    private $mimeType;

    /**
     * @ORM\Column(name="size", type="decimal")
     * @Gedmo\UploadableFileSize
     */
    private $size;

    public function getDefaultPath()
    {
        return realpath(__DIR__ . '/../../../../media');
    }

    public function getId()
    {
        return $this->id;
    }

    public function getPath()
    {
        return $this->path;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getMimeType()
    {
        return $this->mimeType;
    }

    public function getSize()
    {
        return $this->size;
    }
}

Add a accesor for size

Add a accesor for size


<?php

class WeatherCollection implements Iterator {

//	we'll write this class as an in-class exercise

}

?>

<?php

class WeatherCollection implements Iterator {

//	we'll write this class as an in-class exercise

	public function addToCollection($weatherdto) {

	}

}

?>

Add blank addToCollection() method; will finish in class


<?php

return array(

    'account_already_exists' => 'An account with the this email already exists.',
    'account_not_found'      => 'The email account or password is incorrect.',
    'account_not_activated'  => 'This user account is not activated.',
    'account_suspended'      => 'This user account is suspended.',
    'account_banned'         => 'This user account is banned.',

    'signin' => array(
        'error'   => 'There was a problem while trying to log you in, please try again.',
        'success' => 'You have successfully logged in.',
    ),

    'signup' => array(
        'error'   => 'There was a problem while trying to create your account, please try again.',
        'success' => 'Account sucessfully created.',
    ),

        'forgot-password' => array(
            'error'   => 'There was a problem while trying to get a reset password code, please try again.',
            'success' => 'Password recovery email successfully sent.',
        ),

        'forgot-password-confirm' => array(
            'error'   => 'There was a problem while trying to reset your password, please try again.',
            'success' => 'Your password has been successfully reset.',
        ),

    'activate' => array(
        'error'   => 'There was a problem while trying to activate your account, please try again.',
        'success' => 'Your account has been successfully activated.',
    ),

);

<?php

return array(

    'account_already_exists' => 'An account with the this email already exists.',
    'account_not_found'      => 'The username or password is incorrect.',
    'account_not_activated'  => 'This user account is not activated.',
    'account_suspended'      => 'This user account is suspended.',
    'account_banned'         => 'This user account is banned.',

    'signin' => array(
        'error'   => 'There was a problem while trying to log you in, please try again.',
        'success' => 'You have successfully logged in.',
    ),

    'signup' => array(
        'error'   => 'There was a problem while trying to create your account, please try again.',
        'success' => 'Account sucessfully created.',
    ),

        'forgot-password' => array(
            'error'   => 'There was a problem while trying to get a reset password code, please try again.',
            'success' => 'Password recovery email successfully sent.',
        ),

        'forgot-password-confirm' => array(
            'error'   => 'There was a problem while trying to reset your password, please try again.',
            'success' => 'Your password has been successfully reset.',
        ),

    'activate' => array(
        'error'   => 'There was a problem while trying to activate your account, please try again.',
        'success' => 'Your account has been successfully activated.',
    ),

);

Update for change to username on sign in


<?php

namespace AppBundle\Tests\Functional\Controller;

class SecurityControllerTest extends \AppBundle\Tests\Functional\TestCase
{
    public function testRedirectForAnonymous()
    {
        $client = static::createClient();

        $client->request('GET', '/');

        $this->assertTrue($client->getResponse()->isRedirect('http://localhost/login'));
    }

    public function testLogin()
    {
        $client = static::createClient();

        $client->request('GET', '/');

        $this->assertTrue($client->getResponse()->isRedirect('http://localhost/login'));

        $crawler = $client->followRedirect();

        $form = $crawler->filter('button')->form([
            '_username' => 'admin',
            '_password' => 'secret',
        ]);

        $client->submit($form);

        $this->assertTrue($client->getResponse()->isRedirect('http://localhost/'));
    }

    public function testLoginFailed()
    {
        $client = static::createClient();

        $client->request('GET', '/');

        $this->assertTrue($client->getResponse()->isRedirect('http://localhost/login'));

        $crawler = $client->followRedirect();

        $form = $crawler->filter('button')->form([
            '_username' => 'failed',
            '_password' => 'failed',
        ]);

        $client->submit($form);

        $crawler = $client->followRedirect();

        $this->assertEquals(
            'Invalid credentials.',
            $crawler->filter('div.login > div')->extract(['_text'])[0]
        );
    }
}

<?php

namespace AppBundle\Tests\Functional\Controller;

class SecurityControllerTest extends \AppBundle\Tests\Functional\TestCase
{
    public function testRedirectForAnonymous()
    {
        $client = static::createClient();

        $client->request('GET', '/');

        $this->assertTrue($client->getResponse()->isRedirect('http://localhost/login'));
    }

    public function testLogin()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/login');

        $form = $crawler->filter('button')->form([
            '_username' => 'admin',
            '_password' => 'secret',
        ]);

        $client->submit($form);

        $this->assertTrue($client->getResponse()->isRedirect('http://localhost/'));
    }

    public function testLoginInvalidCredentials()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/login');

        $form = $crawler->filter('button')->form([
            '_username' => 'failed',
            '_password' => 'failed',
        ]);

        $client->submit($form);

        $crawler = $client->followRedirect();

        $this->assertEquals('Invalid credentials.', $crawler->filter('div.login > div')->html());
    }

    public function testLoginRegistrationButton()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/login');

        $link = $crawler->filter('a[href="/sign_up"]')->link();

        $crawler = $client->click($link);

        $this->assertEquals('Sign up', $crawler->filter('title')->html());
    }
}

Add test to check registration button exists on login page


<?php

namespace Oro\Bundle\SecurityBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;

class AclPermissionController extends Controller
{
    /**
     * @Route(
     *  "/acl-access-levels/{oid}", name="oro_security_access_levels" , requirements={"oid"="((\w+):)+(.*)"
     * })
     */
    public function aclAccessLevelsAction($oid)
    {
        if (strpos($oid, 'entity') !== false) {
            $oid = str_replace('_', '\\', $oid);
        }

        $levels = $this
            ->get('oro_security.acl.manager')
            ->getAccessLevels($oid);
        $translator = $this->get('translator');
        foreach ($levels as $id => $label) {
            $levels[$id] = $translator->trans('oro.security.access-level.' . $label);
        }

        return new JsonResponse(
            $levels
        );
    }
}

<?php

namespace Oro\Bundle\SecurityBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;

class AclPermissionController extends Controller
{
    /**
     * @Route(
     *  "/acl-access-levels/{oid}", name="oro_security_access_levels" , requirements={"oid"="\w+:[\w\(\)]+"
     * })
     */
    public function aclAccessLevelsAction($oid)
    {
        if (strpos($oid, 'entity') !== false) {
            $oid = str_replace('_', '\\', $oid);
        }

        $levels = $this
            ->get('oro_security.acl.manager')
            ->getAccessLevels($oid);
        $translator = $this->get('translator');
        foreach ($levels as $id => $label) {
            $levels[$id] = $translator->trans('oro.security.access-level.' . $label);
        }

        return new JsonResponse(
            $levels
        );
    }
}

BAP-1534: Fix acl access levels selector on root entity


<?php

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

class CreateLocalesTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('locales', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('language', 2);
			$table->timestamps();
		});
	}

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

}

<?php

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

class CreateLocalesTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('locales', function (Blueprint $table) {
            $table->increments('id');
            $table->string('language', 2);
            $table->timestamps();
        });
    }

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

Add PSR-2 syntax on migrations.

Add PSR-2 syntax on migrations.


<?php
class Kwf_Trl_Parser_JsParser
{
    public static function parseContent($content)
    {
        $process = new Symfony\Component\Process\Process(getcwd().'/'.VENDOR_PATH.'/bin/node '.__DIR__.'/JsParser.js');
        $process = $process->setInput($content);
        $process->run();
        if (!$process->isSuccessful()) {
            throw new Kwf_Exception("Parsing js file failed: ".$process->getErrorOutput());
        }
        return json_decode($process->getOutput(), true);
    }
}

<?php
class Kwf_Trl_Parser_JsParser
{
    public static function parseContent($content)
    {
        $vendorPath = 'vendor';
        if (defined('VENDOR_PATH')) {
            $vendorPath = VENDOR_PATH;
        }
        $process = new Symfony\Component\Process\Process(getcwd()."/$vendorPath/bin/node ".__DIR__.'/JsParser.js');
        $process = $process->setInput($content);
        $process->run();
        if (!$process->isSuccessful()) {
            throw new Kwf_Exception("Parsing js file failed: ".$process->getErrorOutput());
        }
        return json_decode($process->getOutput(), true);
    }
}

Trl: Check if VENDOR_PATH is defined before using


<?php

use yii\db\Migration;

class m151220_112320_lang extends Migration
{
    public function safeUp()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%lang}}', [
            'id' => $this->string(2)->notNull(),
            'locale' => $this->string(8)->notNull(),
            'name' => $this->string(32)->notNull(),
            'status' => $this->smallInteger(),
            'PRIMARY KEY (id)',
        ], $tableOptions);

        $this->createIndex('lang_name_idx', 'lang', 'name', true);
        $this->createIndex('lang_status_idx', 'lang', 'status');

        $this->insert('lang', [
            'id' => 'en',
            'locale' => 'en-US',
            'name' => 'ENG',
            'status' => 10,
        ]);
    }

    public function safeDown()
    {
        $this->dropTable('lang');
    }
}

<?php

use yii\db\Migration;
use lav45\translate\LocaleHelperTrait;

class m151220_112320_lang extends Migration
{
    use LocaleHelperTrait;

    public function safeUp()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%lang}}', [
            'id' => $this->string(2)->notNull(),
            'locale' => $this->string(8)->notNull(),
            'name' => $this->string(32)->notNull(),
            'status' => $this->smallInteger(),
            'PRIMARY KEY (id)',
        ], $tableOptions);

        $this->createIndex('lang_name_idx', 'lang', 'name', true);
        $this->createIndex('lang_status_idx', 'lang', 'status');

        $source_language = Yii::$app->sourceLanguage;
        $source_language_id = $this->getPrimaryLanguage($source_language);

        $this->insert('{{%lang}}', [
            'id' => strtolower($source_language_id),
            'locale' => $source_language,
            'name' => strtoupper($source_language_id),
            'status' => 10,
        ]);
    }

    public function safeDown()
    {
        $this->dropTable('{{%lang}}');
    }
}

Use application sourceLanguage in default migrate


<?php

class StorageQuotaUpgrade
{
    public static function startUpgrade()
    {
        echo "* Updating storage usage for new quota tracking".PHP_EOL;
        self::setStorageUsage();
    }

    private static function setStorageUsage()
    {
        $musicDir = CcMusicDirsQuery::create()
            ->filterByType('stor')
            ->filterByExists(true)
            ->findOne();
        $storPath = $musicDir->getDirectory();

        $freeSpace = disk_free_space($storPath);
        $totalSpace = disk_total_space($storPath);

        Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
    }
}

<?php

class StorageQuotaUpgrade
{
    public static function startUpgrade()
    {
        echo "* Updating storage usage for new quota tracking".PHP_EOL;
        self::setStorageUsage();
    }

    private static function setStorageUsage()
    {
        $musicDir = CcMusicDirsQuery::create()
            ->filterByType('stor')
            ->filterByExists(true)
            ->findOne();
        $storPath = $musicDir->getDirectory();

        $f = $storPath;
        $io = popen('/usr/bin/du -bs ' . $f, 'r');
        $size = fgets($io, 4096);
        $size = substr($size, 0, strpos($size, "\t"));
        pclose($io);

        Application_Model_Preference::setDiskUsage($size);
    }
}

CC-5781: Upgrade script for new storage quota implementation

Upgrade script for saas only


<?php

use App\Models\Club;
use App\Models\Competition;
use App\Models\Division;
use App\Models\Season;
use App\Models\Team;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RolesAndPermissionsSeeder extends Seeder
{
    use SeederProgressBar;

    public function run()
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        Permission::create(['name' => 'manage raw data']);

        Role::create(['name' => 'Site Administrator']);
        Role::create(['name' => 'League Administrator'])
            ->givePermissionTo('manage raw data');
        Role::create(['name' => 'Division Administrator']);

        $allRolesCount = Season::count() + Competition::count() + Division::count() +
            Club::count() + Team::count();

        $this->initProgressBar($allRolesCount);
        Season::all()->each(function (Season $season) {
            Role::create(['name' => "Season {$season->getId()} Administrator"]);
            $this->advanceProgressBar();
        });
        Competition::all()->each(function (Competition $competition) {
            Role::create(['name' => "Competition {$competition->getId()} Administrator"]);
            $this->advanceProgressBar();
        });
        Division::all()->each(function (Division $division) {
            Role::create(['name' => "Division {$division->getId()} Administrator"]);
            $this->advanceProgressBar();
        });

        Club::all()->each(function (Club $club) {
            Role::create(['name' => "Club {$club->getId()} Secretary"]);
            $this->advanceProgressBar();
        });
        Team::all()->each(function (Team $team) {
            Role::create(['name' => "Team {$team->getId()} Secretary"]);
            $this->advanceProgressBar();
        });
        $this->finishProgressBar();
    }
}

<?php

use App\Models\Club;
use App\Models\Competition;
use App\Models\Division;
use App\Models\Season;
use App\Models\Team;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RolesAndPermissionsSeeder extends Seeder
{
    use SeederProgressBar;

    public function run()
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        Permission::create(['name' => 'manage raw data']);

        Role::create(['name' => 'Site Administrator']);
        Role::create(['name' => 'League Administrator'])
            ->givePermissionTo('manage raw data');
        Role::create(['name' => 'Division Administrator']);
    }
}

Remove creating roles in seeder

Remove creating roles in seeder

The seasons, competitions, divisions, clubs and teams roles are now
created automatically by a listener, following the creationg of the
model.


<tr<?php echo $event->getOutOfState() ?>>
  {{ $event->getDate() }}

  @if (trim($event->url) != "")
  url }}}" target="_blank">{{ $event->title }}
  @else
  {{ $event->title }}
  @endif

  @if (trim($event->location) == "Knights of Columbus")
  {{ $event->location }}
  @elseif (trim($event->address) != "")
  address }}}&z=12">{{ $event->location }}
  @else
  {{ $event->location }}
  @endif

<tr<?php echo $event->getOutOfState() ?>>
  {{ $event->getDate() }}

  @if (trim($event->url) != "")
  url }}}" target="_blank">{{ $event->title }}
  @else
  {{ $event->title }}
  @endif

  @if (trim($event->location) == "Knights of Columbus")
  {{ $event->location }}
  @elseif (trim($event->address) != "")
  address }}}&z=12" target="_blank">{{ $event->location }}
  @else
  {{ $event->location }}
  @endif

Make sure we open links that go to google maps in a new window/tab.


<?php

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

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

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

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

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

exec($execstr);

echo file_get_contents($output);

?>

<?php

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

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

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

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

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

exec($execstr);

echo file_get_contents($output);

// Remove the temporary files
unlink($template);
unlink($config);
unlink($output);

?>

Delete files after they have been processed.


#!/usr/bin/env php
<?php
\chdir(__DIR__);

\set_time_limit(0); // unlimited max execution time

$fp = \fopen(__DIR__ . '/data/ca-certificates.crt', 'w+b');

$options = [
    \CURLOPT_FILE => $fp,
    \CURLOPT_TIMEOUT => 3600,
    \CURLOPT_URL => 'https://curl.haxx.se/ca/cacert.pem',
];

$ch = \curl_init();
\curl_setopt_array($ch, $options);
\curl_exec($ch);
\curl_close($ch);
\fclose($fp);

#!/usr/bin/env php
<?php
\chdir(__DIR__);

\set_time_limit(0); // unlimited max execution time

$fp = \fopen(__DIR__ . '/data/ca-certificates.crt', 'w+b');

$options = [
    \CURLOPT_FILE => $fp,
    \CURLOPT_TIMEOUT => 3600,
    \CURLOPT_URL => 'https://curl.se/ca/cacert.pem',
];

$ch = \curl_init();
\curl_setopt_array($ch, $options);
\curl_exec($ch);
\curl_close($ch);
\fclose($fp);

Change CA cert bundle URL

Change CA cert bundle URL

The curl domain has changed from curl.haxx.se to curl.se. Calling update_certs.php with the old CA bundle URL may result in the text of the 301 response being downloaded instead of the bundle file, breaking communication with Stripe.


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

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

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

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

Remove manual alias because it is added automatically with config plugin


<?php
namespace tunect\Yii2JsErrorHandler;

use yii\base\BootstrapInterface;

class Bootstrap implements BootstrapInterface
{
    /**
     * @inheritdoc
     */
    public function bootstrap($app)
    {
		if (($app instanceof \yii\web\Application) && $app->request->isAjax) {
            return;
        }
        $name = Module::$moduleName;

		if (!$app->hasModule($name)) {
			$app->setModule($name, new Module($name));
		}
        if ($app instanceof \yii\web\Application) {
            $rules[] = [
                'class' => 'yii\web\GroupUrlRule',
                'prefix' => $name,
                'rules' => [
                    '/' => 'default/index',
                    '<action:[\w-]+>' => 'default/<action>',
                ],
            ];
            $app->getUrlManager()->addRules($rules, false);
			$app->getModule($name)->registerErrorHandler();

        } elseif ($app instanceof \yii\console\Application) {
			$app->controllerMap = array_merge($app->controllerMap, [
				'migrate' => [
					'migrationNamespaces' => [
						'tunect\Yii2JsErrorHandler\migrations',
					],
				],
			]);
			if (empty($app->controllerMap['migrate']['class'])) {
				$app->controllerMap['migrate']['class'] = 'yii\console\controllers\MigrateController';
			}
        }
    }
}

<?php
namespace tunect\Yii2JsErrorHandler;

use yii\base\BootstrapInterface;

class Bootstrap implements BootstrapInterface
{
    /**
     * @inheritdoc
     */
    public function bootstrap($app)
    {
        $name = Module::$moduleName;

		if (!$app->hasModule($name)) {
			$app->setModule($name, new Module($name));
		}
        if ($app instanceof \yii\web\Application) {
            $rules[] = [
                'class' => 'yii\web\GroupUrlRule',
                'prefix' => $name,
                'rules' => [
                    '/' => 'default/index',
                    '<action:[\w-]+>' => 'default/<action>',
                ],
            ];
            $app->getUrlManager()->addRules($rules, false);
			$app->getModule($name)->registerErrorHandler();

        } elseif ($app instanceof \yii\console\Application) {
			$app->controllerMap = array_merge($app->controllerMap, [
				'migrate' => [
					'migrationNamespaces' => [
						'tunect\Yii2JsErrorHandler\migrations',
					],
				],
			]);
			if (empty($app->controllerMap['migrate']['class'])) {
				$app->controllerMap['migrate']['class'] = 'yii\console\controllers\MigrateController';
			}
        }
    }
}

Fix self-queries ignoring (since self queries are ajax)


<?php

/**
 * PHP version 7.3
 *
 * @category ShipmentPoint
 * @package  RetailCrm\Api\Model\Entity\Integration\Delivery
 */

namespace RetailCrm\Api\Model\Entity\Integration\Delivery;

use RetailCrm\Api\Component\Serializer\Annotation as JMS;

/**
 * Class ShipmentPoint
 *
 * @category ShipmentPoint
 * @package  RetailCrm\Api\Model\Entity\Integration\Delivery
 */
class ShipmentPoint
{
    /**
     * @var string
     *
     * @JMS\Type("string")
     * @JMS\SerializedName("code")
     */
    public $code;

    /**
     * @var int
     *
     * @JMS\Type("int")
     * @JMS\SerializedName("shipmentPointId")
     */
    public $shipmentPointId;

    /**
     * @var string
     *
     * @JMS\Type("string")
     * @JMS\SerializedName("shipmentPointLabel")
     */
    public $shipmentPointLabel;
}

<?php

/**
 * PHP version 7.3
 *
 * @category ShipmentPoint
 * @package  RetailCrm\Api\Model\Entity\Integration\Delivery
 */

namespace RetailCrm\Api\Model\Entity\Integration\Delivery;

use RetailCrm\Api\Component\Serializer\Annotation as JMS;

/**
 * Class ShipmentPoint
 *
 * @category ShipmentPoint
 * @package  RetailCrm\Api\Model\Entity\Integration\Delivery
 */
class ShipmentPoint
{
    /**
     * @var string
     *
     * @JMS\Type("string")
     * @JMS\SerializedName("code")
     */
    public $code;

    /**
     * @var string
     *
     * @JMS\Type("string")
     * @JMS\SerializedName("shipmentPointId")
     */
    public $shipmentPointId;

    /**
     * @var string
     *
     * @JMS\Type("string")
     * @JMS\SerializedName("shipmentPointLabel")
     */
    public $shipmentPointLabel;
}

Fix data type of shipment point id for /api/v5/integration-modules/{code}/edit


<?php

	loadlib("s3");

	########################################################################

	function wof_s3_put_file($rel, $path, $args=array(), $more=array()) {

		$bucket = array(
			'id' => $GLOBALS['cfg']['aws']['s3_bucket'],
			'key' => $GLOBALS['cfg']['aws']['access_key'],
			'secret' => $GLOBALS['cfg']['aws']['access_secret'],
		);

		if (! file_exists("{$rel}{$path}")) {
			return array(
				'ok' => 0,
				'error' => "'{$rel}{$path}' not found."
			);
		}

		$data = file_get_contents("{$rel}{$path}");
		$args = array_merge(array(
			'id' => $path,
			'data' => $data
		), $args);

		$rsp = s3_put($bucket, $args, $more);
		return $rsp;
	}

	# the end

<?php

	loadlib("s3");

	########################################################################

	function wof_s3_put_file($rel, $path, $args=array(), $more=array()) {

		$bucket = array(
			'id' => $GLOBALS['cfg']['aws']['s3_bucket'],
			'key' => $GLOBALS['cfg']['aws']['access_key'],
			'secret' => $GLOBALS['cfg']['aws']['access_secret'],
		);

		if (! file_exists("{$rel}{$path}")) {
			return array(
				'ok' => 0,
				'error' => "'{$rel}{$path}' not found."
			);
		}

		$data = file_get_contents("{$rel}{$path}");
		$args = array_merge(array(
			'id' => "data/$path",
			'data' => $data
		), $args);

		$rsp = s3_put($bucket, $args, $more);
		return $rsp;
	}

	# the end

Update the correct S3 path

:bug: Update the correct S3 path


<?php

// previous_form is the name of the from which this data came
function LogPostValuesToLog($filename, $previous_form) {
	$output = array();
	$output[$previous_form] = array();

	foreach($_POST as $key => $value) {
		$output[$previous_form][$key] = $value;
	}
	$output_json = json_encode($output);

	// Write to file on server (get rid of this!)
	$trace_file = fopen($filename, "a") or die("Unable to open trace file!");
	fwrite($trace_file, $output_json);
	fclose($trace_file);
}
?>

<?php

// previous_form is the name of the from which this data came
function LogPostValuesToLog($filename, $previous_form) {
	$output = array();
	$output[$previous_form] = array();

	foreach($_POST as $key => $value) {
		$output[$previous_form][$key] = $value;
	}
	$output_json = json_encode($output);

	// Write to file on server (get rid of this!)
	$trace_file = fopen($filename, "a") or die("Unable to open trace file at $filename!");
	fwrite($trace_file, $output_json);
	fclose($trace_file);
}
?>

Print filename in error message

Print filename in error message


<?php
include "guestbook.html";
if ($_POST) {
    if (isset($_COOKIE['posts'])) {
        if ($_COOKIE['posts'] < 5) {
            $posts = $_COOKIE['posts'] + 1;
            setcookie('posts', $posts, time() + 100 * 10);
        } else {
            echo "
You've attempted to submit too many posts at once.
";
            return "";
        }
    } else {
        setcookie('posts', 1, time() + 120 * 10);
    }
    if (empty($_POST["name"]) || empty($_POST["comment"])) {
        echo "";
    } else {
        $allowed_tags = '
';
        $stripName    = strip_tags($_POST['name'], $allowed_tags);
        $stripComment = strip_tags($_POST['comment'], $allowed_tags);
        $name         = $stripName;
        $comment      = $stripComment;
        $handle       = fopen("guestbook.html", "a");
        fwrite($handle, "" . $name . ":
" . $comment . "

");
        fclose($handle);
    }
}
?>
<!DOCTYPE html>

      <form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
         Name:
<input type="text" title="Enter your Username" name="name" />

         Message:
<textarea name="comment" maxlength="1000" cols="25" rows="6"></textarea>

         <input type="submit" name="submit" value="submit">
      </form>

<?php
include "guestbook.html";
if ($_POST) {
    if (empty($_POST["name"]) || empty($_POST["comment"])) {
        echo "";
    } else {
        $allowed_tags = '
';
        $stripName    = strip_tags($_POST['name'], $allowed_tags);
        $stripComment = strip_tags($_POST['comment'], $allowed_tags);
        $name         = $stripName;
        $comment      = $stripComment;
        $handle       = fopen("guestbook.html", "a");
        fwrite($handle, "" . $name . ":
" . $comment . "

");
        fclose($handle);
    }
}
?>
<!DOCTYPE html>

      <form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
         Name:
<input type="text" title="Enter your Username" name="name" />

         Message:
<textarea name="comment" maxlength="1000" cols="25" rows="6"></textarea>

         <input type="submit" name="submit" value="submit">
      </form>

Revert "Avoiding flood of posts from same user"

This reverts commit f900a1a15abee7996feb71d8917d53f5de059572.