<?php

class AuthController extends BaseController {

    public function login()
    {
        $remember = Input::get('remember') == 'true' ? true : false;

        if (Auth::attempt(['shadow_name' => Str::lower(Input::get('username')),
            'password' => Input::get('password'), 'is_activated' => true], $remember))
        {
            if (Auth::user()->removed_at || Auth::user()->blocked_at)
            {
                Auth::logout();
                return Response::json(['error' => 'Account blocked or removed'], 400);
            }

            return Response::json(['user' => Auth::user()]);
        }

        return Response::json(['error' => 'Invalid login or password'], 400);
    }

    public function logout()
    {
        Auth::logout();
    }

}}

<?php

class AuthController extends BaseController {

    public function login()
    {
        $remember = Input::get('remember') == 'true' ? true : false;

        if (Auth::attempt(['shadow_name' => Str::lower(Input::get('username')),
            'password' => Input::get('password'), 'is_activated' => true], $remember))
        {
            if (Auth::user()->removed_at || Auth::user()->blocked_at)
            {
                Auth::logout();
                return Response::json(['error' => 'Account blocked or removed'], 400);
            }

            $folders = Auth::user()->folders->toArray();

            foreach ($folders as &$folder)
            {
                $folder['groups'] = Group::whereIn('_id', $folder['groups'])->get()->toArray();
            }

            $data['user'] = array_merge(Auth::user()->toArray(), [
                'subscribed_groups' => Group::whereIn('_id', Auth::user()->subscribedGroups())->get()->toArray(),
                'blocked_groups' => Group::whereIn('_id', Auth::user()->blockedGroups())->get()->toArray(),
                'moderated_groups' => Group::whereIn('_id', Auth::user()->moderatedGroups())->get()->toArray(),
                'folders' => $folders,
            ]);

            return Response::json($data);
        }

        return Response::json(['error' => 'Invalid login or password'], 400);
    }

    public function logout()
    {
        Auth::logout();
    }

}

Add more data to api login response

Add more data to api login response


<?php
namespace App\Controllers;

use App\Framework\Mvc\Controller\BasicController;
use App\Services\Instagram\InstagramService;

class HomeController extends BasicController {

    public function indexAction($hashtag)
    {
        // If there is no hashtag parameter, $tag is assigned as "Salvador"
        $hashtag = (empty($hashtag["_GET"]["hashtag"])) ? "Salvador" : $hashtag["_GET"]["hashtag"];

        $this->app->container->singleton('InstagramService', function () {
            return new InstagramService();
        });

        $instagram = $this->app->InstagramService;
        $result = $instagram->getPhotosBasedOnTag($hashtag);

        // Show hashtag name
        echo "Hashtag: #" . $hashtag . "
";

        // Show 20 photos
        foreach ($result->data as $data)
        {
            echo "images->low_resolution->url." alt=".$data->caption->text.">";
        }
    }

}

<?php
namespace App\Controllers;

use App\Framework\Mvc\Controller\BasicController;
use App\Services\Instagram\InstagramService;

class HomeController extends BasicController {

    /**
     * Request photos based on hashtag
     *
     * @param string $hashtag
     * @return array
     */
    public function indexAction($hashtag)
    {

        // If there is no hashtag parameter, $tag is assigned as "Salvador"
        $hashtag = (empty($hashtag["_GET"]["hashtag"])) ? "Salvador" : $hashtag["_GET"]["hashtag"];

        $this->app->container->singleton('InstagramService', function () {
            return new InstagramService();
        });

        $instagram = $this->app->InstagramService;
        $result = $instagram->getPhotosBasedOnTag($hashtag);

        // Show hashtag name
        echo "Hashtag: #" . $hashtag . "
";

        $result = json_decode($result, true);

        // Show 20 photos
        foreach ($result["data"] as $data)
        {
            echo "";
        }
    }

}

Add comment to indexAction in Home controller


<?php

declare(strict_types=1);

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

class CreateAttributeEntityTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(config('rinvex.attributable.tables.attribute_entity'), function (Blueprint $table) {
            // Columns
            $table->integer('attribute_id')->unsigned();
            $table->string('entity_type');

            // Indexes
            $table->unique(['attribute_id', 'entity_type'], 'attributable_attribute_id_entity_type');
            $table->foreign('attribute_id')->references('id')->on(config('rinvex.attributable.tables.attributes'))
                  ->onDelete('cascade')->onUpdate('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists(config('rinvex.attributable.tables.attribute_entity'));
    }
}

<?php

declare(strict_types=1);

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

class CreateAttributeEntityTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(config('rinvex.attributable.tables.attribute_entity'), function (Blueprint $table) {
            // Columns
            $table->integer('attribute_id')->unsigned();
            $table->string('entity_type');
            $table->timestamps();

            // Indexes
            $table->unique(['attribute_id', 'entity_type'], 'attributable_attribute_id_entity_type');
            $table->foreign('attribute_id')->references('id')->on(config('rinvex.attributable.tables.attributes'))
                  ->onDelete('cascade')->onUpdate('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists(config('rinvex.attributable.tables.attribute_entity'));
    }
}

Add missing timestamps database table fields


<?php

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

class AddAdAppendDomainSettings extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('settings', function (Blueprint $table) {
            $table->boolean('ad_append_domain')->nullable(false)->default('0');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('settings', function (Blueprint $table) {
            $table->dropColumn('ad_append_domain');
        });
    }
}

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use App\Models\Setting;

class AddAdAppendDomainSettings extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('settings', function (Blueprint $table) {
            $table->boolean('ad_append_domain')->nullable(false)->default('0');
        });
        $s = Setting::first(); // we are deliberately *not* using the ::getSettings() method, as it caches things, and our Settings table is being migrated right now
        \Log::info("is ad? ".($s->is_ad)." is enabled? ".($s->ldap_enabled)." ad_domain? ".($s->ad_domain));
        if($s->is_ad && $s->ldap_enabled && $s->ad_domain) { //backwards-compatibility setting; < v5 always appended AD Domains
            $s->ad_append_domain = 1;
            $s->save();
        }
}

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('settings', function (Blueprint $table) {
            $table->dropColumn('ad_append_domain');
        });
    }
}

Update ad_append_domain setting for backwards-compatibility with v4 and earlier


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="author" content="http://james-brooks.uk">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <link rel="alternate" type="application/rss+xml" href="/rss" />

    <title>{{ isset($pageTitle) ? $pageTitle : Setting::get('app_name') }} | Cachet</title>

    <link href='//fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="{{ elixir('css/all.css') }}">

    @include('partials.stylesheet')

    @if($stylesheet = Setting::get('stylesheet'))
    <style type='text/css'>
    {{ $stylesheet }}
    </style>
    @endif

    <script src="{{ elixir('js/all.js') }}"></script>
</head>
<body class='status-page'>
    <div class='container'>
    @yield('content')
    </div>

    @include('partials.support-link')
</body>
</html>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <!-- RSS Feed -->
    <link rel="alternate" type="application/rss+xml" href="/rss" />

    <!-- Mobile friendliness -->
    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="apple-mobile-web-app-capable" content="yes">

    <!-- Mobile IE allows us to activate ClearType technology for smoothing fonts for easy reading -->
    <meta http-equiv="cleartype" content="on">

    <title>{{ isset($pageTitle) ? $pageTitle : Setting::get('app_name') }} | Cachet</title>

    <link href='//fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="{{ elixir('css/all.css') }}">

    @include('partials.stylesheet')

    @if($stylesheet = Setting::get('stylesheet'))
    <style type='text/css'>
    {{ $stylesheet }}
    </style>
    @endif

    <script src="{{ elixir('js/all.js') }}"></script>
</head>
<body class='status-page'>
    <div class='container'>
    @yield('content')
    </div>

    @include('partials.support-link')
</body>
</html>

Update meta values and remove author link.


<?php
namespace Mapbender\CoreBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Mapbender\CoreBundle\Entity\SRS;

/**
 * The LoadEpsgData loads the epsg parameter from a text file into a database table.
 *
 * @author Paul Schmidt
 */
class LoadEpsgData implements FixtureInterface
{

    /**
     * @inheritdoc
     */
    public function load(ObjectManager $manager)
    {
        $filepath = __DIR__ . '/../../../Resources/proj4/proj4js_epsg.txt';
        $file = @fopen($filepath, "r");
        while (!feof($file)) {
            $help = trim(str_ireplace("\n", "", fgets($file)));
            if (strlen($help) === 0) {
                continue;
            }
            $temp = explode("|", $help);
            if ($temp[0] === null || strlen($temp[0]) === 0) {
                continue;
            }
            $srs = new SRS();
            $srs->setName($temp[0]);
            $srs->setTitle($temp[1]);
            $srs->setDefinition($temp[2]);

            $manager->persist($srs);
        }
        $manager->flush();
        fclose($file);
    }

}

<?php

namespace Mapbender\CoreBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Mapbender\CoreBundle\Entity\SRS;

/**
 * The LoadEpsgData loads the epsg parameter from a text file into a database table.
 *
 * @author Paul Schmidt
 */
class LoadEpsgData implements FixtureInterface
{

    /**
     * @inheritdoc
     */
    public function load(ObjectManager $manager)
    {
        $filepath = __DIR__.'/../../../Resources/proj4/proj4js_epsg.txt';
        $file     = @fopen($filepath, "r");
        $repo     = $manager->getRepository($class    = get_class(new SRS()));
        $imported = 0;
        $updated = 0;
        echo "EPSG ";
        while (!feof($file)) {
            $help = trim(str_ireplace("\n", "", fgets($file)));
            if (strlen($help) === 0) {
                continue;
            }
            $temp = explode("|", $help);
            if ($temp[0] === null || strlen($temp[0]) === 0) {
                continue;
            }
            if ($srs = $repo->findOneByName($temp[0])) {
                $srs->setTitle($temp[1]);
                $srs->setDefinition($temp[2]);
                $updated++;
            } else {
                $srs->setName($temp[0]);
                $srs->setTitle($temp[1]);
                $srs->setDefinition($temp[2]);
                $imported++;
            }
            $manager->persist($srs);
        }
        $manager->flush();
        echo "updated: " . $updated . ", imported: " . $imported . PHP_EOL;
        fclose($file);
    }
}

Fix DataFixtures EPSG's import and implement EPSG's update


<?php

use Fhaculty\Graph\Algorithm\Directed as AlgorithmDirected;
use Fhaculty\Graph\Graph;

class DirectedTest extends TestCase
{
    public function testGraphEmpty()
    {
        $graph = new Graph();

        $alg = new AlgorithmDirected($graph);

        $this->assertFalse($alg->isDirected());
    }

    public function testGraphUndirected()
    {
        // 1 -- 2
        $graph = new Graph();
        $graph->createVertex(1)->createEdge($graph->createVertex(2));

        $alg = new AlgorithmDirected($graph);

        $this->assertFalse($alg->isDirected());
    }

    public function testGraphDirected()
    {
        // 1 -> 2
        $graph = new Graph();
        $graph->createVertex(1)->createEdgeTo($graph->createVertex(2));

        $alg = new AlgorithmDirected($graph);

        $this->assertTrue($alg->isDirected());
    }

    public function testGraphMixed()
    {
        // 1 -- 2 -> 3
        $graph = new Graph();
        $graph->createVertex(1)->createEdge($graph->createVertex(2));
        $graph->getVertex(2)->createEdgeTo($graph->createVertex(3));

        $alg = new AlgorithmDirected($graph);

        $this->assertTrue($alg->isDirected());
    }
}

<?php

use Fhaculty\Graph\Algorithm\Directed as AlgorithmDirected;
use Fhaculty\Graph\Graph;

class DirectedTest extends TestCase
{
    public function testGraphEmpty()
    {
        $graph = new Graph();

        $alg = new AlgorithmDirected($graph);

        $this->assertFalse($alg->hasDirected());
        $this->assertFalse($alg->hasUndirected());
        $this->assertFalse($alg->isMixed());
    }

    public function testGraphUndirected()
    {
        // 1 -- 2
        $graph = new Graph();
        $graph->createVertex(1)->createEdge($graph->createVertex(2));

        $alg = new AlgorithmDirected($graph);

        $this->assertFalse($alg->hasDirected());
        $this->assertTrue($alg->hasUndirected());
        $this->assertFalse($alg->isMixed());
    }

    public function testGraphDirected()
    {
        // 1 -> 2
        $graph = new Graph();
        $graph->createVertex(1)->createEdgeTo($graph->createVertex(2));

        $alg = new AlgorithmDirected($graph);

        $this->assertTrue($alg->hasDirected());
        $this->assertFalse($alg->hasUndirected());
        $this->assertFalse($alg->isMixed());
    }

    public function testGraphMixed()
    {
        // 1 -- 2 -> 3
        $graph = new Graph();
        $graph->createVertex(1)->createEdge($graph->createVertex(2));
        $graph->getVertex(2)->createEdgeTo($graph->createVertex(3));

        $alg = new AlgorithmDirected($graph);

        $this->assertTrue($alg->hasDirected());
        $this->assertTrue($alg->hasUndirected());
        $this->assertTrue($alg->isMixed());
    }
}

Add tests for Algorithm\Directed (100% coverage)


<?php
namespace TYPO3\Flow\Tests\Functional\Http\Client;

/*
 * This file is part of the TYPO3.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

/**
 * Functional tests for the HTTP client internal request engine
 *
 * @requires extension curl
 */
class CurlEngineTest extends \TYPO3\Flow\Tests\FunctionalTestCase
{
    /**
     * @var boolean
     */
    protected $testableSecurityEnabled = true;

    /**
     * @return void
     */
    public function setUp()
    {
        parent::setUp();
        $curlEngine = $this->objectManager->get(\TYPO3\Flow\Http\Client\CurlEngine::class);
        $this->browser->setRequestEngine($curlEngine);
    }

    /**
     * Check if the Curl Engine can send a GET request to typo3.org
     *
     * @test
     */
    public function getRequestReturnsResponse()
    {
        $response = $this->browser->request('http://typo3.org');
        $this->assertContains('This website is powered by TYPO3', $response->getContent());
    }
}

<?php
namespace TYPO3\Flow\Tests\Functional\Http\Client;

/*
 * This file is part of the TYPO3.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

/**
 * Functional tests for the HTTP client internal request engine
 *
 * @requires extension curl
 */
class CurlEngineTest extends \TYPO3\Flow\Tests\FunctionalTestCase
{
    /**
     * @var boolean
     */
    protected $testableSecurityEnabled = true;

    /**
     * @return void
     */
    public function setUp()
    {
        parent::setUp();
        $curlEngine = $this->objectManager->get(\TYPO3\Flow\Http\Client\CurlEngine::class);
        $this->browser->setRequestEngine($curlEngine);
    }

    /**
     * Check if the Curl Engine can send a GET request to neos.io
     *
     * @test
     */
    public function getRequestReturnsResponse()
    {
        $response = $this->browser->request('https://www.neos.io');
        $this->assertContains('This website is powered by Neos', $response->getContent());
    }
}

Change typo3.org reference to neos.io

TASK: Change typo3.org reference to neos.io

This change uses www.neos.io instead of typo3.org for testing the CurlEngine.


<?php
namespace Change\Commands;

use Change\Commands\Events\Event;

/**
 * @name \Change\Commands\GenerateDbSchema
 */
class GenerateDbSchema
{
	/**
	 * @param Event $event
	 */
	public function execute(Event $event)
	{
		$application = $event->getApplication();
		$applicationServices = new \Change\Application\ApplicationServices($application);
		$generator = new \Change\Db\Schema\Generator($application->getWorkspace(), $applicationServices->getDbProvider());
		try
		{
			if ($event->getParam('with-modules'))
			{
				$generator->generate();
				$event->addInfoMessage('Change and Modules Db schema generated.');
			}
			else
			{
				$generator->generateSystemSchema();
				$event->addInfoMessage('Change Db schema generated.');
			}
		}
		catch (\Exception $e )
		{
			$applicationServices->getLogging()->exception($e);
			$event->addErrorMessage($e->getMessage());
		}
	}
}

<?php
namespace Change\Commands;

use Change\Commands\Events\Event;

/**
 * @name \Change\Commands\GenerateDbSchema
 */
class GenerateDbSchema
{
	/**
	 * @param Event $event
	 */
	public function execute(Event $event)
	{
		$application = $event->getApplication();
		$applicationServices = new \Change\Application\ApplicationServices($application);
		$generator = new \Change\Db\Schema\Generator($application->getWorkspace(), $applicationServices->getDbProvider());
		try
		{
			if ($event->getParam('with-modules'))
			{
				$generator->generate();
				$event->addInfoMessage('Change and Modules DB schema generated.');
			}
			else
			{
				$generator->generateSystemSchema();
				$event->addInfoMessage('Change DB schema generated (to generate Modules DB schema, add -m option).');
			}
		}
		catch (\Exception $e )
		{
			$applicationServices->getLogging()->exception($e);
			$event->addErrorMessage($e->getMessage());
		}
	}
}

[ENHANCE] Add precision in generate-db-schema's messages.


<?php

defined('SYSPATH') or die('No direct script access.');

/**
 * Helper class to work with Kohana Profiler
 *
 * @package Aurora
 * @author Samuel Demirdjian
 * @copyright (c) 2013, Samuel Demirdjian
 * @license http://license.enov.ws/mit MIT
 *
 */
class Aurora_Aurora_Profiler
{

	protected static $category = 'Aurora';
	public static function start($aurora, $function) {
		$name = Aurora_Type::cname($aurora) . '::' . $function;
		$benchmark =
		  (Kohana::$profiling === TRUE) ?
		  Profiler::start(static::$category, $name) :
		  FALSE;
		return $benchmark;
	}
	public static function stop($benchmark) {
		if (!empty($benchmark)) {
			// Stop the benchmark
			Profiler::stop($benchmark);
		}
	}
	public static function delete($benchmark) {
		if (!empty($benchmark)) {
			// Delete the benchmark
			Profiler::delete($benchmark);
		}
	}
}

<?php

defined('SYSPATH') or die('No direct script access.');

/**
 * Helper class to work with Kohana Profiler
 *
 * @package Aurora
 * @author Samuel Demirdjian
 * @copyright (c) 2013, Samuel Demirdjian
 * @license http://license.enov.ws/mit MIT
 *
 */
class Aurora_Aurora_Profiler
{

	/**
	 * @var string The profiling category under which benchmarks will appear
	 */
	protected static $category = 'Aurora';
	/**
	 * Add a profiling mark and start counter
	 *
	 * @param Aurora $aurora
	 * @param string $function
	 * @return string benchmark id in Profiler
	 */
	public static function start($aurora, $function) {
		$name = Aurora_Type::cname($aurora) . '::' . $function;
		$benchmark =
		  (Kohana::$profiling === TRUE) ?
		  Profiler::start(static::$category, $name) :
		  FALSE;
		return $benchmark;
	}
	/**
	 * Stop a profiling mark
	 *
	 * @param string $benchmark
	 */
	public static function stop($benchmark) {
		if (!empty($benchmark)) {
			// Stop the benchmark
			Profiler::stop($benchmark);
		}
	}
	/**
	 * Delete a profiling mark
	 *
	 * @param string $benchmark
	 */
	public static function delete($benchmark) {
		if (!empty($benchmark)) {
			// Delete the benchmark
			Profiler::delete($benchmark);
		}
	}
}

Add some comments to Aurora_Profiler class


<?php

/**
 * This file is part of cocur/slugify.
 *
 * (c) Florian Eckerstorfer <florian@eckerstorfer.co>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Cocur\Slugify\Bridge\Laravel;

use Cocur\Slugify\Slugify;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;

/**
 * SlugifyServiceProvider
 *
 * @package    cocur/slugify
 * @subpackage bridge
 * @author     Florian Eckerstorfer <florian@eckerstorfer.co>
 * @author     Colin Viebrock
 * @copyright  2012-2014 Florian Eckerstorfer
 * @license    http://www.opensource.org/licenses/MIT The MIT License
 */
class SlugifyServiceProvider extends LaravelServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bindShared('slugify', function () {
            return new Slugify();
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return string[]
     */
    public function provides()
    {
        return array('slugify');
    }
}

<?php

/**
 * This file is part of cocur/slugify.
 *
 * (c) Florian Eckerstorfer <florian@eckerstorfer.co>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Cocur\Slugify\Bridge\Laravel;

use Cocur\Slugify\Slugify;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;

/**
 * SlugifyServiceProvider
 *
 * @package    cocur/slugify
 * @subpackage bridge
 * @author     Florian Eckerstorfer <florian@eckerstorfer.co>
 * @author     Colin Viebrock
 * @copyright  2012-2014 Florian Eckerstorfer
 * @license    http://www.opensource.org/licenses/MIT The MIT License
 */
class SlugifyServiceProvider extends LaravelServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('slugify', function () {
            return new Slugify();
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return string[]
     */
    public function provides()
    {
        return array('slugify');
    }
}

Use singleton instead of bindShared

Use singleton instead of bindShared

bindShared is deprecated (https://github.com/laravel/framework/blob/5.1/src/Illuminate/Container/Container.php#L289) and was removed in Laravel 5.2


<?php
namespace wcf\system\template\plugin;
use wcf\system\template\TemplateEngine;
use wcf\util\DateUtil;

/**
 * Template modifier plugin which formats a unix timestamp.
 * The default date format contains year, month and day.
 *
 * Usage:
 * 	{$timestamp|date}
 * 	{"132845333"|date:"Y-m-d"}
 *
 * @author	Marcel Werk
 * @copyright	2001-2012 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	com.woltlab.wcf
 * @subpackage	system.template.plugin
 * @category	Community Framework
 */
class DateModifierTemplatePlugin implements IModifierTemplatePlugin {
	/**
	 * @see	wcf\system\template\IModifierTemplatePlugin::execute()
	 */
	public function execute($tagArgs, TemplateEngine $tplObj) {
		return DateUtil::format(DateUtil::getDateTimeByTimestamp($tagArgs[0]), (!empty($tagArgs[2]) ? $tagArgs[2] : DateUtil::DATE_FORMAT));
	}
}

<?php
namespace wcf\system\template\plugin;
use wcf\system\template\TemplateEngine;
use wcf\util\DateUtil;

/**
 * Template modifier plugin which formats a unix timestamp.
 * The default date format contains year, month and day.
 *
 * Usage:
 * 	{$timestamp|date}
 * 	{"132845333"|date:"Y-m-d"}
 *
 * @author	Marcel Werk
 * @copyright	2001-2012 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	com.woltlab.wcf
 * @subpackage	system.template.plugin
 * @category	Community Framework
 */
class DateModifierTemplatePlugin implements IModifierTemplatePlugin {
	/**
	 * @see	wcf\system\template\IModifierTemplatePlugin::execute()
	 */
	public function execute($tagArgs, TemplateEngine $tplObj) {
		return DateUtil::format(DateUtil::getDateTimeByTimestamp($tagArgs[0]), (!empty($tagArgs[1]) ? $tagArgs[1] : DateUtil::DATE_FORMAT));
	}
}

Use proper argument in DateModifierTemplatePlugin

Closes #1108


<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        try {
            // Miscellaneous Data (e.g. counts)
            $this->call(MiscSeeder::class);

            // Users, Stats, Ranks
            $this->call(UserSeeder::class);

            // Beatmaps and sets
            $this->call(BeatmapSeeder::class);

            // Events
            $this->call(EventSeeder::class);

            // Scores
            $this->call(ScoreSeeder::class);

            // BanchoStats
            $this->call(BanchoStatsSeeder::class);

            // Forums, topics, posts etc
            $this->call(ForumSeeder::class);

            // Users Profile Data (Favourite maps, First place ranks, Playcounts)
            $this->call(UserProfileSeeder::class);

            //Store Products
            $this->call(ProductSeeder::class);
        } catch (ErrorException $er) {
            $this->command->error($er->getMessage());
        } catch (Exception $ex) {
            $this->command->error($ex->getMessage());
        } catch (\Illuminate\Database\QueryException $qe) {
            $this->command->error($qe->getMessage());
        }
    }
}

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        try {
            // Miscellaneous Data (e.g. counts)
            $this->call(MiscSeeder::class);

            // Users, Stats, Ranks
            $this->call(UserSeeder::class);

            // Beatmaps and sets
            $this->call(BeatmapSeeder::class);

            // Events
            $this->call(EventSeeder::class);

            // Scores
            $this->call(ScoreSeeder::class);

            // BanchoStats
            $this->call(BanchoStatsSeeder::class);

            // Forums, topics, posts etc
            $this->call(ForumSeeder::class);

            // Users Profile Data (Favourite maps, First place ranks, Playcounts)
            $this->call(UserProfileSeeder::class);

            // Store Products
            $this->call(ProductSeeder::class);

            // Build propagation history (user count data for each build in 30min intervals)
            $this->call(BuildPropagationHistorySeeder::class);
        } catch (ErrorException $er) {
            $this->command->error($er->getMessage());
        } catch (Exception $ex) {
            $this->command->error($ex->getMessage());
        } catch (\Illuminate\Database\QueryException $qe) {
            $this->command->error($qe->getMessage());
        }
    }
}

Add build history seeder to initial seed


<?php

class phpBrowserStack extends BrowserStack
{
    function __construct($username, $accessKey, $apiVersion = '3')
    {
        parent::__construct($username, $accessKey, $apiVersion);
    }

    public function test()
    {

    }
}

class BrowserStack
{
    protected $username;
    protected $accessKey;
    protected $apiVersion;

    protected static $apiURL = 'http://api.browserstack.com';

    function __construct($username, $accessKey, $apiVersion)
    {
        $this->username     = $username;
        $this->accessKey    = $accessKey;
        $this->apiVersion   = $apiVersion;
    }
}

?>

<?php

class phpBrowserStack extends BrowserStack
{
    function __construct($username, $access_key, $api_version = '3')
    {
        parent::__construct($username, $access_key, $api_version);
    }

    public function test()
    {

    }
}

class BrowserStack
{
    protected static $BASE_API_URL = 'http://api.browserstack.com';
    protected static $REST_API_URL = 'https://www.browserstack.com/automate';

    protected $username;
    protected $access_key;
    protected $api_version;

    protected $valid_statuses = array('running', 'done', 'failed');

    function __construct($username, $access_key, $api_version)
    {
        $this->username = $username;
        $this->access_key = $access_key;
        $this->api_version = $api_version;
    }

    protected function constructBuildsEndpoint()
    {
        return (BrowserStack::$REST_API_URL . '/builds.json');
    }

    protected function constructSessionsEndpoint($build_id, $session_id = NULL, $logs = FALSE)
    {
        $baseURL = BrowserStack::$REST_API_URL . '/builds/' . $build_id;

        if (!empty($session_id) && !empty($logs))
            return ($baseURL . '/sessions/' . $session_id . '/logs.json');
        else if (!empty($session_id))
            return ($baseURL . '/sessions/' . $session_id . '.json');
        else
            return ($baseURL . '/sessions.json');
    }

    protected function addLimitToEndpoint($endpoint_URL, $limit = NULL)
    {
        if ($limit > 0)
            return ($endpoint_URL . '?limit=' . $limit);

        return FALSE;
    }

    protected function addStatusFilterToEndpoint($endpoint_URL, $status = NULL)
    {
        if (in_array($status, $this->valid_statuses))
            return ($endpoint_URL . '?status=' . $status);

        return FALSE;
    }

}

?>

Add functions to construct endpoint urls for REST API


<?php namespace Flarum\Events;

use Flarum\Http\RouteCollection;

class RegisterForumRoutes
{
    /**
     * @var RouteCollection
     */
    public $routes;

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

<?php namespace Flarum\Events;

use Flarum\Http\RouteCollection;
use Psr\Http\Message\ServerRequestInterface;

class RegisterForumRoutes
{
    /**
     * @var RouteCollection
     */
    public $routes;

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

    public function get($url, $name, $action = 'Flarum\Forum\Actions\IndexAction')
    {
        $this->route('get', $url, $name, $action);
    }

    protected function route($method, $url, $name, $action)
    {
        $this->routes->$method($url, $name, $this->action($action));
    }

    protected function action($class)
    {
        return function (ServerRequestInterface $httpRequest, $routeParams) use ($class) {
            /** @var \Flarum\Support\Action $action */
            $action = app($class);

            return $action->handle($httpRequest, $routeParams);
        };
    }
}

Improve forum route registration API

Improve forum route registration API


<?
require 'scat.php';

head("transactions");

$type= $_REQUEST['type'];
if ($type) {
  $criteria= "type = '".$db->real_escape_string($type)."'";
} else {
  $criteria= '1=1';
}

/*
$q= $_GET['q'];
?>
<form method="get" action="<?=$_SERVER['PHP_SELF']?>">
<input id="focus" type="text" name="q" value="<?=htmlspecialchars($q)?>">
<input type="submit" value="Search">
</form>
<br>
<?
*/

$q= "SELECT
            txn.type AS meta,
            CONCAT(id, '|', type, '|', txn.number) AS Number\$txn,
            txn.created AS Created\$date,
            SUM(ordered) AS Ordered,
            SUM(shipped) AS Shipped,
            SUM(allocated) AS Allocated
       FROM txn
       LEFT JOIN txn_line ON (txn.id = txn_line.txn)
      WHERE $criteria
      GROUP BY txn.id
      ORDER BY created DESC
      LIMIT 200";

dump_table($db->query($q));
dump_query($q);

<?
require 'scat.php';

head("transactions");

$type= $_REQUEST['type'];
if ($type) {
  $criteria= "type = '".$db->real_escape_string($type)."'";
} else {
  $criteria= '1=1';
}

/*
$q= $_GET['q'];
?>
<form method="get" action="<?=$_SERVER['PHP_SELF']?>">
<input id="focus" type="text" name="q" value="<?=htmlspecialchars($q)?>">
<input type="submit" value="Search">
</form>
<br>
<?
*/

$q= "SELECT
            txn.type AS meta,
            CONCAT(txn.id, '|', type, '|', txn.number) AS Number\$txn,
            txn.created AS Created\$date,
            SUM(ordered) AS Ordered,
            SUM(shipped) AS Shipped,
            SUM(allocated) AS Allocated
       FROM txn
       LEFT JOIN txn_line ON (txn.id = txn_line.txn)
      WHERE $criteria
      GROUP BY txn.id
      ORDER BY created DESC
      LIMIT 200";

dump_table($db->query($q));
dump_query($q);

Fix column name in query

Fix column name in query


<?php

/**
 * Copyright (c) 2014 Thomas Müller <deepdiver@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace Test\DB;

class MDB2SchemaManager extends \PHPUnit_Framework_TestCase {

	public function tearDown() {
		\OC_DB::dropTable('table');
	}

	public function testAutoIncrement() {

		if (\OC::$server->getConfig()->getSystemValue('dbtype', 'sqlite') === 'oci') {
			$this->markTestSkipped('Adding auto increment columns in Oracle is not supported.');
		}

		$connection = \OC_DB::getConnection();
		$manager = new \OC\DB\MDB2SchemaManager($connection);

		$manager->createDbFromStructure(__DIR__ . '/ts-autoincrement-before.xml');
		$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('abc'));
		$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('abc'));
		$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('123'));
		$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('123'));
		$manager->updateDbFromStructure(__DIR__ . '/ts-autoincrement-after.xml');

		$this->assertTrue(true);
	}

}

<?php

/**
 * Copyright (c) 2014 Thomas Müller <deepdiver@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace Test\DB;

class MDB2SchemaManager extends \PHPUnit_Framework_TestCase {

	public function tearDown() {
		// do not drop the table for Oracle as it will create a bogus transaction
		// that will break the following test suites requiring transactions
		if (\OC::$server->getConfig()->getSystemValue('dbtype', 'sqlite') === 'oci') {
			return;
		}
		\OC_DB::dropTable('table');
	}

	public function testAutoIncrement() {

		if (\OC::$server->getConfig()->getSystemValue('dbtype', 'sqlite') === 'oci') {
			$this->markTestSkipped('Adding auto increment columns in Oracle is not supported.');
		}

		$connection = \OC_DB::getConnection();
		$manager = new \OC\DB\MDB2SchemaManager($connection);

		$manager->createDbFromStructure(__DIR__ . '/ts-autoincrement-before.xml');
		$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('abc'));
		$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('abc'));
		$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('123'));
		$connection->executeUpdate('insert into `*PREFIX*table` values (?)', array('123'));
		$manager->updateDbFromStructure(__DIR__ . '/ts-autoincrement-after.xml');

		$this->assertTrue(true);
	}

}

Fix unit test messing up the transaction on Oracle

Since the unit test is skipped anyway for Oracle, the dropTable() call
should be skipped as well to avoid having a leftover transaction and
cause further transactions to be nested and break the next test suites
requiring transactions.


<?php

use UWDOEM\Encryption\Cipher;

class CipherTest extends PHPUnit_Framework_TestCase {

    static function setUpBeforeClass() {
        Cipher::createInstance("blaksjdfoiuwer");
    }
    public function testEncrypt() {
        $plainText = "plaintext";

        $encryptedText1 = Cipher::getInstance()->encrypt($plainText);
        $encryptedText2 = Cipher::getInstance()->encrypt($plainText);

        // Assert that a given plain text will not encrypt to the same encrypted text every time
        $this->assertNotEquals($encryptedText1, $encryptedText2);
    }

    public function testEncryptDecrypt() {

        $plainText = "plaintext";
        $encryptedText = Cipher::getInstance()->encrypt($plainText);

        // Assert that the encrypted text is not the same as the plain text
        $this->assertNotEquals($plainText, $encryptedText);

        // Assert that the encrypted text is equal to the plain text when decrypted
        $this->assertEquals($plainText, Cipher::getInstance()->decrypt($encryptedText));
    }

}

<?php

use UWDOEM\Encryption\Cipher;

class CipherTest extends PHPUnit_Framework_TestCase {

    /**
     * @expectedException              Exception
     * @expectedExceptionMessageRegExp #called before initialization.*#
     */
    public function testGetInstanceBeforeCreate() {
        Cipher::getInstance();
    }

    public function testCipherCreation() {
        Cipher::createInstance("blaksjdfoiuwer");
    }

    /**
     * @expectedException              Exception
     * @expectedExceptionMessageRegExp #Only one cipher instance may be created.*#
     */
    public function testCreateInstanceTwice() {
        Cipher::createInstance("blaksjdfoiuwer");
    }

    public function testEncrypt() {
        $plainText = "plaintext";

        $encryptedText1 = Cipher::getInstance()->encrypt($plainText);
        $encryptedText2 = Cipher::getInstance()->encrypt($plainText);

        // Assert that a given plain text will not encrypt to the same encrypted text every time
        $this->assertNotEquals($encryptedText1, $encryptedText2);
    }

    public function testEncryptDecrypt() {

        $plainText = "plaintext";
        $encryptedText = Cipher::getInstance()->encrypt($plainText);

        // Assert that the encrypted text is not the same as the plain text
        $this->assertNotEquals($plainText, $encryptedText);

        // Assert that the encrypted text is equal to the plain text when decrypted
        $this->assertEquals($plainText, Cipher::getInstance()->decrypt($encryptedText));
    }

}

Create tests for cipher creation, retrieval.


<img class="stapler-thumbnail" src="{{ $urlThumb }}" title="{{ $filename }}" width="{{ $width }}" height="{{ $height }}">

<img class="stapler-thumbnail" src="{{ $urlThumb }}" alt="{{ $filename }}" width="{{ $width }}" height="{{ $height }}">

Replace title with alt attribute in stapler_image list template


<?php

namespace Ramsey\Uuid\Test\Generator;

use phpmock\phpunit\PHPMock;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Generator\SodiumRandomGenerator;

class SodiumRandomGeneratorTest extends TestCase
{
    use PHPMock;

    protected function skipIfLibsodiumExtensionNotLoaded()
    {
        if (!extension_loaded('libsodium')) {
            $this->markTestSkipped(
                'The libsodium extension is not available.'
            );
        }
    }

    public function testGenerateReturnsBytes()
    {
        $this->skipIfLibsodiumExtensionNotLoaded();
        $generator = new SodiumRandomGenerator();

        $bytes = $generator->generate(16);

        $this->assertInternalType('string', $bytes);
        $this->assertEquals(16, strlen($bytes));
    }

    public function testFactoryUsesSodiumRandomGenerator()
    {
        $this->skipIfLibsodiumExtensionNotLoaded();
        $uuidFactory = new \Ramsey\Uuid\UuidFactory();
        $uuidFactory->setRandomGenerator(new SodiumRandomGenerator());
        \Ramsey\Uuid\Uuid::setFactory($uuidFactory);

        $uuid = \Ramsey\Uuid\Uuid::uuid4();

        $this->assertInstanceOf(
            'Ramsey\Uuid\Generator\SodiumRandomGenerator',
            $uuid->getFactory()->getRandomGenerator()
        );
    }

    /**
     * @runInSeparateProcess
     * @preserveGlobalState disabled
     */
    public function testGenerateUsesSodiumLibrary()
    {
        $randomBytesFunc = $this->getFunctionMock('Sodium', 'randombytes_buf');
        $randomBytesFunc->expects($this->once())
            ->with(10);
        $generator = new SodiumRandomGenerator();
        $generator->generate(10);
    }
}

<?php

namespace Ramsey\Uuid\Test\Generator;

use phpmock\phpunit\PHPMock;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Generator\SodiumRandomGenerator;

class SodiumRandomGeneratorTest extends TestCase
{
    use PHPMock;

    protected function skipIfLibsodiumExtensionNotLoaded()
    {
        if (!extension_loaded('libsodium')) {
            $this->markTestSkipped(
                'The libsodium extension is not available.'
            );
        }
    }

    public function testGenerateReturnsBytes()
    {
        $this->skipIfLibsodiumExtensionNotLoaded();
        $generator = new SodiumRandomGenerator();

        $bytes = $generator->generate(16);

        $this->assertInternalType('string', $bytes);
        $this->assertEquals(16, strlen($bytes));
    }

    public function testFactoryUsesSodiumRandomGenerator()
    {
        $this->skipIfLibsodiumExtensionNotLoaded();
        $uuidFactory = new \Ramsey\Uuid\UuidFactory();
        $uuidFactory->setRandomGenerator(new SodiumRandomGenerator());
        \Ramsey\Uuid\Uuid::setFactory($uuidFactory);

        $uuid = \Ramsey\Uuid\Uuid::uuid4();

        $this->assertInstanceOf(
            'Ramsey\Uuid\Generator\SodiumRandomGenerator',
            $uuid->getFactory()->getRandomGenerator()
        );
    }
}

Remove test that fails because of qualified function call


<?php

namespace SilverStripe\VersionFeed\Filters;

use SilverStripe\VersionFeed\VersionFeedController;
use SilverStripe\Core\Config\Configurable;
use Psr\SimpleCache\CacheInterface;
use SilverStripe\Core\Injector\Injector;

/**
 * Conditionally executes a given callback, attempting to return the desired results
 * of its execution.
 */
abstract class ContentFilter {

	use configurable;

	/**
	 * Nested content filter
	 *
	 * @var ContentFilter
	 */
	protected $nestedContentFilter;

	/**
	 * Cache lifetime
	 *
	 * @config
	 * @var int
	 */
	private static $cache_lifetime = 300;

	public function __construct($nestedContentFilter = null) {
		$this->nestedContentFilter = $nestedContentFilter;
	}

	/**
	 * Gets the cache to use
	 *
	 * @return Zend_Cache_Frontend
	 */
	protected function getCache() {
		return Injector::inst()->get(
			CacheInterface::class . '.VersionFeedController'
		);
	}

	/**
	 * Evaluates the result of the given callback
	 *
	 * @param string $key Unique key for this
	 * @param callable $callback Callback for evaluating the content
	 * @return mixed Result of $callback()
	 */
	public function getContent($key, $callback) {
		if($this->nestedContentFilter) {
			return $this->nestedContentFilter->getContent($key, $callback);
		} else {
			return call_user_func($callback);
		}
	}
}

<?php

namespace SilverStripe\VersionFeed\Filters;

use SilverStripe\VersionFeed\VersionFeedController;
use SilverStripe\Core\Config\Configurable;
use Psr\SimpleCache\CacheInterface;
use SilverStripe\Core\Injector\Injector;

/**
 * Conditionally executes a given callback, attempting to return the desired results
 * of its execution.
 */
abstract class ContentFilter {

	use Configurable;

	/**
	 * Nested content filter
	 *
	 * @var ContentFilter
	 */
	protected $nestedContentFilter;

	/**
	 * Cache lifetime
	 *
	 * @config
	 * @var int
	 */
	private static $cache_lifetime = 300;

	public function __construct($nestedContentFilter = null) {
		$this->nestedContentFilter = $nestedContentFilter;
	}

	/**
	 * Gets the cache to use
	 *
	 * @return Zend_Cache_Frontend
	 */
	protected function getCache() {
		return Injector::inst()->get(
			CacheInterface::class . '.VersionFeedController'
		);
	}

	/**
	 * Evaluates the result of the given callback
	 *
	 * @param string $key Unique key for this
	 * @param callable $callback Callback for evaluating the content
	 * @return mixed Result of $callback()
	 */
	public function getContent($key, $callback) {
		if($this->nestedContentFilter) {
			return $this->nestedContentFilter->getContent($key, $callback);
		} else {
			return call_user_func($callback);
		}
	}
}

FIX Capitalisation of trait usage

FIX Capitalisation of trait usage


<?php

namespace Ilios\CoreBundle\Tests\DataLoader;

class LearningMaterialUserRoleData extends AbstractDataLoader
{
    protected function getData()
    {
        $arr = array();

        $arr[] = array(
            'id' => 1,
            'title' => $this->faker->text(10),
            'learningMaterials' => ['1']
        );

        $arr[] = array(
            'id' => 2,
            'title' => $this->faker->text(10),
            'learningMaterials' => ['2']
        );

        return $arr;
    }

    public function create()
    {
        return [];
    }

    public function createInvalid()
    {
        return [];
    }
}

<?php

namespace Ilios\CoreBundle\Tests\DataLoader;

class LearningMaterialUserRoleData extends AbstractDataLoader
{
    protected function getData()
    {
        $arr = array();

        $arr[] = array(
            'id' => 1,
            'title' => $this->faker->text(10),
            'learningMaterials' => ['1']
        );

        $arr[] = array(
            'id' => 2,
            'title' => $this->faker->text(10),
            'learningMaterials' => ['2']
        );

        return $arr;
    }

    public function create()
    {
        return array(
            'id' => 3,
            'title' => $this->faker->text(10),
            'learningMaterials' => ['1', '2']
        );
    }

    public function createInvalid()
    {
        return [];
    }
}

Add LM User role create data

Add LM User role create data


<?php

/**
 * Application component for registering with the Grunt's live reload plugin.
 */
class LiveReload extends CApplicationComponent
{
    /**
     * @var string the host name of the server running the live reload server.
     */
    public $host = 'localhost';
    /**
     * @var array live reload ports.
     */
    public $port = 35729;
    /**
     * @var string the component ID for the client script component.
     */
    public $clientScriptID = 'clientScript';

    /**
     * Registers the live reload servers.
     */
    public function register()
    {
        if (($cs = Yii::app()->getComponent($this->clientScriptID)) !== null) {
            $cs->registerScriptFile(
                $this->host . ':' . (string)$this->port . '/livereload.js',
                CClientScript::POS_END
            );
        }
    }
}

<?php

/**
 * Application component for registering with the Grunt's live reload plugin.
 */
class LiveReload extends CApplicationComponent
{
    /**
     * @var string the host name of the server running the live reload server.
     */
    public $host = 'localhost';
    /**
     * @var array live reload ports.
     */
    public $port = 35729;
    /**
     * @var string the component ID for the client script component.
     */
    public $clientScriptID = 'clientScript';

    /**
     * Registers the live reload servers.
     */
    public function register()
    {
        if (($cs = Yii::app()->getComponent($this->clientScriptID)) !== null) {
            $cs->registerScriptFile(
                "{$this->host}:{$this->port}/livereload.js",
                CClientScript::POS_END
            );
        }
    }
}

Refactor the script file url

Refactor the script file url


@extends('clearboard.main.template')

@section('title', '404 Not Found')

@section('content')

404 Not Found

The page you requested doesn't exist.

Goto the homepage

@endsection

Add user friendly 404 page

Add user friendly 404 page


<?php

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

namespace Symfony\Component\Serializer\Normalizer;

use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;

/**
 * SerializerAware Normalizer implementation
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
abstract class SerializerAwareNormalizer implements SerializerAwareInterface
{
    protected $serializer;

    /**
     * {@inheritdoc}
     */
    public function setSerializer(SerializerInterface $serializer)
    {
        $this->serializer = $serializer;
    }
}

<?php

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

namespace Symfony\Component\Serializer\Normalizer;

use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;

/**
 * SerializerAware Normalizer implementation
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
abstract class SerializerAwareNormalizer implements SerializerAwareInterface
{
    /**
     * @var SerializerInterface
     */
    protected $serializer;

    /**
     * {@inheritdoc}
     */
    public function setSerializer(SerializerInterface $serializer)
    {
        $this->serializer = $serializer;
    }
}

Add a docblock to help type hinting

[Serializer] Add a docblock to help type hinting


<?php

if(isset($_POST['stop']))
{
	// Stop
}
if(isset($_POST['restart']))
{
	// neustarten
}

?>

Samba Übersicht

<fieldset>

Pfad zur Datei mit Inhalt:

    <?php echo __file__;?>

</fieldset>
<fieldset>
<form action="index.php?p=samba" method="POST">

Stop

<input type="submit" class="button pink" name="stop" value="stop">

Restart

<input type="submit" class="button black" name="restart" value="neustarten">

</form>
</fieldset>

Stop / Restart Samba Grundgerüst hinzugefügt


<?php
/**
 * PHP version 7.0
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace Ewallet\Slim\Providers;

use Pimple\{Container, ServiceProviderInterface};
use Slim\App;
use Slim\Http\{Request, Response};

class EwalletControllerProvider implements ServiceProviderInterface
{
    /** @var App */
    private $app;

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

    /**
     * @param Container $container
     */
    public function register(Container $container)
    {
        $router = $this->app->getContainer()['router'];
        $this->app->get(
            '/',
            function (Request $request, Response $response) use ($router) {
                return $response->withRedirect($request->getUri()->withPath(
                    $router->pathFor('transfer_form')
                ));
            }
        )->setName('ewallet_home');
        $this->app->get(
            '/transfer-form',
            'ewallet.transfer_form_controller:enterTransferInformation'
        )->setName('transfer_form');
        $this->app->post(
            '/transfer-funds',
            'ewallet.transfer_funds_controller:transfer'
        )->setName('transfer_funds');
    }
}

<?php
/**
 * PHP version 7.0
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
namespace Ewallet\Slim\Providers;

use Pimple\{Container, ServiceProviderInterface};
use Slim\App;
use Slim\Http\{Request, Response};

class EwalletControllerProvider implements ServiceProviderInterface
{
    /** @var App */
    private $app;

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

    /**
     * @param Container $container
     */
    public function register(Container $container)
    {
        $router = $this->app->getContainer()->get('router');
        $this->app->get(
            '/',
            function (Request $request, Response $response) use ($router) {
                return $response->withRedirect($request->getUri()->withPath(
                    $router->pathFor('transfer_form')
                ));
            }
        )->setName('ewallet_home');
        $this->app->get(
            '/transfer-form',
            'ewallet.transfer_form_controller:enterTransferInformation'
        )->setName('transfer_form');
        $this->app->post(
            '/transfer-funds',
            'ewallet.transfer_funds_controller:transfer'
        )->setName('transfer_funds');
    }
}

Replace array access to slims's container with a call to 'get'.


<?php

$array = [];

$array[] = 10;
$array[][] = 10;
$array[];
var_dump($array[]);
while ($foo = $array[]) {}

$array['foo']['bar'];
$array['foo'][];
$array[]['bar'];
$array[][];

$firstElement = &$array[];
(function ($ref) {})($array[]);
//(function (&$ref) {})($array[]); // Should work but doesn't

// Technically works but makes no sense
$array[] += 20;
$array[] -= 20;
$array[] *= 20;
$array[] /= 20;

// NodeScopeResolver exceptions
isset($array[]);
unset($array[]);
empty($array[]);
$foo[] ?? $foo;
//global $array[]; // Parse error
//static $array[]; // Parse error
//function () use ($array[]) {} // Parse error

list($array[], $array[]) = [1, 2];

Add `list` test for OffsetAccessWithoutDimForReadingRule


<?php namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Foundation\Http\Middleware\VerifyPostSize',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
        'App\Http\Middleware\VerifyCsrfToken',
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => 'App\Http\Middleware\Authenticate',
        'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
        'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
    ];
}

<?php namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
        'App\Http\Middleware\VerifyCsrfToken',
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => 'App\Http\Middleware\Authenticate',
        'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
        'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
    ];
}

Revert "[5.1] Add new middleware"

Revert "[5.1] Add new middleware"


<?php
/**
 * This file is part of the Axstrad library.
 *
 * (c) Dan Kempster <dev@dankempster.co.uk>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Dan Kempster <dev@dankempster.co.uk>
 * @package Axstrad\DoctineExtensions
 */
namespace Axstrad\DoctrineExtensions\Activatable;

use Doctrine\Common\EventArgs;
use Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs;
use Gedmo\Mapping\MappedEventSubscriber;
use Axstrad\DoctrineExtensions\Exception\InvalidArgumentException;

/**
 * Axstrad\DoctrineExtensions\Activatable\ActivatableListener
 */
class ActivatableListener extends MappedEventSubscriber
{
    /**
     */
    public function getSubscribedEvents()
    {
        return array(
            'loadClassMetadata',
        );
    }

    /**
     * Mapps additional metadata
     *
     * @param EventArgs $eventArgs
     * @return void
     */
    public function loadClassMetadata(EventArgs $eventArgs)
    {
        if ($eventArgs instanceof LoadClassMetadataEventArgs) {
            throw InvalidArgumentException::create(
                'Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs',
                $eventArgs
            );
        }
        $ea = $this->getEventAdapter($eventArgs);
        $this->loadMetadataForObjectClass($ea->getObjectManager(), $eventArgs->getClassMetadata());
    }

    /**
     * {@inheritDoc}
     */
    public function getNamespace()
    {
        return __NAMESPACE__;
    }
}

<?php
/**
 * This file is part of the Axstrad library.
 *
 * (c) Dan Kempster <dev@dankempster.co.uk>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Dan Kempster <dev@dankempster.co.uk>
 * @package Axstrad\DoctineExtensions
 */
namespace Axstrad\DoctrineExtensions\Activatable;

use Doctrine\Common\EventArgs;
use Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs;
use Gedmo\Mapping\MappedEventSubscriber;
use Axstrad\DoctrineExtensions\Exception\InvalidArgumentException;

/**
 * Axstrad\DoctrineExtensions\Activatable\ActivatableListener
 */
class ActivatableListener extends MappedEventSubscriber
{
    /**
     */
    public function getSubscribedEvents()
    {
        return array(
            'loadClassMetadata',
        );
    }

    /**
     * Mapps additional metadata
     *
     * @param EventArgs $eventArgs
     * @return void
     */
    public function loadClassMetadata(EventArgs $eventArgs)
    {
        if (!$eventArgs instanceof LoadClassMetadataEventArgs) {
            throw InvalidArgumentException::create(
                'Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs',
                $eventArgs
            );
        }
        $ea = $this->getEventAdapter($eventArgs);
        $this->loadMetadataForObjectClass($ea->getObjectManager(), $eventArgs->getClassMetadata());
    }

    /**
     * {@inheritDoc}
     */
    public function getNamespace()
    {
        return __NAMESPACE__;
    }
}

Fix object class assertion bug

Fix object class assertion bug


<?php

namespace PhpGitHooks\Module\Configuration\Infrastructure\Hook;

use Symfony\Component\Process\Process;

class HookCopier
{
    private $hookDir = '.git/hooks/';

    public function copyPreCommitHook()
    {
        $this->copyHookFile('pre-commit');
    }

    public function copyCommitMsgHook()
    {
        $this->copyHookFile('commit-msg');
    }

    public function copyPrePushHook()
    {
        $this->copyHookFile('pre-push');
    }

    /**
     * @param string $hookFile
     *
     * @return bool
     */
    private function hookExists($hookFile)
    {
        return file_exists(sprintf('%s%s', $this->hookDir, $hookFile));
    }

    /**
     * @param string $hookFile
     */
    private function copyFile($hookFile)
    {
        $copy = new Process(sprintf("mkdir -p {$this->hookDir} && cp %s %s", $hookFile, $this->hookDir));
        $copy->run();
    }

    /**
     * @param $hookFile
     */
    private function setPermissions($hookFile)
    {
        $permissions = new Process(sprintf('chmod 775 %s%s', $this->hookDir, $hookFile));
        $permissions->run();
    }

    /**
     * @param string $file
     */
    private function copyHookFile($file)
    {
        if (false === $this->hookExists($file)) {
            $this->copyFile(sprintf('%s/%s', __DIR__ . '/../../../../Infrastructure/Hook', $file));
            $this->setPermissions($file);
        }
    }
}

<?php

namespace PhpGitHooks\Module\Configuration\Infrastructure\Hook;

use Symfony\Component\Process\Process;

class HookCopier
{
    private $hookDir = '.git/hooks/';

    public function copyPreCommitHook(): void
    {
        $this->copyHookFile('pre-commit');
    }

    public function copyCommitMsgHook(): void
    {
        $this->copyHookFile('commit-msg');
    }

    public function copyPrePushHook(): void
    {
        $this->copyHookFile('pre-push');
    }

    private function hookExists(string $hookFile): bool
    {
        return file_exists(sprintf('%s%s', $this->hookDir, $hookFile));
    }

    private function copyFile(string $hookFile): void
    {
        $copy = new Process(sprintf("mkdir -p {$this->hookDir} && cp %s %s", $hookFile, $this->hookDir));
        $copy->run();
    }

    private function setPermissions(string $hookFile): void
    {
        $permissions = new Process(sprintf('chmod 775 %s%s', $this->hookDir, $hookFile));
        $permissions->run();
    }

    private function copyHookFile(string $file): void
    {
        if (false === $this->hookExists($file)) {
            $this->copyFile(sprintf('%s/%s', __DIR__ . '/../../../../Infrastructure/Hook', $file));
            $this->setPermissions($file);
        }
    }
}

Replace phpdoc blocks by language type hints


<?php

class Analytics_Options_Serializer {

	public function init() {
		add_action( 'admin_post_analytics_options', array( $this, 'save' ) );
	}

	public static function save() {

		$option_name = 'analytics';

		if ( empty( $_POST['id'] ) ||
		     empty( $_POST['vendor-type'] ) ||
		     empty( $_POST['config'] ) ) {
			return;
		}

		$new_analytics_options = array(
			$_POST['id'],
			$_POST['vendor-type'],
			stripslashes($_POST['config'])
		);

		$inner_option_name = $_POST['vendor-type'] . '-' . $_POST['id'];

		$analytics_options = get_option($option_name);
		if ( ! $analytics_options ) {
			$analytics_options = array();
		}

		if ( isset($_POST['delete']) ) {
			unset($analytics_options[$inner_option_name]);
		} else {
			$analytics_options[$inner_option_name] = $new_analytics_options;
		}
		update_option( $option_name, $analytics_options, false);

		// TODO(@amedina): change this hardwired redirect to use a variable reference
		header('Location: http://localhost:8888/amp-wp-plugin-dev/wp-admin/admin.php?page=amp-analytics-options');
	}
}

<?php

class Analytics_Options_Serializer {

	public function init() {
		add_action( 'admin_post_analytics_options', array( $this, 'save' ) );
	}

	public static function save() {

		$option_name = 'analytics';

		if ( empty( $_POST['id'] ) ||
		     empty( $_POST['vendor-type'] ) ||
		     empty( $_POST['config'] ) ) {
			return;
		}

		$new_analytics_options = array(
			$_POST['id'],
			$_POST['vendor-type'],
			stripslashes($_POST['config'])
		);

		$inner_option_name = $_POST['vendor-type'] . '-' . $_POST['id'];

		$analytics_options = get_option($option_name);
		if ( ! $analytics_options ) {
			$analytics_options = array();
		}

		if ( isset($_POST['delete']) ) {
			unset($analytics_options[$inner_option_name]);
		} else {
			$analytics_options[$inner_option_name] = $new_analytics_options;
		}
		update_option( $option_name, $analytics_options, false);

		// [Redirect] Keep the user in the analytics options page
		header('Location: ' . admin_url('admin.php?page=amp-analytics-options'));
	}
}

Fix hardwired redirect to analytics options page


<?php
include_once("app/models/Utils.php");

class Dbc
{
  protected static $instance = null;
  protected function __construct()
  {
    // Thou shalt not construct that which is unconstructable!
  }
  protected function __clone()
  {
    // Me not like clones! Me smash clones!
  }
  public static function getWriter()
  {
    if (!isset(static::$instance)) {
      //$GLOBALS['DB_CREATIONS'] = $GLOBALS['DB_CREATIONS']+1;
      $pars = findAccessParameters();
      $host = $pars[0];
      $user = $pars[1];
      $passwd = $pars[2];
      static::$instance = new PDO('mysql:host='.$host.';dbname=Teaching;charset=utf8',$user,$passwd);
    }
    return static::$instance;
  }
  public static function getReader()
  {
    if (!isset(static::$instance)) {
      //$GLOBALS['DB_CREATIONS'] = $GLOBALS['DB_CREATIONS']+1;
      $pars = findAccessParameters();
      $host = $pars[0];
      $user = $pars[1];
      $passwd = $pars[2];
      static::$instance = new PDO('mysql:host='.$host.';dbname=Teaching;charset=utf8',$user,$passwd);
    }
    return static::$instance;
  }
}

?>

<?php
include_once("app/models/AccessParameters.php");
include_once("app/models/Utils.php");

class Dbc
{
  protected static $instance = null;
  protected function __construct()
  {
    // Thou shalt not construct that which is unconstructable!
  }
  protected function __clone()
  {
    // Me not like clones! Me smash clones!
  }
  public static function getWriter()
  {
    if (!isset(static::$instance)) {
      $p = AccessParameters::get();
      static::$instance = new PDO('mysql:host='.$p['host'].';dbname=Teaching;charset=utf8',
                                  $p['user'],$p['passwd']);
    }
    return static::$instance;
  }
  public static function getReader()
  {
    if (!isset(static::$instance)) {
      $p = AccessParameters::get();
      static::$instance = new PDO('mysql:host='.$p['host'].';dbname=Teaching;charset=utf8',
                                  $p['user'],$p['passwd']);
    }
    return static::$instance;
  }
}

?>

Make access parameters a singleton.

Make access parameters a singleton.


<?php

use Roots\Sage\Config;
use Roots\Sage\Wrapper;

?>

<?php get_template_part('templates/head'); ?>
  <body <?php body_class(); ?>>

      <?php
        do_action('get_header');
        get_template_part('templates/header');
      ?>

            <?php include Wrapper\template_path(); ?>

          <?php if (Config\display_sidebar()) : ?>

              <?php include Wrapper\sidebar_path(); ?>

          <?php endif; ?>

    <?php
      get_template_part('templates/footer');
      wp_footer();
    ?>

Add cookie warning in compliance to eu cookie laws


<?php

$m = new Mustache_Engine([
  'loader' => new Mustache_Loader_FilesystemLoader(__DIR__.'/build/govuk_template/views/layouts', [
    'extension' => '.html',
  ]),
]);

$template = $m->loadTemplate('govuk_template');

echo $template->render([
  'pageTitle' => \Missing\String::get_output(function () { wp_title('|', true, 'right'); }),
  'assetPath' => get_template_directory_uri().'/build/govuk_template/assets/',
  'head' => \Missing\String::get_output('wp_head'),
  'bodyClasses' => implode(' ', array_map('esc_attr', get_body_class())),
  'cookieMessage' => \Missing\String::get_output(function () { get_template_part('templates/cookies'); }),
  'content' => \Missing\String::get_output(function () { get_template_part('templates/base'); }),
  'footerSupportLinks' => \Missing\String::get_output(function () { get_template_part('templates/footer'); }),
  'bodyEnd' => \Missing\String::get_output('wp_footer'),
]);

<?php

$m = new Mustache_Engine([
  'loader' => new Mustache_Loader_FilesystemLoader(__DIR__.'/build/govuk_template/views/layouts', [
    'extension' => '.html',
  ]),
]);

$template = $m->loadTemplate('govuk_template');

echo $template->render([
  'pageTitle' => html_entity_decode(\Missing\String::get_output(function () { wp_title('|', true, 'right'); })),
  'assetPath' => get_template_directory_uri().'/build/govuk_template/assets/',
  'head' => \Missing\String::get_output('wp_head'),
  'bodyClasses' => implode(' ', array_map('esc_attr', get_body_class())),
  'cookieMessage' => \Missing\String::get_output(function () { get_template_part('templates/cookies'); }),
  'content' => \Missing\String::get_output(function () { get_template_part('templates/base'); }),
  'footerSupportLinks' => \Missing\String::get_output(function () { get_template_part('templates/footer'); }),
  'bodyEnd' => \Missing\String::get_output('wp_footer'),
]);

Revert the mess WordPress makes

Revert the mess WordPress makes


<!DOCTYPE html>

@include('partials.header')

    @include('partials.navigation')

        @include('partials.title')
        @section('controls')
        @show
        @include('partials.notifications')
        @section('content')
        @show

    @include('partials.footer')

<!DOCTYPE html>

@include('partials.header')

    @include('partials.navigation')

        @include('partials.title')
        @include('partials.notifications')
        @section('controls')
        @show
        @section('content')
        @show

    @include('partials.footer')

Move notifications above the controls

Move notifications above the controls


<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('username');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('username')->unique();
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

Make the username field unique

Make the username field unique


<?php

namespace BNETDocs\Libraries;

use CarlBennett\MVC\Libraries\Router;
use CarlBennett\MVC\Libraries\Session as BaseSession;

class Session extends BaseSession  {

  const COOKIE_NAME = 'uid';
  const LOGIN_TTL   = 86400; // 1 day

  public static function checkLogin(Router &$router) {
    // Check if logged in by session but long-term cookie not set
    if (isset($_SESSION['user_id']) && !isset($_COOKIE[self::COOKIE_NAME])) {
      $router->setResponseCookie(
        self::COOKIE_NAME,    // key
        $_SESSION['user_id'], // value
        self::LOGIN_TTL,      // ttl
        true,                 // http only
        true,                 // secure
        getenv('HTTP_HOST'),  // domain
        '/'                   // path
      );
    }
    // Check for login manipulation
    if (isset($_SESSION['user_id']) && isset($_COOKIE[self::COOKIE_NAME])
      && $_SESSION['user_id'] != $_COOKIE[self::COOKIE_NAME]) {
      unset($_SESSION['user_id']);
      $router->setResponseCookie(
        self::COOKIE_NAME, '', 0, true, true, // delete it
        getenv('HTTP_HOST'), '/'
      );
    }
  }

}

<?php

namespace BNETDocs\Libraries;

use CarlBennett\MVC\Libraries\Router;
use CarlBennett\MVC\Libraries\Session as BaseSession;

class Session extends BaseSession  {

  const COOKIE_NAME = 'uid';
  const LOGIN_TTL   = 2592000; // 1 month

  public static function checkLogin(Router &$router) {
    // Check if logged in by session but long-term cookie not set
    if (isset($_SESSION['user_id']) && !isset($_COOKIE[self::COOKIE_NAME])) {
      $router->setResponseCookie(
        self::COOKIE_NAME,    // key
        $_SESSION['user_id'], // value
        self::LOGIN_TTL,      // ttl
        true,                 // http only
        true,                 // secure
        getenv('HTTP_HOST'),  // domain
        '/'                   // path
      );
    }
    // Check for login manipulation
    if (isset($_SESSION['user_id']) && isset($_COOKIE[self::COOKIE_NAME])
      && $_SESSION['user_id'] != $_COOKIE[self::COOKIE_NAME]) {
      unset($_SESSION['user_id']);
      $router->setResponseCookie(
        self::COOKIE_NAME, '', 0, true, true, // delete it
        getenv('HTTP_HOST'), '/'
      );
    }
  }

}

Change session cookie ttl to 1 month

Change session cookie ttl to 1 month


<?php

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

namespace Symfony\Component\Security\Tests\Core\Util;

use Symfony\Component\Security\Core\Util\StringUtils;

class StringUtilsTest extends \PHPUnit_Framework_TestCase
{
    public function testEquals()
    {
        $this->assertTrue(StringUtils::equals('password', 'password'));
        $this->assertFalse(StringUtils::equals('password', 'foo'));
    }
}

<?php

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

namespace Symfony\Component\Security\Tests\Core\Util;

use Symfony\Component\Security\Core\Util\StringUtils;

/**
 * Data from PHP.net's hash_equals tests
 */
class StringUtilsTest extends \PHPUnit_Framework_TestCase
{
    public function dataProviderTrue()
    {
        return array(
            array('same', 'same'),
            array('', ''),
            array(123, 123),
            array(null, ''),
            array(null, null),
        );
    }

    public function dataProviderFalse()
    {
        return array(
            array('not1same', 'not2same'),
            array('short', 'longer'),
            array('longer', 'short'),
            array('', 'notempty'),
            array('notempty', ''),
            array(123, 'NaN'),
            array('NaN', 123),
            array(null, 123),
        );
    }

    /**
     * @dataProvider dataProviderTrue
     */
    public function testEqualsTrue($known, $user)
    {
        $this->assertTrue(StringUtils::equals($known, $user));
    }

    /**
     * @dataProvider dataProviderFalse
     */
    public function testEqualsFalse($known, $user)
    {
        $this->assertFalse(StringUtils::equals($known, $user));
    }
}

Add more tests for StringUtils::equals

[Security] Add more tests for StringUtils::equals


<?php

final class PhabricatorAuthAuthProviderPHIDType extends PhabricatorPHIDType {

  const TYPECONST = 'AUTH';

  public function getTypeName() {
    return pht('Auth Provider');
  }

  public function newObject() {
    return new PhabricatorAuthProviderConfig();
  }

  public function getPHIDTypeApplicationClass() {
    return 'PhabricatorAuthApplication';
  }

  protected function buildQueryForObjects(
    PhabricatorObjectQuery $query,
    array $phids) {

    return id(new PhabricatorAuthProviderConfigQuery())
      ->withPHIDs($phids);
  }

  public function loadHandles(
    PhabricatorHandleQuery $query,
    array $handles,
    array $objects) {

    foreach ($handles as $phid => $handle) {
      $provider = $objects[$phid];

      $handle->setName($provider->getProviderName());
    }
  }

}

<?php

final class PhabricatorAuthAuthProviderPHIDType extends PhabricatorPHIDType {

  const TYPECONST = 'AUTH';

  public function getTypeName() {
    return pht('Auth Provider');
  }

  public function newObject() {
    return new PhabricatorAuthProviderConfig();
  }

  public function getPHIDTypeApplicationClass() {
    return 'PhabricatorAuthApplication';
  }

  protected function buildQueryForObjects(
    PhabricatorObjectQuery $query,
    array $phids) {

    return id(new PhabricatorAuthProviderConfigQuery())
      ->withPHIDs($phids);
  }

  public function loadHandles(
    PhabricatorHandleQuery $query,
    array $handles,
    array $objects) {

    foreach ($handles as $phid => $handle) {
      $provider = $objects[$phid]->getProvider();

      if ($provider) {
        $handle->setName($provider->getProviderName());
      }
    }
  }

}

Fix an issue with AuthProviderConfig handles

Summary: Fixes T11156. These were never correct, but also never actually used until I made timelines load object handles unconditionally in D16111.

Test Plan: Viewed an auth provider with transactions, no more fatal.

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T11156

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


<?php
/**
 * Checks current directory for a running Vagrant virtual machine
 *
 * Author: John Kary <john@johnkary.net>
 */
$cwd = getcwd();
$filecontents = getVagrantFileRunningInDir($cwd);

if (false === $filecontents) {
    // No vagrant file in this dir
    exit(1);
}

$uuid = getDirVagrantUuid($filecontents);
$runningVms = getRunningVms();

if (!isVmRunning($runningVms, $uuid)) {
    // VM not running
    exit(1);
}

// VM running
exit(0);

function getVagrantFileRunningInDir($dir)
{
    $path = realpath($dir . '/.vagrant');

    if (false === $path) {
        // File with UUID doesn't exist
        return false;
    }

    return file_get_contents($path);
}
function getDirVagrantUuid($filecontents)
{
    $vagrantJson = json_decode($filecontents);

    return $vagrantJson->active->default;
}
function getRunningVms()
{
    exec('vboxmanage list runningvms', $output);

    return $output;
}
function isVmRunning($runningVms, $uuid)
{
    return (bool) strstr(implode(' ', $runningVms), $uuid);
}

<?php
/**
 * Checks current directory for a running Vagrant virtual machine
 *
 * Author: John Kary <john@johnkary.net>
 */
$cwd = getcwd();
$uuid = getVagrantUuidInDir($cwd);

if (false === $uuid) {
    // No vagrant file in this dir
    exit(1);
}

$runningVms = getRunningVms();
if (!isVmRunning($runningVms, $uuid)) {
    // VM not running
    exit(1);
}

// VM running
exit(0);

function getVagrantUuidInDir($dir)
{
    $path = realpath($dir . '/.vagrant/machines/default/virtualbox/id');

    if (false === $path) {
        // File with UUID doesn't exist
        return false;
    }

    return file_get_contents($path);
}
function getRunningVms()
{
    exec('vboxmanage list runningvms', $output);

    return $output;
}
function isVmRunning($runningVms, $uuid)
{
    return (bool) strstr(implode(' ', $runningVms), $uuid);
}

Update for compatibility with Vagrant 1.2

1.2 changed how the box UUID was written to the filesystem. Instead of
JSON it's now written as a single file .vagrant/machines/default/virtualbox/id


<?php

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

class CreateMentionsPostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('mentionsPosts', function (Blueprint $table) {
            $table->integer('post_id')->unsigned();
            $table->integer('mentions_id')->unsigned();
            $table->primary(['post_id', 'mentions_id']);
        });
    }

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

<?php

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

class CreateMentionsPostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('mentions_posts', function (Blueprint $table) {
            $table->integer('post_id')->unsigned();
            $table->integer('mentions_id')->unsigned();
            $table->primary(['post_id', 'mentions_id']);
        });
    }

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

Fix mistake in table name

Fix mistake in table name


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Bundle\CoreBundle\Doctrine\ORM\Handler;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\ORMException;
use Sylius\Bundle\ResourceBundle\Controller\ResourceDeleteHandlerInterface;
use Sylius\Component\Resource\Exception\DeleteHandlingException;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

final class ResourceDeleteHandler implements ResourceDeleteHandlerInterface
{
    /** @var ResourceDeleteHandlerInterface */
    private $decoratedHandler;

    /** @var EntityManagerInterface */
    private $entityManager;

    public function __construct(ResourceDeleteHandlerInterface $decoratedHandler, EntityManagerInterface $entityManager)
    {
        $this->decoratedHandler = $decoratedHandler;
        $this->entityManager = $entityManager;
    }

    /**
     * @throws DeleteHandlingException
     */
    public function handle(ResourceInterface $resource, RepositoryInterface $repository): void
    {
        $this->entityManager->beginTransaction();

        try {
            $this->decoratedHandler->handle($resource, $repository);

            $this->entityManager->commit();
        } catch (ORMException $exception) {
            $this->entityManager->rollback();

            throw new DeleteHandlingException();
        }
    }
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Bundle\CoreBundle\Doctrine\ORM\Handler;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\ORMException;
use Sylius\Bundle\ResourceBundle\Controller\ResourceDeleteHandlerInterface;
use Sylius\Component\Resource\Exception\DeleteHandlingException;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

final class ResourceDeleteHandler implements ResourceDeleteHandlerInterface
{
    /** @var ResourceDeleteHandlerInterface */
    private $decoratedHandler;

    /** @var EntityManagerInterface */
    private $entityManager;

    public function __construct(ResourceDeleteHandlerInterface $decoratedHandler, EntityManagerInterface $entityManager)
    {
        $this->decoratedHandler = $decoratedHandler;
        $this->entityManager = $entityManager;
    }

    /**
     * @throws DeleteHandlingException
     */
    public function handle(ResourceInterface $resource, RepositoryInterface $repository): void
    {
        $this->entityManager->beginTransaction();

        try {
            $this->decoratedHandler->handle($resource, $repository);

            $this->entityManager->commit();
        } catch (ORMException $exception) {
            $this->entityManager->rollback();

            throw new DeleteHandlingException(
                'Ups, something went wrong during deleting a resource, please try again.',
                'something_went_wrong_error',
                500,
                0,
                $exception
            );
        }
    }
}

Add previous exception to DeleteHandlingException


<?php

namespace Craft;

/**
 * YouTube Video Model.
 *
 * Contains video data.
 *
 * @author    Bob Olde Hampsink <b.oldehampsink@itmundi.nl>
 * @copyright Copyright (c) 2015, Itmundi
 * @license   MIT
 *
 * @link      http://github.com/boboldehampsink
 */
class YouTube_VideoModel extends BaseModel
{
    /**
     * YouTube Embed URL prefix.
     */
    const YOUTUBE_EMBED_PREFIX = 'https://www.youtube.com/embed/';

    /**
     * YouTube Watch URL prefix.
     */
    const YOUTUBE_WATCH_PREFIX = 'https://www.youtube.com/watch?v=';

    /**
     * Define model attributes.
     *
     * @return array
     */
    public function defineAttributes()
    {
        return array(
            'id' => AttributeType::String,
        );
    }

    /**
     * Return full YouTube (embed) url.
     *
     * @param bool $embed
     *
     * @return string
     */
    public function getUrl($embed = true)
    {
        if ($embed) {
            return self::YOUTUBE_EMBED_PREFIX.$this->id;
        } else {
            return self::YOUTUBE_WATCH_PREFIX.$this->id;
        }
    }
}

<?php

namespace Craft;

/**
 * YouTube Video Model.
 *
 * Contains video data.
 *
 * @author    Bob Olde Hampsink <b.oldehampsink@itmundi.nl>
 * @copyright Copyright (c) 2015, Itmundi
 * @license   MIT
 *
 * @link      http://github.com/boboldehampsink
 */
class YouTube_VideoModel extends BaseModel
{
    /**
     * YouTube Embed URL prefix.
     */
    const YOUTUBE_EMBED_PREFIX = 'https://www.youtube.com/embed/';

    /**
     * YouTube Watch URL prefix.
     */
    const YOUTUBE_WATCH_PREFIX = 'https://www.youtube.com/watch?v=';

    /**
     * Define model attributes.
     *
     * @return array
     */
    public function defineAttributes()
    {
        return array(
            'id' => AttributeType::String,
        );
    }

    /**
     * Return ID as string.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->id;
    }

    /**
     * Return full YouTube (embed) url.
     *
     * @param bool $embed
     *
     * @return string
     */
    public function getUrl($embed = true)
    {
        if ($embed) {
            return self::YOUTUBE_EMBED_PREFIX.$this->id;
        } else {
            return self::YOUTUBE_WATCH_PREFIX.$this->id;
        }
    }
}

Return video model ID as model's string representation


<?php

class CM_RenderAdapter_Page extends CM_RenderAdapter_Component {

    protected function _prepareViewResponse(CM_Frontend_ViewResponse $viewResponse) {
        $viewResponse->set('pageTitle', $this->fetchTitle());
    }

    /**
     * @return string|null
     */
    public function fetchDescription() {
        return $this->_fetchMetaTemplate('meta-description');
    }

    /**
     * @return string|null
     */
    public function fetchKeywords() {
        return $this->_fetchMetaTemplate('meta-keywords');
    }

    /**
     * @return string|null
     */
    public function fetchTitle() {
        return $this->_fetchMetaTemplate('title');
    }

    /**
     * @param string $templateName
     * @return string|null
     */
    protected function _fetchMetaTemplate($templateName) {
        $templatePath = $this->_getMetaTemplatePath($templateName);
        if (null === $templatePath) {
            return null;
        }
        return trim($this->getRender()->fetchTemplate($templatePath, $this->_getViewResponse()->getData()));
    }

    /**
     * @param string $templateName
     * @return string|null
     */
    protected function _getMetaTemplatePath($templateName) {
        $templatePath = $this->getRender()->getTemplatePath($this->_getView(), $templateName);
        if (null === $templatePath) {
            $templatePath = $this->getRender()->getLayoutPath('Page/Abstract/' . $templateName . '.tpl', null, null, null, false);
        }
        return $templatePath;
    }
}

<?php

class CM_RenderAdapter_Page extends CM_RenderAdapter_Component {

    protected function _prepareViewResponse(CM_Frontend_ViewResponse $viewResponse) {
        $viewResponse->set('pageTitle', $this->fetchTitle());
    }

    /**
     * @return string|null
     */
    public function fetchDescription() {
        return $this->_fetchMetaTemplate('meta-description');
    }

    /**
     * @return string|null
     */
    public function fetchKeywords() {
        return $this->_fetchMetaTemplate('meta-keywords');
    }

    /**
     * @return string|null
     */
    public function fetchTitle() {
        return $this->_fetchMetaTemplate('title');
    }

    /**
     * @param string $templateName
     * @return string|null
     */
    protected function _fetchMetaTemplate($templateName) {
        $templatePath = $this->_getMetaTemplatePath($templateName);
        if (null === $templatePath) {
            return null;
        }
        $this->_getPage()->checkAccessible($this->getRender()->getEnvironment());
        $html = $this->getRender()->fetchTemplate($templatePath, $this->_getViewResponse()->getData());
        return trim($html);
    }

    /**
     * @param string $templateName
     * @return string|null
     */
    protected function _getMetaTemplatePath($templateName) {
        $templatePath = $this->getRender()->getTemplatePath($this->_getView(), $templateName);
        if (null === $templatePath) {
            $templatePath = $this->getRender()->getLayoutPath('Page/Abstract/' . $templateName . '.tpl', null, null, null, false);
        }
        return $templatePath;
    }

    /**
     * @return CM_Page_Abstract
     */
    private function _getPage() {
        return $this->_getView();
    }
}

Call "checkAccessible()" before rendering any page templates

To prevent that we render for example "title.tpl" which might access $viewer, for whose existance we chek in checkAccessible


<?php
/* Development */
define('SAVEQUERIES', true);
define('WP_DEBUG', true);
define('SCRIPT_DEBUG', true);

<?php
/* Development */
define('SAVEQUERIES', true);
define('WP_DEBUG', false);
define('SCRIPT_DEBUG', false);

Disable WP debug for dvelopment environment


</body>
<script src="assets/js/app.min.js" charset="utf-8"></script>
</html>

  <script src="assets/js/app.min.js" charset="utf-8"></script>
</body>
</html>

Move app.min.js above closing body tag

Move app.min.js above closing body tag


<?php
namespace Bolt\Database\Table;

class ContentType extends BaseTable
{
    /**
     * {@inheritdoc}
     */
    protected function addColumns()
    {
        // @codingStandardsIgnoreStart
        $this->table->addColumn('id',             'integer',  ['autoincrement' => true]);
        $this->table->addColumn('slug',           'string',   ['length' => 128]);
        $this->table->addColumn('datecreated',    'datetime', []);
        $this->table->addColumn('datechanged',    'datetime', []);
        $this->table->addColumn('datepublish',    'datetime', ['notnull' => false, 'default' => null]);
        $this->table->addColumn('datedepublish',  'datetime', ['notnull' => false, 'default' => null]);
        $this->table->addColumn('templatefields', 'text',     ['default' => '']);
        $this->table->addColumn('username',       'string',   ['length' => 32, 'default' => '', 'notnull' => false]); // We need to keep this around for backward compatibility. For now.
        $this->table->addColumn('ownerid',        'integer',  ['notnull' => false]);
        $this->table->addColumn('status',         'string',   ['length' => 32]);
        // @codingStandardsIgnoreEnd
    }

    /**
     * {@inheritdoc}
     */
    protected function addIndexes()
    {
        $this->table->addIndex(['slug']);
        $this->table->addIndex(['datecreated']);
        $this->table->addIndex(['datechanged']);
        $this->table->addIndex(['datepublish']);
        $this->table->addIndex(['datedepublish']);
        $this->table->addIndex(['status']);
    }

    /**
     * {@inheritdoc}
     */
    protected function setPrimaryKey()
    {
        $this->table->setPrimaryKey(['id']);
    }
}

Move the default contenttype table definition into a class


<?php

function debug_collectionInfoStart($debug, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Collecting data\n", $log);
    }
}

function debug_collectionInfoEnd($debug, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Finished collecting data\n\n", $log);
    }
}

function debug_collectionInterval($debug, $interval, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Collecting data every " . $interval . " seconds\n\n", $log);
    }
}

function debug($echo, $log) {

    if ($echo != "" && $echo !== NULL) {
        echo $echo;
    }

    if ($log == TRUE) {
    	if (!file_exists("logs/debug.log")) {
    		$dbglog = fopen("logs/debug.log", "w");
			fclose($dbglog);
    	}

        file_put_contents("logs/debug.log", date("r") . "  -  " . $echo, FILE_APPEND);
    }
}
?>

<?php

function debug_collectionInfoStart($debug, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Collecting data\n", $log);
    }
}

function debug_collectionInfoEnd($debug, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Finished collecting data\n\n", $log);
    }
}

function debug_collectionInterval($debug, $interval, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Collecting data every " . $interval . " seconds\n\n", $log);
    }
}

function debug($echo, $log) {

    if ($echo != "" && $echo !== NULL) {
        echo $echo;
    }

    if ($log == TRUE) {
    	if (!file_exists("logs/debug.log")) {
    		mkdir("logs");
    		$dbglog = fopen("logs/debug.log", "w");
			fclose($dbglog);
    	}

        file_put_contents("logs/debug.log", date("r") . "  -  " . $echo, FILE_APPEND);
    }
}
?>

Make logs dir if missing

Make logs dir if missing


<?php

namespace Omnipay\WeChat\Message;

use Symfony\Component\HttpFoundation\ParameterBag;

class WechatPurchaseRequest extends BaseAbstractRequest
{
    public function initialize(array $parameters = array())
    {
        if (null !== $this->response) {
            throw new \RuntimeException('Request cannot be modified after it has been sent!');
        }

        $this->parameters = new ParameterBag;
        foreach ($parameters as $k => $v) {
            $this->parameters->set($k, $v);
        }
        return $this;
    }

    public function getData()
    {
        $this->validate('code_url', 'timestamp');

        $params['code_url'] = $this->parameters->get('code_url');
        $params['timestamp'] = $this->parameters->get('timestamp');

        if (empty($params['code_url'])) {
            throw new \RuntimeException('The code_url that pre-purchase responded is empty, check your parameters!');
        }

        return $params;
    }

    public function sendData($data)
    {
        return new WechatPurchaseResponse($this, $data);
    }
}

<?php

namespace Omnipay\WeChat\Message;

use Symfony\Component\HttpFoundation\ParameterBag;

class WechatPurchaseRequest extends BaseAbstractRequest
{
    public function initialize(array $parameters = array())
    {
        if (null !== $this->response) {
            throw new \RuntimeException('Request cannot be modified after it has been sent!');
        }

        $this->parameters = new ParameterBag;
        foreach ($parameters as $k => $v) {
            $this->parameters->set($k, $v);
        }
        return $this;
    }

    public function getData()
    {
        $this->validate('code_url');

        $params['code_url'] = $this->parameters->get('code_url');

        if (empty($params['code_url'])) {
            throw new \RuntimeException('The code_url that pre-purchase responded is empty, check your parameters!');
        }

        return $params;
    }

    public function sendData($data)
    {
        return new WechatPurchaseResponse($this, $data);
    }
}

Revert "Return timestamp from pre-purchase"

This reverts commit 4e279ff4535dfa0636a3d6af5c92b8e9dcc4311a.