<?php

namespace LaravelDoctrine\ACL\Permissions;

use LaravelDoctrine\ACL\Contracts\HasPermissions as HasPermissionsContract;
use LaravelDoctrine\ACL\Contracts\HasRoles as HasRolesHasRoles;
use LaravelDoctrine\ACL\Contracts\Permission as PermissionContract;

trait HasPermissions
{
    /**
     * @param PermissionContract|string $name
     *
     * @return bool
     */
    public function hasPermissionTo($name)
    {
        if ($this instanceof HasRolesHasRoles) {
            foreach ($this->getRoles() as $role) {
                if ($role->hasPermissionTo($name)) {
                    return true;
                }
            }
        }

        if ($this instanceof HasPermissionsContract) {
            foreach ($this->getPermissions() as $permission) {
                if ($this->getPermissionName($permission) === $name) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * @param PermissionContract|string $permission
     *
     * @return string
     */
    protected function getPermissionName($permission)
    {
        return $permission instanceof PermissionContract ? $permission->getName() : $permission;
    }
}

<?php

namespace LaravelDoctrine\ACL\Permissions;

use LaravelDoctrine\ACL\Contracts\HasPermissions as HasPermissionsContract;
use LaravelDoctrine\ACL\Contracts\HasRoles as HasRolesHasRoles;
use LaravelDoctrine\ACL\Contracts\Permission as PermissionContract;

trait HasPermissions
{
    /**
     * @param PermissionContract|string $name
     *
     * @return bool
     */
    public function hasPermissionTo($name)
    {
        if ($this instanceof HasPermissionsContract) {
            foreach ($this->getPermissions() as $permission) {
                if ($this->getPermissionName($permission) === $name) {
                    return true;
                }
            }
        }

        if ($this instanceof HasRolesHasRoles) {
            foreach ($this->getRoles() as $role) {
                if ($role->hasPermissionTo($name)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * @param PermissionContract|string $permission
     *
     * @return string
     */
    protected function getPermissionName($permission)
    {
        return $permission instanceof PermissionContract ? $permission->getName() : $permission;
    }
}

Adjust permission check order logic

Adjust permission check order logic


<?php
/**
 * @copyright Copyright (c) 2018 Bjoern Schiessle <bjoern@schiessle.org>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

require_once __DIR__ . '/../lib/base.php';

header('Content-Type: application/json');

$server = \OC::$server;

$isEnabled = $server->getAppManager()->isEnabledForUser('cloud_federation_api');

if ($isEnabled) {
	$capabilities = new OCA\CloudFederationAPI\Capabilities($server->getURLGenerator());
	header('Content-Type: application/json');
	echo json_encode($capabilities->getCapabilities()['ocm']);
} else {
	header($_SERVER["SERVER_PROTOCOL"]." 501 Not Implemented", true, 501);
	exit("501 Not Implemented");
}

<?php
/**
 * @copyright Copyright (c) 2018 Bjoern Schiessle <bjoern@schiessle.org>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

require_once __DIR__ . '/../lib/base.php';

header('Content-Type: application/json');

$server = \OC::$server;

$isEnabled = $server->getAppManager()->isEnabledForUser('cloud_federation_api');

if ($isEnabled) {
	// Make sure the routes are loaded
	\OC_App::loadApp('cloud_federation_api');
	$capabilities = new OCA\CloudFederationAPI\Capabilities($server->getURLGenerator());
	header('Content-Type: application/json');
	echo json_encode($capabilities->getCapabilities()['ocm']);
} else {
	header($_SERVER["SERVER_PROTOCOL"]." 501 Not Implemented", true, 501);
	exit("501 Not Implemented");
}

Make sure the cloud_federation_api routes are loaded

Signed-off-by: Joas Schilling <ab43a7c9cb5b2380afc4ddf8b3e2583169b39a02@schilljs.com>


<?php

namespace Orbt\ResourceMirror\Tests;

use Orbt\ResourceMirror\ResourceMirror;
use Symfony\Component\EventDispatcher\EventDispatcher;

class ResourceMirrorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * A resource mirror can be instantiated.
     */
    public function testCreate()
    {
        $mirror = new ResourceMirror(new EventDispatcher(), 'http://example.com/', sys_get_temp_dir());
        $this->assertInstanceOf('Orbt\ResourceMirror\ResourceMirror', $mirror);
    }

    /**
     * A resource mirror returns the base URL.
     *
     * @depends testCreate
     */
    public function testGetBaseUrl()
    {
        $mirror = new ResourceMirror(new EventDispatcher(), 'http://example.com/', sys_get_temp_dir());
        $this->assertEquals('http://example.com/', $mirror->getBaseUrl());
    }

    /**
     * A resource mirror returns the directory.
     *
     * @depends testCreate
     */
    public function testGetDirectory()
    {
        $mirror = new ResourceMirror(new EventDispatcher(), 'http://example.com/', $tempDir = sys_get_temp_dir());
        $this->assertEquals($tempDir, $mirror->getDirectory());
    }
}

<?php

namespace Orbt\ResourceMirror\Tests;

use Orbt\ResourceMirror\ResourceMirror;
use Symfony\Component\EventDispatcher\EventDispatcher;

class ResourceMirrorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * A resource mirror can be instantiated.
     */
    public function testCreate()
    {
        $mirror = new ResourceMirror(new EventDispatcher(), 'http://example.com/', sys_get_temp_dir());
        $this->assertInstanceOf('Orbt\ResourceMirror\ResourceMirror', $mirror);
    }

    /**
     * A resource mirror returns the base URL.
     *
     * @depends testCreate
     */
    public function testGetBaseUrl()
    {
        $mirror = new ResourceMirror(new EventDispatcher(), 'http://example.com/', sys_get_temp_dir());
        $this->assertEquals('http://example.com/', $mirror->getBaseUrl());
    }

    /**
     * A resource mirror returns the directory.
     *
     * @depends testCreate
     */
    public function testGetDirectory()
    {
        $mirror = new ResourceMirror(new EventDispatcher(), 'http://example.com/', $tempDir = sys_get_temp_dir());
        $this->assertEquals($tempDir, $mirror->getDirectory());
    }

    /**
     * A resource mirror is not created if directory is not writable.
     *
     * @depends testCreate
     * @expectedException \InvalidArgumentException
     */
    public function testCreateBadDirectory()
    {
        new ResourceMirror(new EventDispatcher(), 'http://example.com/', '/a/probably/not/writable/directory');
    }
}

Test creating a mirror with a bad directory.


<?php

class Denkmal_FormAction_EventAdd_Create extends CM_FormAction_Abstract {

    protected function _getRequiredFields() {
        return array('venue', 'date', 'fromTime');
    }

    protected function _checkData(CM_Params $params, CM_Response_View_Form $response, CM_Form_Abstract $form) {
        $event = Denkmal_Form_EventAdd::getEventFromData($params);
        $now = new DateTime();

        if ($event->getFrom() < $now && !$event->getUntil()) {
            $response->addError($response->getRender()->getTranslation('Event in der Vergangenheit'), 'date');
        }
        if ($event->getUntil() < $now && $event->getUntil()) {
            $response->addError($response->getRender()->getTranslation('Event in der Vergangenheit'), 'date');
        }

        if (!$params->has('title') && !$params->has('description')) {
            $response->addError($response->getRender()->getTranslation('Bitte Titel oder KünstlerInnen angeben'), 'title');
        }
    }

    protected function _process(CM_Params $params, CM_Response_View_Form $response, CM_Form_Abstract $form) {
        $venue = Denkmal_Form_EventAdd::getVenueFromData($params);
        $venue->commit();

        $event = Denkmal_Form_EventAdd::getEventFromData($params);
        $event->setVenue($venue);
        $event->commit();
    }
}

<?php

class Denkmal_FormAction_EventAdd_Create extends CM_FormAction_Abstract {

    protected function _getRequiredFields() {
        return array('venue', 'date', 'fromTime');
    }

    protected function _checkData(CM_Params $params, CM_Response_View_Form $response, CM_Form_Abstract $form) {
        $event = Denkmal_Form_EventAdd::getEventFromData($params);
        $now = new DateTime();

        if ($event->getFrom() < $now && !$event->getUntil()) {
            $response->addError($response->getRender()->getTranslation('Event in der Vergangenheit'), 'date');
        }
        if ($event->getUntil() < $now && $event->getUntil()) {
            $response->addError($response->getRender()->getTranslation('Event in der Vergangenheit'), 'date');
        }

        if (!$params->has('title') && !$params->has('artists')) {
            $response->addError($response->getRender()->getTranslation('Bitte Titel oder KünstlerInnen angeben'), 'title');
        }
    }

    protected function _process(CM_Params $params, CM_Response_View_Form $response, CM_Form_Abstract $form) {
        $venue = Denkmal_Form_EventAdd::getVenueFromData($params);
        $venue->commit();

        $event = Denkmal_Form_EventAdd::getEventFromData($params);
        $event->setVenue($venue);
        $event->commit();
    }
}

Fix title+artists check in event-add-form


<?
    $url = $_SERVER['HTTP_HOST'];
    if($url == "map.project-osrm.org") {
    	$file = file_get_contents('map.html');
		echo $file;
    	return;
   }
   $file = file_get_contents('main.html');
	echo $file;
	return;
?>

<?
    $url = $_SERVER['HTTP_HOST'];
    if($url == "map.project-osrm.org" || $url == "www.map.project-osrm.org") {
    	$file = file_get_contents('map.html');
		echo $file;
    	return;
   }
   $file = file_get_contents('main.html');
	echo $file;
	return;
?>

Support for yet another subdomain

Support for yet another subdomain

git-svn-id: b87969873ac19977fdb5a8c3be815cbc91ff9758@242 276ae292-bfe3-402f-8c0b-7b64386c5c79


<?php

namespace Telegram\Bot\Tests\Traits;

use Illuminate\Support\Collection;
use Telegram\Bot\Commands\Command;

trait CommandGenerator
{
    /**
     * @param int $numberRequired
     *
     * @return Collection
     */
    private function commandGenerator($numberRequired)
    {
        $range = range(1, $numberRequired, 1);

        return collect($range)
            ->map(function (int $instanceNumber) {
                return new class ($instanceNumber) extends Command {
                    private $instanceNumber;

                    public function __construct(int $instanceNumber)
                    {
                        $this->instanceNumber = $instanceNumber;
                    }

                    public function getName(): string
                    {
                        return "MockCommand$this->instanceNumber";
                    }

                    public function getAliases(): array
                    {
                        return ["MockAlias$this->instanceNumber"];
                    }

                    public function handle()
                    {
                    }
                };
            });
    }
}

<?php

namespace Telegram\Bot\Tests\Traits;

use Illuminate\Support\Collection;
use Telegram\Bot\Commands\Command;

trait CommandGenerator
{
    /**
     * @param int $numberRequired
     *
     * @return Collection
     */
    private function commandGenerator($numberRequired)
    {
        $range = range(1, $numberRequired, 1);

        return collect($range)
            ->map(function (int $instanceNumber) {
                return new class($instanceNumber) extends Command {
                    private $instanceNumber;

                    public function __construct(int $instanceNumber)
                    {
                        $this->instanceNumber = $instanceNumber;
                    }

                    public function getName(): string
                    {
                        return "MockCommand$this->instanceNumber";
                    }

                    public function getAliases(): array
                    {
                        return ["MockAlias$this->instanceNumber"];
                    }

                    public function handle()
                    {
                    }
                };
            });
    }
}

Apply PHP CS Fixer changes

Apply PHP CS Fixer changes


<?php

namespace Application\Module {

    class User extends \Application\Module {
        public function Index() {
            return $this->Login();
        }

        public function Login() {
            $Request = $this->getRequest();
            $User = $this->getModel("User");
            if (isset($Request['Arguments']['Email'])) {
                $User->setEmail($Request['Arguments']['Email']);
            }
            if (isset($Request['Arguments']['Password'])) {
                $User->setPassword($Request['Arguments']['Password']);
            }

            $Error = null;

            $Email = $User->getEmail();
            $Password = $User->getPassword();

            if (isset($Email)) ;
            else {
                $Error = "No email given.";
            };
            if (isset($Password)) ;
            else {
                $Error = "No password given.";
            }

            $User->Error = $Error;

            $View = $this->getView("Login.phtml", array("User" => $User));

            return $View;
        }

        protected function Info() {
            $User = $this->getModel("User");
            $View = $this->getView("User.phtml", array("User" => $User));

            return $View;
        }
    }
}

?>

<?php

namespace Application\Module {

    class User extends \Application\Module {
        public function Index() {
            return $this->Login();
        }

        public function Login() {
            $Request = $this->getRequest();
            $User = $this->getModel("User");
            if (isset($Request['Arguments']['Email']) && $Request['Arguments']['Email'] !== "") {
                $User->setEmail($Request['Arguments']['Email']);
            }
            if (isset($Request['Arguments']['Password']) && $Request['Arguments']['Password'] !== "") {
                $User->setPassword($Request['Arguments']['Password']);
            }

            $Error = null;

            $Email = $User->getEmail();
            $Password = $User->getPassword();

            if (isset($Email)) ;
            else {
                $Error = "No email given.";
            };
            if (isset($Password)) ;
            else {
                $Error = "No password given.";
            }

            $User->Error = $Error;

            $View = $this->getView("Login.phtml", array("User" => $User));

            return $View;
        }

        protected function Info() {
            $User = $this->getModel("User");
            $View = $this->getView("User.phtml", array("User" => $User));

            return $View;
        }
    }
}

?>

Fix check for email and password.

AP-6: Fix check for email and password.


<?php

namespace App\Http\Middleware;

use Closure;
use Config;
use Route;

class CheckPermissions
{
  /**
   * Handle the ACLs for permissions.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @param  string|null  $guard
   * @return mixed
   */
    public function handle($request, Closure $next, $section = null, $guard = null)
    {

        if (($request->user()->hasAccess($section)) || ($request->user()->isSuperUser())) {
            return $next($request);
        }

        return response()->view('layouts/basic', [
          'content' => view('errors/403')
        ]);

    }
}

<?php

namespace App\Http\Middleware;

use Closure;
use Config;
use Route;
use Gate;

class CheckPermissions
{
  /**
   * Handle the ACLs for permissions.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @param  string|null  $section
   * @return mixed
   */
    public function handle($request, Closure $next, $section = null)
    {

        if (Gate::allows($section)) {
            return $next($request);
        }

        return response()->view('layouts/basic', [
            'content' => view('errors/403')
        ]);

    }
}

Switch to gate for permission check

Switch to gate for permission check


<?php
require_once($argv[1]); // type.php
require_once($argv[2]); // program.php
$file_prefix = $argv[3];
$idl_type = $argv[4];
?>
// apps
# include "<?=$file_prefix?>.app.example.h"

void dsn_app_registration_<?=$_PROG->name?>()
{
    // register all possible service apps
    dsn::register_app< <?=$_PROG->get_cpp_namespace().$_PROG->name?>_server_app>("server");
    dsn::register_app< <?=$_PROG->get_cpp_namespace().$_PROG->name?>_client_app>("client");
<?php foreach ($_PROG->services as $svc) { ?>
    dsn::register_app< <?=$_PROG->get_cpp_namespace().$svc->name?>_perf_test_client_app>("client.perf.<?=$svc->name?>");
<?php } ?>
}

# ifndef DSN_RUN_USE_SVCHOST

int main(int argc, char** argv)
{
    dsn_app_registration_<?=$_PROG->name?>();

    // specify what services and tools will run in config file, then run
    dsn_run(argc, argv, true);
    return 0;
}

# else

# include <dsn/internal/module_int.cpp.h>

MODULE_INIT_BEGIN
    dsn_app_registration_<?=$_PROG->name?>();
MODULE_INIT_END

# endif

<?php
require_once($argv[1]); // type.php
require_once($argv[2]); // program.php
$file_prefix = $argv[3];
$idl_type = $argv[4];
?>
// apps
# include "<?=$file_prefix?>.app.example.h"

void dsn_app_registration_<?=$_PROG->name?>()
{
    // register all possible service apps
    dsn::register_app< <?=$_PROG->get_cpp_namespace().$_PROG->name?>_server_app>("server");
    dsn::register_app< <?=$_PROG->get_cpp_namespace().$_PROG->name?>_client_app>("client");
<?php foreach ($_PROG->services as $svc) { ?>
    dsn::register_app< <?=$_PROG->get_cpp_namespace().$svc->name?>_perf_test_client_app>("client.perf.<?=$svc->name?>");
<?php } ?>
}

# ifndef DSN_RUN_USE_SVCHOST

int main(int argc, char** argv)
{
    dsn_app_registration_<?=$_PROG->name?>();

    // specify what services and tools will run in config file, then run
    dsn_run(argc, argv, true);
    return 0;
}

# else

# include <dsn/internal/module_init.cpp.h>

MODULE_INIT_BEGIN(<?=$_PROG->name?>)
    dsn_app_registration_<?=$_PROG->name?>();
MODULE_INIT_END

# endif

Fix codegen template typo for app dll generation


<?php
/**
 * TODO
 *
 * @package silverstripe-mailblock
 * @subpackage extensions
 */

class MailblockSiteConfig extends DataExtension {

	private static $db = array(
		'MailblockEnabled' => 'Boolean',
	);

	public function updateCMSFields(FieldList $fields) {

		$fields->addFieldToTab(
			'Root.Mailblock',
			$enable = CheckboxField::create(
				'MailblockEnabled',
				_t('MailblockConfig.Enabled','Enable mailblock.')
			)
		);
	}
}

<?php
/**
 * Adds a mailblock section to the 'Settings' section of the CMS.
 *
 * @package silverstripe-mailblock
 * @subpackage extensions
 */

class MailblockSiteConfig extends DataExtension implements PermissionProvider {

	private static $db = array(
		'MailblockEnabled' => 'Boolean',
	);

	public function updateCMSFields(FieldList $fields) {
		if(Permission::checkMember($member, 'MANAGE_MAILBLOCK')) {
			$fields->addFieldToTab(
				'Root.Mailblock',
				$enable = CheckboxField::create(
					'MailblockEnabled',
					_t('MailblockConfig.Enabled','Enable mailblock.')
				)
			);
		}
	}

	/**
	 * Provide permissions to the CMS.
	 *
	 * @return array
	 */
	public function providePermissions() {
		return array(
			'MANAGE_MAILBLOCK' => array(
				'name'     => _t('Mailblock.ADMIN_PERMISSION',
					"Access to 'Mailblock' settings"
				),
				'category' => _t('Permission.CMS_ACCESS_CATEGORY',
					'CMS Access'
				),
				'sort'     => 100,
			),
		);
	}
}

Add permission to manage mailblock.

Add permission to manage mailblock.


<?php

namespace Sirius\Validation\Rule;

use Sirius\Validation\Rule\GreaterThan as Rule;

class GreaterThanTest extends \PHPUnit_Framework_TestCase
{

    function setUp()
    {
        $this->rule = new Rule();
    }

    function testDefaultOptions()
    {
        $this->assertNull($this->rule->getOption('min'));
        $this->assertTrue($this->rule->getOption('inclusive'));
    }

    function testExclusiveValidation()
    {
        $this->rule->setOption('inclusive', false);
        $this->rule->setOption('min', 100);
        $this->assertFalse($this->rule->validate(100));
    }

    function testValidationWithoutALimit()
    {
        $this->assertTrue($this->rule->validate(0));
    }
}

<?php

namespace Sirius\Validation\Rule;

use Sirius\Validation\Rule\GreaterThan as Rule;

class GreaterThanTest extends \PHPUnit_Framework_TestCase
{

    function setUp()
    {
        $this->rule = new Rule();
    }

    function testDefaultOptions()
    {
        $this->assertNull($this->rule->getOption('min'));
        $this->assertTrue($this->rule->getOption('inclusive'));
    }

    function testExclusiveValidation()
    {
        $this->rule->setOption('inclusive', false);
        $this->rule->setOption('min', 100);
        $this->assertFalse($this->rule->validate(100));
    }

    function testValidationWithoutALimit()
    {
        $this->assertTrue($this->rule->validate(0));
    }

    function testConstructCvsFormatMinZeroAndInclusiveFalse()
    {
        $this->rule = new Rule('0,false');
        $this->assertSame('0', $this->rule->getOption('min'));
        $this->assertSame(false, $this->rule->getOption('inclusive'));
    }
}

Add test to check cvs format with two options


<?php

namespace ElasticEmail\Email;

use ElasticEmail\Client;
use ElasticEmail\Response;

/**
 * @see http://api.elasticemail.com/public/help#Email_Send
 */
class Send extends Response
{
    const URI = 'email/send';

    /** @var Client */
    private $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function handle(array $params = [], $muiltipartOption = false)
    {
        $options = $this->transform($params, $muiltipartOption);

        $this->response = $this->client->request('POST', self::URI, $options);

        return $this;
    }

    protected function transform(array $params, $multipartOption)
    {
        if (! $multipartOption) {
            return ['form_params' => $params];
        }

        $multipart = [];

        foreach ($params as $key => $value) {
            $multipart[] = [
                'name' => $key,
                'contents' => $value
            ];
        }

        return ['multipart' => $multipart];
    }
}

<?php

namespace ElasticEmail\Email;

use ElasticEmail\Client;
use ElasticEmail\Response;

/**
 * @see http://api.elasticemail.com/public/help#Email_Send
 */
class Send extends Response
{
    const URI = 'email/send';

    /** @var Client */
    private $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function handle(array $params = [], $attachmentPaths = [])
    {
        $options = $this->transform($params, $attachmentPaths);

        $this->response = $this->client->request('POST', self::URI, $options);

        return $this;
    }

    protected function transform(array $params, array $attachmentPaths = [])
    {
        if (empty($attachmentPaths)) {
            return ['form_params' => $params];
        }

        $multipart = [];

        foreach ($params as $key => $value) {
            $multipart[] = [
                'name' => $key,
                'contents' => $value
            ];
        }

        foreach ($attachmentPaths as $path) {
            $pathParts = explode(DIRECTORY_SEPARATOR, $path);
            $filename = end($pathParts);

            $multipart[] = [
                'name' => $filename,
                'contents' => fopen($path, 'r'),
                'filename' => $filename
            ];
        }

        return ['multipart' => $multipart];
    }
}

Add files from passed attachment paths.

Add files from passed attachment paths.


<?php

namespace Just\PosterGenerator;

use Illuminate\Contracts\Config\Repository as ConfigRepository;
use Illuminate\Filesystem\FilesystemManager;
use Symfony\Component\HttpFoundation\File\File;

class Filesystem
{

    /**
     * @param FilesystemManager                       $filesystems
     * @param \Illuminate\Contracts\Config\Repository $config
     */
    public function __construct(FilesystemManager $filesystems, ConfigRepository $config)
    {
        $this->filesystem = $filesystems;
        $this->config = $config;
    }

    /**
     * @param File $file
     * @return bool
     */
    public function put(File $file)
    {
        return $this->getDisk()->put($file->getBasename(), file_get_contents($file->getPathname()), 'public');
    }

    /**
     * @param $path
     * @return string
     */
    public function get($path)
    {
        return $this->getDisk()->get($path);
    }

    /**
     * @param $path
     * @return string
     */
    public function url($path)
    {
        return sprintf(
            'https://s3-eu-west-1.amazonaws.com/%s/%s/%s',
            env('AWS_BUCKET'),
            'posters',
            $path
        );
    }

    /**
     * @return \Illuminate\Contracts\Filesystem\Filesystem
     */
    public function getDisk()
    {
        return $this->filesystem->disk($this->config->get('poster.defaultFilesystem'));
    }

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

}

<?php

namespace Just\PosterGenerator;

use Illuminate\Contracts\Config\Repository as ConfigRepository;
use Illuminate\Filesystem\FilesystemManager;
use Symfony\Component\HttpFoundation\File\File;

class Filesystem
{

    /**
     * @param FilesystemManager                       $filesystems
     * @param \Illuminate\Contracts\Config\Repository $config
     */
    public function __construct(FilesystemManager $filesystems, ConfigRepository $config)
    {
        $this->filesystem = $filesystems;
        $this->config = $config;
    }

    /**
     * @param File $file
     * @return bool
     */
    public function put(File $file)
    {
        return $this->getDisk()->put($file->getBasename(), file_get_contents($file->getPathname()), 'public');
    }

    /**
     * @param $path
     * @return string
     */
    public function get($path)
    {
        return $this->getDisk()->get($path);
    }

    /**
     * @return \Illuminate\Contracts\Filesystem\Filesystem
     */
    public function getDisk()
    {
        return $this->filesystem->disk($this->config->get('poster.defaultFilesystem'));
    }

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

}

Chore: Remove url function should be abstracted per filesystem disk.


Standart Post With a Featured Image

 15 May, 2015

                                0 comments

                         Like

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus eget aliquet ante. Ut blandit bibendum sapien sed condimentum. Sed sit amet justo a quam dapibus semper. Duis sit amet vulputate sapien. Nullam quis nisl dolor. Sed gravida ullamcorper nulla sed rutrum. Nullam vel nisi finibus, luctus velit iaculis, ultricies eros. Sed dapibus, elit in fermentum pulvinar, ligula dui interdum tortor, ac pellentesque lacus lacus tincidunt velit.

In rhoncus vitae ligula non dignissim. Cras mattis augue quis tempus facilisis. Donec finibus leo consequat auctor rhoncus. Vivamus volutpat aliquet lectus nec condimentum. Proin non purus facilisis est egestas aliquet. Phasellus pretium arcu non pellentesque facilisis. Donec finibus diam sit amet tincidunt auctor. Cras in nunc non elit luctus tempus in sed sapien. Mauris at dignissim ex, a varius enim. Aenean gravida, nisl aliquam ultrices pellentesque, quam augue gravida eros, id aliquam dolor est sagittis dolor. Nullam dui quam, semper vel tincidunt porttitor, porttitor ac ligula. Aenean pellentesque nisi vitae urna volutpat volutpat. In pulvinar diam id dolor dictum dignissim.

                    read more

Add example post in home page

Add example post in home page


<?php
/**
 * Copyright © 2019 Magmodules.eu. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magmodules\Channable\Service\Product;

use Magento\Framework\App\ResourceConnection;

/**
 * Class InventorySource
 *
 * @package Magmodules\Channable\Service\Product
 */
class InventorySource
{

    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

    /**
     * Inventory constructor.
     *
     * @param ResourceConnection $resourceConnection
     */
    public function __construct(
        ResourceConnection $resourceConnection
    ) {
        $this->resourceConnection = $resourceConnection;
    }

    /**
     * Returns inventory source (stock_id) by websiteCode
     *
     * @param $websiteCode
     *
     * @return string
     */
    public function execute($websiteCode)
    {
        $source = null;
        $connection = $this->resourceConnection->getConnection();
        $tableName = $this->resourceConnection->getTableName('inventory_stock_sales_channel');

        if (!$connection->isTableExists($tableName)) {
            return $source;
        }

        $select = $connection->select()
            ->from($tableName, ['stock_id'])
            ->where('code = ?', $websiteCode)
            ->limit(1);

        return $connection->fetchOne($select);
    }

}

<?php
/**
 * Copyright © 2019 Magmodules.eu. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magmodules\Channable\Service\Product;

use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Module\Manager as ModuleManager;

/**
 * Class InventorySource
 *
 * @package Magmodules\Channable\Service\Product
 */
class InventorySource
{

    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

    /**
     * @var ModuleManager
     */
    private $moduleManager;

    /**
     * InventorySource constructor.
     *
     * @param ResourceConnection $resourceConnection
     * @param ModuleManager      $moduleManager
     */
    public function __construct(
        ResourceConnection $resourceConnection,
        ModuleManager $moduleManager
    ) {
        $this->resourceConnection = $resourceConnection;
        $this->moduleManager = $moduleManager;
    }

    /**
     * Returns inventory source (stock_id) by websiteCode
     *
     * @param $websiteCode
     *
     * @return string
     */
    public function execute($websiteCode)
    {
        $source = null;

        if (!$this->isMsiEnabled()) {
            return $source;
        }

        $connection = $this->resourceConnection->getConnection();
        $tableName = $this->resourceConnection->getTableName('inventory_stock_sales_channel');

        if (!$connection->isTableExists($tableName)) {
            return $source;
        }

        $select = $connection->select()
            ->from($tableName, ['stock_id'])
            ->where('code = ?', $websiteCode)
            ->limit(1);

        return $connection->fetchOne($select);
    }

    /**
     * @return bool
     */
    public function isMsiEnabled()
    {
        return $this->moduleManager->isEnabled('Magento_Inventory');
    }

}

Check if MSI is enabled (could be disabled afterwards)


<?php
/**
 * @title            Import Class
 * @desc             Generic Importer Class for the pH7CMS.
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Install / Class
 * @version          0.1
 */

namespace PH7;

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

abstract class Import
{
    protected $db;

    public function __construct()
    {
        $this->db = Db::getInstance();

    }
}

<?php
/**
 * @title            Import Class
 * @desc             Generic Importer Class to import data from other platforms (such as phpFox, SocialEngine, mooSocial, Skadate, DatingScript, DatingPro) to pH7CMS.
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Install / Class
 * @version          0.1
 */

namespace PH7;

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

abstract class Import
{
    protected $db;

    public function __construct()
    {
        $this->db = Db::getInstance();
    }
}

Add more details about what the class should do

And remove extra line..


<?php
/**
 * @package		phpmvc
 * @author		NTKSoft Team
 * @copyright   Copyright (C) 2014 NTKSoft, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 *
 */
require BASE_DIR . '/vendor/autoload.php';

require BASE_DIR . '/system/application/Application.php';

$app = Application::singleton();

$providers = $app->getConfig()['providers'];

// Load service provider
$app->getProviderRepository()->load($app, $providers);

return $app;

<?php
/**
 * @package		phpmvc
 * @author		NTKSoft Team
 * @copyright   Copyright (C) 2014 NTKSoft, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 *
 */
require BASE_DIR . '/vendor/autoload.php';

$app = \system\application\Application::singleton();

// Set application to facade
\system\facade\Facade::setContainer($app);

$providers = $app->getConfig()['providers'];

\system\routing\Router::testFacade();

// Load service provider
$app->getProviderRepository()->load($app, $providers);

return $app;

Update code to add namespace and Facade pattern


<?php

namespace PMT\WebBundle\Controller;

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

class AjaxController extends Controller
{
    /**
     * @Route("/ajax/tags.json", name="pmtweb_ajax_tags")
     * @Method("post")
     */
    public function tagsAction()
    {
        $term = trim($this->getRequest()->request->get('q'));

        $tags = $this->getDoctrine()->getRepository('PMT\CoreBundle\Entity\Tag')
            ->findByName($term);

        $tagObjects = array_map(
            function ($tag) {
                return array(
                    'id' => $tag->getName(),
                    'text' => $tag->getName(),
                );
            },
            $tags
        );

        if ($this->getRequest()->request->get('add_new') && !in_array($term, $tags)) {
            array_unshift(
                $tagObjects,
                array(
                    'id' => $term,
                    'text' => 'new: ' . $term,
                )
            );
        }

        $response = new JsonResponse();
        $response->setData(
            array(
                'tags' => $tagObjects,
            )
        );

        return $response;
    }
}

<?php

namespace PMT\WebBundle\Controller;

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

class AjaxController extends Controller
{
    /**
     * @Route("/ajax/tags.json", name="pmtweb_ajax_tags")
     * @Method("post")
     */
    public function tagsAction()
    {
        $term = trim($this->getRequest()->request->get('q'));

        $tags = $this->getDoctrine()->getRepository('PMT\CoreBundle\Entity\Tag')
            ->findByName($term);

        $tagObjects = array_map(
            function ($tag) {
                return array(
                    'id' => $tag->getName(),
                    'text' => $tag->getName(),
                );
            },
            $tags
        );

        if ($this->getRequest()->request->get('add_new') && !in_array($term, $tags)) {
            $tagObjects[] =
                array(
                    'id' => $term,
                    'text' => 'new: ' . $term,
                );
        }

        $response = new JsonResponse();
        $response->setData(
            array(
                'tags' => $tagObjects,
            )
        );

        return $response;
    }
}

Add the new tags at the end

Add the new tags at the end


 <?php

$url1 = $_GET["url1"];
$url2 =  $_GET["url2"];
$type = $_GET["type"];
$pagelyze="DISPLAY=:98 java -jar  /var/lib/pagelyzer/jPagelyzer.jar -get score -cmode ";

$descriptorspec = array(
    0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
    1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
    2 => array("pipe", "w")
 );

if($type == 1)
{
	$cmd = $pagelyze."images -url1 ".$url1." -url2 ".$url2." 2>&1";
}
elseif($type == 2)
{
	$cmd = $pagelyze."structure -url1 ".$url1." -url2 ".$url2." 2>&1";
}
else
{
	$cmd = $pagelyze."hybrid -url1 ".$url1." -url2 ".$url2." 2>&1";
}

$p=proc_open ($cmd, $descriptorspec, $pipes);

$out = stream_get_contents($pipes[1]) ;
$out2 = json_encode($out);
$parts = explode('\n', $out2);
$result = json_encode($parts[sizeof($parts)-2]);
print($result);
proc_close($p);
?>

 <?php

require_once "../StyleJS/json/JSON.php";
$json = new Services_JSON();

$url1 = $_GET["url1"];
$url2 =  $_GET["url2"];
$type = $_GET["type"];

$descriptorspec = array(
    0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
    1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
    2 => array("pipe", "w")
 );

if($type == 1)
{
	$config="config_image.xml";
}
elseif($type == 2)
{
	$config="config_content.xml";
}
else
{
	$config="config_hybrid.xml";
}
$cmd = "java -jar  Pagelyzer-0.0.1-SNAPSHOT-jar-with-dependencies.jar -url1 ".$url1." -url2 ".$url2." -config ".$config." 2>&1";

$p=proc_open ($cmd, $descriptorspec, $pipes);

$out = stream_get_contents($pipes[1]) ;
$out2 = $json->encode($out);
$parts = explode('\n', $out2);
$output = array();
for ($i = 1; $i < sizeof($parts); $i++) {
    $output[] = $json->encode($parts[$i]);

}
echo json_encode($output);

proc_close($p);
?>

Update for new jar and dynamic demo

Update for new jar and dynamic demo


<?php

namespace App\Http\Controllers;

use App\Invoice;
use App\Book;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Services\Purchase;

class Purchases extends Controller
{

    /**
     * Purchase book and generate invoice.
     *
     * @param  Request  $request
     * @return Response
     */
    public function index(Request $request) {
        $invoice = null;
        $purchaseService = new Purchase();
        $purchaseQty = $request->input('qty');
        $book = Book::find($request->input('book_id'));
        $purchasePrice = $purchaseService->purchaseBook($book,$purchaseQty);

        if($purchasePrice !== null) {
            $invoice = new Invoice();
            $invoice->book_id = $book->id;
            $invoice->amount = $purchasePrice;
            $invoice->qty = $purchaseQty;
            $invoice->created_at = date('Y-m-d H:i:s');
            $invoice->updated_at = date('Y-m-d H:i:s');
            $invoice->save();
        }

        return $invoice;
    }
}

<?php

namespace App\Http\Controllers;

use App\Invoice;
use App\Book;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Services\Purchase;

class Purchases extends Controller
{

    /**
     * Purchase book and generate invoice.
     *
     * @param  Request  $request
     * @return Response
     */
    public function index(Request $request) {
        $invoice = null;
        $purchaseService = new Purchase();
        $purchaseQty = $request->input('qty');
        $book = Book::find($request->input('book_id'));
        $purchasePrice = $purchaseService->purchaseBook($book,$purchaseQty);

        if($purchasePrice !== null) {
            $book->quantity -= $purchaseQty;
            $invoice = new Invoice();
            $invoice->book_id = $book->id;
            $invoice->amount = $purchasePrice;
            $invoice->qty = $purchaseQty;
            $invoice->created_at = date('Y-m-d H:i:s');
            $invoice->updated_at = date('Y-m-d H:i:s');
            $invoice->save();
            $book->save();
        }

        return $invoice;
    }
}

Add purchase functionality in back-end.

Add purchase functionality in back-end.


<?php

namespace WyriHaximus\React\Tests\Cake\Orm;

use WyriHaximus\React\Cake\Orm\AsyncTableGenerator;
use WyriHaximus\React\TestApp\Cake\Orm\Table\ScreenshotsTable;

class AsyncTableGeneratorTest extends TestCase
{
    public function testGenerate()
    {
        $tmpDir = sys_get_temp_dir() . DS . uniqid('WyriHaximus-Cake-Async-ORM-', true) . DS;
        mkdir($tmpDir, 0777, true);
        $generator = new AsyncTableGenerator($tmpDir);
        $filename = $generator->generate(ScreenshotsTable::class);
        $this->assertFileEquals(
            dirname(__DIR__) . DS . 'test_app' . DS . 'ExpectedGeneratedAsyncTable' . DS . 'C17a66dcf052f6878c3f1c553db4d6bd0_Ff47f6f78cf1b377de64788b3705cda9c.php',
            $tmpDir . $filename . '.php'
        );
    }
}

<?php

namespace WyriHaximus\React\Tests\Cake\Orm;

use WyriHaximus\React\Cake\Orm\AsyncTableGenerator;
use WyriHaximus\React\Cake\Orm\GeneratedTable;
use WyriHaximus\React\TestApp\Cake\Orm\Table\ScreenshotsTable;

class AsyncTableGeneratorTest extends TestCase
{
    public function testGenerate()
    {
        $tmpDir = sys_get_temp_dir() . DS . uniqid('WyriHaximus-Cake-Async-ORM-', true) . DS;
        mkdir($tmpDir, 0777, true);
        $generator = new AsyncTableGenerator($tmpDir);
        $generatedTable = $generator->generate(ScreenshotsTable::class);
        $this->assertInstanceOf(GeneratedTable::class, $generatedTable);
        $this->assertFileEquals(
            dirname(__DIR__) . DS . 'test_app' . DS . 'ExpectedGeneratedAsyncTable' . DS . 'C17a66dcf052f6878c3f1c553db4d6bd0_Ff47f6f78cf1b377de64788b3705cda9c.php',
            $tmpDir . $generatedTable->getClassName() . '.php'
        );
    }
}

Test against generated table object

Test against generated table object


<?php
namespace Tests\Integration;

use Cache;
use Carbon\Carbon;
use Decoy;
use Tests\TestCase;

class ChangesTest extends TestCase
{

    /**
     * Common init
     *
     * @return void
     */
    protected function setUp() {
        parent::setUp();
        $this->auth();
    }

    /**
     * Test that the commands page loads
     *
     * @return void
     */
    public function testChangesIndex()
    {
        $response = $this->get('admin/changes');
        $response->assertStatus(200);
    }

}

<?php
namespace Tests\Integration;

use App\Tag;
use Bkwld\Decoy\Models\Change;
use Cache;
use Carbon\Carbon;
use Decoy;
use Tests\TestCase;

class ChangesTest extends TestCase
{

    /**
     * The tag that triggreed changes
     *
     * @var Tag
     */
    protected $tag;

    /**
     * Common init
     *
     * @return void
     */
    protected function setUp() {
        parent::setUp();
        $this->auth();

        // Create a series of Change records through messing with the soft
        // deleting Tag model
        $this->tag = factory(Tag::class)->create([ 'name' => 'Name' ]);
        $this->tag->name = 'New name';
        $this->tag->save();
        $this->tag->delete();
    }

    /**
     * Test that the commands page loads
     *
     * @return void
     */
    public function testIndex()
    {
        $response = $this->get('admin/changes');
        $response->assertStatus(200);

        // Test that all the changes from the setUp were created
        $this->assertEquals(3, Change::count());
    }

    /**
     * Test that the edit response returns JSON
     *
     * @return void
     */
    public function testCreatedEdit()
    {
        $response = $this->get('admin/changes/1/edit');
        $response
            ->assertStatus(200)
            ->assertJson([
                'title' => 'Name',
                'action' => 'created',
            ]);
    }

    /**
     * Test that the edit response returns JSON
     *
     * @return void
     */
    public function testUpdatedEdit()
    {
        $response = $this->get('admin/changes/2/edit');
        $response
            ->assertStatus(200)
            ->assertJson([
                'title' => 'New name',
                'action' => 'updated',
            ]);
    }

}

Add tests of Change edit

Add tests of Change edit


<?php

namespace Michaeljennings\Carpenter\Tests\Store;

use Michaeljennings\Carpenter\Store\Laravel4\Eloquent;
use Michaeljennings\Carpenter\Tests\TestCase;

class Laravel4StoreTest extends TestCase
{
    public function testCountReturnsTotalResults()
    {
        $store = $this->makeStore();
        $model = new ExampleEloquentModel();

        $store->model($model);
        $this->assertEquals(0, $store->count());
    }

    public function makeStore()
    {
        return new Eloquent();
    }
}

<?php

namespace Michaeljennings\Carpenter\Tests\Store;

use Michaeljennings\Carpenter\Store\Laravel4\Eloquent;
use Michaeljennings\Carpenter\Tests\TestCase;

class Laravel4StoreTest extends TestCase
{
    public function testCountReturnsTotalResults()
    {
        $store = $this->makeStore();
        $model = new ExampleEloquentModel();

        $store->model($model);
        $this->assertEquals(0, $store->count());
    }

    /**
     * @expectedException \Michaeljennings\Carpenter\Exceptions\ModelNotSetException
     */
    public function testExceptionIsThrownIfCountIsCalledBeforeModelIsSet()
    {
        $store = $this->makeStore();

        $store->count();
    }

    public function makeStore()
    {
        return new Eloquent();
    }
}

Update laravel 4 store test

Update laravel 4 store test


<?php

/*
 * This file is part of the PhpTabs package.
 *
 * Copyright (c) landrok at github.com/landrok
 *
 * For the full copyright and license information, please see
 * <https://github.com/stdtabs/phptabs/blob/master/LICENSE>.
 */

namespace PhpTabs\Component\Renderer;

interface RendererInterface
{
  /**
   * @param  int $index Track index
   * @return string
   */
  public function render($index);

  /**
   * @param  string     $name
   * @param  int|string $value
   * @return \PhpTabs\Model\RendererInterface
   */
  public function setOption($name, $value);

  /**
   * @param  string     $name
   * @param  int|string $default
   * @return int|string
   */
  public function getOption($name, $default);

  /**
   * @param  array $options
   * @return \PhpTabs\Model\RendererInterface
   */
  public function setOptions(array $options);

  /**
   * @return array
   */
  public function getOptions();
}

<?php

/*
 * This file is part of the PhpTabs package.
 *
 * Copyright (c) landrok at github.com/landrok
 *
 * For the full copyright and license information, please see
 * <https://github.com/stdtabs/phptabs/blob/master/LICENSE>.
 */

namespace PhpTabs\Component\Renderer;

interface RendererInterface
{
  /**
   * @param  int $index Track index
   * @return string
   */
  public function render($index);

  /**
   * @param  string     $name
   * @param  int|string $value
   * @return \PhpTabs\Component\Renderer\RendererInterface
   */
  public function setOption($name, $value);

  /**
   * @param  string     $name
   * @param  int|string $default
   * @return int|string
   */
  public function getOption($name, $default);

  /**
   * @param  array $options
   * @return \PhpTabs\Component\Renderer\RendererInterface
   */
  public function setOptions(array $options);

  /**
   * @return array
   */
  public function getOptions();
}

Fix PHPDoc wrong type annotation

Fix PHPDoc wrong type annotation


<?php

class TrackBackPing extends DataObject {
	static $db = array(
		'Title' => 'Varchar',
		'Excerpt' => 'Text',
		'Url' => 'Varchar',
		'BlogName' => 'Varchar'
	);

	static $has_one = array(
		'Page' => 'Page'
	);

	static $has_many = array();

	static $many_many = array();

	static $belongs_many_many = array();
}

?>

<?php

class TrackBackPing extends DataObject {
	static $db = array(
		'Title' => 'Varchar',
		'Excerpt' => 'Text',
		// 2083 is URL-length limit for IE, AFAIK.
		// see: http://www.boutell.com/newfaq/misc/urllength.html
		'Url' => 'Varchar(2048)',
		'BlogName' => 'Varchar'
	);

	static $has_one = array(
		'Page' => 'Page'
	);

	static $has_many = array();

	static $many_many = array();

	static $belongs_many_many = array();
}

?>

Extend URL length from 50 to 2048 chars

BUGFIX: Extend URL length from 50 to 2048 chars


<?php

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::prefix('bans')->group(function() {
    Route::post('list',         'BanController@getBanList');

    Route::middleware('auth.token.server')->group(function() {
        Route::post('store/ban',    'BanController@storeBan');
        Route::post('store/unban',  'BanController@storeUnban');
        Route::post('status',       'BanController@getUserStatus');
        Route::post('history',      'BanController@getUserBanHistory');
    });
});

Route::prefix('servers')->group(function() {
    Route::get('all', 'ServerController@getAllServers');
});

Route::get('discord/sync', 'DiscordSyncController@getRank');

Route::post('minecraft/authenticate', 'TempMinecraftController@authenticate');

<?php

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::prefix('bans')->group(function() {
    Route::post('list',         'BanController@getBanList');

    Route::middleware('auth.token.server')->group(function() {
        Route::post('store/ban',    'BanController@storeBan');
        Route::post('store/unban',  'BanController@storeUnban');
        Route::post('status',       'BanController@getUserStatus');
        Route::post('history',      'BanController@getUserBanHistory');
    });
});

Route::prefix('servers')->group(function() {
    Route::get('all', 'ServerController@getAllServers');
});

Route::post('discord/sync', 'DiscordSyncController@getRank');

Route::post('minecraft/authenticate', 'TempMinecraftController@authenticate');

Convert DiscordSync route to POST

Convert DiscordSync route to POST


<?php

namespace Distil;

use Distil\Exceptions\CannotCreateCriterion;

final class CriterionFactory
{
    /**
     * @var array
     */
    private $criteriaResolvers;

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

    public function createByName(string $name, ...$arguments): Criterion
    {
        $criterion = $this->resolver($name);

        if (is_callable($criterion)) {
            return call_user_func_array($criterion, $arguments);
        }

        return new $criterion(...$arguments);
    }

    private function resolver(string $name): string
    {
        if (array_key_exists($name, $this->criteriaResolvers)) {
            return $this->criteriaResolvers[$name];
        }

        throw CannotCreateCriterion::missingResolver($name, array_keys($this->criteriaResolvers));
    }
}

<?php

namespace Distil;

use Distil\Exceptions\CannotCreateCriterion;

final class CriterionFactory
{
    /**
     * @var array
     */
    private $criteriaResolvers;

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

    public function createByName(string $name, ...$arguments): Criterion
    {
        $criterion = $this->resolver($name);

        if (is_callable($criterion)) {
            return call_user_func_array($criterion, $arguments);
        }

        return new $criterion(...$arguments);
    }

    private function resolver(string $name): string
    {
        if (! array_key_exists($name, $this->criteriaResolvers)) {
            throw CannotCreateCriterion::missingResolver($name, array_keys($this->criteriaResolvers));
        }

        return $this->criteriaResolvers[$name];
    }
}

Switch logic of if statement

Switch logic of if statement


<?php
/**
 * @package     Mautic
 * @copyright   2014 Mautic Contributors. All rights reserved.
 * @author      Mautic
 * @link        http://mautic.org
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */
?>

<form action="" class="panel" id="timeline-filters">

        <input type="text" class="form-control bdr-w-0" name="search" id="search" placeholder="<?php echo $view['translator']->trans('mautic.core.search.placeholder'); ?>">

        <?php if (isset($eventTypes) && is_array($eventTypes)) : ?>
            <select name="eventFilters[]" multiple class="form-control bdr-w-0" data-placeholder="<?php echo $view['translator']->trans('mautic.lead.lead.filter.bundles.placeholder'); ?>">
            <?php foreach ($eventTypes as $typeKey => $typeName) : ?>
                <option value="<?php echo $typeKey; ?>"<?php echo in_array($typeKey, $eventFilter) ? ' selected' : ''; ?> />
                    <?php echo $typeName; ?>
                </option>
            <?php endforeach; ?>
            </select>
        <?php endif; ?>

    <input type="hidden" name="leadId" id="leadId" value="<?php echo $lead->getId(); ?>" />
</form>

<?php
/**
 * @package     Mautic
 * @copyright   2014 Mautic Contributors. All rights reserved.
 * @author      Mautic
 * @link        http://mautic.org
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */
?>

<form action="" class="panel" id="timeline-filters">

        <input type="text" class="form-control bdr-w-0" name="search" id="search" placeholder="<?php echo $view['translator']->trans('mautic.core.search.placeholder'); ?>">

        <?php if (isset($eventTypes) && is_array($eventTypes)) : ?>
            <select name="eventFilters[]" multiple="multiple" class="form-control bdr-w-0" data-placeholder="<?php echo $view['translator']->trans('mautic.lead.lead.filter.bundles.placeholder'); ?>">
            <?php foreach ($eventTypes as $typeKey => $typeName) : ?>
                <option value="<?php echo $typeKey; ?>"<?php echo in_array($typeKey, $eventFilter) ? ' selected' : ''; ?> >
                    <?php echo $typeName; ?>
                </option>
            <?php endforeach; ?>
            </select>
        <?php endif; ?>

    <input type="hidden" name="leadId" id="leadId" value="<?php echo $lead->getId(); ?>" />
</form>

Fix of loading chosen options on Lead timeline filter without need to refresh the page


<?php

namespace Memvents;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class Event extends Model
{

    protected $table = 'events';

    protected $fillable = [
        'name',
        'event_id',
        'time',
        'status',
        'event_url',
        'created'
    ];

    public function getSampleEvents()
    {
        return Storage::get('sample_events.json');
    }
}

<?php

namespace Memvents;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class Event extends Model
{

    protected $table = 'events';

    protected $fillable = [
        'name',
        'event_id',
        'time',
        'status',
        'event_url',
        'created'
    ];

    public function getSampleEvents()
    {
        return Storage::get('sample_events.json');
    }

    public function getEventsWithin7Days()
    {
        $now = Carbon::now()->timestamp;
        $future = Carbon::createFromTimestamp($now)->addWeeks(1)->timestamp;

        return $this->whereBetween('time', [$now, $future])
            ->where('status', 'upcoming')
            ->get();
    }

    public function getEventsWithin3Days()
    {
        $now = Carbon::now()->timestamp;
        $future = Carbon::createFromTimestamp($now)->addWeeks(3)->timestamp;

        return $this->whereBetween('time', [$now, $future])
            ->where('status', 'upcoming')
            ->get();
    }

    public function getEventsWithin24Hours()
    {
        $now = Carbon::now()->timestamp;
        $future = Carbon::createFromTimestamp($now)->addHours(24)->timestamp;

        return $this->whereBetween('time', [$now, $future])
            ->where('status', 'upcoming')
            ->get();
    }
}

Add methods to get upcoming events based on date range


<?php
/**
 * @see https://developers.podio.com/doc/items
 */
class PodioItemDiff extends PodioObject {
  public function __construct($attributes = array()) {
    $this->property('field_id', 'integer');
    $this->property('type', 'string');
    $this->property('external_id', 'integer');
    $this->property('label', 'string');
    $this->property('from', 'array');
    $this->property('to', 'array');

    $this->init($attributes);
  }

  /**
   * @see https://developers.podio.com/doc/items/revert-item-revision-953195
   */
  public static function revert($item_id, $revision_id) {
    $response = Podio::delete("/item/{$item_id}/revision/{$revision_id}");
	if($response->body){
		$body=json_decode($response->body,true);
		return $body['revision'];
	}else
		return false;
  }

  /**
   * @see https://developers.podio.com/doc/items/get-item-revision-difference-22374
   */
  public static function get_for($item_id, $revision_from_id, $revision_to_id) {
    return self::listing(Podio::get("/item/{$item_id}/revision/{$revision_from_id}/{$revision_to_id}"));
  }

}

<?php
/**
 * @see https://developers.podio.com/doc/items
 */
class PodioItemDiff extends PodioObject {
  public function __construct($attributes = array()) {
    $this->property('field_id', 'integer');
    $this->property('type', 'string');
    $this->property('external_id', 'integer');
    $this->property('label', 'string');
    $this->property('from', 'array');
    $this->property('to', 'array');

    $this->init($attributes);
  }

  /**
   * @see https://developers.podio.com/doc/items/revert-item-revision-953195
   */
  public static function revert($item_id, $revision_id) {
    $body = Podio::delete("/item/{$item_id}/revision/{$revision_id}");
    return $body['revision'];
  }

  /**
   * @see https://developers.podio.com/doc/items/get-item-revision-difference-22374
   */
  public static function get_for($item_id, $revision_from_id, $revision_to_id) {
    return self::listing(Podio::get("/item/{$item_id}/revision/{$revision_from_id}/{$revision_to_id}"));
  }

}

Revert "PodioItemDif revert return fixed;"

This reverts commit b5d0dc1efac82ce06a3e82106bb82f110dbc1087.


<?php
/*
 * Copyright 2014-2015 Florian "Bluewind" Pritz <bluewind@server-speed.net>
 *
 * Licensed under AGPLv3
 * (see COPYING for full license text)
 *
 */
namespace controllers\api\v2;

class api_info extends \controllers\api\api_controller {
	static public function get_version()
	{
		return "2.0.0";
	}
}

<?php
/*
 * Copyright 2014-2015 Florian "Bluewind" Pritz <bluewind@server-speed.net>
 *
 * Licensed under AGPLv3
 * (see COPYING for full license text)
 *
 */
namespace controllers\api\v2;

class api_info extends \controllers\api\api_controller {
	static public function get_version()
	{
		return "2.1.0";
	}
}

Update API v2 version info to 2.1.0

Update API v2 version info to 2.1.0

The documentation already refers to 2.1.0 and lists a new feature of
the file/history endpoint, but requests for 2.1.0 are not yet accepted
because the server doesn't know that it actually supports this version.

Signed-off-by: Florian Pritz <753f544d2d01592750fb4bd29251b78abcfc8ecd@xinu.at>


<script src="/js/script.js" type="text/javascript"></script>
<script src='//www.cameratag.com/v15/js/cameratag.min.js' type='text/javascript'></script>
<link rel='stylesheet' href='//www.cameratag.com/v15/css/cameratag.css'>

<script src="/js/script.js" type="text/javascript"></script>
<script src='//cameratag.com/v12/js/cameratag.min.js' type='text/javascript'></script>
<link rel='stylesheet' href='//cameratag.com/static/12/cameratag.css'>

Revert cameratag version. Dont want to mess with it!


<?php
require dirname(__DIR__).'/vendor/autoload.php';

use Icicle\Concurrent\Forking\ForkContext;
use Icicle\Coroutine\Coroutine;
use Icicle\Loop;

class Test extends ForkContext
{
    /**
     * @synchronized
     */
    public $data;

    public function run()
    {
        print "Child sleeping for 4 seconds...\n";
        yield $this->lock();
        sleep(4);
        yield $this->unlock();

        yield $this->synchronized(function () {
            $this->data = 'progress';
        });

        print "Child sleeping for 2 seconds...\n";
        sleep(2);
    }
}

$generator = function () {
    $context = new Test();
    $context->data = 'blank';
    $context->start();

    Loop\timer(1, function () use ($context) {
        $context->synchronized(function ($context) {
            print "Finally got lock from child!\n";
        });
    });

    $timer = Loop\periodic(1, function () use ($context) {
        static $i;
        $i = $i + 1 ?: 1;
        print "Demonstrating how alive the parent is for the {$i}th time.\n";

        if ($context->isRunning()) {
            printf("Context data: '%s'\n", $context->data);
        }
    });

    try {
        yield $context->join();
        print "Context done!\n";
    } catch (Exception $e) {
        print "Error from child!\n";
        print $e."\n";
    } finally {
        $timer->stop();
    }
};

new Coroutine($generator());
Loop\run();

<?php
require dirname(__DIR__).'/vendor/autoload.php';

use Icicle\Concurrent\Forking\ForkContext;
use Icicle\Coroutine\Coroutine;
use Icicle\Loop;

class Test extends ForkContext
{
    /**
     * @synchronized
     */
    public $data;

    public function run()
    {
        print "Child sleeping for 4 seconds...\n";
        sleep(4);

        yield $this->synchronized(function () {
            $this->data = 'progress';
        });

        print "Child sleeping for 2 seconds...\n";
        sleep(2);
    }
}

$generator = function () {
    $context = new Test();
    $context->data = 'blank';
    $context->start();

    Loop\timer(1, function () use ($context) {
        $context->synchronized(function ($context) {
            print "Finally got lock from child!\n";
        });
    });

    $timer = Loop\periodic(1, function () use ($context) {
        static $i;
        $i = $i + 1 ?: 1;
        print "Demonstrating how alive the parent is for the {$i}th time.\n";

        if ($context->isRunning()) {
            $context->synchronized(function ($context) {
                printf("Context data: '%s'\n", $context->data);
            });
        }
    });

    try {
        yield $context->join();
        print "Context done!\n";
    } catch (Exception $e) {
        print "Error from child!\n";
        print $e."\n";
    } finally {
        $timer->stop();
    }
};

new Coroutine($generator());
Loop\run();

Fix missing synchronized read access

Fix missing synchronized read access


<?php

namespace Casinelli\CampaignMonitor;

use Illuminate\Support\ServiceProvider;

class CampaignMonitorServiceProvider extends ServiceProvider
{
    protected $defer = true;

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

    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../../config/campaignmonitor.php', 'campaignmonitor');

        $this->app['campaignmonitor'] = $this->app->share(function ($app) {
            return new CampaignMonitor($app);
        });
    }

    public function provides()
    {
        return ['campaignmonitor'];
    }
}

<?php

namespace Casinelli\CampaignMonitor;

use Illuminate\Support\ServiceProvider;

class CampaignMonitorServiceProvider extends ServiceProvider
{
    protected $defer = true;

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

    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../../config/campaignmonitor.php', 'campaignmonitor');

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

    public function provides()
    {
        return ['campaignmonitor'];
    }
}

Add support for Laravel 5.4

Add support for Laravel 5.4


<?php

namespace PhpSpec\Wrapper\Subject\Expectation;

use Exception;
use PhpSpec\Util\Instantiator;
use PhpSpec\Wrapper\Subject\WrappedObject;
use PhpSpec\Wrapper\Unwrapper;

class ConstructorDecorator extends Decorator implements ExpectationInterface
{
    private $unwrapper;

    public function __construct(ExpectationInterface $expectation, Unwrapper $unwrapper)
    {
        $this->setExpectation($expectation);
        $this->unwrapper = $unwrapper;
    }

    public function match($alias, $subject, array $arguments = array(), WrappedObject $wrappedObject = null)
    {
        try {
            $wrapped = $subject->getWrappedObject();
        } catch (Exception $e) {
            if ($wrappedObject->getClassName()) {
                $instantiator = new Instantiator();
                $wrapped = $instantiator->instantiate($wrappedObject->getClassName());
            }
        }

        return $this->getExpectation()->match($alias, $wrapped, $arguments);
    }
}

<?php

namespace PhpSpec\Wrapper\Subject\Expectation;

use Exception;
use PhpSpec\Exception\Example\ErrorException;
use PhpSpec\Util\Instantiator;
use PhpSpec\Wrapper\Subject\WrappedObject;
use PhpSpec\Wrapper\Unwrapper;

class ConstructorDecorator extends Decorator implements ExpectationInterface
{
    private $unwrapper;

    public function __construct(ExpectationInterface $expectation, Unwrapper $unwrapper)
    {
        $this->setExpectation($expectation);
        $this->unwrapper = $unwrapper;
    }

    public function match($alias, $subject, array $arguments = array(), WrappedObject $wrappedObject = null)
    {
        try {
            $wrapped = $subject->getWrappedObject();
        } catch (ErrorException $e) {
            throw $e;
        } catch (Exception $e) {
            if ($wrappedObject->getClassName()) {
                $instantiator = new Instantiator();
                $wrapped = $instantiator->instantiate($wrappedObject->getClassName());
            }
        }

        return $this->getExpectation()->match($alias, $wrapped, $arguments);
    }
}

Cover case we have an error exception

Cover case we have an error exception


<?php namespace JamylBot\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use JamylBot\Group;

class MustBeAdmin {

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

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     */
    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 ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect('/home')->with('auth_message', 'Must be logged in.');
            }
        }
        /** @var \JamylBot\User $user */
        $user = $this->auth->user();
        if ($user->admin) {
            return $next($request);
        }
        $groupId = $request->groupId ? $request->groupId : $request->groups;
        if ($groupId) {
            /** @var Group $group */
            $group = Group::find($groupId);
            if ($group->isOwner($user->id)) {
                return $next($request);
            }
        }

        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect('/home')->with('auth_message', 'Access Denied');
        }

    }

}

<?php namespace JamylBot\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use JamylBot\Group;

class MustBeAdmin {

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

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     */
    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 ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect('/home')->with('auth_message', 'Must be logged in.');
            }
        }
        /** @var \JamylBot\User $user */
        $user = $this->auth->user();
        if ($user->admin) {
            return $next($request);
        }
        $groupId = $request->group ? $request->group : $request->groups;
        if ($groupId) {
            /** @var Group $group */
            $group = Group::find($groupId);
            if ($group->isOwner($user->id)) {
                return $next($request);
            }
        }

        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect('/home')->with('auth_message', 'Access Denied');
        }

    }

}

Change admin middleware to reflect 5.3 changes

Generated resource route for groupController now calls the variable group, not groupId


<?php

namespace Coyote\Services\Media\Filters;

class Logo extends Thumbnail
{
    /**
     * @var int
     */
    protected $width = 600;

    /**
     * @var int
     */
    protected $height = 600;
}

<?php

namespace Coyote\Services\Media\Filters;

class Logo extends Thumbnail
{
    /**
     * @var int
     */
    protected $width = 140;

    /**
     * @var int
     */
    protected $height = 140;
}

Revert "zmiana rozmiaru loga firm"

Revert "zmiana rozmiaru loga firm"

This reverts commit 04e5107


<?php namespace duxet\Rethinkdb\Eloquent;

use Carbon\Carbon;
use duxet\Rethinkdb\Query\Builder as QueryBuilder;

class Model extends \Illuminate\Database\Eloquent\Model {

    /**
     * Get the format for database stored dates.
     *
     * @return string
     */
    protected function getDateFormat()
    {
        return 'Y-m-d H:i:s';
    }

    /**
     * Return a timestamp as DateTime object.
     *
     * @param  mixed  $value
     * @return \Carbon\Carbon
     */
    protected function asDateTime($value)
    {
        return Carbon::instance($value);
    }

    /**
     * Get a new query builder instance for the connection.
     *
     * @return Builder
     */
    protected function newBaseQueryBuilder()
    {
        $connection = $this->getConnection();
        // Check the connection type
        if ($connection instanceof \duxet\Rethinkdb\Connection)
        {
            return new QueryBuilder($connection);
        }
        return parent::newBaseQueryBuilder();
    }

    /**
     * Create a new Eloquent query builder for the model.
     *
     * @param  \duxet\Rethinkdb\Query\Builder $query
     * @return \duxet\Rethinkdb\Eloquent\Builder|static
     */
    public function newEloquentBuilder($query)
    {
        return new Builder($query);
    }

}

<?php namespace duxet\Rethinkdb\Eloquent;

use Carbon\Carbon;
use duxet\Rethinkdb\Query\Builder as QueryBuilder;

class Model extends \Illuminate\Database\Eloquent\Model {

    /**
     * Get the format for database stored dates.
     *
     * @return string
     */
    protected function getDateFormat()
    {
        return 'Y-m-d H:i:s';
    }

    /**
     * Return DateTime object as Carbon instance.
     *
     * @param  DateTime  $value
     * @return \Carbon\Carbon
     */
    protected function asDateTime($value)
    {
        return Carbon::instance($value);
    }

    /**
     * Get a new query builder instance for the connection.
     *
     * @return Builder
     */
    protected function newBaseQueryBuilder()
    {
        $connection = $this->getConnection();
        // Check the connection type
        if ($connection instanceof \duxet\Rethinkdb\Connection)
        {
            return new QueryBuilder($connection);
        }
        return parent::newBaseQueryBuilder();
    }

    /**
     * Create a new Eloquent query builder for the model.
     *
     * @param  \duxet\Rethinkdb\Query\Builder $query
     * @return \duxet\Rethinkdb\Eloquent\Builder|static
     */
    public function newEloquentBuilder($query)
    {
        return new Builder($query);
    }

}

Update phpdoc for last commit

Update phpdoc for last commit


<?php
/**
 * @package     Mautic
 * @copyright   2014 Mautic Contributors. All rights reserved.
 * @author      Mautic
 * @link        http://mautic.org
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */

namespace MauticAddon\MauticSocialBundle;

use Mautic\CoreBundle\Bundle\IntegrationBundleBase;

/**
 * Class MauticSocialBundle
 */
class MauticSocialBundle extends IntegrationBundleBase
{
}

<?php
/**
 * @package     Mautic
 * @copyright   2014 Mautic Contributors. All rights reserved.
 * @author      Mautic
 * @link        http://mautic.org
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */

namespace MauticAddon\MauticSocialBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * Class MauticSocialBundle
 *
 * @package Mautic\LeadBundle
 */
class MauticSocialBundle extends Bundle
{

}

Revert "Addon bundles should extend IntegrationBundleBase" - This breaks a lot of stuff if you don't have a full installation already, back to the drawing board...

This reverts commit b315f095f702cdef9fd342844323eaefd1eb8539.


<?php

namespace FluxBB\Markdown\Node;

use FluxBB\Markdown\Common\Collection;
use FluxBB\Markdown\Common\Text;

class CodeBlock extends Node implements NodeAcceptorInterface
{

    /**
     * @var Collection
     */
    protected $lines;

    /**
     * @var string
     */
    protected $language;

    public function __construct(Text $text, $language = '')
    {
        $this->lines = new Collection([$text]);
        $this->language = $language;
    }

    public function acceptBlankLine(BlankLine $blankLine)
    {
        $this->lines->add($blankLine->getContent()->replace('/^[ ]{0,4}/', ''));

        return $this;
    }

    public function acceptCodeBlock(CodeBlock $codeBlock)
    {
        $codeBlock->lines->each(function (Text $line) {
            $this->lines->add($line);
        });

        return $this;
    }

    public function getContent()
    {
        $content = new Text($this->lines->join("\n"));

        // Just in case we added blank lines at the end, we remove them, and finally add back the trailing newline.
        $content->replace('/(\n[ ]*)*$/', '')->append("\n");

        return $content;
    }

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

    public function hasLanguage()
    {
        return ! empty($this->language);
    }

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

    public function visit(NodeVisitorInterface $visitor)
    {
        $visitor->visitCodeBlock($this);
    }

}

<?php

namespace FluxBB\Markdown\Node;

use FluxBB\Markdown\Common\Text;

class CodeBlock extends Node implements NodeAcceptorInterface
{

    /**
     * @var Text
     */
    protected $content;

    /**
     * @var string
     */
    protected $language;

    public function __construct(Text $text, $language = '')
    {
        $this->content = $text;
        $this->language = $language;
    }

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

    public function hasLanguage()
    {
        return ! empty($this->language);
    }

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

    public function visit(NodeVisitorInterface $visitor)
    {
        $visitor->visitCodeBlock($this);
    }

}

Simplify code block content storage.

Simplify code block content storage.


<?php

namespace Huntie\JsonApi\Routing;

class Router extends \Illuminate\Routing\Router
{
    /**
     * Route a JSON API resource to a controller.
     *
     * @param string $name
     * @param string $controller
     * @param array  $options
     */
    public function jsonApiResource($name, $controller, array $options = [])
    {
        if ($this->container && $this->container->bound(ResourceRegistrar::class)) {
            $registrar = $this->container->make(ResourceRegistrar::class);
        } else {
            $registrar = new ResourceRegistrar($this);
        }

        $registrar->register($name, $controller, $options);
    }
}

<?php

namespace Huntie\JsonApi\Routing;

class Router extends \Illuminate\Routing\Router
{
    /**
     * Register an array of JSON API resource controllers.
     *
     * @param array $resources
     */
    public function jsonApiResources(array $resources)
    {
        foreach ($resources as $name => $controller) {
            $this->resource($name, $controller);
        }
    }

    /**
     * Route a JSON API resource to a controller.
     *
     * @param string $name
     * @param string $controller
     * @param array  $options
     */
    public function jsonApiResource($name, $controller, array $options = [])
    {
        if ($this->container && $this->container->bound(ResourceRegistrar::class)) {
            $registrar = $this->container->make(ResourceRegistrar::class);
        } else {
            $registrar = new ResourceRegistrar($this);
        }

        $registrar->register($name, $controller, $options);
    }
}

Add jsonApiResources method to add multiple resource route sets


<?php

namespace App;

use Illuminate\Foundation\Application as IlluminateApplication;
use InvalidArgumentException;

/**
 * Extends \Illuminate\Foundation\Application to override some defaults.
 */
class Application extends IlluminateApplication
{
    /**
     * Loads a revision'ed asset file, making use of gulp-rev
     * This is a copycat of L5's Elixir, but catered to our directory structure.
     *
     * @param string $file
     *
     * @return string
     */
    public function rev($file)
    {
        static $manifest = null;

        if (is_null($manifest)) {
            $manifest = json_decode(file_get_contents($this->publicPath().'/build/rev-manifest.json'), true);
        }

        if (isset($manifest[$file])) {
            return "/public/build/{$manifest[$file]}";
        }

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

<?php

namespace App;

use Illuminate\Foundation\Application as IlluminateApplication;
use InvalidArgumentException;

/**
 * Extends \Illuminate\Foundation\Application to override some defaults.
 */
class Application extends IlluminateApplication
{
    /**
     * We have merged public path and base path.
     *
     * @return string
     */
    public function publicPath()
    {
        return $this->basePath;
    }

    /**
     * Loads a revision'ed asset file, making use of gulp-rev
     * This is a copycat of L5's Elixir, but catered to our directory structure.
     *
     * @param string $file
     *
     * @return string
     */
    public function rev($file)
    {
        static $manifest = null;

        if (is_null($manifest)) {
            $manifest = json_decode(file_get_contents($this->publicPath().'/public/build/rev-manifest.json'), true);
        }

        if (isset($manifest[$file])) {
            return "/public/build/{$manifest[$file]}";
        }

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

Fix publicPath in to allow php artisan serve


<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/
Route::group(['middleware' => ['web']], function () {
	Route::auth();

	Route::get('/', function () {
	    return view('welcome');
	});

});

Route::group(['middleware' => ['web', 'auth']], function( ){
	Route::resource('list', 'ListController', [ 'only' => ['store', 'show', 'edit', 'index', 'create'] ]);
	Route::get('/{slug}', ['as' => 'showBySlug', 'uses' => 'ListController@showBySlug']);
	Route::get('/{username}/{slug}', ['as' => 'showByUserSlug', 'uses' => 'ListController@showByUserSlug']);
});

Route::group(['middleware' => ['api', 'auth']], function( ){
	Route::resource('task', 'TaskController', [ 'only' => ['store', 'update', 'destroy'] ] );
	Route::resource('list', 'ListController', [ 'only' => ['update', 'destroy'] ]);
});

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/
Route::group(['middleware' => ['web']], function () {
	Route::auth();

	Route::get('/', function () {
	    return view('welcome');
	});

});

Route::group(['middleware' => ['web', 'auth']], function( ){
	Route::resource('list', 'ListController', [ 'only' => ['store', 'show', 'edit', 'index', 'create'] ]);
	Route::get('/{slug}', ['as' => 'showBySlug', 'uses' => 'ListController@showBySlug']);
	Route::get('/{username}/{slug}', ['as' => 'showByUserSlug', 'uses' => 'ListController@showByUserSlug']);
});

Route::group(['middleware' => ['api', 'web'], 'prefix' => 'api'], function( ){
	Route::get('list/{encryptedListID}/tasks', ['as' => 'api/list/tasks', 'uses' => 'TaskController@getTasks']);
	Route::resource('task', 'TaskController', [ 'only' => ['store', 'update', 'destroy'] ] );
	Route::resource('list', 'ListController', [ 'only' => ['update', 'destroy'] ]);
});

Add API endpoint for getting tasks from a list


<?php

namespace Oro\Bundle\SearchBundle\Engine;

use Oro\Bundle\SearchBundle\Query\Query;
use Oro\Bundle\SearchBundle\Query\Result;

interface EngineV2Interface
{
    /**
     * Performs search in index according to passed query
     *
     * @param Query $query
     * @param array $context
     *
     * @return Result
     */
    public function search(Query $query, $context = []);
}

<?php

namespace Oro\Bundle\SearchBundle\Engine;

use Oro\Bundle\SearchBundle\Query\Query;
use Oro\Bundle\SearchBundle\Query\Result;

interface EngineV2Interface
{
    /**
     * Performs search in index according to passed query
     *
     * @param Query $query
     * @param array $context
     *
     * @return Result
     */
    public function search(Query $query, array $context = []);
}

BB-4074: Create a new Website Search system in the WebsiteSearchBundle
 - cs fixes
 - fix pr comments


<?php

namespace Phug\Formatter\Element;

use Phug\Formatter\AbstractValueElement;

class CodeElement extends AbstractValueElement
{
    public function isCodeBlock()
    {
        $tokens = $tokens = array_slice(
            token_get_all('<?php '.$this->getValue()),
            1
        );

        return is_array($tokens[0]) &&
            (
                end($tokens) === '}' ||
                $this->hasChildren()
            ) &&
            in_array($tokens[0][0], [
                T_CATCH,
                T_CLASS,
                T_DO,
                T_ELSE,
                T_ELSEIF,
                T_EXTENDS,
                T_FINALLY,
                T_FOR,
                T_FOREACH,
                T_FUNCTION,
                T_IF,
                T_IMPLEMENTS,
                T_INTERFACE,
                T_NAMESPACE,
                T_SWITCH,
                T_TRAIT,
                T_TRY,
                T_WHILE,
            ]);
    }
}

<?php

namespace Phug\Formatter\Element;

use Phug\Formatter\AbstractValueElement;

class CodeElement extends AbstractValueElement
{
    public function isCodeBlock()
    {
        $tokens = $tokens = array_slice(
            token_get_all('<?php '.$this->getValue()),
            1
        );

        return isset($tokens[0]) &&
            is_array($tokens[0]) &&
            (
                end($tokens) === '}' ||
                $this->hasChildren()
            ) &&
            in_array($tokens[0][0], [
                T_CATCH,
                T_CLASS,
                T_DO,
                T_ELSE,
                T_ELSEIF,
                T_EXTENDS,
                T_FINALLY,
                T_FOR,
                T_FOREACH,
                T_FUNCTION,
                T_IF,
                T_IMPLEMENTS,
                T_INTERFACE,
                T_NAMESPACE,
                T_SWITCH,
                T_TRAIT,
                T_TRY,
                T_WHILE,
            ]);
    }
}

Fix code block detection for empty block


<?php

namespace Nwidart\Modules\Providers;

use Illuminate\Support\ServiceProvider;

class BootstrapServiceProvider extends ServiceProvider
{
    /**
     * Booting the package.
     */
    public function boot()
    {
        $this->app['modules']->boot();
    }

    /**
     * Register the provider.
     */
    public function register()
    {
        $this->app['modules']->register();
    }
}

<?php

namespace Nwidart\Modules\Providers;

use Illuminate\Support\ServiceProvider;
use Nwidart\Modules\Contracts\RepositoryInterface;

class BootstrapServiceProvider extends ServiceProvider
{
    /**
     * Booting the package.
     */
    public function boot()
    {
        $this->app[RepositoryInterface::class]->boot();
    }

    /**
     * Register the provider.
     */
    public function register()
    {
        $this->app[RepositoryInterface::class]->register();
    }
}

Use the ::class notation to reference the module repository.


<div<?php echo isset( $class ) ? " class=\"$class\"" : '' . isset( $id ) ? " id=\"$id\"" : ''; ?>>
	<label<?php if ( isset( $label_title ) ) { ?> title="<?php echo $label_title; ?>"<?php } else { echo ( isset( $title ) ? " title=\"$title\"" : '' ); } ?> for="<?php echo $field; ?>"><?php echo $this->caption; ?>
	<input<?php if ( isset( $control_title ) ) { ?> title="<?php echo $control_title; ?>"<?php } else { echo ( isset( $title ) ? " title=\"$title\"" : '' ); } ?> type="text" id="<?php echo $field; ?>" name="<?php echo $field; ?>" value="<?php echo htmlspecialchars( $value ); ?>">
	<?php $control->errors_out( '
%s
', '
%s
' ); ?>

<div<?php echo isset( $class ) ? " class=\"$class\"" : ''; ?><? echo isset( $id ) ? " id=\"$id\"" : ''; ?>>
	<label<?php if ( isset( $label_title ) ) { ?> title="<?php echo $label_title; ?>"<?php } else { echo ( isset( $title ) ? " title=\"$title\"" : '' ); } ?> for="<?php echo $field; ?>"><?php echo $this->caption; ?>
	<input<?php if ( isset( $control_title ) ) { ?> title="<?php echo $control_title; ?>"<?php } else { echo ( isset( $title ) ? " title=\"$title\"" : '' ); } ?> type="text" id="<?php echo $field; ?>" name="<?php echo $field; ?>" value="<?php echo htmlspecialchars( $value ); ?>">
	<?php $control->errors_out( '
%s
', '
%s
' ); ?>

Make FormUI text fields output their classes properly. As the formcontrol class is always set, we can probably take out the test entirely, which would make the templates much more readable.

git-svn-id: d0e296eae3c99886147898d36662a67893ae90b2@3638 653ae4dd-d31e-0410-96ef-6bf7bf53c507


<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class BusinessFormRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        switch ($this->method()) {
            case 'PATCH':
            case 'PUT':
                return [
                      'name' => 'required|min:3',
                      'description' => 'required|min:10',
                      'timezone' => 'timezone',
                      'strategy' => 'required'
                    ];
                break;
            case 'POST':
                return [
                      'name' => 'required|min:3',
                      'slug' => 'required|min:3|unique:businesses',
                      'description' => 'required|min:10',
                      'timezone' => 'timezone',
                      'strategy' => 'required'
                    ];
                break;
            default:
                return [];
                break;
        }
    }
}

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class BusinessFormRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        switch ($this->method()) {
            case 'PATCH':
            case 'PUT':
                return [
                      'name' => 'required|min:4',
                      'description' => 'required|min:10',
                      'timezone' => 'timezone',
                      'strategy' => 'required'
                    ];
                break;
            case 'POST':
                return [
                      'name' => 'required|min:4',
                      'slug' => 'required|min:4|unique:businesses',
                      'description' => 'required|min:10',
                      'timezone' => 'timezone',
                      'strategy' => 'required'
                    ];
                break;
            default:
                return [];
                break;
        }
    }
}

Update the minimum name and slug length for Businesses (3->4)


<?php

namespace Sebastienheyd\Boilerplate\Controllers\Logs;

use Arcanedev\LogViewer\Contracts\LogViewer as LogViewerContract;
use Arcanedev\LogViewer\Http\Controllers\LogViewerController as ArcanedevController;

class LogViewerController extends ArcanedevController
{
    /**
     * LogViewerController constructor.
     *
     * @param LogViewerContract $logViewer
     */
    public function __construct(LogViewerContract $logViewer)
    {
        $this->middleware('ability:admin,logs');
        parent::__construct($logViewer);
    }

    protected $showRoute = 'boilerplate.logs.show';

    /**
     * @param string $view
     * @param array  $data
     * @param array  $mergeData
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    protected function view($view, $data = [], $mergeData = [])
    {
        return view('boilerplate::logs.'.$view, $data, $mergeData);
    }
}

<?php

namespace Sebastienheyd\Boilerplate\Controllers\Logs;

use Arcanedev\LogViewer\Contracts\LogViewer as LogViewerContract;
use Arcanedev\LogViewer\Http\Controllers\LogViewerController as ArcanedevController;

class LogViewerController extends ArcanedevController
{
    /**
     * LogViewerController constructor.
     *
     * @param LogViewerContract $logViewer
     */
    public function __construct(LogViewerContract $logViewer)
    {
        $this->middleware('ability:admin,logs');

        if (!config('boilerplate.app.logs')) {
            abort('404');
        }

        parent::__construct($logViewer);
    }

    protected $showRoute = 'boilerplate.logs.show';

    /**
     * @param string $view
     * @param array  $data
     * @param array  $mergeData
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    protected function view($view, $data = [], $mergeData = [])
    {
        return view('boilerplate::logs.'.$view, $data, $mergeData);
    }
}

Abort logs screens when logs are disabled


<?php
class uixul_InitializeAction extends f_action_BaseAction
{
    /**
	 * @param Context $context
	 * @param Request $request
	 */
    public function _execute($context, $request)
    {
    	f_persistentdocument_PersistentProvider::getInstance()->clearFrameworkCache();
    	f_SimpleCache::clear();

        f_util_FileUtils::clearDir(f_util_FileUtils::buildCachePath('template'));
        f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('binding'));
        f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('css'));
        f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('js'));
        f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('htmlpreview'));

        return $this->getSuccessView();
    }
}

<?php
class uixul_InitializeAction extends f_action_BaseAction
{
    /**
	 * @param Context $context
	 * @param Request $request
	 */
    public function _execute($context, $request)
    {
    	f_persistentdocument_PersistentProvider::getInstance()->clearFrameworkCache();
    	//f_SimpleCache::clear();
    	f_DataCacheService::getInstance()->clearAll();

        f_util_FileUtils::clearDir(f_util_FileUtils::buildCachePath('template'));
        f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('binding'));
        f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('css'));
        f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('js'));
        f_util_FileUtils::clearDir(f_util_FileUtils::buildWebCachePath('htmlpreview'));

        return $this->getSuccessView();
    }
}

Replace f_SimpleCache usage by f_DataCacheService


<?php
/**
 * Publishes separate static error pages for each site.
 *
 * @package silverstripe-multisites
 */
class MultisitesErrorPageExtension extends SiteTreeExtension {

	public function alternateFilepathForErrorcode($code, $locale) {
		$path  = ErrorPage::get_static_filepath();
		$parts = array();

		if($site = Multisites::inst()->getActiveSite()) {
			$parts[] = $site->Host;
		}

		$parts[] = $code;

		if($locale && $this->owner->hasExtension('Translatable') && $locale != Translatable::default_locale()) {
			$parts[] = $locale;
		}

		return sprintf("%s/error-%s.html", $path, implode('-', $parts));
	}

}

<?php
/**
 * Publishes separate static error pages for each site.
 *
 * @package silverstripe-multisites
 */
class MultisitesErrorPageExtension extends SiteTreeExtension {

	public function alternateFilepathForErrorcode($code, $locale) {
		$path  = ErrorPage::get_static_filepath();
		$parts = array();

		if($site = Multisites::inst()->getActiveSite()) {
			$parts[] = $site->Host;
		}

		$parts[] = $code;

		if($locale && $this->owner->hasExtension('Translatable') && $locale != Translatable::default_locale()) {
			$parts[] = $locale;
		}

		return sprintf("%s/error-%s.html", $path, implode('-', $parts));
	}

	public function augmentSQL(\SQLQuery &$query) {
		if (Multisites::inst()->getCurrentSiteId()) {
			$query->addWhere('"SiteID" = ' . Multisites::inst()->getCurrentSiteId());
		}
	}
}

FIX Augment sql lookup of error page because it's referenced DataObject::get_one('ErrorPage') which makes it impossible to hook which site to load from