    uri() }}">

            present()->image(540, 400) }}" width="{{ $event->image->width }}" height="{{ $event->image->height }}" alt="">

{{ $event->present()->dateFromTo }}

{{ $event->title }}

                {{ $event->venue }}

{!! nl2br($event->address) !!}

            @empty(!$event->summary)

{{ $event->summary }}

            @endempty
            @empty(!$event->url)

url }}" target="_blank" rel="noopener noreferrer">{{ parse_url($event->url, PHP_URL_HOST) }}

            @endempty

    uri() }}">

            @empty (!$event->image)
            present()->image(540, 400) }}" width="{{ $event->image->width }}" height="{{ $event->image->height }}" alt="{{ $event->image->alt_attribute }}">
            @endempty

{{ $event->present()->dateFromTo }}

{{ $event->title }}

                {{ $event->venue }}

{!! nl2br($event->address) !!}

            @empty(!$event->summary)

{{ $event->summary }}

            @endempty
            @empty(!$event->url)

url }}" target="_blank" rel="noopener noreferrer">{{ parse_url($event->url, PHP_URL_HOST) }}

            @endempty

Check empty image + missing alt attribute.


<?php

namespace BringYourOwnIdeas\Maintenance\Tests\Tasks;

use BringYourOwnIdeas\Maintenance\Util\ComposerLoader;
use SapphireTest;
use BringYourOwnIdeas\Maintenance\Tasks\UpdatePackageInfo;

class UpdatePackageInfoTest extends SapphireTest
{
    public function testGetPackageInfo()
    {
        $loader = $this->getMockBuilder(ComposerLoader::class)->setMethods(['getLock'])->getMock();
        $loader->method('getLock')->willReturn(json_decode(<<<LOCK
{
    "packages": [
        {
            "name": "fake/package",
            "description": "A faux package from a mocked composer.lock for testing purposes",
            "version": "1.0.0"
        }
    ]
}
LOCK
        ));
        $processor = new UpdatePackageInfo;
        $output = $processor->getPackageInfo($loader->getLock()->packages);
        $this->assertInternalType('array', $output);
        $this->assertCount(1, $output);
        $this->assertSame([
            "Name" => "fake/package",
            "Description" => "A faux package from a mocked composer.lock for testing purposes",
            "Version" => "1.0.0"
        ], $output[0]);
    }
}

<?php

namespace BringYourOwnIdeas\Maintenance\Tests\Tasks;

use BringYourOwnIdeas\Maintenance\Util\ComposerLoader;
use SapphireTest;
use BringYourOwnIdeas\Maintenance\Tasks\UpdatePackageInfo;

class UpdatePackageInfoTest extends SapphireTest
{
    public function testGetPackageInfo()
    {
        $loader = $this->getMockBuilder(ComposerLoader::class)->setMethods(['getLock'])->getMock();
        $loader->expects($this->any())->method('getLock')->will($this->returnValue(json_decode(<<<LOCK
{
    "packages": [
        {
            "name": "fake/package",
            "description": "A faux package from a mocked composer.lock for testing purposes",
            "version": "1.0.0"
        }
    ]
}
LOCK
        )));
        $processor = new UpdatePackageInfo;
        $output = $processor->getPackageInfo($loader->getLock()->packages);
        $this->assertInternalType('array', $output);
        $this->assertCount(1, $output);
        $this->assertSame([
            "Name" => "fake/package",
            "Description" => "A faux package from a mocked composer.lock for testing purposes",
            "Version" => "1.0.0"
        ], $output[0]);
    }
}

FIX Use correct mock assertion methods for PHPUnit 3.7


<?php

error_reporting(E_ALL & ~E_STRICT);

require_once "vendor/autoload.php";

require_once "support/AssertLastError.php";

require_once "support/mock-functions/is_uploaded_file.php";
require_once "support/mock-functions/move_uploaded_file.php";

<?php

error_reporting(E_ALL);

require_once "vendor/autoload.php";

require_once "support/AssertLastError.php";

require_once "support/mock-functions/is_uploaded_file.php";
require_once "support/mock-functions/move_uploaded_file.php";

Enable strict errors in test suite

Enable strict errors in test suite


<?php

namespace duncan3dc\SessionsTest;

require __DIR__ . "/../vendor/autoload.php";

const SERVER_PORT = 5355;

# Start the internal web server for cookie based tests
exec("php -S localhost:" . SERVER_PORT . " -t " . __DIR__ . "/web >/dev/null 2>&1 & echo $!", $output, $status);
$pid = (int) $output[0];

# Ensure the internal web server is killed when the tests end
register_shutdown_function(function () use ($pid) {
    exec("kill {$pid}");
});

<?php

namespace duncan3dc\SessionsTest;

require __DIR__ . "/../vendor/autoload.php";

const SERVER_PORT = 15377;

# Start the internal web server for cookie based tests
exec("php -S localhost:" . SERVER_PORT . " -t " . __DIR__ . "/web >/dev/null 2>&1 & echo $!", $output, $status);
$pid = (int) $output[0];

# Ensure the internal web server is killed when the tests end
register_shutdown_function(function () use ($pid) {
    exec("kill {$pid}");
});

Update the port to test on as 5355 is used by systemd-resolve


<?php

namespace Phalcon\Mvc {

	/**
	 * Phalcon\Mvc\ModuleDefinitionInterface initializer
	 */

	interface ModuleDefinitionInterface {

		/**
		 * Registers an autoloader related to the module
		 *
		 * @param \Phalcon\DiInterface $dependencyInjector
		 */
		public function registerAutoloaders();

		/**
		 * Registers services related to the module
		 *
		 * @param \Phalcon\DiInterface $dependencyInjector
		 */
		public function registerServices($dependencyInjector);

	}
}

<?php

namespace Phalcon\Mvc {

	/**
	 * Phalcon\Mvc\ModuleDefinitionInterface initializer
	 */

	interface ModuleDefinitionInterface {

		/**
		 * Registers an autoloader related to the module
		 *
		 * @param \Phalcon\DiInterface $dependencyInjector
		 */
		public function registerAutoloaders($dependencyInjector);

		/**
		 * Registers services related to the module
		 *
		 * @param \Phalcon\DiInterface $dependencyInjector
		 */
		public function registerServices($dependencyInjector);

	}
}

Correct method definition for registerAutoloaders


<?php

namespace Bookboon\ApiBundle\DependencyInjection;

use Bookboon\Api\Cache\RedisCache;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    /**
     * Generates the configuration tree builder.
     *
     * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('bookboonapi');

        $rootNode->children()
            ->scalarNode('id')->isRequired()->end()
            ->scalarNode('secret')->isRequired()->end()
            ->scalarNode('branding')->end()
            ->scalarNode('rotation')->end()
            ->scalarNode('currency')->end()
            ->scalarNode('impersonator_id')->defaultNull()->end()
            ->scalarNode('redirect')->defaultNull()->end()
            ->scalarNode('cache_service')->defaultValue(RedisCache::class)->end()
            ->arrayNode('languages')->isRequired()->prototype('scalar')->end()->end()
            ->arrayNode('scopes')->isRequired()->prototype('scalar')->end()->end()
            ->integerNode('premium_level')->end()
            ->scalarNode('override_api_uri')->defaultNull()->end()
            ->scalarNode('override_auth_uri')->defaultNull()->end()
            ;

        return $treeBuilder;
    }
}

<?php

namespace Bookboon\ApiBundle\DependencyInjection;

use Bookboon\Api\Cache\RedisCache;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    /**
     * Generates the configuration tree builder.
     *
     * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('bookboonapi');

        $treeBuilder
            ->getRootNode()
            ->children()
            ->scalarNode('id')->isRequired()->end()
            ->scalarNode('secret')->isRequired()->end()
            ->scalarNode('branding')->end()
            ->scalarNode('rotation')->end()
            ->scalarNode('currency')->end()
            ->scalarNode('impersonator_id')->defaultNull()->end()
            ->scalarNode('redirect')->defaultNull()->end()
            ->scalarNode('cache_service')->defaultValue(RedisCache::class)->end()
            ->arrayNode('languages')->isRequired()->prototype('scalar')->end()->end()
            ->arrayNode('scopes')->isRequired()->prototype('scalar')->end()->end()
            ->integerNode('premium_level')->end()
            ->scalarNode('override_api_uri')->defaultNull()->end()
            ->scalarNode('override_auth_uri')->defaultNull()->end()
            ;

        return $treeBuilder;
    }
}

Use TreeBuilder constructor, deprecated using RootNode


<?php

namespace PhpParser\Node\Expr;

use PhpParser\Node\Expr;

/**
 * @property Expr $var  Variable
 * @property Expr $expr Expression
 */
abstract class AssignOp extends Expr
{
    /** @var Expr Variable */
    public $var;
    /** @var Expr Expression */
    public $expr;

    /**
     * Constructs a compound assignment operation node.
     *
     * @param Expr  $var        Variable
     * @param Expr  $expr       Expression
     * @param array $attributes Additional attributes
     */
    public function __construct(Expr $var, Expr $expr, array $attributes = array()) {
        parent::__construct($attributes);
        $this->var = $var;
        $this->expr = $expr;
    }

    public function getSubNodeNames() {
        return array('var', 'expr');
    }
}

<?php

namespace PhpParser\Node\Expr;

use PhpParser\Node\Expr;

abstract class AssignOp extends Expr
{
    /** @var Expr Variable */
    public $var;
    /** @var Expr Expression */
    public $expr;

    /**
     * Constructs a compound assignment operation node.
     *
     * @param Expr  $var        Variable
     * @param Expr  $expr       Expression
     * @param array $attributes Additional attributes
     */
    public function __construct(Expr $var, Expr $expr, array $attributes = array()) {
        parent::__construct($attributes);
        $this->var = $var;
        $this->expr = $expr;
    }

    public function getSubNodeNames() {
        return array('var', 'expr');
    }
}

Remove some unecessary @property doc comments


<?php

namespace Oro\Bundle\EmailBundle\Event;

use Symfony\Component\EventDispatcher\Event;
use Oro\Bundle\EmailBundle\Entity\Email;

class EmailBodyAdded extends Event
{
    const NAME = 'oro_email.email_attachment_manager.email_body_added';

    /** @var Email */
    protected $email;

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

    /**
     * @return Email
     */
    public function getEmail()
    {
        return $this->email;
    }

}

CRM-2268: Add attachments to emails
- fix code standards


<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Order;

class OrderController extends Controller
{
    public function index()
    {
        $orders = Order::all();
        return view('admin.orders.index')->with('orders', $orders);
    }

    public function show($id)
    {
        $order = Order::findOrFail($id);
        $status = $order->status;
        $total_amount = 0;
        foreach ($order->orderProducts as $product) {
            $amount = $product->price*$product->quantity;
            $total_amount = $amount + $total_amount;
        }
        return view('admin.orders.show')->with('order', $order)->with('status', $status)->with('total_amount', $total_amount);
    }

    public function edit(Request $request, $id)
    {
        $aa = $request->status;
        $order = Order::findOrFail($id);
        $order->update($request->all());
        return redirect()->route('adminOrdersShow', ['id' => $id]);
    }
}

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Order;

class OrderController extends Controller
{
    public function index()
    {
        $orders = Order::all();
        return view('admin.orders.index')->with('orders', $orders);
    }

    public function show($id)
    {
        $order = Order::findOrFail($id);
        $status = $order->status;
        $total_amount = 0;
        foreach ($order->orderProducts as $product) {
            $amount = $product->price*$product->quantity;
            $total_amount = $amount + $total_amount;
        }
        return view('admin.orders.show')
            ->with('order', $order)
            ->with('status', $status)
            ->with('total_amount', $total_amount);
    }

    public function edit(Request $request, $id)
    {
        $aa = $request->status;
        $order = Order::findOrFail($id);
        $order->update($request->all());
        return redirect()->route('adminOrdersShow', ['id' => $id]);
    }
}

Update admin order show page

fix(shop): Update admin order show page

Update admin order show page

see #401


<?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\Order\Model;

use Sylius\Component\Resource\Model\TimestampableInterface;

interface CommentInterface extends TimestampableInterface
{
    /**
     * @return OrderInterface
     */
    public function getOrder();

    /**
     * @param OrderInterface $order
     */
    public function setOrder(OrderInterface $order = null);

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

    /**
     * @param string $state
     */
    public function setState($state);

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

    /**
     * @param string $comment
     */
    public function setComment($comment);

    /**
     * @return bool
     */
    public function getNotifyCustomer();

    /**
     * @param bool $notifyCustomer
     */
    public function setNotifyCustomer($notifyCustomer);

    /**
     * @return null|string
     */
    public function getAuthor();

    /**
     * @param string $author
     */
    public function setAuthor($author);
}

<?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\Order\Model;

use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;

interface CommentInterface extends ResourceInterface, TimestampableInterface
{
    /**
     * @return OrderInterface
     */
    public function getOrder();

    /**
     * @param OrderInterface $order
     */
    public function setOrder(OrderInterface $order = null);

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

    /**
     * @param string $state
     */
    public function setState($state);

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

    /**
     * @param string $comment
     */
    public function setComment($comment);

    /**
     * @return bool
     */
    public function getNotifyCustomer();

    /**
     * @param bool $notifyCustomer
     */
    public function setNotifyCustomer($notifyCustomer);

    /**
     * @return null|string
     */
    public function getAuthor();

    /**
     * @param string $author
     */
    public function setAuthor($author);
}

Fix cart and item controllers

Fix cart and item controllers


<?php

namespace Moip\Tests\Resource;

use Moip\Tests\MoipTestCase;

/**
* class CustomerTest
*/
class CustomerTest extends MoipTestCase
{
	/**
	 * Test if const \Moip\Resource\Customer::PATH is valid.
	 */
	public function testShouldReceiveConstPathIsValid()
	{
		$path = 'customers';
		$const_path = constant('\Moip\Resource\Customer::PATH');

		$this->assertEquals($path, $const_path);
	}
}

<?php

namespace Moip\Tests\Resource;

use Moip\Tests\MoipTestCase;

/**
* class CustomerTest
*/
class CustomerTest extends MoipTestCase
{
	/**
	 * Test if const \Moip\Resource\Customer::PATH is valid.
	 */
	public function testShouldReceiveConstPathIsValid()
	{
		$path = 'customers';
		$const_path = constant('\Moip\Resource\Customer::PATH');

		$this->assertEquals($path, $const_path);
	}

	/**
	 * Test if const \Moip\Resource\Customer::ADDRESS_BILLING is valid.
	 */
	public function testShouldReceiveConstAddressBillingIsValid()
	{
		$address_billing = 'BILLING';
		$const_address_billing = constant('\Moip\Resource\Customer::ADDRESS_BILLING');

		$this->assertEquals($address_billing, $const_address_billing);
	}
}


<!DOCTYPE html>

	<meta charset="utf-8">
	<title>{{ Config::get('administrator::administrator.title') }}</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta name="description" content="">

	{{ Asset::container('container')->styles() }}

	<link rel="shortcut icon" href="public/img/ico/favicon.ico">
	<link rel="apple-touch-icon-precomposed" sizes="144x144" href="public/img/ico/apple-touch-icon-144-precomposed.png">
	<link rel="apple-touch-icon-precomposed" sizes="114x114" href="public/img/ico/apple-touch-icon-114-precomposed.png">
	<link rel="apple-touch-icon-precomposed" sizes="72x72" href="public/img/ico/apple-touch-icon-72-precomposed.png">
	<link rel="apple-touch-icon-precomposed" href="public/img/ico/apple-touch-icon-57-precomposed.png">

			@include('administrator::partials.header')

			{{ $content }}

			@include('administrator::partials.footer')

	{{ Asset::container('container')->scripts() }}

<!DOCTYPE html>

	<meta charset="utf-8">
	<title>{{ Config::get('administrator::administrator.title') }}</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta name="description" content="">

	{{ Asset::container('container')->styles() }}

			@include('administrator::partials.header')

			{{ $content }}

			@include('administrator::partials.footer')

	{{ Asset::container('container')->scripts() }}

Remove some legacy stuff from original fork of Lara Admin


<?php
namespace Concrete\Core\Error\Provider;

use Concrete\Core\Error\Handler\ErrorHandler;
use Concrete\Core\Error\Handler\JsonErrorHandler;
use Concrete\Core\Foundation\Service\Provider;
use Whoops\Handler\PlainTextHandler;
use Whoops\Run;
use Whoops\Util\Misc;

class WhoopsServiceProvider extends Provider
{
    public function register()
    {
        if (function_exists('ini_set')) {
            ini_set('display_errors', 0);
        }

        $run = new Run();

        $handler = new ErrorHandler();
        $run->pushHandler($handler);

        $json_handler = new JsonErrorHandler();
        $run->pushHandler($json_handler);

        if (Misc::isCommandLine()) {
            $cli_handler = new PlainTextHandler();
            $cli_handler->addTraceFunctionArgsToOutput(true);
            $cli_handler->addTraceToOutput(true);
            $run->pushHandler($cli_handler);
        }

        $run->register();
        $this->app->instance(Run::class, $run);
    }
}

<?php
namespace Concrete\Core\Error\Provider;

use Concrete\Core\Error\Handler\ErrorHandler;
use Concrete\Core\Error\Handler\JsonErrorHandler;
use Concrete\Core\Foundation\Service\Provider;
use Whoops\Handler\PlainTextHandler;
use Whoops\Run;
use Whoops\Util\Misc;

class WhoopsServiceProvider extends Provider
{
    public function register()
    {
        if (function_exists('ini_set')) {
            ini_set('display_errors', 0);
        }

        $run = new Run();

        $handler = new ErrorHandler();
        $run->pushHandler($handler);

        $json_handler = new JsonErrorHandler();
        $run->pushHandler($json_handler);

        if (Misc::isCommandLine()) {
            $cli_handler = new PlainTextHandler();
            if (method_exists($cli_handler, 'setDumper')) {
                // Available since Whoops 2.1.10
                $cli_handler->setDumper(function ($var) {
                    var_dump_safe($var, true, 2);
                });
            }
            $cli_handler->addTraceFunctionArgsToOutput(true);
            $cli_handler->addTraceToOutput(true);
            $run->pushHandler($cli_handler);
        }

        $run->register();
        $this->app->instance(Run::class, $run);
    }
}

Use var_dump_safe instead of var_dump in Whoops PlainTextHandler


Add border to wysiyg value field

Add border to wysiyg value field


<?php
/**
 * PHP version 7.1
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
use Mandragora\Controller\Plugin\Router;
use Zend_Application as Application;

/**
 * Base class used to perform unit testing on Zend applications
 */
abstract class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
    /** @var Application */
    protected $application;

    /**
     * Bootstraps the application before running the tests
     */
    public function setUp()
    {
        $this->bootstrap = [$this, 'applicationBootstrap'];
        parent::setUp();
    }

    /**
     * Initializes the application using the testing environment
     *
     * @throws \Zend_Application_Exception
     */
    public function applicationBootstrap()
    {
        $this->application = new Application(
            APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini'
        );
        $this->application->bootstrap();
        $bootstrap = $this->application->getBootstrap();

        /** @var \Zend_Controller_Front $front */
        $this->_frontController = $bootstrap->getResource('FrontController');
        $this->_frontController->setParam('bootstrap', $bootstrap);

        $this
            ->_frontController
            ->getPlugin(Router::class)
            ->routeStartup($this->getRequest())
        ;
    }
}

<?php
/**
 * PHP version 7.1
 *
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
use Mandragora\Controller\Plugin\Router;
use Zend_Application as Application;

/**
 * Base class used to perform unit testing on Zend applications
 */
abstract class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
    /** @var Application */
    protected $application;

    /**
     * Bootstraps the application before running the tests
     */
    public function setUp()
    {
        $this->bootstrap = [$this, 'applicationBootstrap'];
        parent::setUp();
    }

    /**
     * Initializes the application using the testing environment
     *
     * @throws \Zend_Application_Exception
     */
    public function applicationBootstrap()
    {
        defined('PUBLIC_PATH') || define('PUBLIC_PATH', __DIR__ . '/../admin.edeco.mx');
        $this->application = new Application(
            APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini'
        );
        $this->application->bootstrap();
        $bootstrap = $this->application->getBootstrap();

        /** @var \Zend_Controller_Front $front */
        $this->_frontController = $bootstrap->getResource('FrontController');
        $this->_frontController->setParam('bootstrap', $bootstrap);

        $this
            ->_frontController
            ->getPlugin(Router::class)
            ->routeStartup($this->getRequest())
        ;
    }
}

Fix issue with the output of the integration tests.


<?php
$I = new AcceptanceTester($scenario);
$I->wantTo('ensure that a user can view a list of their projects');
TestCommonUser::logMeIn($I);
$I->click('Projects');
$I->see('Sample Project', 'tr');
$I->see('Test Project', 'tr');
$I->see('user', 'tr');

<?php
$I = new AcceptanceTester($scenario);
$I->wantTo('ensure that a user can view a list of their projects');
TestCommonUser::logMeIn($I);
$I->click('Projects');
$I->see('Sample Project', 'tr');
$I->see('user', 'tr');

Fix test that was checking for a dummy project that doesn't exist


<?php

namespace App\Handler\Email;

class SendSignupReceivedEmailHandler extends AbstractEmailHandler
{
    protected function configureMessage(\Swift_Message $email, $command): void
    {
        $email
            ->setSubject('Your account has been created')
            ->setBody('Thank you! Your account has been created and you will be contacted in 2 business days when it is active.')
        ;
    }
}

<?php

namespace App\Handler\Email;

use App\Command\Email\AbstractSendEmailCommand;
use App\Command\Email\SendSignupReceivedEmailCommand;

class SendSignupReceivedEmailHandler extends AbstractEmailHandler
{
    protected function configureMessage(\Swift_Message $email, AbstractSendEmailCommand $command): void
    {
        $email
            ->setSubject('Your account has been created')
            ->setBody('Thank you! Your account has been created and you will be contacted in 2 business days when it is active.')
        ;
    }
}

Add use command calls to signup handler, pass in command object.


<?php
/*-------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) PHP-Fusion Inc
| http://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Filename: user_forum-stat_include.php
| Author: Digitanium
+--------------------------------------------------------+
| This program is released as free software under the
| Affero GPL license. You can redistribute it and/or
| modify it under the terms of this license which you
| can read by viewing the included agpl.txt or online
| at www.gnu.org/licenses/agpl.html. Removal of this
| copyright header is strictly prohibited without
| written permission from the original author(s).
+--------------------------------------------------------*/
if (!defined("IN_FUSION")) { die("Access Denied"); }

if ($profile_method == "input") {
	//Nothing here
} elseif ($profile_method == "display") {
	echo "
\n";
	echo "".$locale['uf_forum-stat']."	\n";
	echo "".number_format($user_data['user_posts'])."	\n";
	echo "
\n";
} elseif ($profile_method == "validate_insert") {
	//Nothing here
} elseif ($profile_method == "validate_update") {
	//Nothing here
}
?>

<?php
/*-------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) PHP-Fusion Inc
| http://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Filename: user_forum-stat_include.php
| Author: Digitanium
+--------------------------------------------------------+
| This program is released as free software under the
| Affero GPL license. You can redistribute it and/or
| modify it under the terms of this license which you
| can read by viewing the included agpl.txt or online
| at www.gnu.org/licenses/agpl.html. Removal of this
| copyright header is strictly prohibited without
| written permission from the original author(s).
+--------------------------------------------------------*/
if (!defined("IN_FUSION")) { die("Access Denied"); }

if ($profile_method == "input") {
	//Nothing here
	$user_fields = '';
	if (defined('ADMIN_PANEL')) { // To show in admin panel only.
		$user_fields = "
".$locale['uf_forum-stat']."
";
	}
} elseif ($profile_method == "display") {
	$user_fields = array('title'=>$locale['uf_forum-stat'], 'value'=>$user_data['user_posts']);
} elseif ($profile_method == "validate_insert") {
	//Nothing here
} elseif ($profile_method == "validate_update") {
	//Nothing here
}
?>

Change MVC construct for User Fields.

Change MVC construct for User Fields.


<?php namespace Modules\Setting\Database\Seeders;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Modules\Setting\Repositories\SettingRepository;

class SettingDatabaseSeeder extends Seeder
{
    /**
     * @var SettingRepository
     */
    private $setting;

    public function __construct(SettingRepository $setting)
    {
        $this->setting = $setting;
    }

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        $data = [
            'name' => 'core::template',
            'plainValue' => 'Demo',
            'isTranslatable' => false,
        ];

        $this->setting->create($data);
    }
}

<?php namespace Modules\Setting\Database\Seeders;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Modules\Setting\Repositories\SettingRepository;

class SettingDatabaseSeeder extends Seeder
{
    /**
     * @var SettingRepository
     */
    private $setting;

    public function __construct(SettingRepository $setting)
    {
        $this->setting = $setting;
    }

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        $data = [
            'name' => 'core::template',
            'plainValue' => 'Flatly',
            'isTranslatable' => false,
        ];

        $this->setting->create($data);
    }
}

Change the default theme name

Change the default theme name


<?php

namespace App\Api\V1\Controllers;

use Gate;
use Activity;

use App\Models\ScreenGroup;
use App\Models\Client;

class ScreenGroupClientController extends BaseController
{

    public function destroy(ScreenGroup $screengroup, Client $client) {

        if (Gate::denies('edit_screengroup'))
            $this->response->error('permission_denied: edit_screengroup', 401);

        $client->update(['screen_group_id' => 1]);
        $client->save();

        Activity::log([
            'contentId' => $screengroup->id,
            'contentType' => 'ScreenGroupClient',
            'action' => 'Detach',
            'description' => 'Detached Client from ScreenGroup',
            'details' => $screengroup->clients->toJson(),
        ]);

        return $this->response->noContent();
    }

}

<?php

namespace App\Api\V1\Controllers;

use Gate;
use Activity;

use App\Models\ScreenGroup;
use App\Models\Client;

class ScreenGroupClientController extends BaseController
{

    public function destroy(ScreenGroup $screengroup, Client $client) {

        if (Gate::denies('edit_screengroup'))
            $this->response->error('permission_denied: edit_screengroup', 401);

        $client->update(['screen_group_id' => 0]);
        $client->save();

        Activity::log([
            'contentId' => $screengroup->id,
            'contentType' => 'ScreenGroupClient',
            'action' => 'Detach',
            'description' => 'Detached Client from ScreenGroup',
            'details' => $screengroup->clients->toJson(),
        ]);

        return $this->response->noContent();
    }

}

Set SG to 0 on detach

ScreengroupClients: Set SG to 0 on detach


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

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

class DefaultController extends Controller
{
    public function indexAction(Request $request)
    {
        return $this->render('MunicipalesBundle:Default:index.html.twig');
    }
}

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

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

class DefaultController extends Controller
{
    public function indexAction(Request $request)
    {
        return $this->render('MunicipalesBundle:Census:index.html.twig');
    }
}

Load Census folder view as default

Load Census folder view as default


<?php
/**
 * Trait for application object handling
 *
 * @file      ApplicationTrait.php
 *
 * PHP version 5.4+
 *
 * @author    Yancharuk Alexander <alex at itvault dot info>
 * @copyright © 2012-2016 Alexander Yancharuk
 * @date      2016-10-21 16:44
 * @license   The BSD 3-Clause License
 *            <https://tldrlegal.com/license/bsd-3-clause-license-(revised)>
 */

namespace Application;

trait ApplicationTrait
{
	protected $application;

	/**
	 * Get application object
	 *
	 * @return mixed
	 */
	public function getApplication()
	{
		return $this->application;
	}

	/**
	 * Set application
	 *
	 * @param mixed $application
	 *
	 * @return $this
	 */
	public function setApplication($application)
	{
		$this->application = $application;

		return $this;
	}
}

<?php
/**
 * Trait for application object handling
 *
 * @file      ApplicationTrait.php
 *
 * PHP version 5.4+
 *
 * @author    Yancharuk Alexander <alex at itvault dot info>
 * @copyright © 2012-2016 Alexander Yancharuk
 * @date      2016-10-21 16:44
 * @license   The BSD 3-Clause License
 *            <https://tldrlegal.com/license/bsd-3-clause-license-(revised)>
 */

namespace Application;

trait ApplicationTrait
{
	protected $application;

	/**
	 * Get application object
	 *
	 * @return $this
	 */
	public function getApplication()
	{
		return $this->application;
	}

	/**
	 * Set application
	 *
	 * @param mixed $application
	 *
	 * @return $this
	 */
	public function setApplication($application)
	{
		$this->application = $application;

		return $this;
	}
}

Fix application trai doc-tag return

Fix application trai doc-tag return


<?php

declare(strict_types=1);

return [
    'whitelist' => [
        '\Phpcq\PluginApi\*'
    ],
];

<?php

declare(strict_types=1);

use Isolated\Symfony\Component\Finder\Finder;

// Symfony polyfills must live in global namespace.
$symfonyPolyfill = (static function (): array {
    $files = [];
    foreach (
        Finder::create()
            ->files()
            ->in(__DIR__ . '/../../vendor/symfony/polyfill-*')
            ->name('bootstrap.php') as $bootstrap
    ) {
        $files[] = $bootstrap->getPathName();
    }

    return $files;
})();

return [
    'whitelist' => [
        '\Phpcq\PluginApi\*'
    ],
    'files-whitelist' => $symfonyPolyfill,
];

Whitelist symfony polyfills for global namespace


<?php
/*
 * Created on Aug 19, 2009
 *
 *  SVN INFORMATION:::
 * -------------------
 * Last Author::::::::: $Author$
 * Current Revision:::: $Revision$
 * Repository Location: $HeadURL$
 * Last Updated:::::::: $Date$
 */

abstract class cs_webapplibsAbstract extends cs_versionAbstract {

	protected $gfObj;

	//-------------------------------------------------------------------------
    function __construct($makeGfObj=true) {
		$this->set_version_file_location(dirname(__FILE__) . '/../VERSION');
		$this->get_version();
		$this->get_project();

		if($makeGfObj === true) {
			//make a cs_globalFunctions{} object.
			//TODO::: find a way to avoid h
			$this->gfObj = new cs_globalFunctions();
		}
    }//end __construct()
	//-------------------------------------------------------------------------
}

?>

<?php
/*
 * Created on Aug 19, 2009
 *
 *  SVN INFORMATION:::
 * -------------------
 * Last Author::::::::: $Author$
 * Current Revision:::: $Revision$
 * Repository Location: $HeadURL$
 * Last Updated:::::::: $Date$
 */

abstract class cs_webapplibsAbstract extends cs_versionAbstract {

	protected $gfObj;

	//-------------------------------------------------------------------------
    public function __construct($makeGfObj=true) {
		$this->set_version_file_location(dirname(__FILE__) . '/../VERSION');

		if($makeGfObj === true) {
			//make a cs_globalFunctions{} object.
			//TODO::: find a way to avoid h
			$this->gfObj = new cs_globalFunctions();
		}
    }//end __construct()
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	public function load_schema($dbType, cs_phpDb $db) {
		$file = dirname(__FILE__) .'/../setup/schema.'. $dbType .'.sql';
		try {
			$result = $db->run_sql_file($file);
		}
		catch(Exception $e) {
			throw new exception(__METHOD__ .": failed to load schema file (". $file ."), DETAILS::: ". $e->getMessage());
		}
		return($result);
	}//end load_schema()
	//-------------------------------------------------------------------------
}

?>

Add method to load database schema, remove unnecessary calls from constructor.


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

namespace Darvin\ContentBundle\Traits;

use Doctrine\ORM\QueryBuilder;

/**
 * Translatable entity repository trait
 */
trait TranslatableRepositoryTrait
{
    /**
     * @param \Doctrine\ORM\QueryBuilder $qb        Query builder
     * @param string|null                $locale    Locale
     * @param bool                       $addSelect Whether to add select
     *
     * @return self
     */
    protected function joinTranslations(QueryBuilder $qb, ?string $locale = null, bool $addSelect = true)
    {
        $qb->innerJoin('o.translations', 'translations');

        if (!empty($locale)) {
            $qb->andWhere('translations.locale = :locale')->setParameter('locale', $locale);
        }
        if ($addSelect) {
            $qb->addSelect('translations');
        }

        return $this;
    }
}

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

namespace Darvin\ContentBundle\Traits;

use Doctrine\ORM\QueryBuilder;

/**
 * Translatable entity repository trait
 */
trait TranslatableRepositoryTrait
{
    /**
     * @param \Doctrine\ORM\QueryBuilder $qb        Query builder
     * @param string|null                $locale    Locale
     * @param bool                       $addSelect Whether to add select
     *
     * @return self
     */
    protected function joinTranslations(QueryBuilder $qb, ?string $locale = null, bool $addSelect = true)
    {
        $qb->innerJoin('o.translations', 'translations');

        if (!empty($locale)) {
            $qb->andWhere('translations.locale = :locale')->setParameter('locale', $locale);
        }
        if ($addSelect) {
            $qb->addSelect('translations');
        }

        return $this;
    }

    /**
     * @param \Doctrine\ORM\QueryBuilder $qb        Query builder
     * @param string|null                $locale    Locale
     * @param bool                       $addSelect Whether to add select
     *
     * @return self
     */
    protected function leftJoinTranslations(QueryBuilder $qb, ?string $locale = null, bool $addSelect = true)
    {
        $qb->leftJoin('o.translations', 'translations');

        if (!empty($locale)) {
            $qb
                ->andWhere($qb->expr()->orX(
                    'translations.locale IS NULL',
                    'translations.locale = :locale'
                ))
                ->setParameter('locale', $locale);
        }
        if ($addSelect) {
            $qb->addSelect('translations');
        }

        return $this;
    }
}

Add left join translations method to the translatable repository trait.


<?php

namespace Opifer\ContentBundle\ValueProvider;

use Symfony\Component\Form\FormBuilderInterface;
use Opifer\EavBundle\ValueProvider\AbstractValueProvider;
use Opifer\EavBundle\ValueProvider\ValueProviderInterface;

class ContentValueProvider extends AbstractValueProvider implements ValueProviderInterface
{

    /**
     * {@inheritDoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('content', 'contentpicker', [
            'label'    => false,
        ]);
    }

    /**
     * {@inheritDoc}
     */
    public function getEntity()
    {
        return 'Opifer\ContentBundle\Entity\ContentValue';
    }

    /**
     * {@inheritDoc}
     */
    public function getLabel()
    {
        return 'Content picker';
    }
}

<?php

namespace Opifer\ContentBundle\ValueProvider;

use Symfony\Component\Form\FormBuilderInterface;
use Opifer\EavBundle\ValueProvider\AbstractValueProvider;
use Opifer\EavBundle\ValueProvider\ValueProviderInterface;

class ContentValueProvider extends AbstractValueProvider implements ValueProviderInterface
{

    /**
     * {@inheritDoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('content', 'contentpicker', [
            'label'    => false,
        ]);
    }

    /**
     * {@inheritDoc}
     */
    public function getEntity()
    {
        return 'Opifer\ContentBundle\Entity\ContentValue';
    }

    /**
     * {@inheritDoc}
     */
    public function getLabel()
    {
        return 'Content item';
    }
}

Set Content item as name of the UI element


<?php

namespace DreamFactory\Core\Resources\System;

use DreamFactory\Core\Contracts\ServiceTypeInterface;
use DreamFactory\Core\Exceptions\NotFoundException;
use DreamFactory\Core\Resources\BaseRestResource;
use DreamFactory\Core\Utility\ResourcesWrapper;
use ServiceManager;

class ServiceType extends BaseRestResource
{
    /**
     * {@inheritdoc}
     */
    protected static function getResourceIdentifier()
    {
        return 'name';
    }

    /**
     * Handles GET action
     *
     * @return array
     * @throws \DreamFactory\Core\Exceptions\NotFoundException
     */
    protected function handleGET()
    {
        if (!empty($this->resource)) {
            if (null === $type = ServiceManager::getServiceType($this->resource)) {
                throw new NotFoundException("Service type '{$this->resource}' not found.");
            }

            return $type->toArray();
        }

        $resources = [];
        $group = $this->request->getParameter('group');
        $types = ServiceManager::getServiceTypes($group);
        /** @type ServiceTypeInterface $type */
        foreach ($types as $type) {
            $resources[] = $type->toArray();
        }

        return ResourcesWrapper::wrapResources($resources);
    }
}

<?php

namespace DreamFactory\Core\Resources\System;

use DreamFactory\Core\Contracts\ServiceTypeInterface;
use DreamFactory\Core\Enums\ApiOptions;
use DreamFactory\Core\Exceptions\NotFoundException;
use DreamFactory\Core\Resources\BaseRestResource;
use DreamFactory\Core\Utility\ResourcesWrapper;
use ServiceManager;

class ServiceType extends BaseRestResource
{
    /**
     * {@inheritdoc}
     */
    protected static function getResourceIdentifier()
    {
        return 'name';
    }

    /**
     * Handles GET action
     *
     * @return array
     * @throws \DreamFactory\Core\Exceptions\NotFoundException
     */
    protected function handleGET()
    {
        if (!empty($this->resource)) {
            /** @type ServiceTypeInterface $type */
            if (null === $type = ServiceManager::getServiceType($this->resource)) {
                throw new NotFoundException("Service type '{$this->resource}' not found.");
            }

            return $type->toArray();
        }

        $resources = [];
        $group = $this->request->getParameter('group');
        $types = ServiceManager::getServiceTypes($group);
        /** @type ServiceTypeInterface $type */
        foreach ($types as $type) {
            $resources[] = $type->toArray();
        }

        $asList = $this->request->getParameterAsBool(ApiOptions::AS_LIST);
        $idField = $this->request->getParameter(ApiOptions::ID_FIELD, static::getResourceIdentifier());
        $fields = $this->request->getParameter(ApiOptions::FIELDS, ApiOptions::FIELDS_ALL);

        return ResourcesWrapper::cleanResources($resources, $asList, $idField, $fields);
    }
}

Allow API options to work on service_type


<?php
/*
 * Limb PHP Framework
 *
 * @link http://limb-project.com
 * @copyright  Copyright © 2004-2009 BIT(http://bit-creative.com)
 * @license    LGPL http://www.gnu.org/copyleft/lesser.html
 */

lmb_require('limb/macro/src/tags/form/lmbMacroCheckableInputWidget.class.php');

/**
 * class lmbMacroJSCheckboxWidget.
 *
 * @package macro
 * @version $Id$
 */
class lmbMacroJSCheckboxWidget extends lmbMacroCheckableInputWidget
{
  protected $skip_render = array('name', 'checked_value');
  protected $hidden_id;

  function renderAttributes()
  {
    parent :: renderAttributes();

    $this->hidden_id = uniqid('js_checkbox_');
    echo " onchange=\"this.form.elements['{$this->hidden_id}'].value = this.checked * ((!isNaN(this.value*this.checked)) ? this.value : 1)\"";
  }

  function renderHidden()
  {
    $hidden_name = $this->getAttribute('name');

    if($this->isChecked())
      $value = 1;
    else
      $value = 0;

    echo "<input type=\"hidden\" id=\"{$this->hidden_id}\" name=\"{$hidden_name}\" value=\"{$value}\" />";
  }
}

<?php
/*
 * Limb PHP Framework
 *
 * @link http://limb-project.com
 * @copyright  Copyright © 2004-2009 BIT(http://bit-creative.com)
 * @license    LGPL http://www.gnu.org/copyleft/lesser.html
 */

lmb_require('limb/macro/src/tags/form/lmbMacroCheckableInputWidget.class.php');

/**
 * class lmbMacroJSCheckboxWidget.
 *
 * @package macro
 * @version $Id$
 */
class lmbMacroJSCheckboxWidget extends lmbMacroCheckableInputWidget
{
  protected $skip_render = array('name', 'checked_value');
  protected $hidden_id;

  function renderAttributes()
  {
    parent :: renderAttributes();

    $this->hidden_id = uniqid('js_checkbox_');
    echo " onchange=\"var el = (this.form != undefined) ? this.form.elements['{$this->hidden_id}'] : document.getElementById('{$this->hidden_id}'); el.value = (isNaN(this.checked) ? 0 : 1) * (isNaN(this.value) ? 1 : this.value);\"";
  }

  function renderHidden()
  {
    $hidden_name = $this->getAttribute('name');

    if($this->isChecked())
      $value = 1;
    else
      $value = 0;

    echo "<input type=\"hidden\" id=\"{$this->hidden_id}\" name=\"{$hidden_name}\" value=\"{$value}\" />";
  }
}

Fix tag 'js_checkbox' for usage that outside of the tag 'form'


<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Lifecycle Building Center</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width" />

        <link rel="stylesheet" type="text/css" href="/assets/style/bootstrap.min.css" media="screen,projection" />

								Link

								Link

								Link

								Link

<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Lifecycle Building Center</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="description" content="" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" type="text/css" href="/assets/style/bootstrap-responsive.min.css" media="screen,projection" />

								Home

								Contact

Switch to responsive bootstrap CSS and add needed nav items


<?php

class TypeJugglingTest extends PHPUnit_Framework_TestCase
{
    public function testFromFalseOrNullToArray()
    {
        foreach (array(false, null) as $testValue) {
            $var = $testValue;
            $var['foo'] = 10;
            $this->assertEquals('array', gettype($var));
        }
    }

    /**
     * @expectedException PHPUnit_Framework_Error
     * @expectedExceptionMessage Creating default object from empty value
     */
    public function testFromFalseToObject()
    {
        $var = false;
        $var->name = 'bob';
    }

    /**
     * @expectedException PHPUnit_Framework_Error_Warning
     * @expectedExceptionMessage Cannot use a scalar value as an array
     */
    public function testFromTrueToArray()
    {
        $var = true;
        $var['foo'] = 10;
        $this->assertEquals('array', gettype($var));
    }

    /**
     * @expectedException PHPUnit_Framework_Error_Warning
     */
    public function testFromStringToArray()
    {
        $this->markTestSkipped('This crash my (and Travis) PHP cli');
        // ... but PHP 5.4.6 on Ubuntu and PHPUnit 3.6.10 is ok, mmm
        $var = '2.5';
        $var['foo'] = 10;
    }
}

<?php

class TypeJugglingTest extends PHPUnit_Framework_TestCase
{
    public function testFromFalseOrNullToArray()
    {
        foreach (array(false, null) as $testValue) {
            $var = $testValue;
            $var['foo'] = 10;
            $this->assertEquals('array', gettype($var));
        }
    }

    public function testFromFalseToObject()
    {
        if (version_compare(PHP_VERSION, '5.3', '>='))
            $this->setExpectedException('PHPUnit_Framework_Error_Notice');
        if (version_compare(PHP_VERSION, '5.4', '>='))
            $this->setExpectedException('PHPUnit_Framework_Error_Warning');
        $var = false;
        $var->name = 'bob';
    }

    /**
     * @expectedException PHPUnit_Framework_Error_Warning
     * @expectedExceptionMessage Cannot use a scalar value as an array
     */
    public function testFromTrueToArray()
    {
        $var = true;
        $var['foo'] = 10;
        $this->assertEquals('array', gettype($var));
    }

    /**
     * @expectedException PHPUnit_Framework_Error_Warning
     */
    public function testFromStringToArray()
    {
        $this->markTestSkipped('This crash my (and Travis) PHP cli');
        // ... but PHP 5.4.6 on Ubuntu and PHPUnit 3.6.10 is ok, mmm
        $var = '2.5';
        $var['foo'] = 10;
    }
}

Make falseToObject test pass on PHP 5.2

Make falseToObject test pass on PHP 5.2


<?php

namespace App\Http\Middleware;

use App\User;
use Auth;
use Closure;
use Illuminate\Contracts\Auth\Guard;

class Api
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

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

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $apikey = $request->get('key');
        if (!$apikey) {
            return response()->json(["message" => "Missing API key", 'code' => 401]);
        }

        $user = User::where('apikey', $apikey)->first();
        if (!$user) {
            return response()->json(["message" => "Invalid API key", 'code' => 401]);
        }

        if (!$user->enabled) {
            return response()->json(["message" => "Your account has not been approved by an admin", 'code' => 401]);
        }

        if ($user->banned) {
            return response()->json(["message" => "You are banned", 'code' => 401]);
        }

        Auth::onceUsingId($user->id);
        return $next($request);
    }
}

<?php

namespace App\Http\Middleware;

use App\User;
use Auth;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Input;

class Api
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

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

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!Input::has('key')) {
            return response()->json(["message" => "Missing API key", 'code' => 401]);
        }

        $apikey = Input::get('key');
        $user = User::where('apikey', $apikey)->first();
        if (!$user) {
            return response()->json(["message" => "Invalid API key", 'code' => 401]);
        }

        if (!$user->enabled) {
            return response()->json(["message" => "Your account has not been approved by an admin", 'code' => 401]);
        }

        if ($user->banned) {
            return response()->json(["message" => "You are banned", 'code' => 401]);
        }

        Auth::onceUsingId($user->id);
        return $next($request);
    }
}

Use Input instead of request

Use Input instead of request


<?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;

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

use Neos\Flow\Annotations as Flow;

class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource
{
    /**
     * Loads the specified configuration file and returns its content as an
     * array. If the file does not exist or could not be loaded, an empty
     * array is returned
     *
     * @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml")
     * @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files
     * @return array
     * @throws \Neos\Flow\Configuration\Exception\ParseErrorException
     */

    public function load($pathAndFilename, $allowSplitSource = false)
    {
        if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) {
            return [];
        } else {
            return parent::load($pathAndFilename, $allowSplitSource);
        }
    }
}

<?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;

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

use Neos\Flow\Annotations as Flow;

class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource
{
    /**
     * Loads the specified configuration file and returns its content as an
     * array. If the file does not exist or could not be loaded, an empty
     * array is returned
     *
     * @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml")
     * @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files
     * @return array
     * @throws \Neos\Flow\Configuration\Exception\ParseErrorException
     */

    public function load($pathAndFilename, $allowSplitSource = false): array
    {
        if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) {
            return [];
        } else {
            return parent::load($pathAndFilename, $allowSplitSource);
        }
    }
}

Fix test error with YamlSource

Fix test error with YamlSource


<?php namespace Phaza\LaravelPostgis;

use Bosnadev\Database\PostgresConnection;

class PostgisConnection extends PostgresConnection {
	/**
	 * Get the default schema grammar instance.
	 *
	 * @return \Illuminate\Database\Grammar
	 */
	protected function getDefaultSchemaGrammar()
	{
		return $this->withTablePrefix(new Schema\Grammars\PostgisGrammar);
	}
}

<?php namespace Phaza\LaravelPostgis;

class PostgisConnection extends Connection {
	/**
	 * Get the default schema grammar instance.
	 *
	 * @return \Illuminate\Database\Grammar
	 */
	protected function getDefaultSchemaGrammar()
	{
		return $this->withTablePrefix(new Schema\Grammars\PostgisGrammar);
	}
}

Use correct connection parent class

Use correct connection parent class


<?php

return [
    // External router settings
    'external_router' => [
        'default_url' => 'home',
        'prefixes' => [],
        'prefix_options' => [],
        'data_type' => 'query_string',
        'auto_trim' => true,
        'auto_null' => true
    ],

    // Auth settings
    'auth' => [
        'cookie_lifetime' => 86400,
        'session_lifetime' => 3600,
        'update_gap' => 1800,
        'pull_user' => false
    ],

    // LDAP settings
    'ldap' => [
        'hostname' => 'ldap.example.com',
        'port' => 389,
        'domain' => 'example.com'
    ],

    // Translator settings
    'translator' => [
        'default_locale' => 'en'
    ],
];

<?php

return [
    // View settings
    'view' => [
        'extension' => 'twig'
    ],

    // Auth settings
    'auth' => [
        'cookie_lifetime' => 86400,
        'session_lifetime' => 3600,
        'update_gap' => 1800,
        'pull_user' => false
    ],

    // LDAP settings
    'ldap' => [
        'hostname' => 'ldap.example.com',
        'port' => 389,
        'domain' => 'example.com'
    ],

    // Translator settings
    'translator' => [
        'default_locale' => 'en'
    ],
];

Remove not essential parameters from config file


<?php

namespace Phuby;

class Base64 {
    static function initialized($self) {
        $self->extend('self');
    }

    function decode64($string) {
        return base64_decode($string);
    }

    function encode64($string) {
        return base64_encode($string);
    }
}

<?php

namespace Phuby {
    class Base64 {
        static function initialized($self) {
            $self->extend('self');
            $self->include(__CLASS__.'\InstanceMethods');
        }
    }
}

namespace Phuby\Base64 {
    class InstanceMethods {
        function decode64($string) {
            return base64_decode($string);
        }

        function encode64($string) {
            return base64_encode($string);
        }
    }
}

Move Base64 logic into InstanceMethods module


<?php
/*
 * Copyright 2015 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
 */

namespace Chalk\Frontend;

use Chalk\Chalk;
use Closure;
use Coast\UrlResolver as CoastUrlResolver;

class UrlResolver extends CoastUrlResolver
{
    protected $_resolvers = [];

    public function __invoke()
    {
        $args = func_get_args();
        return call_user_func_array([$this, 'content'], $args);
    }

    public function content($content)
    {
        $info = Chalk::info($content);
        if (!isset($this->_resolvers[$info->name])) {
            return false;
        }
        foreach ($this->_resolvers[$info->name] as $resolver) {
            $result = $resolver($content);
            if (isset($result)) {
                if ($result) {
                    return $result;
                } else {
                    return false;
                }
            }
        }
    }

    public function resolver($entity, Closure $resolver)
    {
        $this->_resolvers[$entity][] = $resolver->bindTo($this);
        return $this;
    }
}

<?php
/*
 * Copyright 2015 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
 */

namespace Chalk\Frontend;

use Chalk\Chalk;
use Closure;
use Coast\UrlResolver as CoastUrlResolver;

class UrlResolver extends CoastUrlResolver
{
    protected $_resolvers = [];

    public function __invoke()
    {
        $args = func_get_args();
        if (!isset($args[0])) {
            $func = array($this, 'string');
        } else {
            $func = array($this, 'content');
        }
        return call_user_func_array($func, $args);
    }

    public function content($content)
    {
        $info = Chalk::info($content);
        if (!isset($this->_resolvers[$info->name])) {
            return false;
        }
        foreach ($this->_resolvers[$info->name] as $resolver) {
            $result = $resolver($content);
            if (isset($result)) {
                if ($result) {
                    return $result;
                } else {
                    return false;
                }
            }
        }
    }

    public function resolver($entity, Closure $resolver)
    {
        $this->_resolvers[$entity][] = $resolver->bindTo($this);
        return $this;
    }
}

Support base url in front-end url resolver.


<?php

namespace ArrayHelpers;

class Arr
{
    /**
     * @param array $array
     * @param string $key
     * @param mixed|null $default
     * @return mixed|null
     */
    public static function get(array $array, $key, $default = null)
    {
        if (!array_key_exists($key, $array)) {
            return $default;
        }

        return $array[$key];
    }
}

<?php

namespace ArrayHelpers;

class Arr
{
    /**
     * @param array $array
     * @param string $key
     * @param mixed|null $default
     * @return mixed|null
     */
    public static function get(array $array, $key, $default = null)
    {
        if (array_key_exists($key, $array)) {
            return $array[$key];
        }

        if (strpos($key, '.') === false) {
            return $default;
        }

        $keys = explode('.', $key);
        while(count($keys) > 0) {
            $subSet = $array[array_shift($keys)];
            if (is_array($subSet)) {
                return static::get($subSet, join('.', $keys), $default);
            }
        }

        return $default;
    }
}

Implement support of dot notation in get method


<?php

require_once __DIR__ . '/../bootstrap.php';

function generateAndOutput5(Broadway\Uuid\UuidGeneratorInterface $generator) {
    for ($i = 0; $i < 8; $i++) {
        echo sprintf("[%d] %s\n", $i, $generator->generate());
    }
}

echo "A random generated uuid:\n";
$randomGenerator = new Broadway\Uuid\Rfc4122\Version4Generator();
generateAndOutput5($randomGenerator);

echo "\n";

echo "A generator that will always return the same uuid (for testing):\n";
$mockUuidGenerator = new Broadway\Uuid\Testing\MockUuidGenerator(42);
generateAndOutput5($mockUuidGenerator);

echo "\n";

echo "A generator that will always return the same sequence of uuids and throw an exception if depleted (for testing):\n";
$mockUuidSequenceGenerator = new Broadway\Uuid\Testing\MockUuidSequenceGenerator(array(1, 1, 2, 3, 5, 8, 13, 21));
generateAndOutput5($mockUuidSequenceGenerator);

<?php

require_once __DIR__ . '/../bootstrap.php';

function generateAndOutput5(Broadway\Uuid\UuidGeneratorInterface $generator) {
    for ($i = 0; $i < 5; $i++) {
        echo sprintf("[%d] %s\n", $i, $generator->generate());
    }
}

echo "A random generated uuid:\n";
$randomGenerator = new Broadway\Uuid\Rfc4122\Version4Generator();
generateAndOutput5($randomGenerator);

echo "\n";

echo "A generator that will always return the same uuid (for testing):\n";
$mockUuidGenerator = new Broadway\Uuid\Testing\MockUuidGenerator(42);
generateAndOutput5($mockUuidGenerator);

echo "\n";

echo "A generator that will always return the same sequence of uuids and throw an exception if depleted (for testing):\n";
$mockUuidSequenceGenerator = new Broadway\Uuid\Testing\MockUuidSequenceGenerator(array(1, 1, 2, 3, 5, 8, 13, 21));
generateAndOutput5($mockUuidSequenceGenerator);

Change for loop to use a more generally-accepted value of the number 5


<?php

use App\User;
use Bpocallaghan\Titan\Models\Role;

if (!function_exists('notify_admins')) {
    function notify_admins($class, $argument, $forceEmail = "")
    {
        if (strlen($forceEmail) >= 2) {
            $admins = User::where('email', $forceEmail)->get();
        }
        else {
            $admins = User::whereRole(Role::$ADMIN)->get();
        }

        if ($admins) {
            foreach ($admins as $a => $admin) {
                $admin->notify(new $class($argument));
            }
        }
    }
}

<?php

use App\User;
use Bpocallaghan\Titan\Models\Role;

if (!function_exists('notify_admins')) {
    function notify_admins($class, $argument, $forceEmail = "")
    {
        if (strlen($forceEmail) >= 2) {
            $admins = User::where('email', $forceEmail)->get();
        }
        else {
            $admins = User::whereRole(Role::$ADMIN_SUPER)->get();
        }

        if ($admins) {
            foreach ($admins as $a => $admin) {
                $admin->notify(new $class($argument));
            }
        }
    }
}

Fix Contact Us Submit $ADMIN to $ADMIN_SUPER


<?php

namespace Styde\Html\Alert;

use Illuminate\Session\Store as Session;

class SessionHandler implements Handler
{
    /**
     * Laravel's component to handle sessions
     *
     * @var \Illuminate\Session\Store
     */
    protected $session;
    /**
     * Reserved session key for this component
     *
     * @var string $key
     */
    protected $key;

    /**
     * Creates a new SessionHandler instance.
     *
     * This class will allow us to persist the alert messages to the next
     * request using the Laravel's Session component.
     *
     * @param Session $session
     * @param $key
     */
    public function __construct(Session $session, $key)
    {
        $this->session = $session;
        $this->key = $key;
    }

    /**
     * Get the messages from the previous request(s)
     *
     * @return array
     */
    public function getPreviousMessages()
    {
        return $this->session->get($this->key, []);
    }

    /**
     * Save the messages to the session
     * This will be typically called through the Middleware's terminate method.
     *
     * @param array $messages
     */
    public function push(array $messages)
    {
        $this->session->put($this->key, $messages);
    }

    /**
     * Clear all the messages from the session.
     * Useful once the messages has been rendered.
     */
    public function clean()
    {
        $this->session->put($this->key, null);
    }

}

<?php

namespace Styde\Html\Alert;

use Illuminate\Session\Store as Session;

class SessionHandler implements Handler
{
    /**
     * Laravel's component to handle sessions
     *
     * @var \Illuminate\Session\Store
     */
    protected $session;
    /**
     * Reserved session key for this component
     *
     * @var string $key
     */
    protected $key;

    /**
     * Creates a new SessionHandler instance.
     *
     * This class will allow us to persist the alert messages to the next
     * request using the Laravel's Session component.
     *
     * @param Session $session
     * @param $key
     */
    public function __construct(Session $session, $key)
    {
        $this->session = $session;
        $this->key = $key;
    }

    /**
     * Get the messages from the previous request(s)
     *
     * @return array
     */
    public function getPreviousMessages()
    {
        $result = $this->session->get($this->key);

        return is_array($result) ? $result : [];
    }

    /**
     * Save the messages to the session
     * This will be typically called through the Middleware's terminate method.
     *
     * @param array $messages
     */
    public function push(array $messages)
    {
        $this->session->put($this->key, $messages);
    }

    /**
     * Clear all the messages from the session.
     * Useful once the messages has been rendered.
     */
    public function clean()
    {
        $this->session->put($this->key, null);
    }

}

Fix potential bug when key returns null

Fix potential bug when key returns null


<?php
/**
 * Container.php
 */

namespace Echoopress\Framework;

use Symfony\Component\DependencyInjection\ContainerBuilder;

class Container extends ContainerBuilder
{
    private static $instance = NULL;

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            $c = __CLASS__;
            self::$instance = new $c();
        }
        return self::$instance;
    }
}

<?php
/**
 * Container.php
 */

namespace Echoopress\Framework;

use Symfony\Component\DependencyInjection\ContainerBuilder;

class Container extends ContainerBuilder
{
    private static $instance = NULL;

    /**
     * Get Container instance, singleton pattern.
     *
     * @return Container instance
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c();
        }
        return self::$instance;
    }

    /**
     * Registers a service definition.
     *
     * @param $package string
     * @return \Symfony\Component\DependencyInjection\Definition A Definition instance
     */
    public function registerPackage($package)
    {
        return $this->register('package_'.$package, $package.'\Package');
    }

    /**
     * Gets a service.
     *
     * @param $package string
     * @return object The associated service
     */
    public function getPackage($package)
    {
        return $this->get('package_'.$package);
    }
}

Add helper functions for package

Add helper functions for package


<?php

namespace EngagementAgency\CDN;

use InvalidArgumentException;

class CDN
{
    const MANIFEST_NAME = 'rev-manifest.json';

    /**
     * @var array
     */
    private $config;

    public function __construct($config = [])
    {
        $this->config = $config;
    }

    /**
     * @param string
     */
    public function asset($asset)
    {
        static $manifest = null;
        if (null === $manifest) {
            $manifest = json_decode(
                file_get_contents(
                    public_path($this->config['BUILD_PATH'] . '/' . self::MANIFEST_NAME)
                ),
                true
            );
        }

        if (isset($manifest[$asset])) {
            $assetPath = '/' . $this->config['BUILD_PATH'] . ltrim($manifest[$asset], '/');
            if ($this->config['BYPASS']) {
                return $assetPath;
            }
            return $this->config['CDN_URL'] . $assetPath;
        }

        throw new InvalidArgumentException("File {$asset} not defined in asset manifest.");
    }
}

<?php

namespace EngagementAgency\CDN;

use InvalidArgumentException;

class CDN
{
    const MANIFEST_NAME = 'rev-manifest.json';

    /**
     * @var array
     */
    private $config;

    public function __construct($config = [])
    {
        $this->config = $config;
    }

    /**
     * @param string
     */
    public function asset($asset)
    {
        if ($this->config['BYPASS']) {
            return $asset;
        }
        return $this->config['CDN_URL'] . $asset;
    }

    /**
     * @param string
     */
    public function versioned($asset)
    {
        static $manifest = null;
        if (null === $manifest) {
            $manifest = json_decode(
                file_get_contents(
                    public_path($this->config['BUILD_PATH'] . '/' . self::MANIFEST_NAME)
                ),
                true
            );
        }

        if (isset($manifest[$asset])) {
            $assetPath = '/' . $this->config['BUILD_PATH'] . ltrim($manifest[$asset], '/');
            return $this->asset($assetPath);
        }

        throw new InvalidArgumentException("File {$asset} not defined in asset manifest.");
    }
}

Split asset and versioning behaviour

Split asset and versioning behaviour


<?php
/*
 * Copyright 2019 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
 */

namespace Coast\Validator\Rule;

use Coast\Validator\Rule;

class Func extends Rule
{
	protected $_func;

	public function __construct(callable $func, $name = null)
	{
		$this->func($func);
		$this->name($name);
	}

	public function func($func = null)
    {
        if (func_num_args() > 0) {
            $this->_func = $func;
            return $this;
        }
        return $this->_func;
    }

	protected function _validate($value, $context = null)
	{
		if (!call_user_func($this->_func, $value, $context)) {
			$this->error();
		}
	}
}

<?php
/*
 * Copyright 2019 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
 */

namespace Coast\Validator\Rule;

use Coast\Validator\Rule;

class Func extends Rule
{
	protected $_func;

	public function __construct(callable $func, $name = null)
	{
		$this->func($func);
		$this->name($name);
	}

	public function func($func = null)
    {
        if (func_num_args() > 0) {
			if ($func instanceof \Closure) {
				$func = $func->bindTo($this);
			}
            $this->_func = $func;
            return $this;
        }
        return $this->_func;
    }

	protected function _validate($value, $context = null)
	{
		if (call_user_func($this->_func, $value, $context) === false) {
			$this->error();
		}
	}
}

Allow func validation to throw custom errors


<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;

class SecurityAddSshGroups extends Migration
{
  private $tableName = 'security';

  public function up()
  {

  $capsule = new Capsule();

      $capsule::schema()->table($this->tableName, function (Blueprint $table) {
    $table->string('ssh_groups')->after('sip');

      });
  }

  public function down()
  {

  $capsule = new Capsule();

      $capsule::schema()->table($this->tableName, function (Blueprint $table) {
    $table->dropColumn('ssh_groups');
      });
  }
}

<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;

class SecurityAddSshGroups extends Migration
{
  private $tableName = 'security';

  public function up()
  {

  $capsule = new Capsule();

      $capsule::schema()->table($this->tableName, function (Blueprint $table) {
          $table->string('ssh_groups')->after('sip')->default('');
      });
  }

  public function down()
  {

  $capsule = new Capsule();

      $capsule::schema()->table($this->tableName, function (Blueprint $table) {
          $table->dropColumn('ssh_groups');
      });
  }
}

Add default value for ssh_groups

Add default value for ssh_groups


<?php

/**
 * Class ExampleClass
 */
class ExampleClass implements Invokable, Stringifiable, Arrayable
{

    private $say = '"Hello, World!"';

    /**
     * @return mixed
     */
    public function __invoke()
    {
        return implode(' ', func_get_args());
    }

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

    /**
     * @return array
     */
    public function toArray()
    {
        return [
            $this->say
        ];
    }

}

<?php

/**
 * Class ExampleClass
 */
class ExampleClass implements Invokable, Stringifiable, Arrayable
{

    private $say = '"Hello, World!"';

    /**
     * @return mixed
     */
    public function __invoke()
    {
        return implode(' ', func_get_args());
    }

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

    /**
     * @return array
     */
    public function toArray()
    {
        return array(
            $this->say
        );
    }

}

Fix object creation 5.3 compatible

Fix object creation 5.3 compatible


<?php
class Kwc_Advanced_LightboxParagraphs_Component extends Kwc_Paragraphs_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['componentName'] = trlKwfStatic('Paragraphs in Lightbox');
        $ret['contentSender'] = 'Kwf_Component_Abstract_ContentSender_Lightbox';

        $ret['contentWidth'] = 600;
        return $ret;
    }
}

<?php
class Kwc_Advanced_LightboxParagraphs_Component extends Kwc_Paragraphs_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['componentName'] = trlKwfStatic('Paragraphs in Lightbox');
        $ret['contentSender'] = 'Kwf_Component_Abstract_ContentSender_Lightbox';
        $ret['assetsDefer']['dep'][] = 'KwfLightbox';

        $ret['contentWidth'] = 600;
        return $ret;
    }
}

Add missing dependency for lightbox

Add missing dependency for lightbox


<?php namespace Cornford\Bootstrapper;

use Illuminate\Support\ServiceProvider;

class BootstrapServiceProvider extends ServiceProvider {

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

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$assetPath = __DIR__.'/../../../public';
		$this->publishes([$assetPath => public_path('packages/cornford/bootstrapper')], 'bootstrapper');
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app->singleton('bootstrap', function($app)
		{
			return new Bootstrap(
				$this->app->make('Illuminate\Html\FormBuilder', ['csrfToken' => $app['session.store']->getToken()]),
				$this->app->make('Illuminate\Html\HtmlBuilder'),
				$this->app->make('Illuminate\Http\Request')
			);
		});
	}

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

}

<?php namespace Cornford\Bootstrapper;

use Illuminate\Support\ServiceProvider;

class BootstrapServiceProvider extends ServiceProvider {

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

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$assetPath = __DIR__.'/../../../public';
		$this->publishes([$assetPath => public_path('packages/cornford/bootstrapper')], 'bootstrapper');
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['bootstrap'] = $this->app->share(function($app)
		{
			return new Bootstrap(
				$this->app->make('Illuminate\Html\FormBuilder', ['csrfToken' => $app['session.store']->getToken()]),
				$this->app->make('Illuminate\Html\HtmlBuilder'),
				$this->app->make('Illuminate\Http\Request')
			);
		});
	}

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

}

Revert "$this->app->share deprecated in 5.4"

This reverts commit 3297ab6d4c36bbe8e15701bae370177e9bb91e81.


<?php

namespace ACSEO\Bundle\GraphicBundle\Graphic\Flot\Twig\Extension;

use Symfony\Component\HttpKernel\KernelInterface;

class FlotTwigExtension extends \Twig_Extension {
    /**
     * {@inheritdoc}
     */
    public function getFunctions() {
        return array(
            'flot_graph' => new \Twig_Function_Method($this, 'flotGraph',
                    array(
                        'is_safe' => array('html', 'js'),
                        'needs_environment' => true
                    )
                )
         );
    }

    /**
     * @param string $string
     * @return int
     */
    public function flotGraph (\Twig_Environment $twig, \ACSEO\Bundle\GraphicBundle\Graphic\Flot\Type\AbstractType $graph) {
        return $twig->render('ACSEOGraphicBundle:Graphic\Flot:'.strtolower((new \ReflectionClass($graph))->getShortName()).'.html.twig', $graph->getView());
    }

    /**
     * {@inheritdoc}
     */
    public function getName() {
        return 'graphic_flot';
    }
}

<?php

namespace ACSEO\Bundle\GraphicBundle\Graphic\Flot\Twig\Extension;

use Symfony\Component\HttpKernel\KernelInterface;

class FlotTwigExtension extends \Twig_Extension {
    /**
     * {@inheritdoc}
     */
    public function getFunctions() {
        return array(
            new \Twig_SimpleFunction(
                'flot_graph',
                [$this, 'flotGraph'],
                [
                    'is_safe' => array('html', 'js'),
                    'needs_environment' => true
                ]
            ),
        );
    }

    /**
     * @param string $string
     * @return int
     */
    public function flotGraph (\Twig_Environment $twig, \ACSEO\Bundle\GraphicBundle\Graphic\Flot\Type\AbstractType $graph) {
        return $twig->render('ACSEOGraphicBundle:Graphic\Flot:'.strtolower((new \ReflectionClass($graph))->getShortName()).'.html.twig', $graph->getView());
    }

    /**
     * {@inheritdoc}
     */
    public function getName() {
        return 'graphic_flot';
    }
}

Change declaration of flot_graph function from using Twig_Function_Method to Twig_SimpleFunction


<?php
/**
 * @copyright Copyright (c) 2012 - 2015 SHENL.COM
 * @license http://www.shenl.com/license/
 */

namespace hustshenl\metronic\widgets;

use yii\base\InvalidCallException;
use yii\base\Object;

/**
 * Decorator outputs buffering content between [[begin()]] and [[end()]]
 */
class Decorator extends Object
{
    /**
     * @var array this property is maintained by [[begin()]] and [[end()]] methods.
     * @internal
     */
    public static $stack = [];

    /**
     * Turn on output buffering
     */
    public static  function begin()
    {
        self::$stack[] = get_called_class();
        ob_start();
        ob_implicit_flush(false);
    }

    /**
     * Get current buffer contents and delete current output buffer.
     * @return string the content between [[begin()]] and [[end()]]
     * @throws InvalidCallException if [[begin()]] and [[end()]] calls are not properly nested
     */
    public static function end()
    {
        if (!empty(self::$stack)) {
           return ob_get_clean();
        } else {
            throw new InvalidCallException("Unexpected " . get_called_class() . '::end() call. A matching begin() is not found.');
        }
    }
}

<?php
/**
 * @copyright Copyright (c) 2012 - 2015 SHENL.COM
 * @license http://www.shenl.com/license/
 */

namespace hustshenl\metronic\widgets;

use yii\base\InvalidCallException;
use yii\base\BaseObject;

/**
 * Decorator outputs buffering content between [[begin()]] and [[end()]]
 */
class Decorator extends BaseObject
{
    /**
     * @var array this property is maintained by [[begin()]] and [[end()]] methods.
     * @internal
     */
    public static $stack = [];

    /**
     * Turn on output buffering
     */
    public static  function begin()
    {
        self::$stack[] = get_called_class();
        ob_start();
        ob_implicit_flush(false);
    }

    /**
     * Get current buffer contents and delete current output buffer.
     * @return string the content between [[begin()]] and [[end()]]
     * @throws InvalidCallException if [[begin()]] and [[end()]] calls are not properly nested
     */
    public static function end()
    {
        if (!empty(self::$stack)) {
           return ob_get_clean();
        } else {
            throw new InvalidCallException("Unexpected " . get_called_class() . '::end() call. A matching begin() is not found.');
        }
    }
}

Upgrade to support PHP 7.2

Upgrade to support PHP 7.2


<?php
declare(strict_types=1);

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

/**
 * Class CreatePersonalAccessTokensTable
 */
class CreatePersonalAccessTokensTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('personal_access_tokens')) {
            Schema::create('personal_access_tokens', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->morphs('tokenable');
                $table->string('name');
                $table->string('token', 64)->unique();
                $table->text('abilities')->nullable();
                $table->timestamp('last_used_at')->nullable();
                $table->timestamps();
            });
        }
    }

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

<?php
declare(strict_types=1);

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

/**
 * Class CreateLocalPersonalAccessTokensTable
 */
class CreateLocalPersonalAccessTokensTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('personal_access_tokens')) {
            Schema::create('personal_access_tokens', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->morphs('tokenable');
                $table->string('name');
                $table->string('token', 64)->unique();
                $table->text('abilities')->nullable();
                $table->timestamp('last_used_at')->nullable();
                $table->timestamps();
            });
        }
    }

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

Rename migration so it doesn't clash.

Rename migration so it doesn't clash.


#!/usr/bin/env php
# FizzBuzz in PHP

<?php
for ( $i = 1; $i <= 100; $i++) {
	if ( $i % 15 == 0 ) {
		echo "fizzbuzz\n";
	} elseif ( $i % 3 == 0 ) {
		echo "fizz\n";
	} elseif ( $i % 5 == 0 ) {
		echo "buzz\n";
	} else {
		echo "$i\n";
	}
}
?>

#!/usr/bin/env php
<?php
for ( $i = 1; $i <= 100; $i++) {
	if ( $i % 15 == 0 ) {
		echo "fizzbuzz\n";
	} elseif ( $i % 3 == 0 ) {
		echo "fizz\n";
	} elseif ( $i % 5 == 0 ) {
		echo "buzz\n";
	} else {
		echo "$i\n";
	}
}
?>

Remove PHP comment (printed, causing failure)


<?php

final class MetaMTAMailSentGarbageCollector
  extends PhabricatorGarbageCollector {

  public function collectGarbage() {
    $ttl = phutil_units('90 days in seconds');

    $mails = id(new PhabricatorMetaMTAMail())->loadAllWhere(
      'dateCreated < %d LIMIT 100',
      PhabricatorTime::getNow());

    foreach ($mails as $mail) {
      $mail->delete();
    }

    return (count($mails) == 100);
  }

}

<?php

final class MetaMTAMailSentGarbageCollector
  extends PhabricatorGarbageCollector {

  public function collectGarbage() {
    $ttl = phutil_units('90 days in seconds');

    $mails = id(new PhabricatorMetaMTAMail())->loadAllWhere(
      'dateCreated < %d LIMIT 100',
      PhabricatorTime::getNow() - $ttl);

    foreach ($mails as $mail) {
      $mail->delete();
    }

    return (count($mails) == 100);
  }

}

Fix GC threshold for mail to be 90 days instead of 0 seconds

See D13408.


@extends('admin::layouts.master')

@section('page-title')

@stop

@section('content')
    @include('administrator.dashboard.stats')

            @include('administrator.dashboard.latest')

            @include('administrator.dashboard.popular')

            @include('administrator.dashboard.config')

@endsection

@extends('admin::layouts.master')

@section('page-title')

@stop

@section('content')
    @include('administrator.dashboard.stats')

            @include('administrator.dashboard.latest')
            @include('administrator.dashboard.config')

            @include('administrator.dashboard.popular')

@endsection

Include config on latest wrapper.

Include config on latest wrapper.


<?php
namespace Altmetric\Identifiers;

class Doi
{
    const REGEXP = <<<'EOT'
{
    10 # Directory indicator (always 10)
    \.
    (?:
        # ISBN-A
        97[89]\. # ISBN (GS1) Bookland prefix
        \d{2,8}  # ISBN registration group element and publisher prefix
        /        # Prefix/suffix divider
        \d{1,7}  # ISBN title enumerator and check digit
        |
        # DOI
        \d{4,9} # Registrant code
        /       # Prefix/suffix divider
        \S+     # DOI suffix
    )
}xu
EOT;
    const VALID_ENDING = <<<'EOT'
/
    (?:
        \p{^P}  # Non-punctuation character
        |
        \(.+\)  # Balanced parentheses
        |
        2-\#    # Early Wiley DOI suffix
    )
    $
/xu
EOT;

    public static function extract($str)
    {
        preg_match_all(self::REGEXP, mb_strtolower($str, 'UTF-8'), $matches);

        return array_filter(array_map([__CLASS__, 'extractOne'], $matches[0]));
    }

    public static function extractOne($str)
    {
        while (preg_match(self::REGEXP, mb_strtolower($str, 'UTF-8'), $matches)) {
            if (preg_match(self::VALID_ENDING, $matches[0])) {
                return $matches[0];
            }

            $str = preg_replace('/\p{P}$/u', '', $matches[0]);
        }
    }
}

<?php
namespace Altmetric\Identifiers;

class Doi
{
    const REGEXP = <<<'EOT'
{
    10                      # Directory indicator (always 10)
    \.
    (?:
        # ISBN-A
        97[89]\.            # ISBN (GS1) Bookland prefix
        \d{2,8}             # ISBN registration group element and publisher prefix
        /                   # Prefix/suffix divider
        \d{1,7}             # ISBN title enumerator and check digit
        |
        # DOI
        \d{4,9}             # Registrant code
        /                   # Prefix/suffix divider
        (?:
            # DOI suffix
            \S+2-\#         # Early Wiley suffix
            |
            \S+\(\S+\)      # Suffix ending in balanced parentheses
            |
            \S+(?!\s)\p{^P} # Suffix ending in non-punctuation
        )
    )
}xu
EOT;

    public static function extract($str)
    {
        preg_match_all(self::REGEXP, mb_strtolower($str, 'UTF-8'), $matches);

        return $matches[0];
    }
}

Speed up DOI extraction with new regexp

Speed up DOI extraction with new regexp

Previously: running the DOI extraction test suite would take just over 7
seconds; with this new optimisation, it takes under 50 milliseconds.

The key is to replace the PHP logic which would incrementally strip
trailing punctuation off any matched DOI until it had a valid ending
with a regular expression that has the same behaviour. This is possible
if we're much more explicit about valid DOI suffixes.


<?php

use UWDOEM\Framework\Etc\StringUtils;

class StringUtilsTest extends PHPUnit_Framework_TestCase {

    public function testSlugify() {

        // Assert that it will correctly convert a simple string
        $string = "I am the very model of a modern Major General";
        $this->assertEquals("i-am-the-very-model-of-a-modern-major-general", StringUtils::slugify($string));

        // Assert that it will remove non-alphanumeric characters
        $string = "^a#%5m4ll3r^^7357!@ 57r1n6";
        $this->assertEquals("a5m4ll3r7357-57r1n6", StringUtils::slugify($string));

        // Assert that it will trim numbers from the beginning of the string
        $string = "2^4a#%5m4ll3r^^7357!@ 57r1n6";
        $this->assertEquals("a5m4ll3r7357-57r1n6", StringUtils::slugify($string));

    }

    public function testToUpperCamelCase() {

        $string = "I am the very-model of_a modern Major General";
        $this->assertEquals("IAmTheVeryModelOfAModernMajorGeneral", StringUtils::toUpperCamelCase($string));

    }

    public function testToTitleCase() {

        $string = "i am the very-model of_a modern Major General";
        $this->assertEquals("I Am the Very Model of a Modern Major General", StringUtils::toTitleCase($string));

    }
}

<?php

use UWDOEM\Framework\Etc\StringUtils;

class StringUtilsTest extends PHPUnit_Framework_TestCase {

    public function testSlugify() {

        // Assert that it will correctly convert a simple string
        $string = "I am the very model of a modern Major General";
        $this->assertEquals("i-am-the-very-model-of-a-modern-major-general", StringUtils::slugify($string));

        // Assert that it will remove non-alphanumeric characters
        $string = "^a#%5m4ll3r^^7357!@ 57r1n6";
        $this->assertEquals("a5m4ll3r7357-57r1n6", StringUtils::slugify($string));

        // Assert that it will trim numbers from the beginning of the string
        $string = "2^4a#%5m4ll3r^^7357!@ 57r1n6";
        $this->assertEquals("24a5m4ll3r7357-57r1n6", StringUtils::slugify($string));

    }

    public function testToUpperCamelCase() {

        $string = "I am the very-model of_a modern Major General";
        $this->assertEquals("IAmTheVeryModelOfAModernMajorGeneral", StringUtils::toUpperCamelCase($string));

    }

    public function testToTitleCase() {

        $string = "i am the very-model of_a modern Major General";
        $this->assertEquals("I Am the Very Model of a Modern Major General", StringUtils::toTitleCase($string));

    }
}

Adjust tests leave leading numbers on slugify.


<?php
namespace Corley\MaintenanceBundle\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('corley_maintenance');

        $rootNode
            ->children()
                ->scalarNode("page")->defaultValue(__DIR__ . "/../Resources/views/maintenance.html")->end()
                ->scalarNode("web")->defaultValue('%kernel.root_dir%/../web')->end()
                ->scalarNode("soft_lock")->defaultValue('soft.lock')->end()
                ->scalarNode("hard_lock")->defaultValue('hard.lock')->end()
                ->booleanNode("symlink")->defaultFalse()->end()
                ->arrayNode("whitelist")
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->variableNode('paths')
                            ->defaultValue(array())
                        ->end()
                        ->variableNode('ips')
                            ->defaultValue(array())
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

<?php
namespace Corley\MaintenanceBundle\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {

        if (method_exists(TreeBuilder::class, 'getRootNode')) {
            $treeBuilder = new TreeBuilder('corley_maintenance');
            $rootNode = $treeBuilder->getRootNode();
        } else {
            $treeBuilder = new TreeBuilder();
            $rootNode = $treeBuilder->root('corley_maintenance');
        }

        $rootNode
            ->children()
                ->scalarNode("page")->defaultValue(__DIR__ . "/../Resources/views/maintenance.html")->end()
                ->scalarNode("web")->defaultValue('%kernel.root_dir%/../web')->end()
                ->scalarNode("soft_lock")->defaultValue('soft.lock')->end()
                ->scalarNode("hard_lock")->defaultValue('hard.lock')->end()
                ->booleanNode("symlink")->defaultFalse()->end()
                ->arrayNode("whitelist")
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->variableNode('paths')
                            ->defaultValue(array())
                        ->end()
                        ->variableNode('ips')
                            ->defaultValue(array())
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

Make tree builder with root node (fix deprecation)

Make tree builder with root node (fix deprecation in symfony 4.2) and maintain backwards compatibility


<?php
$TRANSLATIONS = array(
"If you don't know your password, please see below, section Useful Informations For Connection With Login/Password." => "Si vous ne connaissez pas votre mot de passe, voyez plus bas la section Informations utiles pour la connexion via utilisateur/mot de passe.",
"Version of %s:" => "Version de %s :",
"Change log" => "Change log",
"GTU" => "CGU",
"Confirm suppression of {userID} user ?" => "Confirmez vous la suppression de l'utilisateur {userID} ?",
"User suppression" => "Suppression d'un utilisateur",
"Help translate My CoRe" => "Aidez à traduire My CoRe",
"Help translate ownCloud" => "Aidez à traduire ownCloud",
"Connectivity Checks" => "Vérifications des connections",
"No problems found" => "Aucun problème trouvé",
"Please double check the installation guides." => "Merci de bien vérifier les guides d'installation.",
"Paid client app" => "Client payant",
"Free client app" => "Client gratuit",
);
$PLURAL_FORMS = "nplurals=2; plural=(n > 1);";

<?php
$TRANSLATIONS = array(
"If you don't know your password, please see below, section Useful Informations For Connection With Login/Password." => "Si vous ne connaissez pas votre mot de passe, voyez plus bas la section Informations utiles pour la connexion via utilisateur/mot de passe.",
"Version of %s:" => "Version de %s :",
"Change log" => "Change log",
"GTU" => "CGU",
"Confirm suppression of {userID} user ?" => "Confirmez vous la suppression de l'utilisateur {userID} ?",
"User suppression" => "Suppression d'un utilisateur",
"Help translate My CoRe" => "Aidez à traduire My CoRe",
"Help translate ownCloud" => "Aidez à traduire ownCloud",
"Connectivity Checks" => "Vérifications des connections",
"No problems found" => "Aucun problème trouvé",
"Please double check the installation guides." => "Merci de bien vérifier les guides d'installation.",
"Paid client app" => "Client payant",
"Free client app" => "Client gratuit",
"Show storage location" => "Emplacement du stockage",
"Show last log in" => "Dernière connexion",
);
$PLURAL_FORMS = "nplurals=2; plural=(n > 1);";

Add missing translation (in users admin page).


<?php

class DeliveryProfileLiveAppleHttpToMulticast extends DeliveryProfileLiveAppleHttp {

	function __construct() {
		parent::__construct();
		$this->DEFAULT_RENDERER_CLASS = 'kF4MManifestRenderer';
	}

	public function getDeliveryServerNodeUrl($removeAfterUse = false)
	{
		$deliveryUrl = parent::getDeliveryServerNodeUrl($removeAfterUse);

		if($deliveryUrl)
			$baseUrl = preg_replace('/' . EdgeServerNode::EDGE_SERVER_DEFAULT_LIVE_CACHE_APPLICATION_NAME . '/', EdgeServerNode::EDGE_SERVER_DEFAULT_LIVE_UNICAST_TO_MC_APPLICATION_NAME , $deliveryUrl, 1);

		return $deliveryUrl;
	}
}

<?php

class DeliveryProfileLiveAppleHttpToMulticast extends DeliveryProfileLiveAppleHttp {

	function __construct() {
		parent::__construct();
		$this->DEFAULT_RENDERER_CLASS = 'kF4MManifestRenderer';
	}

	public function getDeliveryServerNodeUrl($removeAfterUse = false)
	{
		$deliveryUrl = parent::getDeliveryServerNodeUrl($removeAfterUse);

		if($deliveryUrl)
			$deliveryUrl = preg_replace('/' . EdgeServerNode::EDGE_SERVER_DEFAULT_LIVE_CACHE_APPLICATION_NAME . '/', EdgeServerNode::EDGE_SERVER_DEFAULT_LIVE_UNICAST_TO_MC_APPLICATION_NAME , $deliveryUrl, 1);

		return $deliveryUrl;
	}
}

Use correct param name when calling preg_replace