<?php

namespace AmpProject;

use AmpProject\Tests\TestCase;

/**
 * Tests for AmpProject\CssLength.
 *
 * @todo   This is only a stub and basic smoke test, more tests need to be added here, as the plugin didn't have any.
 *
 * @covers \AmpProject\CssLength
 * @package ampproject/amp-toolbox
 */
class CssLengthTest extends TestCase
{

    /**
     * Test instantiating empty CssLength.
     *
     * @covers \AmpProject\CssLength::__construct()
     * @covers \AmpProject\CssLength::isValid()
     * @covers \AmpProject\CssLength::isDefined()
     */
    public function testEmptyCssLengthIsValidButNotDefined()
    {
        $length = new CssLength(null);
        $this->assertTrue($length->isValid());
        $this->assertFalse($length->isDefined());
    }
}

<?php

namespace AmpProject;

use AmpProject\Tests\TestCase;

/**
 * Tests for AmpProject\CssLength.
 *
 * @todo   This is only a stub and basic smoke test, more tests need to be added here, as the plugin didn't have any.
 *
 * @covers \AmpProject\CssLength
 * @package ampproject/amp-toolbox
 */
class CssLengthTest extends TestCase
{

    public function dataCssLength()
    {
        return [
            'empty'            => [null, false, false, true, false, false, false],
            'allowed auto'     => ['auto', true, false, true, true, true, false],
            'disallowed auto'  => ['auto', false, false, false, true, true, false],
            'allowed fluid'    => ['fluid', false, true, true, true, false, true],
            'disallowed fluid' => ['fluid', false, false, false, true, false, true],
            '10px'             => ['10px', false, false, true, true, false, false],
        ];
    }

    /**
     * Test CssLength.
     *
     * @dataProvider dataCssLength()
     */
    public function testCssLength($value, $allowAuto, $allowFluid, $valid, $defined, $auto, $fluid)
    {
        $length = new CssLength($value);
        $length->validate($allowAuto, $allowFluid);

        $this->assertEquals($valid, $length->isValid());
        $this->assertEquals($defined, $length->isDefined());
        $this->assertEquals($fluid, $length->isFluid());
        $this->assertEquals($auto, $length->isAuto());
    }
}

Add missing test scenarios for CssLength.php


<?php

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

class CreateCoinDataCodesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('coin_data_codes', function (Blueprint $table) {
            $table->increments('id');
            $table->string('uid', 6)->unique();
            $table->string('code', 20);
            $table->integer('coin_data_id')->unsigned();
            $table->integer('coin_data_provider')->unsigned();
        });
    }

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

<?php

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

class CreateCoinDataCodesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('coin_data_codes', function (Blueprint $table) {
            $table->increments('id');
            $table->string('uid', 6)->unique();
            $table->string('code', 20);
            $table->integer('coin_data_name_id')->unsigned();
            $table->integer('coin_data_provider_id')->unsigned();
        });
    }

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

Update table name to match previous refactor


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

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

passthru('./vendor/bin/phpcs --standard=PSR1 -n src tests *.php', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

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

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

$phpcsCLI = new PHP_CodeSniffer_CLI();
$phpcsArguments = array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'), 'warningSeverity' => 0);
$phpcsViolations = $phpcsCLI->process($phpcsArguments);
if ($phpcsViolations > 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

Use phpcs as a library.

Use phpcs as a library.


<?php
function GetAuctionData($gameID){
    $data = json_decode(file_get_contents('https://www.g2a.com/marketplace/product/auctions/?id=' . $gameID), true);
    $data = array_values(array_values($data)[0])[0];
    $result = array();
    $result['price'] = $data['p'];
    $result['rating'] = $data['r'];
    $result['sells'] = $data['tr'];
    $result['country'] = GetCountry($data['c']);
    return $result;
}

function GetCountry($code){
    $data = json_decode(file_get_contents('http://restcountries.eu/rest/v1/alpha/' . $code), true);
    return $data['name'];
}
function GetLowestPrice($gameID){
    $data = GetAuctionData($gameID);
    return $data[0];
}

/* Finds a game's entity ID (needed for using the G2A API) by extracting it from the game's page on G2A */
function GetGameEntityID($gameURL){
    $gameSite = file_get_contents($gameURL);
    /* Find the game's ID in the page's HTML */
    preg_match("/(?<=productID = )(.*)(?=;)/", $gameSite, $entityID);
    if (count($entityID) >= 1){
        return $entityID[0];
    } else {
        return false;
    }
}
function IsPriceLowEnough($price, $limit){
    return $price <= $limit;
}
?>

<?php
function GetAuctionData($gameID){
    $data = json_decode(file_get_contents('https://www.g2a.com/marketplace/product/auctions/?id=' . $gameID), true);
    $data = array_values(array_values($data)[0])[0];
    $result = array();
    $result['price'] = (float) $data['p'];
    $result['rating'] = $data['r'];
    $result['sells'] = $data['tr'];
    $result['country'] = GetCountry($data['c']);
    return $result;
}

function GetCountry($code){
    $data = json_decode(file_get_contents('http://restcountries.eu/rest/v1/alpha/' . $code), true);
    return $data['name'];
}
function GetLowestPrice($gameID){
    $data = GetAuctionData($gameID);
    return $data[0];
}

/* Finds a game's entity ID (needed for using the G2A API) by extracting it from the game's page on G2A */
function GetGameEntityID($gameURL){
    $gameSite = file_get_contents($gameURL);
    /* Find the game's ID in the page's HTML */
    preg_match("/(?<=productID = )(.*)(?=;)/", $gameSite, $entityID);
    if (count($entityID) >= 1){
        return $entityID[0];
    } else {
        return false;
    }
}
function IsPriceLowEnough($price, $limit){
    return $price <= $limit;
}
?>

Convert price to float to compare

Convert price to float to compare


<?php

class ViewData
{
    /**
     * @var int $time
     */
    private $time;

    /**
     * @var float $distance
     */
    private $distance;

    const SPEED_PRECISION = 2;

    public function __construct()
    {
        $this->time = $_POST['time'];
        $this->distance = $_POST['distance'];
    }

    /**
     * @return int
     */
    public function getTime(): int
    {
        return $this->time;
    }

    /**
     * @return float
     */
    public function getDistance(): float
    {
        return $this->distance;
    }

    /**
     * @return bool
     */
    public function hasSentData(): bool
    {
        return isset($this->time) && isset($this->distance);
    }

    /**
     * @return string
     */
    public function getAveragePace(): string
    {
        return $this->decimalToMinuteString($this->time / $this->distance);
    }

    /**
     * @return string
     */
    public function getAverageSpeed(): string
    {
        return round($this->distance / ($this->time / 60), self::SPEED_PRECISION);
    }

    /**
     * @param float $timeAsDecimal
     * @return string
     */
    private function decimalToMinuteString(float $timeAsDecimal): string
    {
        $whole = floor($timeAsDecimal);
        $decimal = $timeAsDecimal - $whole;
        $roundedMinutes = round($decimal * 60, 0);
        $minutes = str_pad($roundedMinutes, 2, "0", STR_PAD_LEFT);

        return "{$whole}:{$minutes}";
    }
}

<?php

class ViewData
{
    /**
     * @var int $time
     */
    private $time;

    /**
     * @var float $distance
     */
    private $distance;

    const SPEED_PRECISION = 2;

    public function __construct()
    {
        $this->time = $_POST['time'];
        $this->distance = $_POST['distance'];
    }

    /**
     * @return int
     */
    public function getTime(): ?int
    {
        return $this->time;
    }

    /**
     * @return float
     */
    public function getDistance(): ?float
    {
        return $this->distance;
    }

    /**
     * @return bool
     */
    public function hasSentData(): bool
    {
        return isset($this->time) && isset($this->distance);
    }

    /**
     * @return string
     */
    public function getAveragePace(): string
    {
        return $this->decimalToMinuteString($this->time / $this->distance);
    }

    /**
     * @return string
     */
    public function getAverageSpeed(): string
    {
        return round($this->distance / ($this->time / 60), self::SPEED_PRECISION);
    }

    /**
     * @param float $timeAsDecimal
     * @return string
     */
    private function decimalToMinuteString(float $timeAsDecimal): string
    {
        $whole = floor($timeAsDecimal);
        $decimal = $timeAsDecimal - $whole;
        $roundedMinutes = round($decimal * 60, 0);
        $minutes = str_pad($roundedMinutes, 2, "0", STR_PAD_LEFT);

        return "{$whole}:{$minutes}";
    }
}

Change time and distance getter return types to be nullable


<?php

use Mockery as m;
use Samrap\Validation\Validator;

class ValidatorTest extends PHPUnit_Framework_TestCase
{
    public function tearDown()
    {
        m::close();
    }

    public function testValidatorPasses()
    {
        $validator = $this->getValidator();

        $rules = ['foo' => 'bar'];
        $this->assertEmpty($validator->validate($rules)->errors());
    }

    public function testValidatorFails()
    {
        $errors = ['foo' => 'baz'];
        $validator = $this->getValidator($errors);

        $rules = ['foo' => 'bar'];
        $this->assertEquals($errors, $validator->validate($rules)->errors());
    }

    protected function getValidator($errors = [])
    {
        $laravelValidator = m::mock('\Illuminate\Validation\Validator');
        $laravelValidator->shouldReceive('errors')->andReturn($errors);

        $factory = m::mock('Illuminate\Validation\Factory');
        $factory->shouldReceive('make')->andReturn($laravelValidator);

        $validator = new Validator($factory);

        return $validator;
    }
}

<?php

use Mockery as m;
use Samrap\Validation\Validator;

class ValidatorTest extends PHPUnit_Framework_TestCase
{
    public function tearDown()
    {
        m::close();
    }

    public function testValidatorPasses()
    {
        $validator = $this->getValidator();

        $rules = ['foo' => 'bar'];
        $this->assertEmpty($validator->validate($rules)->errors());
    }

    public function testValidatorFails()
    {
        $errors = ['foo' => 'baz'];
        $validator = $this->getValidator($errors);

        $rules = ['foo' => 'bar'];
        $this->assertEquals($errors, $validator->validate($rules)->errors());
    }

    protected function getValidator($errors = [])
    {
        $laravelValidator = m::mock('\Illuminate\Validation\Validator');
        $laravelValidator->shouldReceive('errors')->andReturn($errors);

        $factory = m::mock('Illuminate\Validation\Factory');
        $factory->shouldReceive('make')->andReturn($laravelValidator);

        $validator = new Validator($factory);
        $validator->rules = ['foo' => 'bar'];

        return $validator;
    }
}

Modify tests to implement the required rules property.


<?php

/*
 * User Login for CouchCMS (https://github.com/cheesypoof/UserLoginForCouchCMS)
 * Copyright (c) 2014 Increment Web Services (http://incrementwebservices.com/)
 * Released under the MIT License (https://github.com/cheesypoof/UserLoginForCouchCMS/blob/master/LICENSE)
 */

if ( !defined( 'K_ADMIN' ) ) {
	require_once( K_COUCH_DIR . '/addons/password-compatibility.php' );

	// Password hashing strength
	// Leave this alone
	define( 'USER_PASSWORD_HASH_COST_FACTOR', '10' );

	// Life of remember cookies
	// 2 weeks in seconds
	define( 'USER_REMEMBER_COOKIE_EXPIRE', 1209600 );

	// Enter a random value to make your remember cookies more secure
	// Changing this invalidates all remember cookies
	define( 'USER_REMEMBER_COOKIE_SECRET_KEY', '3]UbHj!Q=E?cNN}B(@P,&x(t' );

	// Start session
	if ( !session_id() )
		@session_start();

	// Check if visitor is logged in or trying to log in with remember cookie
	if ( isset( $_SESSION['user_id'] ) || isset( $_COOKIE['remember'] ) ) {
		define( 'AUTHENTICATE', isset( $_SESSION['user_id'] ) ? 'session' : 'cookie' );

		// Prevent Couch caching
		$_GET['nc'] = 1;
	}
}

<?php

/*
 * User Login for CouchCMS (https://github.com/cheesypoof/UserLoginForCouchCMS)
 * Copyright (c) 2014 Increment Web Services (http://incrementwebservices.com/)
 * Released under the MIT License (https://github.com/cheesypoof/UserLoginForCouchCMS/blob/master/LICENSE)
 */

if ( !defined( 'K_ADMIN' ) ) {
	require_once( K_COUCH_DIR . '/addons/password-compatibility.php' );

	// Password hashing strength
	// Leave this alone
	define( 'USER_PASSWORD_HASH_COST_FACTOR', 10 );

	// Life of remember cookies
	// 2 weeks in seconds
	define( 'USER_REMEMBER_COOKIE_EXPIRE', 1209600 );

	// Enter a random value to make your remember cookies more secure
	// Changing this invalidates all remember cookies
	define( 'USER_REMEMBER_COOKIE_SECRET_KEY', '3]UbHj!Q=E?cNN}B(@P,&x(t' );

	// Start session
	if ( !session_id() )
		@session_start();

	// Check if visitor is logged in or trying to log in with remember cookie
	if ( isset( $_SESSION['user_id'] ) || isset( $_COOKIE['remember'] ) ) {
		define( 'AUTHENTICATE', isset( $_SESSION['user_id'] ) ? 'session' : 'cookie' );

		// Prevent Couch caching
		$_GET['nc'] = 1;
	}
}

Use an integer for hash cost factor

Use an integer for hash cost factor


@extends('panelViews::mainTemplate')
@section('page-wrapper')

@if(Session::has('message'))

{{ Session::get('message') }}

@endif

@if ($demo_status == true)

You are not allowed to change the password in demo version of panel.

@else

			<form action="{{ action('\Serverfireteam\Panel\RemindersController@postChangePassword') }}" method="POST">
				Email Address: <input class="form-control" type="email" name="email">

				{{ \Lang::get('panel::fields.currentPassword') }}
				<input class="form-control" type="password" name="current_password">

				{{ \Lang::get('panel::fields.password') }} <input  class="form-control" type="password" name="password">

				{{ \Lang::get('panel::fields.rePassword') }}
				<input class="form-control" type="password" name="password_confirmation">

				<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
				<input class="btn btn-default" type="submit" value="{{ \Lang::get('panel::fields.ChangePassword') }}">
			</form>

@endif
@stop

@extends('panelViews::mainTemplate')
@section('page-wrapper')

@if(Session::has('message'))

{{ Session::get('message') }}

@endif

@if ($demo_status == true)

You are not allowed to change the password in demo version of panel.

@else

			<form action="{{ action('\Serverfireteam\Panel\RemindersController@postChangePassword') }}" method="POST">
				{{ \Lang::get('panel::fields.emailAddress') }} <input class="form-control" type="email" name="email">

				{{ \Lang::get('panel::fields.currentPassword') }}
				<input class="form-control" type="password" name="current_password">

				{{ \Lang::get('panel::fields.password') }} <input  class="form-control" type="password" name="password">

				{{ \Lang::get('panel::fields.rePassword') }}
				<input class="form-control" type="password" name="password_confirmation">

				<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
				<input class="btn btn-default" type="submit" value="{{ \Lang::get('panel::fields.ChangePassword') }}">
			</form>

@endif
@stop

Set Email Address string to be read from l10n


<?php

namespace Spraed\PDFGeneratorBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();

        $rootNode = $treeBuilder->root('spraed_pdf_generator');

        $rootNode->children()
            ->arrayNode('java')
            ->children()
            ->scalarNode('full_pathname')->defaultValue('')->end()
            ->end()
            ->end() // java
            ->end();

        return $treeBuilder;
    }
}

<?php

namespace Spraed\PDFGeneratorBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('spraed_pdf_generator');

        $treeBuilder->getRootNode()
            ->children()
            ->arrayNode('java')
            ->children()
            ->scalarNode('full_pathname')->defaultValue('')->end()
            ->end()
            ->end() // java
            ->end();

        return $treeBuilder;
    }
}

Set root name in constructor of TreeBuilder


<?php

namespace Blablacar\RedisBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    /**
     * Generates the configuration tree.
     *
     * @return TreeBuilder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('blablacar_redis');

        $rootNode
            ->children()
                ->arrayNode('clients')
                    ->isRequired()
                    ->requiresAtLeastOneElement()
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('host')->defaultValue('127.0.0.1')->cannotBeEmpty()->end()
                            ->integerNode('port')->defaultValue(6379)->cannotBeEmpty()->end()
                            ->integerNode('base')->treatNullLike(0)->defaultValue(0)->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('session')
                    ->canBeUnset()
                    ->children()
                        ->scalarNode('client')->isRequired()->end()
                        ->scalarNode('prefix')->defaultValue('session')->cannotBeEmpty()->end()
                        ->integerNode('ttl')->end()
                        ->integerNode('spin_lock_wait')->defaultValue(150000)->end()
                        ->integerNode('lock_max_wait')->defaultValue(500000)->end()
                    ->end()
                ->end()
                ->booleanNode('enable_logger')->defaultTrue()->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

<?php

namespace Blablacar\RedisBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    /**
     * Generates the configuration tree.
     *
     * @return TreeBuilder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('blablacar_redis');

        $rootNode
            ->children()
                ->arrayNode('clients')
                    ->isRequired()
                    ->requiresAtLeastOneElement()
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('host')->defaultValue('127.0.0.1')->cannotBeEmpty()->end()
                            ->integerNode('port')->defaultValue(6379)->end()
                            ->integerNode('base')->treatNullLike(0)->defaultValue(0)->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('session')
                    ->canBeUnset()
                    ->children()
                        ->scalarNode('client')->isRequired()->end()
                        ->scalarNode('prefix')->defaultValue('session')->cannotBeEmpty()->end()
                        ->integerNode('ttl')->end()
                        ->integerNode('spin_lock_wait')->defaultValue(150000)->end()
                        ->integerNode('lock_max_wait')->defaultValue(500000)->end()
                    ->end()
                ->end()
                ->booleanNode('enable_logger')->defaultTrue()->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

Remove cannotBeEmpty call on integernode


@inject('pages', 'BruceCms\Pages\Page')

			Home

		@foreach($pages->unhidden()->get() as $page)

				link) }}">{{ $page->title }}

		@endforeach

@inject('pages', 'BruceCms\Pages\Page')

		@foreach($pages->unhidden()->get() as $page)

				link) }}">{{ $page->title }}

		@endforeach

Remove home nav partial, since it's redundant now.


<?php

namespace BNETDocs\Views\Attachment;

use \CarlBennett\MVC\Libraries\Common;
use \BNETDocs\Libraries\Exceptions\IncorrectModelException;
use \BNETDocs\Libraries\Model;
use \BNETDocs\Libraries\View;
use \BNETDocs\Models\Attachment\Download as DownloadModel;
use \DateTime;

class DownloadRaw extends View {

  public function getMimeType() {
    return "application/octet-stream";
  }

  public function render(Model &$model) {
    if (!$model instanceof DownloadModel) {
      throw new IncorrectModelException();
    }
    $model->extra_headers = [
      "Content-Disposition" => "attachment;filename=\""
        . $model->attachment->getFilename() . "\"",
      "Last-Modified" => $model->attachment->getCreatedDateTime()->format(
        DateTime::RFC1123
      )
    ];
    echo $model->attachment->getContent();
  }

}

<?php

namespace BNETDocs\Views\Attachment;

use \CarlBennett\MVC\Libraries\Common;
use \BNETDocs\Libraries\Exceptions\IncorrectModelException;
use \BNETDocs\Libraries\Model;
use \BNETDocs\Libraries\View;
use \BNETDocs\Models\Attachment\Download as DownloadModel;
use \DateTime;

class DownloadRaw extends View {

  public function getMimeType() {
    return "application/octet-stream";
  }

  public function render(Model &$model) {
    if (!$model instanceof DownloadModel) {
      throw new IncorrectModelException();
    }
    $model->extra_headers = [
      "Content-Disposition" => "attachment;filename=\""
        . $model->attachment->getFilename() . "\"",
      "Content-Length" => (string) strlen($model->attachment->getContent()),
      "Last-Modified" => $model->attachment->getCreatedDateTime()->format(
        DateTime::RFC1123
      )
    ];
    echo $model->attachment->getContent();
  }

}

Add Content-Length header on attachment downloader


<?php
if ($app->has_error()) {
	foreach($app->get_all_errors() as $error) {
		echo "
$error
";
	}
}
?>

<?php
if (isset($app) && $app->has_error()) {
	foreach($app->get_all_errors() as $error) {
		echo "
$error
";
	}
}
?>

Check that we have an app object before using it


<?php

namespace phpSmug\Tests;

/**
 * @class
 * Test properties of our codebase rather than the actual code.
 */
class PsrComplianceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function testPSR()
    {
        // If we can't find the command-line tool, we mark the test as skipped
        // so it shows as a warning to the developer rather than passing silently.
        if (!file_exists('vendor/bin/php-cs-fixer')) {
            $this->markTestSkipped(
                'Needs linter to check PSR compliance'
            );
        }

        // Let's check all PSR compliance for our code and tests.
        // Add any other pass you want to test to this array.
        foreach (array('lib/', 'examples/', 'test/') as $path) {
            // Run linter in dry-run mode so it changes nothing.
            exec(
                escapeshellcmd('vendor/bin/php-cs-fixer fix --dry-run '.$_SERVER['PWD']."/$path"),
                $output,
                $return_var
            );

            // If we've got output, pop its first item ("Fixed all files...")
            // and trim whitespace from the rest so the below makes sense.
            if ($output) {
                array_pop($output);
                $output = array_map('trim', $output);
            }

            // Check shell return code: if nonzero, report the output as a failure.
            $this->assertEquals(
                0,
                $return_var,
                "PSR linter reported errors in $path: \n\t".implode("\n\t", $output)
            );
        }
    }
}

<?php

namespace phpSmug\Tests;

/**
 * @class
 * Test properties of our codebase rather than the actual code.
 */
class PsrComplianceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function testPSR()
    {
        // If we can't find the command-line tool, we mark the test as skipped
        // so it shows as a warning to the developer rather than passing silently.
        if (!file_exists('vendor/bin/php-cs-fixer')) {
            $this->markTestSkipped(
                'Needs linter to check PSR compliance'
            );
        }

        // Run linter in dry-run mode so it changes nothing.
        exec(
            escapeshellcmd('vendor/bin/php-cs-fixer fix --diff -v --dry-run .'),
            $output,
            $return_var
        );

        // If we've got output, pop its first item ("Fixed all files...")
        // shift off the last two lines, and trim whitespace from the rest.
        if ($output) {
            array_pop($output);
            array_shift($output);
            array_shift($output);
            $output = array_map('trim', $output);
        }

        // Check shell return code: if nonzero, report the output as a failure.
        $this->assertEquals(
            0,
            $return_var,
            "PSR linter reported errors in: \n\t".implode("\n\t", $output)
        );
    }
}

Improve PSR test to produce useful output


<?php
namespace Concrete\Core\Url\Components;

/**
 * c5 specific path component for league/url
 */
class Path extends \League\Url\Components\Path
{

    protected $trail = false;

    /**
     * @param \League\Url\Components\Path $old_path
     * @param bool                        $trailing_slash
     */
    public function __construct($data, $trailing_slash = false) {
        $this->set($data);
        $this->trail = !!$trailing_slash;
    }

    /**
     * {@inheritdoc}
     */
    public function get()
    {
        $res = array();
        foreach (array_values($this->data) as $value) {
            $res[] = rawurlencode($value);
        }
        if (!$res) {
            return null;
        }

        return implode($this->delimiter, $res) . (!!$this->trail ? '/' : '');
    }

    public function withoutDispatcher()
    {
        $path = clone $this;
        if ($path[0] == DISPATCHER_FILENAME) {
            $path->offsetUnset(0);
        }

        return $path;
    }

}

<?php
namespace Concrete\Core\Url\Components;

/**
 * c5 specific path component for league/url
 */
class Path extends \League\Url\Components\Path
{

    protected $trail = false;

    /**
     * @param \League\Url\Components\Path $old_path
     * @param bool                        $trailing_slash
     */
    public function __construct($data, $trailing_slash = false) {
        $this->set($data);
        $this->trail = !!$trailing_slash;
    }

    /**
     * {@inheritdoc}
     */
    public function get()
    {
        $res = array();
        foreach (array_values($this->data) as $value) {
            $res[] = rawurlencode($value);
        }
        if (!$res) {
            return null;
        }

        foreach ($res as $key => $value) {
            if ($value == '') {
                unset($res[$key]);
            }
        }

        return implode($this->delimiter, $res) . (!!$this->trail ? '/' : '');
    }

    public function withoutDispatcher()
    {
        $path = clone $this;
        if ($path[0] == DISPATCHER_FILENAME) {
            $path->offsetUnset(0);
        }

        return $path;
    }

}

Remove any empty nodes before combining into a path


<?php

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

namespace Surfnet\StepupBundle\Monolog\Processor;

use Surfnet\StepupBundle\Exception\Art;

class ArtProcessor
{
    /**
     * @param array $record
     * @return array
     */
    public function __invoke(array $record)
    {
        if (!isset($record['context']['exception'])) {
            return;
        }

        $record['extra']['art'] = Art::forException($record['context']['exception']);

        return $record;
    }
}

<?php

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

namespace Surfnet\StepupBundle\Monolog\Processor;

use Surfnet\StepupBundle\Exception\Art;

class ArtProcessor
{
    /**
     * @param array $record
     * @return array
     */
    public function __invoke(array $record)
    {
        if (!isset($record['context']['exception'])) {
            return $record;
        }

        $record['extra']['art'] = Art::forException($record['context']['exception']);

        return $record;
    }
}

Return $record in case of no exception.

Return $record in case of no exception.


<?php

class CM_AdproviderAdapter_Epom extends CM_AdproviderAdapter_Abstract {

    public function getHtml($zoneData, array $variables) {
        $zoneId = CM_Util::htmlspecialchars($zoneData['zoneId']);
        $variables = $this->_variableKeysToUnderscore($variables);
        $variables['key'] = '2ea5b261f06ca771033a5fa9e22493f1';

        $html = '

';
        return $html;
    }

    private function _variableKeysToUnderscore($variables) {
        foreach ($variables as $key => $value) {
            unset ($variables[$key]);
            $underscoreKey = str_replace('-', '_', $key);
            $variables[$underscoreKey] = $value;
        }
        return $variables;
    }
}

Clean obsolete epom key usage.

Clean obsolete epom key usage.


<?
/* Site-wide utility functions */

require_once('secureConstants.php');

function mysqliConn() {
	$db = new mysqli(
		$GLOBALS['DB']['SERVER'],
		$GLOBALS['DB']['USERNAME'],
		$GOLBALS['DB']['PASSWORD'],
		$GLOBALS['DB']['DATABASE']
	);

	if ($db->connect_errno) {
		header('HTTP/1.1 500 Internal Server Error');
		exit('Database connection failed. Contact system administrator. Error code: ' . $db->connect_errno);
	}

	return $db;
}

function pdoConn() {
	$dsn = "mysql:dbname={$GLOBALS['DB']['DATABASE']};host={$GLOBALS['DB']['SERVER']}";

	try {
		$db = new PDO($dsn, $GLOBALS['DB']['USERNAME'],	$GOLBALS['DB']['PASSWORD']);
	} catch (PDOException $e) {
		header('HTTP/1.1 500 Internal Server Error');
		exit('Database connection failed. Contact system administrator. Error code: ' . $e->getMessage());
	}

	return $db;
}

<?php
/* Site-wide utility functions */

require_once('secureConstants.php');

function mysqliConn() {
	$db = new mysqli(
		$GLOBALS['DB']['SERVER'],
		$GLOBALS['DB']['USERNAME'],
		$GOLBALS['DB']['PASSWORD'],
		$GLOBALS['DB']['DATABASE']
	);

	if ($db->connect_errno) {
		header('HTTP/1.1 500 Internal Server Error');
		exit('Database connection failed. Contact system administrator. Error code: ' . $db->connect_errno);
	}

	return $db;
}

function pdoConn() {
	$dsn = "mysql:dbname={$GLOBALS['DB']['DATABASE']};host={$GLOBALS['DB']['SERVER']}";

	try {
		$db = new PDO($dsn, $GLOBALS['DB']['USERNAME'],	$GOLBALS['DB']['PASSWORD']);
	} catch (PDOException $e) {
		header('HTTP/1.1 500 Internal Server Error');
		exit('Database connection failed. Contact system administrator. Error code: ' . $e->getMessage());
	}

	return $db;
}

Fix error that caused code output

Fix error that caused code output


<?php namespace Orchestra\Support\Traits;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Redirect;
use Orchestra\Support\Facades\Messages;

trait ControllerResponseTrait
{
    /**
     * Queue notification and redirect.
     *
     * @param  string  $to
     * @param  string  $message
     * @param  string  $type
     * @return Response
     */
    public function redirectWithMessage($to, $message = null, $type = 'success')
    {
        ! is_null($message) && Messages::add($type, $message);

        return $this->redirect($to);
    }

    /**
     * Queue notification and redirect.
     *
     * @param  string  $to
     * @param  mixed   $errors
     * @return Response
     */
    public function redirectWithErrors($to, $errors)
    {
        return $this->redirect($to)->withInput()->withErrors($errors);
    }

    /**
     * Redirect.
     *
     * @param  string  $to
     * @param  string  $message
     * @param  string  $type
     * @return Response
     */
    public function redirect($to)
    {
        return Redirect::to($to);
    }

    /**
     * Halt current request using App::abort().
     *
     * @param  integer $status
     * @return Response
     */
    public function suspend($status)
    {
        return App::abort($status);
    }
}

<?php namespace Orchestra\Support\Traits;

use Illuminate\Support\Facades\App;
use Orchestra\Support\Facades\Messages;
use Illuminate\Support\Facades\Redirect;
use Symfony\Component\HttpKernel\Exception\HttpException
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException

trait ControllerResponseTrait
{
    /**
     * Queue notification and redirect.
     *
     * @param  string  $to
     * @param  string  $message
     * @param  string  $type
     * @return mixed
     */
    public function redirectWithMessage($to, $message = null, $type = 'success')
    {
        ! is_null($message) && Messages::add($type, $message);

        return $this->redirect($to);
    }

    /**
     * Queue notification and redirect.
     *
     * @param  string  $to
     * @param  mixed   $errors
     * @return mixed
     */
    public function redirectWithErrors($to, $errors)
    {
        return $this->redirect($to)->withInput()->withErrors($errors);
    }

    /**
     * Redirect.
     *
     * @param  string  $to
     * @return mixed
     */
    public function redirect($to)
    {
        return Redirect::to($to);
    }

    /**
     * Halt current request using App::abort().
     *
     * @param  int  $code
     * @return void
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     */
    public function suspend($code)
    {
        if ($status == 404) {
            throw new NotFoundHttpException('');
        }

        throw new HttpException($code, '', null, []);
    }
}

Handle App::abort() no longer exist.

Handle App::abort() no longer exist.

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


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @since         3.7.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\TestSuite\Constraint\Response;

use Cake\Http\Response;

/**
 * HeaderEquals
 *
 * @internal
 */
class HeaderEquals extends ResponseBase
{
    /**
     * @var string
     */
    protected $headerName;

    /**
     * Constructor.
     *
     * @param Response $response Response
     * @param string $headerName Header name
     */
    public function __construct($response, $headerName)
    {
        parent::__construct($response);

        $this->headerName = $headerName;
    }

    /**
     * Checks assertion
     *
     * @param mixed $other Expected content
     * @return bool
     */
    public function matches($other)
    {
        return $this->response->getHeaderLine($this->headerName) === $other;
    }

    /**
     * Assertion message
     *
     * @return string
     */
    public function toString()
    {
        return sprintf('equals content in header \'%s\'', $this->headerName);
    }
}

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @since         3.7.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\TestSuite\Constraint\Response;

use Cake\Http\Response;

/**
 * HeaderEquals
 *
 * @internal
 */
class HeaderEquals extends ResponseBase
{
    /**
     * @var string
     */
    protected $headerName;

    /**
     * @var string|null
     */
    protected $responseHeader;

    /**
     * Constructor.
     *
     * @param Response $response Response
     * @param string $headerName Header name
     */
    public function __construct($response, $headerName)
    {
        parent::__construct($response);

        $this->headerName = $headerName;
        $this->responseHeader = $this->response->getHeaderLine($this->headerName);
    }

    /**
     * Checks assertion
     *
     * @param mixed $other Expected content
     * @return bool
     */
    public function matches($other)
    {
        return $this->responseHeader === $other;
    }

    /**
     * Assertion message
     *
     * @return string
     */
    public function toString()
    {
        return sprintf('equals content in header \'%s\': `%s`', $this->headerName, $this->responseHeader);
    }
}

Fix header comparison debug output

Fix header comparison debug output


<?php
require_once('commonfunction.php');
include_once (GLPI_ROOT . "/config/based_config.php");
include_once (GLPI_ROOT . "/inc/dbmysql.class.php");
include_once (GLPI_CONFIG_DIR . "/config_db.php");

class GLPIInstallTest extends PHPUnit_Framework_TestCase {

   /**
    * @test
    */
   public function installDatabase() {

      $DBvars = get_class_vars('DB');

      drop_database(
         $DBvars['dbuser'],
         $DBvars['dbhost'],
         $DBvars['dbdefault'],
         $DBvars['dbpassword']
      );

      $result = load_mysql_file(
         $DBvars['dbuser'],
         $DBvars['dbhost'],
         $DBvars['dbdefault'],
         $DBvars['dbpassword'],
         GLPI_ROOT ."/install/mysql/glpi-0.85.5-empty.sql"
      );

      $this->assertEquals( 0, $result['returncode'],
         "Failed to install GLPI database:\n".
         implode("\n", $result['output'])
      );

   }
}

<?php
require_once('commonfunction.php');
include_once (GLPI_ROOT . "/config/based_config.php");
include_once (GLPI_ROOT . "/inc/dbmysql.class.php");
include_once (GLPI_CONFIG_DIR . "/config_db.php");

class GLPIInstallTest extends PHPUnit_Framework_TestCase {

   /**
    * @test
    */
   public function installDatabase() {

      $DBvars = get_class_vars('DB');

      drop_database(
         $DBvars['dbuser'],
         $DBvars['dbhost'],
         $DBvars['dbdefault'],
         $DBvars['dbpassword']
      );

      $result = load_mysql_file(
         $DBvars['dbuser'],
         $DBvars['dbhost'],
         $DBvars['dbdefault'],
         $DBvars['dbpassword'],
         GLPI_ROOT ."/install/mysql/glpi-0.90-empty.sql"
      );

      $this->assertEquals( 0, $result['returncode'],
         "Failed to install GLPI database:\n".
         implode("\n", $result['output'])
      );

   }
}

Fix unit test for 0.90 version of GLPI

Fix unit test for 0.90 version of GLPI


<?php

namespace Xu\Foundation\Bootstrap;

// @codeCoverageIgnoreStart
use Xu\Foundation\Foundation;
use Xu\Facades\Facade;

// Load xu functions files.
// Please note that missing files will produce a fatal error.
$xu_files = require_once __DIR__ . '/files.php';

foreach ( $xu_files as $file ) {
    $file = __DIR__ . '/../../../src/' . $file;
    if ( file_exists( $file ) ) {
        require_once $file;
    } else {
        trigger_error( sprintf( __( 'Error locating %s for inclusion', 'xu' ), $file ), E_USER_ERROR );
    }
}

unset( $file );

/**
 * Load modules.
 */
function load_modules() {
    foreach ( glob( __DIR__ . '/../../modules/*.php' ) as $file ) {
        $feature = 'xu-' . basename( $file, '.php' );

        if ( current_theme_supports( $feature ) ) {
            require_once $file;
        }
    }
}
// @codeCoverageIgnoreEnd

<?php

namespace Xu\Foundation\Bootstrap;

// @codeCoverageIgnoreStart
use Xu\Foundation\Foundation;
use Xu\Facades\Facade;

// Load xu functions files.
// Please note that missing files will produce a fatal error.
$xu_files = require_once __DIR__ . '/files.php';

foreach ( $xu_files as $file ) {
    $file = __DIR__ . '/../../../src/' . $file;
    if ( file_exists( $file ) ) {
        require_once $file;
    } else {
        trigger_error( sprintf( __( 'Error locating %s for inclusion', 'xu' ), $file ), E_USER_ERROR );
    }
}

unset( $file );

/**
 * Load modules.
 */
function load_modules() {
    foreach ( glob( __DIR__ . '/../../modules/*.php' ) as $file ) {
        $feature = 'xu-' . basename( $file, '.php' );

        if ( current_theme_supports( $feature ) ) {
            require_once $file;
        }
    }
}

// Requires WordPress to be loaded.
if ( function_exists( 'add_action' ) ) {
    add_action( 'after_setup_theme', __NAMESPACE__ . '\\load_modules' );
}
// @codeCoverageIgnoreEnd

Add add_action only if it exists

Add add_action only if it exists


                            <a href="<?=Core::$basepath;?>">
                                Home

                    © , template made with by Creative Tim

Add new target blank for external link

Add new target blank for external link


<?php namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;
use Laravel\Lumen\Routing\Controller;
use Illuminate\Support\Facades\View;

class StatusController extends Controller {

    // maintenance, unavailable, landing, prelaunch

    /**
     * Show contact page.
     *
     * @return Response
     */
    public function status()
    {
        if (View::exists('status'.config('b3_config.status'))) {
            return view('status.' . $status, ['page_title' => ucfirst(config('b3_config.status'))]);
        }
        else {
            return view('status.unavailable', ['page_title' => 'Unavailable']);
        }

    }

}

<?php namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;
use Laravel\Lumen\Routing\Controller;
use Illuminate\Support\Facades\View;

class StatusController extends Controller {

    // maintenance, unavailable, landing, prelaunch

    /**
     * Show contact page.
     *
     * @return Response
     */
    public function status()
    {
        if (View::exists('status.'.config('b3_config.status'))) {
            return view('status.' . config('b3_config.status'), ['page_title' => ucfirst(config('b3_config.status'))]);
        }
        else {
            return view('status.unavailable', ['page_title' => 'Unavailable']);
        }

    }

}

Fix bug where status controller would only return "unavailable"


<!doctype html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>Gificiency</title>
   <link href="http://fonts.googleapis.com/css?family=Roboto:100" rel="stylesheet" type="text/css">
   <link rel="stylesheet" href="assets/stylesheets/gificiency.css">
</head>
<body class="cell">
  <form class="form" action="">
    <input type="text" name="search" placeholder="Search..." class="search" />
  </form>
  <ul class="links">
    <?php require_once 'lib/gificiency.php'; ?>
    <?php if ($env == 'development'): ?>
      <?php require_once 'lib/seeds.php'; ?>
    <?php else: ?>
      print_files($url, $dir);
    <?php endif; ?>
  </ul>

  <script src="http://code.jquery.com/jquery-1.10.0.min.js" type="text/javascript"></script>
  <script src="assets/javascripts/vendor/underscore.min.js" type="text/javascript"></script>
  <script src="assets/javascripts/gificiency.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function() {
      new Gificiency({
        searchField: $('.search'),
        items: $('.links li'),
        links: $('.link')
      });
    });
  </script>

</body>
</html>

<!doctype html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>Gificiency</title>
   <link href="http://fonts.googleapis.com/css?family=Roboto:100" rel="stylesheet" type="text/css">
   <link rel="stylesheet" href="assets/stylesheets/gificiency.css">
</head>
<body class="cell">
  <form class="form" action="">
    <input type="text" name="search" placeholder="Search..." class="search" />
  </form>
  <ul class="links">
    <? require_once 'lib/gificiency.php'; ?>
    <? if ($env == 'development'): ?>
      <? require_once 'lib/seeds.php'; ?>
    <? else: ?>
      <?= print_files($url, $dir); ?>
    <? endif; ?>
  </ul>

  <script src="http://code.jquery.com/jquery-1.10.0.min.js" type="text/javascript"></script>
  <script src="assets/javascripts/vendor/underscore.min.js" type="text/javascript"></script>
  <script src="assets/javascripts/gificiency.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function() {
      new Gificiency({
        searchField: $('.search'),
        items: $('.links li'),
        links: $('.link')
      });
    });
  </script>

</body>
</html>

Fix a bug with the print_files output function


<?php
/**
 *
 * Template Name: My Sidebar Page
 *
 * The Template for displaying all single posts.
 *
 * @package socket.io-website
 */

get_header(); ?>

	<div id="primary" class="content-area">
		<main id="main" class="site-main" role="main">
			<?php get_template_part( 'sidebar' ); ?>
			<?php while ( have_posts() ) : the_post(); ?>

				<?php get_template_part( 'content', 'page' ); ?>

			<?php endwhile; // end of the loop. ?>

		</main><!-- #main -->
	</div><!-- #primary -->

<?php get_footer(); ?>

<?php
/**
 *
 * Template Name: My Sidebar Page
 *
 * The Template for displaying all single posts.
 *
 * @package socket.io-website
 */

get_header(); ?>

	<?php get_template_part( 'sidebar' ); ?>
	<div id="primary" class="content-area with-sidebar">
		<main id="main" class="site-main" role="main">
			<?php while ( have_posts() ) : the_post(); ?>

				<?php get_template_part( 'content', 'page' ); ?>

			<?php endwhile; // end of the loop. ?>

		</main><!-- #main -->
	</div><!-- #primary -->

<?php get_footer(); ?>

Add class and extract sidebar from content


<?php

namespace Phapi\Contract\Middleware;

use Phapi\Contract\Http\Request;
use Phapi\Contract\Http\Response;

/**
 * Interface Middleware
 *
 * Middleware accepts a request and a response and optionally a callback
 * ($next) that is called if the middleware allows further middleware to
 * process the request.
 *
 * If a middleware doesn't need or desire to allow further processing it
 * should not call the callback ($next) and should instead return a response.
 *
 * @category Phapi
 * @package  Phapi\Contract
 * @author   Peter Ahinko <peter@ahinko.se>
 * @license  MIT (http://opensource.org/licenses/MIT)
 * @link     https://github.com/phapi/contract
 */
interface Middleware {

    /**
     * Process an incoming request and/or response.
     *
     * Accepts a request and a response (PSR-7 compatible) instance and
     * does something with them.
     *
     * The middleware must pass a request and a response to the ($next)
     * callback and finally either return the response from the ($next)
     * callback or by modifying the response before returning it.
     *
     * Examples:
     * return $next();
     *
     * OR
     *
     * $response = $next();
     * // Modify response
     * ...
     * return $response;
     *
     * @param Request $request
     * @param Response $response
     * @param callable $next
     * @return Request
     */
    public function __invoke(Request $request, Response $response, callable $next = null);

}

<?php

namespace Phapi\Contract\Middleware;

use Psr\Http\Message\ServerRequestInterface as RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * Interface Middleware
 *
 * Middleware accepts a request and a response and optionally a callback
 * ($next) that is called if the middleware allows further middleware to
 * process the request.
 *
 * If a middleware doesn't need or desire to allow further processing it
 * should not call the callback ($next) and should instead return a response.
 *
 * @category Phapi
 * @package  Phapi\Contract
 * @author   Peter Ahinko <peter@ahinko.se>
 * @license  MIT (http://opensource.org/licenses/MIT)
 * @link     https://github.com/phapi/contract
 */
interface Middleware {

    /**
     * Process an incoming request and/or response.
     *
     * Accepts a request and a response (PSR-7 compatible) instance and
     * does something with them.
     *
     * The middleware must pass a request and a response to the ($next)
     * callback and finally either return the response from the ($next)
     * callback or by modifying the response before returning it.
     *
     * Examples:
     * return $next();
     *
     * OR
     *
     * $response = $next();
     * // Modify response
     * ...
     * return $response;
     *
     * @param RequestInterface $request
     * @param ResponseInterface $response
     * @param callable $next
     * @return ResponseInterface
     */
    public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next = null);

}

Revert "Updated middleware contract to force use of Request and Response contracts."

This reverts commit 47d2083f48b676d359c2b2eb3836b2ce2f85909d.


<?php

namespace SAML2\Compat;

abstract class AbstractContainer
{
    /**
     * Get a PSR-3 compatible logger.
     * @return \Psr\Log\LoggerInterface
     */
    abstract public function getLogger();

    /**
     * Generate a random identifier for identifying SAML2 documents.
     */
    abstract public function generateId();

    /**
     * Log an incoming message to the debug log.
     *
     * Type can be either:
     * - **in** XML received from third party
     * - **out** XML that will be sent to third party
     * - **encrypt** XML that is about to be encrypted
     * - **decrypt** XML that was just decrypted
     *
     * @param string $message
     * @param string $type
     * @return void
     */
    abstract public function debugMessage($message, $type);

    /**
     * Trigger the user to perform a GET to the given URL with the given data.
     *
     * @param string $url
     * @param array $data
     * @return void
     */
    abstract public function redirect($url, array $data = []);

    /**
     * Trigger the user to perform a POST to the given URL with the given data.
     *
     * @param string $url
     * @param array $data
     * @return void
     */
    abstract public function postRedirect($url, array $data = []);
}

<?php

namespace SAML2\Compat;

abstract class AbstractContainer
{
    /**
     * Get a PSR-3 compatible logger.
     * @return \Psr\Log\LoggerInterface
     */
    abstract public function getLogger();

    /**
     * Generate a random identifier for identifying SAML2 documents.
     */
    abstract public function generateId();

    /**
     * Log an incoming message to the debug log.
     *
     * Type can be either:
     * - **in** XML received from third party
     * - **out** XML that will be sent to third party
     * - **encrypt** XML that is about to be encrypted
     * - **decrypt** XML that was just decrypted
     *
     * @param string $message
     * @param string $type
     * @return void
     */
    abstract public function debugMessage($message, $type);

    /**
     * Trigger the user to perform a GET to the given URL with the given data.
     *
     * @param string $url
     * @param array $data
     * @return void
     */
    abstract public function redirect($url, $data = []);

    /**
     * Trigger the user to perform a POST to the given URL with the given data.
     *
     * @param string $url
     * @param array $data
     * @return void
     */
    abstract public function postRedirect($url, $data = []);
}

Revert type hints on abstract container for now.

This is our only abstract class in the compat suite and we expect
people to implement this. Adding a type hint breaks existing
implementations. So it's not really good to do this in a patch
release.


<?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>

            <a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name; ?>"><?php echo $context->name; ?> ::
                <?php echo $context->version['release']; ?>

Version:
                <?php echo $context->version['release']; ?>

Stability:
                <?php echo $context->stability['release']; ?>

Released on:
                <abbr class="releasedate" title="<?php echo $context->date.' '.$context->time; ?>"><?php echo $context->date; ?>

License:
                <?php echo $context->license['name']; ?>

        <?php echo $savant->render($context->name . '-' . $context->version['release'], 'InstallInstructions.tpl.php'); ?>

Release Notes

        <?php echo nl2br($context->notes); ?>

<?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>

            <a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name; ?>"><?php echo $context->name; ?>-<?php echo $context->version['release']; ?>

Version:
                <?php echo $context->version['release']; ?>

Stability:
                <?php echo $context->stability['release']; ?>

Released on:
                <abbr class="releasedate" title="<?php echo $context->date.' '.$context->time; ?>"><?php echo $context->date; ?>

License:
                <?php echo $context->license['name']; ?>

        <?php echo $savant->render($context->name . '-' . $context->version['release'], 'InstallInstructions.tpl.php'); ?>

Release Notes

        <?php echo nl2br($context->notes); ?>

Use PackageName-x.x.x for consistency with CLI install usage.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Team extends Model
{
    use SoftDeletes;

    /**
     *  Get the Users that are members of this Team
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }

    /**
     * Get all of the team's attendance.
     */
    public function attendance()
    {
        return $this->morphMany('App\Attendance', 'attendable');
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Team extends Model
{
    use SoftDeletes;

    /**
     * The attributes that are not mass assignable.
     *
     * @var array
     */
    protected $guarded = [
        'id',
        'deleted_at',
        'created_at',
        'updated_at'
    ];

    /**
     *  Get the Users that are members of this Team
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }

    /**
     * Get all of the team's attendance.
     */
    public function attendance()
    {
        return $this->morphMany('App\Attendance', 'attendable');
    }
}

Add $guarded for mass assignment

Add $guarded for mass assignment


<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshopTest;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Filesystem\Filesystem;

abstract class BaseTest extends TestCase
{
    private $tempDirectory;

    public function getTemporaryDirectory(): string
    {
        if (!$this->tempDirectory) {
            $tempDirectory = sprintf('%s/%s', realpath(sys_get_temp_dir()), $this->getName());
            mkdir($tempDirectory, 0777, true);

            $this->tempDirectory = realpath($tempDirectory);
        }

        return $this->tempDirectory;
    }

    public function tearDown(): void
    {
        if ($this->tempDirectory) {
            (new Filesystem())->remove($this->tempDirectory);
        }
    }
}

<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshopTest;

use PhpSchool\PhpWorkshop\Utils\Path;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Filesystem\Filesystem;

abstract class BaseTest extends TestCase
{
    private $tempDirectory;

    public function getTemporaryDirectory(): string
    {
        if (!$this->tempDirectory) {
            $tempDirectory = sprintf('%s/%s', realpath(sys_get_temp_dir()), $this->getName());
            mkdir($tempDirectory, 0777, true);

            $this->tempDirectory = realpath($tempDirectory);
        }

        return $this->tempDirectory;
    }

    public function getTemporaryFile(string $filename): string
    {
        $file = Path::join($this->getTemporaryDirectory(), $filename);

        if (file_exists($file)) {
            return $file;
        }

        @mkdir(dirname($file), 0777, true);
        touch($file);

        return $file;
    }

    public function tearDown(): void
    {
        if ($this->tempDirectory) {
            (new Filesystem())->remove($this->tempDirectory);
        }
    }
}

Add getTemporaryFile method to base test class


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Transformers;

use Spatie\MediaLibrary\Models\Media;
use League\Fractal\TransformerAbstract;

class MediaTransformer extends TransformerAbstract
{
    /**
     * @return array
     */
    public function transform(Media $media): array
    {
        return [
            'id' => (int) $media->getKey(),
            'name' => (string) $media->name,
            'file_name' => (string) $media->file_name,
            'mime_type' => (string) $media->mime_type,
            'size' => (string) $media->getHumanReadableSizeAttribute(),
            'created_at' => (string) $media->created_at,
            'updated_at' => (string) $media->updated_at,
            'delete' => (string) route('adminarea.rooms.media.delete', ['room' => $media->model, 'media' => $media]),
        ];
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Foundation\Transformers;

use Spatie\MediaLibrary\Models\Media;
use League\Fractal\TransformerAbstract;

class MediaTransformer extends TransformerAbstract
{
    /**
     * @return array
     */
    public function transform(Media $media): array
    {
        return [
            'id' => (int) $media->getKey(),
            'name' => (string) $media->name,
            'file_name' => (string) $media->file_name,
            'mime_type' => (string) $media->mime_type,
            'size' => (string) $media->getHumanReadableSizeAttribute(),
            'created_at' => (string) $media->created_at,
            'updated_at' => (string) $media->updated_at,
            'delete' => (string) route('adminarea.rooms.media.destroy', ['room' => $media->model, 'media' => $media]),
        ];
    }
}

Rename controller action delete to destroy


<?php

namespace Jalle19\Laravel\UnshittyFlash;

use Illuminate\Support\ServiceProvider;

/**
 * Class FlashServiceProvider
 * @package Jalle19\Laravel\UnshittyFlash
 */
class FlashServiceProvider extends ServiceProvider
{

    /**
     * Registers bindings into the container
     */
    public function register()
    {
        $this->app->singleton(FlashService::class, function() {
            return new FlashService(config('flash'));
        });
    }

}

<?php

namespace Jalle19\Laravel\UnshittyFlash;

use Illuminate\Support\ServiceProvider;

/**
 * Class FlashServiceProvider
 * @package Jalle19\Laravel\UnshittyFlash
 */
class FlashServiceProvider extends ServiceProvider
{

    /**
     * Registers bindings into the container
     */
    public function register()
    {
        $this->app->singleton(FlashService::class, function() {
            return new FlashService(config('flash'));
        });
    }

    /**
     *
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../config/flash.php' => config_path('flash.php'),
        ]);
    }

}

Add configuration file publishing to the service provider


<?php
namespace Passengers\Event;

use Cake\Event\Event;
use Cake\Event\EventListenerInterface;
use Cake\Controller\Component\AuthComponent;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\ORM\Association;
use Cake\ORM\Tableregistry;

class SignInEvent implements EventListenerInterface {

    public function implementedEvents()
    {
        return array(
	        'Controller.Users.beforeSignIn' => array(
                'callable' => 'beforeUsersControllerSignIn',
            ),
        );
    }

    public function beforeUsersControllerSignIn(Event $event)
    {
        $controller = $event->subject();
        $active = true;
        if($controller->request->is('post')){
            if($login = $controller->request->data('username')){
				$active = $controller->Users->find('all', [
					'conditions' => [
						'Users.active' => true,
						'OR' => [
							'Users.email' => $login,
							'Users.username' => $login
						]
					]
				])->count();
			}
        }
        if($active){
            $event->stopPropagation();
            return __d('passengers', 'Sorry, but your account has been not activated yet.');
        }
    }

}

<?php
namespace Passengers\Event;

use Cake\Event\Event;
use Cake\Event\EventListenerInterface;
use Cake\Controller\Component\AuthComponent;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\ORM\Association;
use Cake\ORM\Tableregistry;

class SignInEvent implements EventListenerInterface {

    public function implementedEvents()
    {
        return array(
	        'Controller.Users.beforeSignIn' => array(
                'callable' => 'beforeUsersControllerSignIn',
            ),
        );
    }

    public function beforeUsersControllerSignIn(Event $event)
    {
        $controller = $event->subject();
        $active = true;
        if($controller->request->is('post')){
            if($login = $controller->request->data('username')){
				$active = $controller->Users->find('all', [
					'conditions' => [
						'Users.active' => true,
						'OR' => [
							'Users.email' => $login,
							'Users.username' => $login
						]
					]
				])->count();
			}
        }
        if(!$active){
            $event->stopPropagation();
            return __d('passengers', 'Sorry, but your account has been not activated yet.');
        }
    }

}

Fix user active state verification

Fix user active state verification


<?php

// args: phar path, privkey, privkey password
$pkeyid = openssl_pkey_get_private("file://".realpath($_SERVER['argv'][2]), $_SERVER['argv'][3]);
if (!openssl_sign(file_get_contents($_SERVER['argv'][1]), $sha384sig, $pkeyid, OPENSSL_ALGO_SHA384)) {
    echo 'Failed to sign';
    exit(1);
}
openssl_free_key($pkeyid);

$sha384sig = trim(base64_encode($sha384sig), '=');
file_put_contents($_SERVER['argv'][1].'.sig', json_encode(['sha384' => $sha384sig], JSON_UNESCAPED_SLASHES));

<?php

// args: phar path, privkey, privkey password
$pkeyid = openssl_pkey_get_private("file://".realpath($_SERVER['argv'][2]), $_SERVER['argv'][3]);
if (!openssl_sign(file_get_contents($_SERVER['argv'][1]), $sha384sig, $pkeyid, OPENSSL_ALGO_SHA384)) {
    echo 'Failed to sign';
    exit(1);
}
openssl_free_key($pkeyid);

$sha384sig = base64_encode($sha384sig);
file_put_contents($_SERVER['argv'][1].'.sig', json_encode(['sha384' => $sha384sig], JSON_UNESCAPED_SLASHES));

Remove trimming to avoid warnings in some base64 implementations


@extends('layout.master')

@section('main_content')

@include('layout.header', ['header' => 'Users', 'subtitle' => 'View & edit member profiles.'])

All Users

We currently have {{ number_format($users->total()) }} members in Northstar.

          @include('search.search')

          @if ($users)
              @include('users.partials.index-table', ['users' => $users])
              {!! $users->links(\Aurora\Http\Presenters\ForgePaginationPresenter::class) !!}
          @endif

@stop

Remove call to unused global function.

Remove call to unused global function.


<?php

namespace App\Http\Controllers;

use App\EquipmentBarcode;
use Illuminate\Http\Request;
use App\Services\ApiService;

class EquipmentBarcodeController extends Controller
{
    /**
     * @param Request $request
     * @return App\Services\ApiService
     */
    public function index(Request $request)
    {
        $status = $request->input('status', '-1');
        $search = $request->input('search', '');
        $order_field = $request->input('orderby_field', 'id');
        $order_method = $request->input('orderby_method', 'desc');
        $limit = $request->input('limit', 15);
        $barcode = EquipmentBarcode::Where(function($query) use ($search, $status) {
            if ($status != '-1') {
                $query->where('status', $status);
            }
            $query->Where('barcode', 'LIKE', '%' . $search . '%');
        })->orderBy($order_field, $order_method)
            ->paginate($limit);

        return ApiService::returnApiResponse('Success.', $barcode);
    }
}

<?php

namespace App\Http\Controllers;

use App\EquipmentBarcode;
use Illuminate\Http\Request;
use App\Services\ApiService;

class EquipmentBarcodeController extends Controller
{
    /**
     * @param Request $request
     * @return App\Services\ApiService
     */
    public function index(Request $request)
    {
        $status = $request->input('status', '-1');
        $search = $request->input('search', '');
        $order_field = $request->input('orderby_field', 'id');
        $order_method = $request->input('orderby_method', 'desc');
        $limit = $request->input('limit', 15);
        $barcode = EquipmentBarcode::Where(function($query) use ($search, $status) {
            if ($status != '-1') {
                $query->where('status', $status);
            }
            $query->Where('barcode', 'LIKE', '%' . $search . '%');
        })->orderBy($order_field, $order_method)
            ->paginate($limit);

        return ApiService::returnApiResponse('Success.', $barcode);
    }

    /**
     * @param Request $request
     * @param         $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        $equipmentBarcode = EquipmentBarcode::find($id);
        if ($equipmentBarcode && $request->has('barcode')) {
            $equipmentBarcode->barcode = $request->input('barcode');
            $equipmentBarcode->save();

            return ApiService::returnApiResponse('Success.', $equipmentBarcode);
        }

        return ApiService::returnApiResponse('Not found.', [], false, 404);

    }
}

Add eq barcode update faeature

Add eq barcode update faeature


<?php
namespace Concrete\Core\Html\Service;

class Seo
{
    private $siteName = '';
    private $titleSegments = array();
    private $titleSegmentSeparator = ' :: ';
    private $titleFormat = '%1$s :: %2$s';
    private $hasCustomTitle = false;

    public function setSiteName($name)
    {
        $this->siteName = $name;
    }

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

    public function setCustomTitle($title)
    {
        $this->hasCustomTitle = true;
        $this->titleSegments = array();
        $this->addTitleSegmentBefore($title);
        return $this;
    }

    public function addTitleSegment($segment)
    {
        array_push($this->titleSegments, $segment);
        return $this;
    }

    public function addTitleSegmentBefore($segment)
    {
        array_unshift($this->titleSegments, $segment);
        return $this;
    }

    public function setTitleFormat($format)
    {
        $this->titleFormat = $format;
        return $this;
    }

    public function setTitleSegmentSeparator($separator)
    {
        $this->titleSegmentSeparator = $separator;
        return $this;
    }

    public function getTitle()
    {
        $segments = '';
        if (count($this->titleSegments) > 0) {
            $segments = implode($this->titleSegmentSeparator, $this->titleSegments);
        }
        return sprintf($this->titleFormat, $this->siteName, $segments);
    }
}

<?php
namespace Concrete\Core\Html\Service;

class Seo
{
    private $siteName = '';
    private $titleSegments = array();
    private $titleSegmentSeparator = ' :: ';
    private $titleFormat = '%1$s :: %2$s';
    private $hasCustomTitle = false;

    public function setSiteName($name)
    {
        $this->siteName = $name;
    }

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

    public function setCustomTitle($title)
    {
        $this->hasCustomTitle = true;
        $this->clearTitleSegments();
        $this->addTitleSegmentBefore($title);
        return $this;
    }

    public function addTitleSegment($segment)
    {
        array_push($this->titleSegments, $segment);
        return $this;
    }

    public function addTitleSegmentBefore($segment)
    {
        array_unshift($this->titleSegments, $segment);
        return $this;
    }

    public function clearTitleSegments()
    {
        $this->titleSegments = array();
    }

    public function setTitleFormat($format)
    {
        $this->titleFormat = $format;
        return $this;
    }

    public function setTitleSegmentSeparator($separator)
    {
        $this->titleSegmentSeparator = $separator;
        return $this;
    }

    public function getTitle()
    {
        $segments = '';
        if (count($this->titleSegments) > 0) {
            $segments = implode($this->titleSegmentSeparator, $this->titleSegments);
        }
        return sprintf($this->titleFormat, $this->siteName, $segments);
    }
}

Add clearTitleSegments method to seo helper


<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 cc=80; */

/**
 * @package     omeka
 * @subpackage  fedora-connector
 * @copyright   2012 Rector and Board of Visitors, University of Virginia
 * @license     http://www.apache.org/licenses/LICENSE-2.0.html
 */

define('FEDORA_DIR', dirname(dirname(dirname(__FILE__))));
define('FEDORA_TEST_DIR', FEDORA_DIR.'/tests/phpunit');
define('OMEKA_DIR', dirname(dirname(FEDORA_DIR)));

// Bootstrap Omeka.
require_once OMEKA_DIR.'/application/tests/bootstrap.php';

// Laod the base test case.
require_once FEDORA_TEST_DIR.'/cases/FedoraConnector_Case_Default.php';
require_once FEDORA_DIR . '/libraries/FedoraConnector/AbstractImporter.php';
require_once FEDORA_DIR . '/importers/DC.php';

Make sure to load the importers.

Make sure to load the importers.


<!DOCTYPE html>

	<meta charset="utf-8">
	<link href="css/app.css" rel="stylesheet" />
<title>Radiological Equipment Database</title>

Radiological Equipment Database

	@yield('content')

<!DOCTYPE html>

	<meta charset="utf-8">
	<link href="/css/app.css" rel="stylesheet" />
<title>Radiological Equipment Database</title>

Radiological Equipment Database

	@yield('content')

Fix path to app.css file

Fix path to app.css file


<?php

namespace Omnipay\AuthorizeNet\Message;

/**
 * Authorize.Net CIM Get payment profiles Response
 */
class CIMGetProfileResponse extends CIMCreatePaymentProfileResponse
{
    protected $xmlRootElement = 'getCustomerProfileResponse';

    /**
     * Get the payment profile id corresponding to the specified last4 by looking into the payment profiles
     * of the customer
     *
     * @param $last4
     *
     * @return null|string
     */
    public function getMatchingPaymentProfileId($last4)
    {
        if (!$this->isSuccessful()) {
            return null;
        }

        foreach ($this->data['profile'][0]['paymentProfiles'] as $paymentProfile) {
            // For every payment  profile check if the last4 matches the last4 of the card in request.
            $cardLast4 = substr($paymentProfile['payment'][0]['creditCard'][0]['cardNumber'][0], -4);
            if ($last4 == $cardLast4) {
                return (string)$paymentProfile['customerPaymentProfileId'];
            }
        }

        return null;
    }

    public function getCustomerPaymentProfileId()
    {
        if ($this->isSuccessful()) {
            return $this->request->getCustomerPaymentProfileId();
        }
        return null;
    }
}

<?php

namespace Omnipay\AuthorizeNet\Message;

/**
 * Authorize.Net CIM Get payment profiles Response
 */
class CIMGetProfileResponse extends CIMCreatePaymentProfileResponse
{
    protected $xmlRootElement = 'getCustomerProfileResponse';

    /**
     * Get the payment profile id corresponding to the specified last4 by looking into the payment profiles
     * of the customer
     *
     * @param $last4
     *
     * @return null|string
     */
    public function getMatchingPaymentProfileId($last4)
    {
        if (!$this->isSuccessful()) {
            return null;
        }

        foreach ($this->data['profile'][0]['paymentProfiles'] as $paymentProfile) {
            // For every payment  profile check if the last4 matches the last4 of the card in request.
            $cardLast4 = substr($paymentProfile['payment'][0]['creditCard'][0]['cardNumber'], -4);
            if ($last4 == $cardLast4) {
                return (string)$paymentProfile['customerPaymentProfileId'];
            }
        }

        return null;
    }

    public function getCustomerPaymentProfileId()
    {
        if ($this->isSuccessful()) {
            return $this->request->getCustomerPaymentProfileId();
        }
        return null;
    }
}

Fix duplicate payment profile handling

Fix duplicate payment profile handling


<?php namespace WebEd\Base\Providers;

use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
use WebEd\Base\Settings\Http\Controllers\SettingController;

class HookServiceProvider extends ServiceProvider
{
    /**
     * @var Request
     */
    protected $request;
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        app()->booted(function () {
            $this->request = request();

            $this->booted();
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {

    }

    /**
     * Callback when app booted
     *
     * @return void
     */
    protected function booted()
    {
        add_filter('settings.before-edit.post', function ($data, SettingController $controller) {
            if($controller->request->get('_tab') === 'advanced') {
                $data['construction_mode'] = (int)($this->request->has('construction_mode'));
                $data['show_admin_bar'] = (int)($this->request->has('show_admin_bar'));
            }
            return $data;
        });
    }
}

<?php namespace WebEd\Base\Providers;

use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;

class HookServiceProvider extends ServiceProvider
{
    /**
     * @var Request
     */
    protected $request;
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        app()->booted(function () {
            $this->request = request();

            $this->booted();
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {

    }

    /**
     * Callback when app booted
     *
     * @return void
     */
    protected function booted()
    {
        add_filter(BASE_FILTER_BEFORE_UPDATE, function ($data, $screenName, $action) {
            if ($screenName !== WEBED_SETTINGS) {
                return $data;
            }
            if($this->request->get('_tab') === 'advanced') {
                $data['construction_mode'] = (int)($this->request->has('construction_mode'));
                $data['show_admin_bar'] = (int)($this->request->has('show_admin_bar'));
            }
            return $data;
        });
    }
}

Fix bug cannot update advanced section

Fix bug cannot update advanced section


<?php
//Spreadsheet process or constants for PHPExcel wrapper
/** CYMAPGT_PHPExcelWrapperFactory root directory */
if (!(defined('SPREADSHEETPROCESSOR_CACHEGETALL'))) {
    define('SPREADSHEETPROCESSOR_CACHEGETALL', 0);
}

if (!(defined('SPREADSHEETPROCESSOR_CACHEGETCUR'))) {
    define('SPREADSHEETPROCESSOR_CACHEGETCUR', 1);
}

if (!(defined('SSPREADSHEETPROCESSOR_CACHEGETVAL'))) {
    define('SPREADSHEETPROCESSOR_CACHEGETVAL', 2);
}

<?php
//Spreadsheet process or constants for PHPExcel wrapper
/** CYMAPGT_PHPExcelWrapperFactory root directory */
if (!(defined('SPREADSHEETPROCESSOR_CACHEGETALL'))) {
    define('SPREADSHEETPROCESSOR_CACHEGETALL', 0);
}

if (!(defined('SPREADSHEETPROCESSOR_CACHEGETCUR'))) {
    define('SPREADSHEETPROCESSOR_CACHEGETCUR', 1);
}

if (!(defined('SPREADSHEETPROCESSOR_CACHEGETVAL'))) {
    define('SPREADSHEETPROCESSOR_CACHEGETVAL', 2);
}

Fix error in Update named constant declarations to include check that avoids duplicate declaration when package is required by different other packages


<?php

/**
 * Change variable price display to show range, rather than the minimum price.
 **/
add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);

function custom_variation_price( $price, $product ) {

     $price = '';
     $price .= woocommerce_price($product->max_variation_price);
     return $price;

}

/**
 * disable the password strength check
 **/
function wc_ninja_remove_password_strength() {
	if ( wp_script_is( 'wc-password-strength-meter', 'enqueued' ) ) {
		wp_dequeue_script( 'wc-password-strength-meter' );
	}
}
add_action( 'wp_print_scripts', 'wc_ninja_remove_password_strength', 100 );

Remove the password strength javascript from the login and checkout pages


<?php
require('maze_utility.php');

assert(coordinate_to_column('a1n') == 0);
assert(coordinate_to_column('b3s') == 1);
assert(coordinate_to_column('c5e') == 2);
assert(coordinate_to_column('d1s') == 3);
assert(coordinate_to_column('e4w') == 4);

assert(coordinate_to_row('a1n') == 0);
assert(coordinate_to_row('b3s') == 2);
assert(coordinate_to_row('c5e') == 4);
assert(coordinate_to_row('d1s') == 0);
assert(coordinate_to_row('e4w') == 3);

echo 'All OK.' . PHP_EOL;

<?php
require_once('maze_utility.php');

error_reporting(E_ALL);
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);
assert(coordinate_to_column('a1n') == 0);
assert(coordinate_to_column('b3s') == 1);
assert(coordinate_to_column('c5e') == 2);
assert(coordinate_to_column('d1s') == 3);
assert(coordinate_to_column('e4w') == 4);

assert(coordinate_to_row('a1n') == 0);
assert(coordinate_to_row('b3s') == 2);
assert(coordinate_to_row('c5e') == 4);
assert(coordinate_to_row('d1s') == 0);
assert(coordinate_to_row('e4w') == 3);

echo 'All OK.' . PHP_EOL;

Fix maze utility test script

Fix maze utility test script


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

namespace Sylius\Component\Sequence;

class SyliusSequenceEvents
{
    const PRE_GENERATE = 'sylius.sequence.%s.pre_generate';
    const POST_GENERATE = 'sylius.sequence.%s.post_generate';
    const GENERATOR_NOT_FOUND = 'sylius.sequence.%s.generator_not_found';
}

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

namespace Sylius\Component\Sequence;

class SyliusSequenceEvents
{
    const PRE_GENERATE = 'sylius.sequence.%s.pre_generate';
    const POST_GENERATE = 'sylius.sequence.%s.post_generate';
}

Throw exception if sequence generator not found


<?php

namespace OpenCFP\Domain\Model;

class Favorite extends Eloquent
{
    protected $table = 'favorites';
    public $timestamps = false;

    public function talk()
    {
        $this->belongsTo(Talk::class, 'talk_id');
    }
}

<?php

namespace OpenCFP\Domain\Model;

class Favorite extends Eloquent
{
    protected $table = 'favorites';
    public $timestamps = false;

    public function talk()
    {
        return $this->belongsTo(Talk::class, 'talk_id');
    }
}

Add a missing return statement

Add a missing return statement


<?php

/**
 * managedinstalls class
 *
 * @package munkireport
 * @author
 **/
class managedinstalls_controller extends Module_controller
{

	/*** Protect methods with auth! ****/
	function __construct()
	{
		// Store module path
		$this->module_path = dirname(__FILE__);
		$this->view_path = dirname(__FILE__) . '/views/';
	}

	  /**
	 * Get managedinstalls information for serial_number
	 *
	 * @param string $serial serial number
	 **/
	public function get_data($serial_number = '')
	{
	      $obj = new View();
	      if( ! $this->authorized())
	      {
	          $obj->view('json', array('msg' => 'Not authorized'));
	          return;
	      }

	      $managedinstalls = new managedinstalls_model($serial_number);
	      $obj->view('json', array('msg' => $managedinstalls->rs));
	}

	/**
	 * undocumented function summary
	 *
	 * Undocumented function long description
	 *
	 * @param type var Description
	 * @return {11:return type}
	 */
	public function listing($value='')
	{
		if( ! $this->authorized())
		{
			redirect('auth/login');
		}
		$data['page'] = 'clients';
		$data['scripts'] = array("clients/client_list.js");
        $obj = new View();
        $obj->view('managed_installs_list', $data, $this->view_path);
	}

} // END class default_module

<?php

/**
 * managedinstalls class
 *
 * @package munkireport
 * @author
 **/
class managedinstalls_controller extends Module_controller
{

	/*** Protect methods with auth! ****/
	function __construct()
	{
		// Store module path
		$this->module_path = dirname(__FILE__);
		$this->view_path = dirname(__FILE__) . '/views/';
	}

	  /**
	 * Get managedinstalls information for serial_number
	 *
	 * @param string $serial serial number
	 **/
	public function get_data($serial_number = '')
	{
		$out = array();
        if( ! $this->authorized())
        {
          $out['error'] = 'Not authorized';
        }
        else
        {
          $model = new Managedinstalls_model;
          foreach($model->retrieve_records($serial_number) as $prefs)
          {
            $out[] = $prefs->rs;
          }
        }

        $obj = new View();
        $obj->view('json', array('msg' => $out));
	}

	/**
	 * undocumented function summary
	 *
	 * Undocumented function long description
	 *
	 * @param type var Description
	 * @return {11:return type}
	 */
	public function listing($value='')
	{
		if( ! $this->authorized())
		{
			redirect('auth/login');
		}
		$data['page'] = 'clients';
		$data['scripts'] = array("clients/client_list.js");
        $obj = new View();
        $obj->view('managed_installs_list', $data, $this->view_path);
	}

} // END class default_module

Fix get_data in managed installs

Fix get_data in managed installs


<?php

namespace NyroDev\UtilityBundle\Listener;

use Gedmo\Loggable\LoggableListener as SrcLoggableListener;

class LoggableListener extends SrcLoggableListener
{
    protected function prePersistLogEntry($logEntry, $object)
    {
        if (method_exists($object, 'getTranslatableLocale') && method_exists($logEntry, 'setLocale') && $object->getTranslatableLocale()) {
            $logEntry->setLocale($object->getTranslatableLocale());
        }
    }
}

<?php

namespace NyroDev\UtilityBundle\Listener;

use Gedmo\Loggable\LoggableListener as SrcLoggableListener;

class LoggableListener extends SrcLoggableListener
{
    protected function prePersistLogEntry($logEntry, $object)
    {
        if (method_exists($object, 'getTranslatableLocale') && method_exists($logEntry, 'setLocale') && $object->getTranslatableLocale()) {
            $locale = $object->getTranslatableLocale();
            if (strpos($locale, 'change_') === 0) {
                $tmp = explode('change_', $locale);
                $locale = $tmp[1];
            }
            $logEntry->setLocale($locale);
        }
    }
}

Fix logable listener to remove change_ when needed


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 * @package   Zend_Db
 */

namespace Zend\Db\Adapter;

use Zend\ServiceManager\FactoryInterface;

/**
 * @category   Zend
 * @package    Zend_Db
 * @subpackage Adapter
 */
class AdapterServiceFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = $serviceLocator->get('Configuration');
        return new Adapter($config['db']);
    }
}

<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 * @package   Zend_Db
 */

namespace Zend\Db\Adapter;

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

/**
 * @category   Zend
 * @package    Zend_Db
 * @subpackage Adapter
 */
class AdapterServiceFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = $serviceLocator->get('Configuration');
        return new Adapter($config['db']);
    }
}

Add missing use statements to service factories


<?php

namespace Bijective;

/**
 * @author Brian Freytag <brian@idltg.in>
 */
class BijectiveTranslator implements BijectiveInterface
{
    /** @var string */
    private $alphabet;

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

    /**
     * Encodes any integer into an encoded string
     *
     * @param integer $int
     *
     * @throws \InvalidArgumentException
     * @return string
     */
    public function encode($int)
    {
        if (!is_int($int)) {
            throw new \InvalidArgumentException('You can only encode an integer');
        }

        if ($int == 0) {
            return $this->alphabet[0];
        }

        $string = '';
        $base = strlen($this->alphabet);

        while ($int > 0) {
            $string .= $this->alphabet[($int % $base)];

            $int = floor($int / $base);
        }

        return strrev($string);
    }

    /**
     * Decodes any string into an interval value
     *
     * @param $str
     *
     * @throws \InvalidArgumentException
     * @return int
     */
    public function decode($str)
    {
        if (!is_string($str)) {
            throw new \InvalidArgumentException('You can only decode a string');
        }

        $int = 0;

        $base = strlen($this->alphabet);

        for ($i=0; $i < strlen($str); $i++) {
            $pos = strpos($this->alphabet, $str[$i]);

            $int = $int * $base + $pos;
        }

        return $int;
    }
}

<?php

namespace Bijective;

/**
 * @author Brian Freytag <brian@idltg.in>
 */
class BijectiveTranslator implements BijectiveInterface
{
    /** @var string */
    private $alphabet;

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

    /**
     * Encodes any integer into an encoded string
     *
     * @param integer $int
     *
     * @throws \InvalidArgumentException
     * @return string
     */
    public function encode($int)
    {
        if (!ctype_digit($int)) {
            throw new \InvalidArgumentException('You can only encode a number');
        }

        if ($int == 0) {
            return $this->alphabet[0];
        }

        $string = '';
        $base = strlen($this->alphabet);

        while ($int > 0) {
            $string .= $this->alphabet[($int % $base)];

            $int = floor($int / $base);
        }

        return strrev($string);
    }

    /**
     * Decodes any string into an interval value
     *
     * @param $str
     *
     * @throws \InvalidArgumentException
     * @return int
     */
    public function decode($str)
    {
        if (!is_string($str)) {
            throw new \InvalidArgumentException('You can only decode a string');
        }

        $int = 0;

        $base = strlen($this->alphabet);

        for ($i=0; $i < strlen($str); $i++) {
            $pos = strpos($this->alphabet, $str[$i]);

            $int = $int * $base + $pos;
        }

        return $int;
    }
}

Change type check in encode to ctype_digit() for greater compatibility


<?php
/**
 * This file is part of the Composite Utils package.
 *
 * (c) Emily Shepherd <emily@emilyshepherd.me>
 *
 * For the full copyright and license information, please view the
 * LICENSE.md file that was distributed with this source code.
 *
 * @package spaark/composite-utils
 * @author Emily Shepherd <emily@emilyshepherd.me>
 * @license MIT
 */

namespace Spaark\CompositeUtils\Test\Model;

use Some\Test\NamespacePath\ClassName;
use Some\Other\Test\ClassName as AliasedClass;
use Spaark\CompositeUtils\Model\Collection\HashMap;

/**
 * @generic TypeA
 * @generic TypeB string
 */
class TestEntity
{
    /**
     * @var string
     * @readable
     * @writable
     * @construct required
     */
    protected $prop1 = 'foo';

    /**
     * @var ?string
     * @readable
     * @construct new
     */
    protected $prop2 = '123';

    /**
     * @var HashMap
     * @construct optional
     * @writable
     */
    protected $prop3;

    /**
     * @var boolean
     * @construct optional new
     */
    protected $prop4;

    /**
     * @var TestEntity
     */
    protected $prop5;

    public function __construct()
    {
        $this->prop3 = new HashMap();
    }

    /**
     * @param TestEntity $b
     */
    public function methodName(HashMap $a, $b) { }
}

<?php
/**
 * This file is part of the Composite Utils package.
 *
 * (c) Emily Shepherd <emily@emilyshepherd.me>
 *
 * For the full copyright and license information, please view the
 * LICENSE.md file that was distributed with this source code.
 *
 * @package spaark/composite-utils
 * @author Emily Shepherd <emily@emilyshepherd.me>
 * @license MIT
 */

namespace Spaark\CompositeUtils\Test\Model;

use Some\Test\NamespacePath\ClassName;
use Some\Other\Test\ClassName as AliasedClass;
use Spaark\CompositeUtils\Model\Collection\HashMap;

/**
 * @generic TypeA
 * @generic TypeB string
 */
class TestEntity
{
    /**
     * @var string
     * @readable true
     * @writable
     * @construct required
     */
    protected $prop1 = 'foo';

    /**
     * @var ?string
     * @readable
     * @writeable false
     * @construct new
     */
    protected $prop2 = '123';

    /**
     * @var HashMap
     * @construct optional
     * @writable 1
     */
    protected $prop3;

    /**
     * @var boolean
     * @construct optional new
     * @readable false
     * @writable false
     */
    protected $prop4;

    /**
     * @var TestEntity
     */
    protected $prop5;

    public function __construct()
    {
        $this->prop3 = new HashMap();
    }

    /**
     * @param TestEntity $b
     */
    public function methodName(HashMap $a, $b) { }
}

Update boolean params to broaden ReflectorFactory::setBool tests


<?php namespace Orchestra\Routing;

class RoutingServiceProvider extends \Illuminate\Routing\RoutingServiceProvider
{
    /**
     * Register the router instance.
     *
     * @return void
     */
    protected function registerRouter()
    {
        $this->app['router'] = $this->app->share(function ($app) {
            return new Router($app['events'], $app);
        });
    }
}

<?php namespace Orchestra\Routing;

use Illuminate\Http\Request;

class RoutingServiceProvider extends \Illuminate\Routing\RoutingServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerRequestOnConsole();

        parent::register();
    }

    /**
     * Register the requst on console interface.
     *
     * @return void
     */
    protected function registerRequestOnConsole()
    {
        if ($this->app->runningInConsole()) {
            $this->app->instance('request', Request::createFromGlobals());
        }
    }

    /**
     * Register the router instance.
     *
     * @return void
     */
    protected function registerRouter()
    {
        $this->app['router'] = $this->app->share(function ($app) {
            return new Router($app['events'], $app);
        });
    }
}

Create an instance of request for console interface.

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


<?php namespace Orchestra\Contracts\Config;

interface PackageRepository
{
    /**
     * Register a package for cascading configuration.
     *
     * @param  string  $package
     * @param  string  $hint
     * @param  string  $namespace
     * @return void
     */
    public function package($package, $hint, $namespace = null);
}

<?php namespace Orchestra\Contracts\Config;

interface PackageRepository
{
    /**
     * Register a package with custom file.
     *
     * @param  string  $package
     * @return void
     */
    public function file($package);

    /**
     * Register a package for cascading configuration.
     *
     * @param  string  $package
     * @param  string  $hint
     * @param  string  $namespace
     * @return void
     */
    public function package($package, $hint, $namespace = null);
}

Add support to register subdirectory config for Laravel 5 packages.

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