<?php

namespace Kerox\Messenger\Model;

use Kerox\Messenger\Helper\ValidatorTrait;

class ThreadControl implements \JsonSerializable
{
    use ValidatorTrait;

    /**
     * @var int
     */
    protected $recipientId;

    /**
     * @var null|int
     */
    protected $targetAppId;

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

    /**
     * PassThreadControl constructor.
     *
     * @param int      $recipientId
     * @param int|null $targetAppId
     */
    public function __construct(int $recipientId, int $targetAppId = null)
    {
        $this->recipientId = $recipientId;
        $this->targetAppId = $targetAppId;
    }

    /**
     * @param string $metadata
     */
    public function setMetadata(string $metadata): void
    {
        $this->isValidString($metadata, 1000);

        $this->metadata = $metadata;
    }

    /**
     * @return array
     */
    public function jsonSerialize(): array
    {
        $json = [
            'recipient'     => [
                'id' => $this->recipientId
            ],
            'target_app_id' => $this->targetAppId,
            'metadata'      => $this->metadata,
        ];

        return array_filter($json);
    }
}

<?php

namespace Kerox\Messenger\Model;

use Kerox\Messenger\Helper\ValidatorTrait;

class ThreadControl implements \JsonSerializable
{
    use ValidatorTrait;

    /**
     * @var int
     */
    protected $recipientId;

    /**
     * @var null|int
     */
    protected $targetAppId;

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

    /**
     * PassThreadControl constructor.
     *
     * @param int      $recipientId
     * @param int|null $targetAppId
     */
    public function __construct(int $recipientId, int $targetAppId = null)
    {
        $this->recipientId = $recipientId;
        $this->targetAppId = $targetAppId;
    }

    /**
     * @param string $metadata
     */
    public function setMetadata(string $metadata)
    {
        $this->isValidString($metadata, 1000);

        $this->metadata = $metadata;
    }

    /**
     * @return array
     */
    public function jsonSerialize(): array
    {
        $json = [
            'recipient'     => [
                'id' => $this->recipientId
            ],
            'target_app_id' => $this->targetAppId,
            'metadata'      => $this->metadata,
        ];

        return array_filter($json);
    }
}

[n/a] Fix type hinting return for setMetadata method


<?php

namespace Laravel\Socialite\One;

use InvalidArgumentException;

class TwitterProvider extends AbstractProvider
{
    /**
     * {@inheritdoc}
     */
    public function user()
    {
        if (! $this->hasNecessaryVerifier()) {
            throw new InvalidArgumentException('Invalid request. Missing OAuth verifier.');
        }

        $user = $this->server->getUserDetails($token = $this->getToken());

        $instance = (new User)->setRaw(array_merge($user->extra, $user->urls))
                ->setToken($token->getIdentifier(), $token->getSecret());

        return $instance->map([
            'id' => $user->uid, 'nickname' => $user->nickname,
            'name' => $user->name, 'email' => $user->email, 'avatar' => $user->imageUrl,
            'avatar_original' => str_replace('_normal', '', $user->imageUrl),
        ]);
    }
}

<?php

namespace Laravel\Socialite\One;

use InvalidArgumentException;

class TwitterProvider extends AbstractProvider
{
    /**
     * {@inheritdoc}
     */
    public function user()
    {
        if (! $this->hasNecessaryVerifier()) {
            throw new InvalidArgumentException('Invalid request. Missing OAuth verifier.');
        }

        $user = $this->server->getUserDetails($token = $this->getToken());

        $extraDetails = [
            'location' => $user->location,
            'description' => $user->description,
        ];

        $instance = (new User)->setRaw(array_merge($user->extra, $user->urls, $extraDetails))
                ->setToken($token->getIdentifier(), $token->getSecret());

        return $instance->map([
            'id' => $user->uid, 'nickname' => $user->nickname,
            'name' => $user->name, 'email' => $user->email, 'avatar' => $user->imageUrl,
            'avatar_original' => str_replace('_normal', '', $user->imageUrl),
        ]);
    }
}

Add twitter location and description fields


#! /usr/bin/env php
<?
include('../config.php');
include(mnminclude.'webimages.php');

$sql = "select link_id from links where link_status='queued' and link_thumb_status = 'unknown' and link_date > date_sub(now(), interval 8 hour) and link_date < date_sub(now(), interval 1 minute) and link_votes > 1 and link_votes > link_negatives * 10 order by link_date desc limit 10";

$res = $db->get_col($sql);
foreach ($res as $l) {
	$link = new Link();
	$link->id = $l;
	$link->read();
	echo $link->get_permalink().": ";
	if (($thumb = $link->get_thumb())) {
		echo $thumb;
	} else {
		echo "NO thumb";
	}
	echo "\n";
	ob_flush(); flush();
}

?>

#! /usr/bin/env php
<?php
include(dirname(__FILE__).'/../config.php');
include(mnminclude.'webimages.php');

$sql = "select link_id from links where link_status='queued' and link_thumb_status = 'unknown' and link_date > date_sub(now(), interval 8 hour) and link_date < date_sub(now(), interval 1 minute) and link_votes > 1 and link_votes > link_negatives * 10 order by link_date desc limit 10";

$res = $db->get_col($sql);
foreach ($res as $l) {
	$link = Link::from_db($l, null, false);
	echo $link->get_permalink().": ";
	if (($thumb = $link->get_thumb())) {
		echo $thumb;
	} else {
		echo "NO thumb";
	}
	echo "\n";
	ob_flush(); flush();
}

?>

Allow to run from any directory.
Use from_db

git-svn-id: bc46a84f389827447d29da2b7e0abe424efe24cf@4441 cbe1a1ec-7179-4919-8e32-4551e8279a00


<?php

namespace Beanie\Exception;

use Beanie\Command;
use Beanie\Exception;
use Beanie\Server\Server;

class DeadlineSoonException extends Exception
{
    const DEFAULT_CODE = 408;
    const DEFAULT_MESSAGE = 'There is a deadline for a running job approaching soon on \'%s\'. \'%s\' failed.';

    public function __construct(Command $command, Server $server)
    {
        parent::__construct(
            sprintf(self::DEFAULT_MESSAGE, (string) $server, get_class($command)),
            self::DEFAULT_CODE
        );
    }
}

<?php

namespace Beanie\Exception;

use Beanie\Command;
use Beanie\Exception;

class DeadlineSoonException extends AbstractServerCommandException
{
    const DEFAULT_CODE = 408;
    const DEFAULT_MESSAGE = 'There is a deadline for a running job approaching soon on \'%2$s\'. \'%1$s\' failed.';
}

Use positional params for sprintf

Use positional params for sprintf


<?php
namespace PharIo\Phive {

    abstract class XmlRepository {

        /**
         * @var string
         */
        private $filename = '';

        /**
         * @var \DOMDocument
         */
        private $dom;

        /**
         * @var \DOMXPath
         */
        private $xPath;

        /**
         * @param File $filename
         */
        public function __construct(Filename $filename) {
            $this->filename = $filename;
            $this->init();
        }

        /**
         * @return \DOMDocument
         */
        protected function getDom() {
            return $this->dom;
        }

        /**
         * @return string
         */
        protected function getFilename() {
            return $this->filename;
        }

        /**
         * @return \DOMXPath
         */
        protected function getXPath() {
            return $this->xPath;
        }

        /**
         * @return string
         */
        abstract protected function getRootElementName();

        /**
         * @return string
         */
        abstract protected function getNamespace();

        /**
         *
         */
        private function init() {
            $this->dom = new \DOMDocument('1.0', 'UTF-8');
            $this->dom->preserveWhiteSpace = false;
            $this->dom->formatOutput = true;
            if ($this->filename->exists()) {
                $this->dom->load($this->filename->asString());
            } else {
                $this->dom->appendChild($this->dom->createElement($this->getRootElementName()));
            }
            $this->xPath = new \DOMXPath($this->dom);
            $this->xPath->registerNamespace('phive', $this->getNamespace());
        }

    }

}

<?php
namespace PharIo\Phive {

    abstract class XmlRepository {

        /**
         * @var string
         */
        private $filename = '';

        /**
         * @var \DOMDocument
         */
        private $dom;

        /**
         * @var \DOMXPath
         */
        private $xPath;

        /**
         * @param File $filename
         */
        public function __construct(Filename $filename) {
            $this->filename = $filename;
            $this->init();
        }

        /**
         * @return \DOMDocument
         */
        protected function getDom() {
            return $this->dom;
        }

        /**
         * @return string
         */
        protected function getFilename() {
            return $this->filename;
        }

        /**
         * @return \DOMXPath
         */
        protected function getXPath() {
            return $this->xPath;
        }

        /**
         * @return string
         */
        abstract protected function getRootElementName();

        /**
         * @return string
         */
        abstract protected function getNamespace();

        /**
         *
         */
        private function init() {
            $this->dom = new \DOMDocument('1.0', 'UTF-8');
            $this->dom->preserveWhiteSpace = false;
            $this->dom->formatOutput = true;
            if ($this->filename->exists()) {
                $this->dom->load($this->filename->asString());
            } else {
                $this->dom->appendChild($this->dom->createElementNS($this->getNamespace(), $this->getRootElementName()));
            }
            $this->xPath = new \DOMXPath($this->dom);
            $this->xPath->registerNamespace('phive', $this->getNamespace());
        }

    }

}

Make fallback XML root element be in correct namespace


<?
$fn= "order.txt";
if (preg_match('/^([-A-Za-z0-9_])+\\.([A-Za-z0-9]+)$/', $_REQUEST['fn'])) {
  $fn= $_REQUEST['fn'];
}
header('Content-Type: application/tsv');
header('Content-Disposition: attachment; filename="' . $fn . '"');
$file = urldecode($_REQUEST['file']);
echo $file;

<?
$fn= "order.csv";
if (preg_match('/^([-A-Za-z0-9_])+\\.([A-Za-z0-9]+)$/', $_REQUEST['fn'])) {
  $fn= $_REQUEST['fn'];
}
header('Content-Type: application/tsv');
header('Content-Disposition: attachment; filename="' . $fn . '"');
$file = urldecode($_REQUEST['file']);
echo $file;

Change default name to .csv instead of .txt


<?php

declare(strict_types=1);

namespace Budgegeria\Bundle\IntlFormatBundle\Twig;

use Budgegeria\IntlFormat\IntlFormat;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

class IntlFormatterExtension extends AbstractExtension
{
    /**
     * @var IntlFormat
     */
    private $intlFormat;

    public function __construct(IntlFormat $intlFormat)
    {
        $this->intlFormat = $intlFormat;
    }

    public function getFilters()
    {
        return [
            new TwigFilter('intl_format', [$this, 'format']),
        ];
    }

    public function getFunctions()
    {
        return [
            new TwigFunction('intl_format', [$this, 'format']),
        ];
    }

    public function format(string $message, ...$values) : string
    {
        return $this->intlFormat->format($message, ...$values);
    }
}

<?php

declare(strict_types=1);

namespace Budgegeria\Bundle\IntlFormatBundle\Twig;

use Budgegeria\IntlFormat\IntlFormatInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

class IntlFormatterExtension extends AbstractExtension
{
    /**
     * @var IntlFormatInterface
     */
    private $intlFormat;

    public function __construct(IntlFormatInterface $intlFormat)
    {
        $this->intlFormat = $intlFormat;
    }

    public function getFilters()
    {
        return [
            new TwigFilter('intl_format', [$this, 'format']),
        ];
    }

    public function getFunctions()
    {
        return [
            new TwigFunction('intl_format', [$this, 'format']),
        ];
    }

    public function format(string $message, ...$values) : string
    {
        return $this->intlFormat->format($message, ...$values);
    }
}

Change constructor argument to use interface


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Core\Shipping\Checker\Rule;

use Sylius\Component\Core\Model\ShipmentInterface;
use Sylius\Component\Shipping\Checker\Rule\RuleCheckerInterface;
use Sylius\Component\Shipping\Model\ShippingSubjectInterface;

abstract class OrderTotalRuleChecker implements RuleCheckerInterface
{
    public function isEligible(ShippingSubjectInterface $subject, array $configuration): bool
    {
        if (!$subject instanceof ShipmentInterface) {
            return false;
        }

        $order = $subject->getOrder();
        if (null === $order) {
            return false;
        }

        $channel = $order->getChannel();
        if (null === $channel) {
            return false;
        }

        $amount = $configuration['total'][$channel->getCode()]['amount'] ?? null;
        if (null === $amount) {
            return false;
        }

        return $this->compare($order->getTotal(), $amount);
    }

    abstract protected function compare(int $total, int $threshold): bool;
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Core\Shipping\Checker\Rule;

use Sylius\Component\Core\Model\ShipmentInterface;
use Sylius\Component\Shipping\Checker\Rule\RuleCheckerInterface;
use Sylius\Component\Shipping\Model\ShippingSubjectInterface;

abstract class OrderTotalRuleChecker implements RuleCheckerInterface
{
    public function isEligible(ShippingSubjectInterface $subject, array $configuration): bool
    {
        if (!$subject instanceof ShipmentInterface) {
            return false;
        }

        $order = $subject->getOrder();
        if (null === $order) {
            return false;
        }

        $channel = $order->getChannel();
        if (null === $channel) {
            return false;
        }

        $amount = $configuration[$channel->getCode()]['amount'] ?? null;
        if (null === $amount) {
            return false;
        }

        return $this->compare($order->getTotal(), $amount);
    }

    abstract protected function compare(int $total, int $threshold): bool;
}

Fix order total shipping rules

Fix order total shipping rules


<?php
return [
    'request' => [
        'class' => \blink\http\Request::class,
        'middleware' => [],
    ],
    'response' => [
        'class' => \blink\http\Response::class,
        'middleware' => [
            \rethink\hrouter\restapi\middleware\ResponseFormatter::class,
        ],
    ],
    'session' => [
        'class' => 'blink\session\Manager',
        'expires' => 3600 * 24 * 15,
        'storage' => [
            'class' => 'blink\session\FileStorage',
            'path' => __DIR__ . '/../../runtime/sessions'
        ]
    ],
    'auth' => [
        'class' => 'blink\auth\Auth',
        'model' => 'app\models\User',
    ],
    'haproxy' => [
        'class' => \rethink\hrouter\Haproxy::class,
    ],
    'log' => [
        'class' => 'blink\log\Logger',
        'targets' => [
            'file' => [
                'class' => 'blink\log\StreamTarget',
                'enabled' => true,
                'stream' => 'php://stderr',
                'level' => 'info',
            ]
        ],
    ],
];

<?php
return [
    'request' => [
        'class' => \blink\http\Request::class,
        'middleware' => [],
    ],
    'response' => [
        'class' => \blink\http\Response::class,
        'middleware' => [
            \rethink\hrouter\restapi\middleware\ResponseFormatter::class,
        ],
    ],
    'session' => [
        'class' => 'blink\session\Manager',
        'expires' => 3600 * 24 * 15,
        'storage' => [
            'class' => 'blink\session\FileStorage',
            'path' => __DIR__ . '/../../runtime/sessions'
        ]
    ],
    'auth' => [
        'class' => 'blink\auth\Auth',
        'model' => 'app\models\User',
    ],
    'haproxy' => [
        'class' => \rethink\hrouter\Haproxy::class,
    ],
    'log' => [
        'class' => 'blink\log\Logger',
        'targets' => [
            'file' => [
                'class' => 'blink\log\StreamTarget',
                'enabled' => BLINK_ENV != 'test',
                'stream' => 'php://stderr',
                'level' => 'info',
            ]
        ],
    ],
];

Disable log component on test environment


<?php

/**
 * Define Constants.
 */
define('ADMIN_DIR', get_template_directory() .'/admin');
define('ADMIN_URL', get_template_directory_uri() .'/admin');

define('AUTHOR', 'Vincent Klaiber');
define('AUTHOR_URL', 'http://vinkla.com');

define('LOGIN_IMAGE_PATH', ADMIN_URL.'/images/admin-login-logo.png');
define('LOGIN_HEADER_URL', 'http://vinkla.com');

/**
 * Load Admin Components.
 */
require_once(ADMIN_DIR .'/admin-remove.php');
require_once(ADMIN_DIR .'/admin-functions.php');

<?php

/**
 * Define Constants.
 */
define('TEMPLATE_DIR', get_template_directory());
define('ADMIN_DIR', get_template_directory().'/admin');
define('ADMIN_URL', get_template_directory_uri().'/admin');

define('AUTHOR', 'Vincent Klaiber');
define('AUTHOR_URL', 'http://vinkla.com');

define('LOGIN_IMAGE_PATH', TEMPLATE_DIR.'/images/admin-login-logo.png');
define('LOGIN_HEADER_URL', 'http://vinkla.com');

/**
 * Load Admin Components.
 */
require_once(ADMIN_DIR .'/admin-remove.php');
require_once(ADMIN_DIR .'/admin-functions.php');

Add a template directory constant.

Add a template directory constant.


<?php
namespace Phpws\Core;

class WebSocketUser implements \Phpws\Interfaces\WebsocketUser {

  public $socket;
  public $id;
  public $watcher;
  public $headers = NULL;
  public $handshaked = false;

  public $handlingPartialPacket = false;
  public $readBuffer = "";
  public $writeNeeded = false;
  public $writeBuffer = "";

  public $partialMessage = "";

  public $hasSentClose = false;

  function __construct($id, $socket) {
    $this->id = $id;
    $this->socket = $socket;
  }
}

<?php
namespace Phpws\Core;

class WebSocketUser implements \Phpws\Interfaces\WebsocketUser {

  public $socket;
  public $id;
  public $watcher;
  public $headers = NULL;
  public $handshaked = false;

  public $handlingPartialPacket = false;
  public $readBuffer = "";
  public $writeNeeded = false;
  public $writeBuffer = "";

  public $partialMessage = "";

  public $hasSentClose = false;

  function __construct($id, $socket) {
    $this->id = $id;
    $this->socket = $socket;
  }

  public function getTlsStatus()
  {
    return false;
  }

  public function getNetHandle()
  {
    return $id;
  }
}

Implement the promises of the user interface...


<?php

namespace App;

use Matthias\SymfonyConsoleForm\Bundle\SymfonyConsoleFormBundle;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Kernel as SymfonyKernel;

class Kernel extends SymfonyKernel
{
    /** @var string */
    private $vendorDirectory;

    public function __construct(string $environment, string $debug, string $vendorDirectory)
    {
        parent::__construct($environment, $debug);
        $this->vendorDirectory = $vendorDirectory;
    }

    public function registerBundles(): array
    {
        return [
            new FrameworkBundle(),
            new TwigBundle(),
            new SymfonyConsoleFormBundle(),
        ];
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__ . '/config.yml');
    }

    public function getCacheDir(): string
    {
        return __DIR__ . '/cache';
    }

    public function getLogDir(): string
    {
        return __DIR__ . '/logs';
    }

    protected function buildContainer(): ContainerInterface
    {
        $container = parent::buildContainer();

        $container->setParameter('vendor_directory', $this->vendorDirectory);

        return $container;
    }
}

<?php

namespace App;

use Matthias\SymfonyConsoleForm\Bundle\SymfonyConsoleFormBundle;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Kernel as SymfonyKernel;

class Kernel extends SymfonyKernel
{
    /** @var string */
    private $vendorDirectory;

    public function __construct(string $environment, bool $debug, string $vendorDirectory)
    {
        parent::__construct($environment, $debug);
        $this->vendorDirectory = $vendorDirectory;
    }

    public function registerBundles(): array
    {
        return [
            new FrameworkBundle(),
            new TwigBundle(),
            new SymfonyConsoleFormBundle(),
        ];
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__ . '/config.yml');
    }

    public function getCacheDir(): string
    {
        return __DIR__ . '/cache';
    }

    public function getLogDir(): string
    {
        return __DIR__ . '/logs';
    }

    protected function buildContainer(): ContainerInterface
    {
        $container = parent::buildContainer();

        $container->setParameter('vendor_directory', $this->vendorDirectory);

        return $container;
    }
}

Fix wrong type for debug

Fix wrong type for debug


<?php
/**
 * @file
 * Contains Drupal\AppConsole\Command\Helper\ChainCommandHelper.
 */

namespace Drupal\AppConsole\Command\Helper;

use Symfony\Component\Console\Helper\Helper;

class ChainCommandHelper extends Helper
{

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

    /**
     * @param $name      string
     * @param $arguments array
     */
    public function addCommand($name, $arguments)
    {
        array_unshift($arguments, ['command' => $name]);
        $this->commands[] = ['name' => $name, 'arguments' => $arguments];
    }

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

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

<?php
/**
 * @file
 * Contains Drupal\AppConsole\Command\Helper\ChainCommandHelper.
 */

namespace Drupal\AppConsole\Command\Helper;

use Symfony\Component\Console\Helper\Helper;

class ChainCommandHelper extends Helper
{

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

    /**
     * @param $name      string
     * @param $inputs array
     */
    public function addCommand($name, $inputs = [])
    {
        array_unshift($inputs, ['command' => $name]);
        $this->commands[] = ['name' => $name, 'inputs' => $inputs];
    }

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

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

Rename paramater arguments as inputs

Rename paramater arguments as inputs


<?php

namespace Opifer\CmsBundle\Controller;

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

/**
 * Template Controller
 */
class TemplateController extends Controller
{
    /**
     * Remove a template
     *
     * @param int $id
     *
     * @return Response
     */
    public function deleteAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $template = $this->get('opifer.eav.template_manager')->getRepository()->find($id);
        $slug = 'templates';

        if (!$template) {
            return $this->createNotFoundException();
        }

        $relatedContent = $em->getRepository('OpiferCmsBundle:Content')
            ->createValuedQueryBuilder('c')
            ->select('COUNT(c)')
            ->where('t.id = :template')
            ->setParameter('template', $id)
            ->getQuery()
            ->getSingleScalarResult();

        if ($relatedContent > 0) {
            $this->addFlash('error', 'template.delete.warning');

            return $this->redirectToRoute('opifer.crud.index', [
                'slug' => $slug
            ]);
        }

        return $this->forward('OpiferCrudBundle:Crud:delete',[
            'entity' => $template,
            'slug' => $slug,
            'id' => $id
        ]);
    }
}

<?php

namespace Opifer\CmsBundle\Controller;

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

/**
 * Template Controller
 */
class TemplateController extends Controller
{
    /**
     * Remove a template
     *
     * @param int $id
     *
     * @return Response
     */
    public function deleteAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $template = $this->get('opifer.eav.template_manager')->getRepository()->find($id);
        $slug = 'templates';

        if (!$template) {
            return $this->createNotFoundException();
        }

        $relatedContent = $em->getRepository('OpiferCmsBundle:Content')
            ->createValuedQueryBuilder('c')
            ->innerJoin('vs.template', 't')
            ->select('COUNT(c)')
            ->where('t.id = :template')
            ->setParameter('template', $id)
            ->getQuery()
            ->getSingleScalarResult();

        if ($relatedContent > 0) {
            $this->addFlash('error', 'template.delete.warning');

            return $this->redirectToRoute('opifer.crud.index', [
                'slug' => $slug
            ]);
        }

        return $this->forward('OpiferCrudBundle:Crud:delete',[
            'entity' => $template,
            'slug' => $slug,
            'id' => $id
        ]);
    }
}

Join template on related content query

Join template on related content query


<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Contracts\Auth\Guard;

use Facebook\FacebookSession;
use Illuminate\Support\Facades\Session;

// add other classes you plan to use, e.g.:
// use Facebook\FacebookRequest;
// use Facebook\GraphUser;
// use Facebook\FacebookRequestException;

/**
 * Class FacebookController
 *
 * @package App\Http\Controllers\Auth
 */
class FacebookController extends Controller
{
    public function token(Guard $auth)
    {
        try {
            $accessToken = $auth->facebookAuth(Input::get('code'));

            return response()->json([
                'user' => [
                    'name' => Auth::user()->name,
                    'id' => Auth::user()->facebookId
                ],
                'token_type' => 'bearer',
                'access_token' => $accessToken
            ]);

        } catch(\Exception $e) {
            Log::error(
                "Exception occured, code: " . $e->getCode()
                . " with message: " . $e->getMessage()
            );
        }

        return response('Bad request.', 400);
    }
}

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Contracts\Auth\Guard;

use Facebook\FacebookSession;
use Illuminate\Support\Facades\Session;

// add other classes you plan to use, e.g.:
// use Facebook\FacebookRequest;
// use Facebook\GraphUser;
// use Facebook\FacebookRequestException;

/**
 * Class FacebookController
 *
 * @package App\Http\Controllers\Auth
 */
class FacebookController extends Controller
{
    public function token(Guard $auth)
    {
        try {
            $accessToken = $auth->facebookAuth(Input::get('code'));

            return response()->json([
                'user' => [
                    'name' => Auth::user()->name,
                    'facebookId' => Auth::user()->facebookId,
                    'id' => Auth::user()->id
                ],
                'token_type' => 'bearer',
                'access_token' => $accessToken
            ]);

        } catch(\Exception $e) {
            Log::error(
                "Exception occured, code: " . $e->getCode()
                . " with message: " . $e->getMessage()
            );
        }

        return response('Bad request.', 400);
    }
}

Add ID of authorized user on facebook auth request


<?php

class BannerImage extends DataObject{

	private static $db = array(
		'Title' => 'Varchar(255)',
		'SubTitle' => 'Varchar(255)',
		'Link' => 'LinkField',
		'Sort' => 'Int'
	);

	private static $has_one = array(
		'Image' => 'Image',
		'Parent' => 'Page'
	);

	private static $summary_fields = array(
		'Image.CMSThumbnail' => 'Image',
		'CMSTitle' => 'Title',
		'Link' => 'Link'
	);

	private static $default_sort = "\"Sort\" ASC, \"ID\" ASC";

	public function getCMSFields(){
		$fields = parent::getCMSFields();
		$image = $fields->fieldByName('Root.Main.Image');
		$fields->removeByName('Image');
		$fields->insertBefore($image,'Title');
		$fields->removeByName('ParentID');
		$fields->removeByName('Sort');
		return $fields;
	}

	function getCMSTitle(){
		if($this->Title){
			return $this->Title;
		}
		if($this->Image()){
			return $this->Image()->Title;
		}
	}

}

<?php

class BannerImage extends DataObject{

	private static $db = array(
		'Title' => 'Varchar(255)',
		'SubTitle' => 'Varchar(255)',
		'Link' => 'LinkField',
		'Sort' => 'Int'
	);

	private static $has_one = array(
		'Image' => 'Image',
		'Parent' => 'Page'
	);

	private static $summary_fields = array(
		'Image.CMSThumbnail' => 'Image',
		'CMSTitle' => 'Title',
		'Link' => 'Link'
	);

	private static $default_sort = "\"Sort\" ASC, \"ID\" ASC";

	public function getCMSFields(){
		$fields = parent::getCMSFields();
		$image = $fields->fieldByName('Root.Main.Image');
		$fields->removeByName('Image');
		$fields->insertBefore($image,'Title');
		$fields->removeByName('ParentID');
		$fields->removeByName('Sort');
		return $fields;
	}

	function getCMSTitle(){
		if($this->Title){
			return $this->Title;
		}
		if($this->Image()){
			return $this->Image()->Title;
		}
	}

	public function canCreate($member = null) {
		return Permission::check("CMS_ACCESS_CMSMain");
	}

	public function canEdit($member = null) {
		return Permission::check("CMS_ACCESS_CMSMain");
	}

	public function canDelete($member = null) {
		return Permission::check("CMS_ACCESS_CMSMain");
	}

	public function canView($member = null) {
		return Permission::check("CMS_ACCESS_CMSMain");
	}

}

Allow content editors to edit banners.

Allow content editors to edit banners.


<?php

namespace Markup\OEmbedBundle\Client;

use Markup\OEmbedBundle\Provider\ProviderInterface;

/**
* A superclass for client implementations.
*/
abstract class AbstractClient implements ClientInterface
{
    /**
     * Resolves the media ID and an oEmbed provider to a URL.
     *
     * @param  ProviderInterface $provider
     * @param  string            $mediaId
     * @param  array             $parameters
     * @return string
     **/
    protected function resolveOEmbedUrl(ProviderInterface $provider, $mediaId, array $parameters = array())
    {
        $mediaUrl = str_replace('$ID$', $mediaId, $provider->getUrlScheme());
        $queryStringSuffix = (!empty($parameters)) ? '?' . http_build_query($parameters) : '';

        return sprintf('%s?url=%s%s', $provider->getApiEndpoint(), $mediaUrl, rawurlencode($queryStringSuffix));
    }
}

<?php

namespace Markup\OEmbedBundle\Client;

use Markup\OEmbedBundle\Provider\ProviderInterface;

/**
* A superclass for client implementations.
*/
abstract class AbstractClient implements ClientInterface
{
    /**
     * Resolves the media ID and an oEmbed provider to a URL.
     *
     * @param  ProviderInterface $provider
     * @param  string            $mediaId
     * @param  array             $parameters
     * @return string
     **/
    protected function resolveOEmbedUrl(ProviderInterface $provider, $mediaId, array $parameters = array())
    {
        $mediaUrl = str_replace('$ID$', $mediaId, $provider->getUrlScheme());

        $mediaUrlHasQueryString = (bool) parse_url($mediaUrl, PHP_URL_QUERY);
        $queryStingPrefix = ($mediaUrlHasQueryString) ? '&' : '?';

        $queryStringSuffix = (!empty($parameters)) ? $queryStingPrefix . http_build_query($parameters) : '';
        return sprintf(
            '%s?url=%s%s',
            $provider->getApiEndpoint(),
            $mediaUrl,
            rawurlencode($queryStringSuffix)
        );
    }
}

Fix url resolution with regards to querysting parameters.


<?php

/**
 *
 * @package    symfony
 * @subpackage plugin
 * @author     Vincent CHALAMON <vincentchalamon@gmail.com>
 * @version    SVN: $Id: actions.class.php 23319 2009-10-25 12:22:23Z Kris.Wallsmith $
 */
class BasesfAdminDashboardActions extends sfActions
{
  public function executeDashboard(sfWebRequest $request)
  {
    try
    {
      $this->ga = new gapi(sfConfig::get('google_analytics_login'), sfConfig::get('google_analytics_password'), sfConfig::get('google_analytics_profile'));
    }
    catch(Exception $e)
    {
      $this->ga = false;
    }
  }
}

<?php

/**
 *
 * @package    symfony
 * @subpackage plugin
 * @author     Vincent CHALAMON <vincentchalamon@gmail.com>
 * @version    SVN: $Id: actions.class.php 23319 2009-10-25 12:22:23Z Kris.Wallsmith $
 */
class BasesfAdminDashboardActions extends sfActions
{
  public function executeDashboard(sfWebRequest $request)
  {
    return $this->redirect('@article');
    try
    {
      $this->ga = new gapi(sfConfig::get('google_analytics_login'), sfConfig::get('google_analytics_password'), sfConfig::get('google_analytics_profile'));
    }
    catch(Exception $e)
    {
      $this->ga = false;
    }
  }
}

Disable dashboard due to Google error API


<?php
	#
	# $Id: ports-broken.php,v 1.1.2.19 2005-01-23 03:12:54 dan Exp $
	#
	# Copyright (c) 1998-2004 DVL Software Limited
	#

	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/common.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/databaselogin.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/getvalues.php');

	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports_page_list_ports.php');

	$Debug = 0;

	$Title = 'Broken ports';

	$page = new freshports_page_list_ports();

	$page->setDB($db);

	$page->setTitle($Title);
	$page->setSQL("ports.broken <> ''", $User->id);

	$page->display();
?>

<?php
	#
	# $Id: ports-broken.php,v 1.1.2.20 2005-01-23 03:41:33 dan Exp $
	#
	# Copyright (c) 1998-2004 DVL Software Limited
	#

	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/common.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/databaselogin.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/getvalues.php');

	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports_page_list_ports.php');

	$page = new freshports_page_list_ports();

	$page->setDB($db);

	$page->setTitle('Broken ports');
	$page->setDescription('These are the broken ports');

	$page->setSQL("ports.broken <> ''", $User->id);

	$page->display();
?>

Use the description, remove debug reference.

git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@3232 46e82423-29d8-e211-989e-002590a4cdd4


<?php
/**
 * @author         Pierre-Henry Soria <hi@ph7.me>
 * @copyright      (c) 2018-2019, Pierre-Henry Soria. All Rights Reserved.
 * @license        MIT License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Core / Class
 */

namespace PH7;

class UserMilestoneCore
{
    const MILLENARIAN = 1000;

    const NUMBER_USERS = [
        100,
        500,
        1000,
        2500,
        5000,
        7500,
        10000,
        25000,
        50000,
        100000,
        250000,
        500000,
        1000000 // Congrats!
    ];

    /** @var UserCoreModel */
    private $oUserModel;

    public function __construct(UserCoreModel $oUserModel)
    {
        $this->oUserModel = $oUserModel;
    }

    /**
     * @return bool
     */
    public function isTotalUserReached()
    {
        return in_array(
            $this->oUserModel->total(),
            self::NUMBER_USERS,
            true
        );
    }
}

<?php
/**
 * @author         Pierre-Henry Soria <hi@ph7.me>
 * @copyright      (c) 2018-2022, Pierre-Henry Soria. All Rights Reserved.
 * @license        MIT License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Core / Class
 */

declare(strict_types=1);

namespace PH7;

class UserMilestoneCore
{
    public const MILLENARIAN = 1000;

    private const NUMBER_USERS = [
        100,
        500,
        1000,
        2500,
        5000,
        7500,
        10000,
        25000,
        50000,
        100000,
        250000,
        500000,
        1000000 // Congrats!
    ];

    private UserCoreModel $oUserModel;

    public function __construct(UserCoreModel $oUserModel)
    {
        $this->oUserModel = $oUserModel;
    }

    public function isTotalUserReached(): bool
    {
        return in_array(
            $this->oUserModel->total(),
            self::NUMBER_USERS,
            true
        );
    }
}

Use PHP 7.1 type declarations

[UserMilestone] Use PHP 7.1 type declarations


@extends('layouts.app')

@section('content')

Locations

chunk(2) as $chunk )

		@foreach ($chunk as $location)
			{{ $location->id }}
			{{ $location->location }}

				<form action="/admin/locations/{{ $location->id }}/edit" method="POST">
					<button type="submit">Edit</button>
				</form>

		@endforeach

@endforeach

Add a Location

<form action="/admin/locations" method="POST">
	{{ csrf_field() }}
New Location: <input type="TEXT" name="location" size="20" />
<button type="SUBMIT">Add location</button> / Main
</form>

@endsection

@extends('layouts.app')

@section('content')

Locations

Click a location to edit

@foreach ($locations->chunk(2) as $chunk )

		@foreach ($chunk as $location)
			{{ $location->id }}
			id }}/edit">{{ $location->location }}
		@endforeach

@endforeach

Add a Location

<form class="form-inline" action="/admin/locations" method="POST">

	{{ csrf_field() }}
New Location: <input type="TEXT" class="form-control" id="location" name="location" size="20" placeholder="Location" />
<button type="SUBMIT" class="btn btn-default">Add location</button> / Main

</form>

@endsection

Make each location a link to the edit page instead of using a button


<?php

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

class CreateSettingsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('settings', function (Blueprint $table) {
			$table->increments('id');
			$table->string('name');
			$table->string('package')->default('mybb.core');
			$table->boolean('is_user_setting')->default('false');

			$table->unique(['name', 'package']);
		});
	}

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

}

<?php

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

class CreateSettingsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('settings', function (Blueprint $table) {
			$table->increments('id');
			$table->string('name');
			$table->string('package')->default('mybb.core');
			$table->boolean('is_user_setting')->default(false);

			$table->unique(['name', 'package']);
		});
	}

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

}

Fix default value for is_user_setting

Fix default value for is_user_setting

Signed-off-by: Euan T <bb3cb0933b629e9456c636be3c1aa8b281a75c82@gmail.com>


<?php
namespace autoauth;

$config = require('config.php');
$layout = new layout\Page("pages/index.{$config->hook->userRole()}.xml");

if($_SERVER['REQUEST_METHOD'] === 'POST')
{
	$name = $config->hook->userName();

	if($config->hook->userRole() === 'admin')
	{
		$name = $_POST['name'] ?: $name;
		$layout->{'//html:input[@maxlength]'}->item(0)->setAttribute('value', $name);
	}

	if(strlen($name))
	{
		//TODO
		$layout->{'//html:input[@readonly]'}->item(0)->setAttribute('value', "UUID for '$name'");
	}
}

$layout->display();

<?php
namespace autoauth;

$config = require('config.php');

if(!$config->hook instanceof hook\IHook)
{
	http_response_code(500);
	die(sprintf('"%s" is not a valid hook, it does not implement "%s".', get_class($config->hook), hook\IHook::class));
}

$layout = new layout\Page("pages/index.{$config->hook->userRole()}.xml");

if($_SERVER['REQUEST_METHOD'] === 'POST')
{
	$name = $config->hook->userName();

	if($config->hook->userRole() === 'admin')
	{
		$name = $_POST['name'] ?: $name;
		$layout->{'//html:input[@maxlength]'}->item(0)->setAttribute('value', $name);
	}

	if(strlen($name))
	{
		//TODO
		$layout->{'//html:input[@readonly]'}->item(0)->setAttribute('value', "UUID for '$name'");
	}
}

$layout->display();

Add the invalid hook message back

Add the invalid hook message back


<?php
namespace MindOfMicah\LaravelDatatables;

use Illuminate\Http\JsonResponse;

class Datatable
{
    protected $model;
    protected $columns;

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

    public function asJsonResponse()
    {
        $data = [];
        $total = $amount_displayed = 0;
        if ($this->model) {
            $model_name = $this->model;
            if ($this->columns) {

            }
            $sql = $model_name::query()->select($this->columns ?: '*');

            $total = ($sql->count());
            $models = $sql->take($this->a->input('length'))->get();
            $data = $models->toArray();

            $total = $total;
            $amount_displayed = count($models);
        }

        $data = ([
            'aaData'=>$data,
            'iTotalRecords'=>$total,
            'iTotalDisplayRecords'=>$amount_displayed
        ]);
        return new JsonResponse($data, 200);
    }

    public function forEloquentModel($model)
    {
        $this->model = $model;
        return $this;
    }

    public function pluckColumns($argument1)
    {
        $this->columns[] = $argument1;
        return $this;
    }
}

<?php
namespace MindOfMicah\LaravelDatatables;

use Illuminate\Http\JsonResponse;

class Datatable
{
    protected $model;
    protected $columns;

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

    public function asJsonResponse()
    {
        $data = [];
        $total = $amount_displayed = 0;
        if ($this->model) {
            $model_name = $this->model;
            if ($this->columns) {

            }
            $sql = $model_name::query()->select($this->columns ?: '*');

            $total = ($sql->count());
            $sql->skip($this->a->input('start'));
            $models = $sql->take($this->a->input('length'))->get();
            $data = $models->toArray();

            $total = $total;
            $amount_displayed = count($models);
        }

        $data = ([
            'aaData'=>$data,
            'iTotalRecords'=>$total,
            'iTotalDisplayRecords'=>$amount_displayed
        ]);
        return new JsonResponse($data, 200);
    }

    public function forEloquentModel($model)
    {
        $this->model = $model;
        return $this;
    }

    public function pluckColumns($argument1)
    {
        $this->columns[] = $argument1;
        return $this;
    }
}

Set a starting point for the datatables

Set a starting point for the datatables


<?php

/*
 * This file is part of Rocketeer
 *
 * (c) Maxime Fabre <ehtnam6@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

namespace Rocketeer\Console\Commands;

use Symfony\Component\Console\Input\InputArgument;

/**
 * An abstract from commands related to plugins.
 */
class AbstractPluginCommand extends AbstractCommand
{
    /**
     * The plugin task to fire.
     *
     * @var string
     */
    protected $pluginTask;

    /**
     * Whether the command's task should be built
     * into a pipeline or run straight.
     *
     * @var bool
     */
    protected $straight = true;

    /**
     * {@inheritdoc}
     */
    public function fire()
    {
        return $this->fireTasksQueue($this->pluginTask);
    }

    /**
     * Get the console command arguments.
     *
     * @return string[][]
     */
    protected function getArguments()
    {
        return [
            ['package', InputArgument::OPTIONAL, 'The package to publish the configuration for'],
        ];
    }
}

<?php

/*
 * This file is part of Rocketeer
 *
 * (c) Maxime Fabre <ehtnam6@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

namespace Rocketeer\Console\Commands;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * An abstract from commands related to plugins.
 */
class AbstractPluginCommand extends AbstractCommand
{
    /**
     * The plugin task to fire.
     *
     * @var string
     */
    protected $pluginTask;

    /**
     * Whether the command's task should be built
     * into a pipeline or run straight.
     *
     * @var bool
     */
    protected $straight = true;

    /**
     * {@inheritdoc}
     */
    public function fire()
    {
        $this->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);

        return $this->fireTasksQueue($this->pluginTask);
    }

    /**
     * Get the console command arguments.
     *
     * @return string[][]
     */
    protected function getArguments()
    {
        return [
            ['package', InputArgument::OPTIONAL, 'The package to publish the configuration for'],
        ];
    }
}

Make plugins command always be verbose

Make plugins command always be verbose


<?php
if (!defined('GNUSOCIAL')) {
    exit(1);
}

class BrowserNotificationsSettingsAction extends Action
{
    function prepare($args)
    {
        parent::prepare($args);

        if (!common_logged_in()) { // Make sure we're logged in
            $this->clientError(_('Not logged in.'));
            return;
        } else if (!common_is_real_login()) { // Make _really_ sure we're logged in...
            common_set_returnto($this->selfUrl());
            $user = common_current_user();
            if (Event::handle('RedirectToLogin', array($this, $user))) {
                common_redirect(common_local_url('login'), 303);
            }
        } else { // k, I think by now we're logged in. For realz.
            $this->user = common_current_user();
        }

        if ($this->isPost()) {
            $this->checkSessionToken();
        }

        return true;
    }

    function handle($args)
    {
        parent::handle($args);

        if ($this->isPost()) {
            $settings = array(
                'enabled' => $this->boolean('enabled', false),
                'mentions_only' => $this->boolean('mentions_only', false)
            );

            BrowserNotificationSettings::save($this->user, $settings);
        }

        $this->showPage();
    }

    function title()
    {
        return _m('Browser Notifications Settings');
    }

    function showContent()
    {
        // TODO: Show 'success'/'error' msg after a form submit

        $form = new BrowserNotificationsSettingsForm($this);
        $form->show();
    }
}

<?php
if (!defined('GNUSOCIAL')) {
    exit(1);
}

class BrowserNotificationsSettingsAction extends SettingsAction
{
    protected function doPost()
    {
        $this->user = common_current_user();

        $settings = array(
            'enabled' => $this->boolean('enabled', false),
            'mentions_only' => $this->boolean('mentions_only', false)
        );

        BrowserNotificationSettings::save($this->user, $settings);

        return _('Settings saved.');
    }

    function title()
    {
        return _m('Browser Notifications Settings');
    }

    function showContent()
    {
        $form = new BrowserNotificationsSettingsForm($this);
        $form->show();
    }
}

Extend SettingsAction instead of just Action

This way a lot of things (login, etc.) are handled for us.


<!DOCTYPE html>
<html class="no-js">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title><?php wp_title('|'); ?></title>
  <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>

<!DOCTYPE html>
<html class="no-js">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?php wp_title('|'); ?></title>
  <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>

Allow user scaling and remove max scale

Allow user scaling and remove max scale


<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }
}

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('front.login');
        }
    }
}

Fix name of login route

Fix name of login route


<?php

declare(strict_types=1);

namespace Sylius\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20200325075815 extends AbstractMigration
{
    public function getDescription() : string
    {
        return '';
    }

    public function up(Schema $schema) : void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_taxon ADD enabled TINYINT(1) NOT NULL');
    }

    public function down(Schema $schema) : void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_taxon DROP enabled');
    }
}

<?php

declare(strict_types=1);

namespace Sylius\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20200325075815 extends AbstractMigration
{
    public function getDescription() : string
    {
        return '';
    }

    public function up(Schema $schema) : void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_taxon ADD enabled TINYINT(1) NOT NULL');
        $this->addSql('UPDATE sylius_taxon SET enabled = 1');
    }

    public function down(Schema $schema) : void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_taxon DROP enabled');
    }
}

Enable all taxons upon migration

Enable all taxons upon migration


<?php
/**
*
*/
class UriParser {

	static function isIndexRoute(string $uri, array $models): bool{
		$indexRegex = '`^'.implode('|', array_map(function($model){ return $model::slug(); }, $models)).'/?$`';
		return preg_match($indexRegex, $uri);
	}

	static function extractModelFromRoute(string $uri, array $models): string{
		$uriBeginning = preg_replace('`^/?|/.*$`', '', $uri);

		$routeMap = array();
		foreach($models as $model){
			$routeMap[$model::slug()] = $model;
		}
		return $routeMap[$uriBeginning];
	}
}

<?php
/**
*
*/
class UriParser {

	static function isIndexRoute(string $uri, array $models): bool{
		$indexRegex = '`^('.implode('|', array_map(function($model){ return $model::slug(); }, $models)).')/?$`';
		return preg_match($indexRegex, $uri);
	}

	static function extractModelFromRoute(string $uri, array $models): string{
		$uriBeginning = preg_replace('`^/?|/.*$`', '', $uri);

		$routeMap = array();
		foreach($models as $model){
			$routeMap[$model::slug()] = $model;
		}
		return $routeMap[$uriBeginning];
	}
}

Fix logic error in regex for index route


<?php
namespace Phortress;

use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_;

/**
 * Namespace Continuation Environments: these are continuation of namespaces
 * for the purposes of variable declarations. When defining namespace-visible
 * identifiers, e.g constants or functions, this sets it on the actual
 * namespace.
 */
class NamespaceContinuationEnvironment extends NamespaceEnvironment {
	public function createNamespace($namespaceName) {
		$this->getNamespaceEnvironment()->createNamespace($namespaceName);
	}

	public function createClass(Class_ $class) {
		return $this->getNamespaceEnvironment()->createClass($class);
	}

	public function createFunction(Stmt $function) {
		return $this->getNamespaceEnvironment()->createFunction($function);
	}

	/**
	 * Gets the namespace environment for this environment. This is a shorthand
	 * for defining functions and constants.
	 *
	 * @return NamespaceEnvironment
	 */
	private function getNamespaceEnvironment() {
		$parent = $this->getParent();
		while ($parent && get_class($parent) === '\Phortress\NamespaceContinuationEnvironment') {
			$parent = $parent->getParent();
		}

		assert($parent, 'NamespaceContinuationEnvironments must be enclosed by a ' .
			'NamespaceEnvironment');
		return $parent;
	}
}

<?php
namespace Phortress;

use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_;

/**
 * Namespace Continuation Environments: these are continuation of namespaces
 * for the purposes of variable declarations. When defining namespace-visible
 * identifiers, e.g constants or functions, this sets it on the actual
 * namespace.
 */
class NamespaceContinuationEnvironment extends NamespaceEnvironment {
	public function createNamespace($namespaceName) {
		$this->getNamespaceEnvironment()->createNamespace($namespaceName);
	}

	public function createClass(Class_ $class) {
		return $this->getNamespaceEnvironment()->createClass($class);
	}

	public function createFunction(Stmt $function) {
		return $this->getNamespaceEnvironment()->createFunction($function);
	}

	public function resolveFunction($functionName) {
		return $this->getNamespaceEnvironment()->resolveFunction($functionName);
	}

	public function resolveClass($className) {
		return $this->getNamespaceEnvironment()->resolveClass($className);
	}

	public function resolveNamespace($namespaceName) {
		return $this->getNamespaceEnvironment()->resolveNamespace($namespaceName);
	}

	public function resolveConstant($constantName) {
		return $this->getNamespaceEnvironment()->resolveConstant($constantName);
	}

	/**
	 * Gets the namespace environment for this environment. This is a shorthand
	 * for defining functions and constants.
	 *
	 * @return NamespaceEnvironment
	 */
	private function getNamespaceEnvironment() {
		$parent = $this->getParent();
		while ($parent && get_class($parent) === '\Phortress\NamespaceContinuationEnvironment') {
			$parent = $parent->getParent();
		}

		assert($parent, 'NamespaceContinuationEnvironments must be enclosed by a ' .
			'NamespaceEnvironment');
		return $parent;
	}
}

Resolve namespace-level identifiers in the enclosing namespace.


<?php namespace Barryvdh\StackMiddleware;

use Closure;
use Illuminate\Contracts\Container\Container;

class Wrapper
{
    /** @var Container $container */
    protected $container;

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

    /**
     * Wrap and register the middleware in the Container
     *
     * @param  $abstract
     * @param  Closure $callable
     */
    public function bind($abstract, Closure $callable)
    {
        $this->container->bind($abstract, function() use($callable) {
            return $this->wrap($callable);
        });
    }

    /**
     * Wrap the StackPHP Middleware in a Laravel Middleware
     *
     * @param  Closure $callable
     * @return ClosureMiddleware
     */
    public function wrap(Closure $callable)
    {
        $kernel = new ClosureHttpKernel();
        $middleware = $callable($kernel);

        return new ClosureMiddleware($kernel, $middleware);
    }
}

<?php namespace Barryvdh\StackMiddleware;

use Closure;
use Illuminate\Contracts\Container\Container;

class Wrapper
{
    /** @var Container $container */
    protected $container;

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

    /**
     * Wrap and register the middleware in the Container
     *
     * @param  string         $abstract
     * @param  Closure|string $callable
     */
    public function bind($abstract, $callable)
    {
        $this->container->bind($abstract, function() use($callable) {
            return $this->wrap($callable);
        });
    }

    /**
     * Wrap the StackPHP Middleware in a Laravel Middleware
     *
     * @param  Closure|string  $callable
     * @return ClosureMiddleware
     */
    public function wrap($callable)
    {
        $kernel = new ClosureHttpKernel();

        if (is_callable($callable)) {
            $middleware = $callable($kernel);
        } else {
            $middleware = new $callable($kernel)
        }

        return new ClosureMiddleware($kernel, $middleware);
    }
}

Allow to use the middleware class name instead


<?php

use Clue\React\Buzz\Browser;
use Clue\React\Buzz\Message\Response;

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

$loop = React\EventLoop\Factory::create();
$client = new Browser($loop);

$client->head('http://www.github.com/clue/http-react')->then(function (Response $result) {
    var_dump($result->getHeaders(), $result->getBody());
});

$client->get('http://google.com')->then(function (Response $response) {
    var_dump($response->getHeaders(), $response->getBody());
});

$client->get('http://www.lueck.tv/psocksd')->then(function (Response $response) {
    var_dump($response->getHeaders(), $response->getBody());
});

$loop->run();

<?php

use Clue\React\Buzz\Browser;
use Clue\React\Buzz\Message\Response;

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

$loop = React\EventLoop\Factory::create();
$client = new Browser($loop);

$client->head('http://www.github.com/clue/http-react')->then(function (Response $result) {
    var_dump($result->getHeaders(), $result->getBody());
});

$client->get('http://google.com/')->then(function (Response $response) {
    var_dump($response->getHeaders(), $response->getBody());
});

$client->get('http://www.lueck.tv/psocksd')->then(function (Response $response) {
    var_dump($response->getHeaders(), $response->getBody());
});

$loop->run();

Update example to include URI path

Update example to include URI path


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

namespace ZendTest\Db\Sql\Ddl\Column;

use Zend\Db\Sql\Ddl\Column\Binary;

class BinaryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Zend\Db\Sql\Ddl\Column\Binary::setLength
     */
    public function testSetLength()
    {
        $column = new Binary('foo', 55);
        $this->assertEquals(55, $column->getLength());
        $this->assertSame($column, $column->setLength(20));
        $this->assertEquals(20, $column->getLength());
    }

    /**
     * @covers Zend\Db\Sql\Ddl\Column\Binary::getLength
     */
    public function testGetLength()
    {
        $column = new Binary('foo', 55);
        $this->assertEquals(55, $column->getLength());
    }

    /**
     * @covers Zend\Db\Sql\Ddl\Column\Binary::getExpressionData
     */
    public function testGetExpressionData()
    {
        $column = new Binary('foo', 10000000);
        $this->assertEquals(
            array(array('%s %s NOT NULL', array('foo', 'BINARY(10000000)'), array($column::TYPE_IDENTIFIER, $column::TYPE_LITERAL))),
            $column->getExpressionData()
        );
    }

}

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

namespace ZendTest\Db\Sql\Ddl\Column;

use Zend\Db\Sql\Ddl\Column\Binary;

class BinaryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Zend\Db\Sql\Ddl\Column\Binary::getExpressionData
     */
    public function testGetExpressionData()
    {
        $column = new Binary('foo', 10000000);
        $this->assertEquals(
            array(array('%s %s NOT NULL', array('foo', 'BINARY(10000000)'), array($column::TYPE_IDENTIFIER, $column::TYPE_LITERAL))),
            $column->getExpressionData()
        );
    }

}

Remove length tests from Binary column, tested in abstraction


<?php

namespace MarkWilson\Test;

require_once __DIR__ . '/../VerbalExpression.php';

use MarkWilson\VerbalExpression;

/**
 * Class VerbalExpressionOutputTest
 *
 * @package MarkWilson\Test
 * @author  Mark Wilson <mark@rippleffect.com>
 */
class VerbalExpressionOutputTest extends \PHPUnit_Framework_TestCase
{
    public function testEquivalentFromJehna()
    {
        $verbalExpression = new VerbalExpression();

        $verbalExpression->startOfLine()
                         ->then('http')
                         ->maybe('s')
                         ->then('://')
                         ->maybe('www.')
                         ->anythingBut(' ')
                         ->endOfLine();

        $this->assertEquals($verbalExpression->compile(), '^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$');

        $this->assertEquals(1, preg_match($verbalExpression->toString(), 'https://www.google.com'));
    }
}

<?php

namespace MarkWilson\Test;

require_once __DIR__ . '/../VerbalExpression.php';

use MarkWilson\VerbalExpression;

/**
 * Class VerbalExpressionOutputTest
 *
 * @package MarkWilson\Test
 * @author  Mark Wilson <mark@rippleffect.com>
 */
class VerbalExpressionOutputTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test equivalent test from original repo
     *
     * @return void
     */
    public function testEquivalentFromJehna()
    {
        $verbalExpression = new VerbalExpression();

        $verbalExpression->startOfLine()
                         ->then('http')
                         ->maybe('s')
                         ->then('://')
                         ->maybe('www.')
                         ->anythingBut(' ')
                         ->endOfLine();

        $this->assertEquals($verbalExpression->compile(), '^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$');

        $this->assertEquals(1, preg_match($verbalExpression->toString(), 'https://www.google.com'));
    }
}

Add docblock to test function

Add docblock to test function


<?php

namespace SecucardConnect\Event;

use SecucardConnect\Product\General\Model\Event;

abstract class AbstractEventHandler implements EventHandler
{
    /**
     * A user callback to invoke.
     * @var callable
     */
    protected $callback;

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

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

    /**
     * @param string $eventTarget
     * @param string $eventType
     * @param callable $callback
     */
    public function __construct($eventTarget = null, $eventType = null, callable $callback = null)
    {
        $this->callback = $callback;
        $this->eventTarget = $eventTarget;
        $this->eventType = $eventType;
    }

    /**
     * Can be used by handlers to determine if a handler should process the given event.
     * The default decision is made by comparing the given and this instances event target and event type.
     * May be overridden to adapt.
     * @param Event $event The event to process.
     * @return bool True if can handle, false else.
     */
    protected function accept($event)
    {
        return $event->target === $this->eventTarget && $event->type === $this->eventType;
    }

    /**
     * Handles a given event.
     * @param $event Event The event to handle.
     * @return bool True if the event was handled, false else. In the latter case another available handler may be
     * invoked with the given event.
     */
    abstract function handle($event);
}

<?php

namespace SecucardConnect\Event;

use SecucardConnect\Product\General\Model\Event;

abstract class AbstractEventHandler implements EventHandler
{
    /**
     * A user callback to invoke.
     * @var callable
     */
    protected $callback;

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

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

    /**
     * @param string $eventTarget
     * @param string $eventType
     * @param callable $callback
     */
    public function __construct($eventTarget = null, $eventType = null, callable $callback = null)
    {
        $this->callback = $callback;
        $this->eventTarget = $eventTarget;
        $this->eventType = $eventType;
    }

    /**
     * Can be used by handlers to determine if a handler should process the given event.
     * The default decision is made by comparing the given and this instances event target and event type.
     * May be overridden to adapt.
     * @param Event $event The event to process.
     * @return bool True if can handle, false else.
     */
    protected function accept($event)
    {
        return $event->target === $this->eventTarget && $event->type === $this->eventType;
    }
}

Fix : Correct event handler base class.

Fix : Correct event handler base class.


<?php

namespace WP_CLI\Bootstrap;

/**
 * Class DefineProtectedCommands.
 *
 * Define the commands that are "protected", meaning that they shouldn't be able
 * to break due to extension code.
 *
 * @package WP_CLI\Bootstrap
 */
final class DefineProtectedCommands implements BootstrapStep {

	/**
	 * Process this single bootstrapping step.
	 *
	 * @param BootstrapState $state Contextual state to pass into the step.
	 *
	 * @return BootstrapState Modified state to pass to the next step.
	 */
	public function process( BootstrapState $state ) {
		$commands        = $this->get_protected_commands();
		$current_command = $this->get_current_command();

		if ( in_array( $current_command, $commands, true ) ) {
			$state->setValue( BootstrapState::IS_PROTECTED_COMMAND, true );
		}

		return $state;
	}

	/**
	 * Get the lost of protected commands.
	 *
	 * @return array
	 */
	private function get_protected_commands() {
		return array(
			'cli info',
		);
	}

	/**
	 * Get the current command as a string.
	 *
	 * @return string Current command to be executed.
	 */
	private function get_current_command() {
		$runner = new RunnerInstance();

		return implode( ' ', (array) $runner()->arguments );
	}
}

<?php

namespace WP_CLI\Bootstrap;

/**
 * Class DefineProtectedCommands.
 *
 * Define the commands that are "protected", meaning that they shouldn't be able
 * to break due to extension code.
 *
 * @package WP_CLI\Bootstrap
 */
final class DefineProtectedCommands implements BootstrapStep {

	/**
	 * Process this single bootstrapping step.
	 *
	 * @param BootstrapState $state Contextual state to pass into the step.
	 *
	 * @return BootstrapState Modified state to pass to the next step.
	 */
	public function process( BootstrapState $state ) {
		$commands        = $this->get_protected_commands();
		$current_command = $this->get_current_command();

		foreach ( $commands as $command ) {
			if ( 0 === strpos( $current_command, $command ) ) {
				$state->setValue( BootstrapState::IS_PROTECTED_COMMAND, true );
			}
		}

		return $state;
	}

	/**
	 * Get the lost of protected commands.
	 *
	 * @return array
	 */
	private function get_protected_commands() {
		return array(
			'cli info',
		    'package',
		);
	}

	/**
	 * Get the current command as a string.
	 *
	 * @return string Current command to be executed.
	 */
	private function get_current_command() {
		$runner = new RunnerInstance();

		return implode( ' ', (array) $runner()->arguments );
	}
}

Add `package *` commands to the list of protected commands.

See https://github.com/wp-cli/package-command/issues/10


<?php
header('Content-Type: application/json');
header('Content-type: text/html; charset=UTF-8');

include_once("config/config.php");
include_once("inc/params.php");
include_once("inc/contact.php");

$lines = file($markdownPath);
$faqs = array();

$currentTitle = "";
$currentContent = "";

foreach ($lines as $line) {
    $subject = $line;
    $pattern = '/^\* .*/';
    if (substr($line, 0, 1) == "#") {
        $pattern = '/^# .*/';
    }
    if(preg_match($pattern, $subject)) {
        if (strlen($currentTitle)>0) {
            $faqs[] = array("title"=>$currentTitle, "detail"=>$currentContent);
        }
        $currentTitle = $line;
        $currentContent = "";
    }else{
        $currentContent .= $line."\n";
    }

}

$help = array('faqs' => $faqs, 'contact' => $contactMarkdown);

print_r(json_encode($help));

?>

<?php
header('Content-Type: application/json');
header('Content-type: text/html; charset=UTF-8');

include_once("config/config.php");
include_once("inc/params.php");
include_once("inc/contact.php");

$lines = file($markdownPath);
$faqs = array();

$currentTitle = "";
$currentContent = "";

foreach ($lines as $line) {
    if(isTitleLine($line)) {
        $hasFinishedSection = strlen($currentTitle)>0;
        if ($hasFinishedSection) {
            $faqs[] = array("title"=>$currentTitle, "detail"=>$currentContent);
        }
        $currentTitle = $line;
        $currentContent = "";
    }else{
        $currentContent .= $line."\n";
    }
}

$help = array('faqs' => $faqs, 'contact' => $contactMarkdown);

print_r(json_encode($help));

function isTitleLine($line) {
    return preg_match('/^# .*/', $line);
}

?>

Make code more self documenting and remove (* title).


<?php

namespace Illuminate\Foundation\Testing;

use Faker\Factory;

trait WithFaker
{
    /**
     * The Faker instance.
     *
     * @var \Faker\Generator
     */
    protected $faker;

    /**
     * Setup up the Faker instance.
     *
     * @return void
     */
    protected function setUpFaker()
    {
        $this->faker = $this->makeFaker();
    }

    /**
     * Get the default Faker instance for a given locale.
     *
     * @param  string|null  $locale
     * @return \Faker\Generator
     */
    protected function faker($locale = null)
    {
        return is_null($locale) ? $this->faker : $this->makeFaker($locale);
    }

    /**
     * Create a Faker instance for the given locale.
     *
     * @param  string|null  $locale
     * @return \Faker\Generator
     */
    protected function makeFaker($locale = null)
    {
        return Factory::create($locale ?? config('app.faker_locale', Factory::DEFAULT_LOCALE));
    }
}

<?php

namespace Illuminate\Foundation\Testing;

use Faker\Factory;
use Faker\Generator;

trait WithFaker
{
    /**
     * The Faker instance.
     *
     * @var \Faker\Generator
     */
    protected $faker;

    /**
     * Setup up the Faker instance.
     *
     * @return void
     */
    protected function setUpFaker()
    {
        $this->faker = $this->makeFaker();
    }

    /**
     * Get the default Faker instance for a given locale.
     *
     * @param  string|null  $locale
     * @return \Faker\Generator
     */
    protected function faker($locale = null)
    {
        return is_null($locale) ? $this->faker : $this->makeFaker($locale);
    }

    /**
     * Create a Faker instance for the given locale.
     *
     * @param  string|null  $locale
     * @return \Faker\Generator
     */
    protected function makeFaker($locale = null)
    {
        $locale = $locale ?? config('app.faker_locale', Factory::DEFAULT_LOCALE);

        if ($this->app->bound(Generator::class)) {
            return $this->app->make(Generator::class, [$locale]);
        }

        return Factory::create($locale);
    }
}

Resolve Faker\Generator out of the container if it is bound

If Faker\Generator is bound in the container then use that instance instead of creating a default version. This allows you to bind your own custom Faker\Generator and add custom faker providers which will be available when using WithFaker


<?php
require __DIR__ . '/../vendor/autoload.php';
session_save_path('.\sessions');
session_start();
if ($debug) {
  error_reporting(E_ALL);
  ini_set('display_errors', 'On');
}
define('BASEPATH', $_SERVER['DOCUMENT_ROOT']);
$connections = array();
include('config.php');

function makeConnection($connection_name = ''){
  global $connections;
  if($connection_name == '') {
    return "No connection type given";
    exit;
  }
  unset($db);
  $driver=$connections[$connection_name]['driver'];
  $dbhost=$connections[$connection_name]['dbhost'];
  $dbname=$connections[$connection_name]['dbname'];
  $dbuser=$connections[$connection_name]['dbuser'];
  $dbpassword=$connections[$connection_name]['dbpassword'];
  if (strlen($dbhost) > 0) {
    try {
      if($driver=="mysql"){
        $db = new PDO("$driver:host=$dbhost;dbname=$dbname", $dbuser, $dbpassword);
      }else{
        $db = new PDO("$driver:SERVER=$dbhost;DATABASE=$dbname", $dbuser, $dbpassword);
      }
      $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
      echo $e->getMessage();
    }
  }
  return $db;
}

<?php
require __DIR__ . '/../vendor/autoload.php';
session_save_path('.\sessions');
session_start();
define('BASEPATH', $_SERVER['DOCUMENT_ROOT']);
$connections = array();
include('config.php');
if ($debug) {
  error_reporting(E_ALL);
  ini_set('display_errors', 'On');
}

function makeConnection($connection_name = ''){
  global $connections;
  if($connection_name == '') {
    return "No connection type given";
    exit;
  }
  unset($db);
  $driver=$connections[$connection_name]['driver'];
  $dbhost=$connections[$connection_name]['dbhost'];
  $dbname=$connections[$connection_name]['dbname'];
  $dbuser=$connections[$connection_name]['dbuser'];
  $dbpassword=$connections[$connection_name]['dbpassword'];
  if (strlen($dbhost) > 0) {
    try {
      if($driver=="mysql"){
        $db = new PDO("$driver:host=$dbhost;dbname=$dbname", $dbuser, $dbpassword);
      }else{
        $db = new PDO("$driver:SERVER=$dbhost;DATABASE=$dbname", $dbuser, $dbpassword);
      }
      $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
      echo $e->getMessage();
    }
  }
  return $db;
}

Enable errors in the right place.

Enable errors in the right place.


<?php
/**
 * Template for web-story post type.
 *
 * @package   Google\Web_Stories
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://github.com/google/web-stories-wp
 */

use Google\Web_Stories\Story_Renderer;

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

the_post();

$current_post = get_post();

if ( $current_post instanceof WP_Post ) {
	echo '<!DOCTYPE html>';
	$renderer = new Story_Renderer( $current_post );
	$rendered = $renderer->render();
	$rendered = str_replace( ' standalone="standalone"', ' standalone', $rendered ); // @todo Remove! Temporary workaround for AMP plugin validation issue.
	echo $rendered; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}

<?php
/**
 * Template for web-story post type.
 *
 * @package   Google\Web_Stories
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://github.com/google/web-stories-wp
 */

use Google\Web_Stories\Story_Renderer;

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

the_post();

$current_post = get_post();

if ( $current_post instanceof WP_Post ) {
	echo '<!DOCTYPE html>';
	$renderer = new Story_Renderer( $current_post );
	echo $renderer->render(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}

Undo temp change for standalone attr replacement


<?php

namespace Plummer\Calendarful\Calendar;

class CalendarFactory implements CalendarFactoryInterface
{
	private $calendarTypes = [];

	public function addCalendarType($type, $calendarType)
	{
		if(!in_array('Plummer\Calendarful\Calendar\CalendarInterface', class_implements($calendarType))) {
			throw new \InvalidArgumentException('File or File path required.');
		}

		$this->calendarTypes[$type] = is_string($calendarType) ?
			$calendarType :
			get_class($calendarType);
	}

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

	public function createCalendar($type)
	{
		if(!isset($this->calendarTypes[$type])) {
			throw new \Exception('The type passed does not exist.');
		}

		$calendar = new $this->calendarTypes[$type]();

		return $calendar;
	}
}

<?php

namespace Plummer\Calendarful\Calendar;

class CalendarFactory implements CalendarFactoryInterface
{
	private $calendarTypes = [];

	public function addCalendarType($type, $calendarType)
	{
		if(is_string($calendarType) and !class_exists($calendarType)) {
			throw new \InvalidArgumentException("Class {$calendarType} des not exist.");
		}
		else if(!in_array('Plummer\Calendarful\Calendar\CalendarInterface', class_implements($calendarType, false))) {
			throw new \InvalidArgumentException('File or File path required.');
		}

		$this->calendarTypes[$type] = is_string($calendarType) ?
			$calendarType :
			get_class($calendarType);
	}

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

	public function createCalendar($type)
	{
		if(!isset($this->calendarTypes[$type])) {
			throw new \Exception('The type passed does not exist.');
		}

		$calendar = new $this->calendarTypes[$type]();

		return $calendar;
	}
}

Check to see if the calendar type parameter is actually an existing class before adding it to the calendar factory.


<?php
$DIR_BASE_CORE = dirname(__DIR__);
define('DIR_BASE', dirname($DIR_BASE_CORE));

require $DIR_BASE_CORE . '/bootstrap/configure.php';
require $DIR_BASE_CORE . '/bootstrap/autoload.php';

if (!\Concrete\Core\Application\Application::isRunThroughCommandLineInterface()) {
    return false;
}

$cms = require $DIR_BASE_CORE . '/bootstrap/start.php';

$app = new \Concrete\Core\Console\Application();
$cms->instance('console', $app);
if ($cms->isInstalled()) {
    $cms->setupPackages();
}
$app->setupDefaultCommands();
$app->run();

<?php
$DIR_BASE_CORE = dirname(__DIR__);
define('DIR_BASE', dirname($DIR_BASE_CORE));

require $DIR_BASE_CORE . '/bootstrap/configure.php';
require $DIR_BASE_CORE . '/bootstrap/autoload.php';

if (!\Concrete\Core\Application\Application::isRunThroughCommandLineInterface()) {
    return false;
}

$cms = require $DIR_BASE_CORE . '/bootstrap/start.php';

$app = new \Concrete\Core\Console\Application();
$cms->instance('console', $app);
if ($cms->isInstalled()) {
    $cms->setupPackages();
}
$app->setupDefaultCommands();

\Events::dispatch('on_before_console_run');

$app->run();

\Events::dispatch('on_after_console_run');

Add events to the console dispatcher

Feature: Add events to the console dispatcher

Former-commit-id: 3089f2463ddacbcaf7ac4572f91c1a48b168f887
Former-commit-id: 6e8a0c48d4897a8fa5ee16a8fe82be4aa216ae7c


Fix issue with ‘respect user's privacy’ code!

It’s Js and not PHP, stupid!


<?php
namespace App\Http\Transformers\Api\v1;

use League\Fractal\TransformerAbstract as FractalTransformer;
use App\Models\User;

class UserTransformer extends FractalTransformer
{
	public function transform(User $user)
	{
		$data = [
		  'id' => $user->id,
            'name' => $user->name,
            'username' => $user->username,
            'email' => $user->email,
        ];
		return $data;
	}
}

<?php
namespace App\Http\Transformers\Api\v1;

use League\Fractal\TransformerAbstract as FractalTransformer;
use App\Models\User;

class UserTransformer extends FractalTransformer
{
	public function transform(User $user)
	{
		$data = [
		  'id' => $user->id,
            'name' => $user->name,
            'username' => $user->username,
            'email' => $user->email,
            'role' => $user->role,
        ];
		return $data;
	}
}

Add role to transformed user data

Add role to transformed user data

it wos sam what done this if it breaks


<?php

/**
 * This file is part of the pantarei/user package.
 *
 * (c) Wong Hoi Sing Edison <hswong3i@pantarei-design.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Pantarei\User\Model;

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

interface UserManagerInterface extends ModelManagerInterface, UserProviderInterface
{
    public function createUser();

    public function deleteUser(UserInterface $user);

    public function reloadUser(UserInterface $user);

    public function updateUser(UserInterface $user);

    public function findUserByUsername($username);
}

<?php

/**
 * This file is part of the pantarei/user package.
 *
 * (c) Wong Hoi Sing Edison <hswong3i@pantarei-design.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Pantarei\User\Model;

use Symfony\Component\Security\Core\User\UserProviderInterface;

interface UserManagerInterface extends ModelManagerInterface, UserProviderInterface
{
    public function createUser();

    public function deleteUser(UserInterface $user);

    public function reloadUser(UserInterface $user);

    public function updateUser(UserInterface $user);

    public function findUserByUsername($username);
}

Remove direct dependency to security userinterface.


@extends('layout')

@section('body')

Search

    <form method="GET" class="tight">

                <input type="text" name="query" />

                <input type="submit" value="Search" />

    </form>
    @if (!empty($query))
        @if (sizeof($earnings))

Earnings

                        Description

                </thread>

                    @foreach ($earnings as $earning)

                            {{ $earning->description }}

                    @endforeach

        @endif
        @if (sizeof($spendings))

Spendings

                        Description

                </thread>

                    @foreach ($spendings as $spending)

                            {{ $spending->description }}

                    @endforeach

        @endif
    @endif
@endsection

@extends('layout')

@section('body')

Search

    <form method="GET" class="tight">

                <input type="text" name="query" />

                <input type="submit" value="Search" />

    </form>
    @if (!empty($query))
        @if (sizeof($earnings))

Earnings

                        Description

                </thread>

                    @foreach ($earnings as $earning)

                            {{ $earning->description }}

                    @endforeach

        @endif
        @if (sizeof($spendings))

Spendings

                        Description

                </thread>

                    @foreach ($spendings as $spending)

                                id }}">{{ $spending->description }}

                    @endforeach

        @endif
    @endif
@endsection

Add hyperlink to spendings in search view


<?php

namespace directapi\services\campaigns\enum;

use directapi\components\Enum;

class CampaignTypeEnum extends Enum
{
    public const TEXT_CAMPAIGN = 'TEXT_CAMPAIGN';
    public const MOBILE_APP_CAMPAIGN = 'MOBILE_APP_CAMPAIGN ';
    public const DYNAMIC_TEXT_CAMPAIGN = 'DYNAMIC_TEXT_CAMPAIGN ';
}

<?php

namespace directapi\services\campaigns\enum;

use directapi\components\Enum;

class CampaignTypeEnum extends Enum
{
    public const TEXT_CAMPAIGN = 'TEXT_CAMPAIGN';
    public const MOBILE_APP_CAMPAIGN = 'MOBILE_APP_CAMPAIGN ';
    public const DYNAMIC_TEXT_CAMPAIGN = 'DYNAMIC_TEXT_CAMPAIGN ';
    public const CPM_BANNER_CAMPAIGN = 'CPM_BANNER_CAMPAIGN ';
}

Add new campaign type constant

Add new campaign type constant


<?php

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

namespace Sylius\Component\Core\Repository;

use Sylius\Component\Core\Model\AddressInterface;
use Sylius\Component\Core\Model\CustomerInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Anna Walasek <anna.walasek@lakion.com>
 */
interface AddressRepositoryInterface extends RepositoryInterface
{
    /**
     * @param CustomerInterface $customer
     *
     * @return AddressInterface[]
     */
    public function findByCustomer(CustomerInterface $customer);
}

<?php

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

namespace Sylius\Component\Core\Repository;

use Sylius\Component\Core\Model\AddressInterface;
use Sylius\Component\Core\Model\CustomerInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Anna Walasek <anna.walasek@lakion.com>
 * @author Jan Góralski <jan.goralski@lakion.com>
 */
interface AddressRepositoryInterface extends RepositoryInterface
{
    /**
     * @param CustomerInterface $customer
     *
     * @return AddressInterface[]
     */
    public function findByCustomer(CustomerInterface $customer);

    /**
     * @param CustomerInterface $customer
     * @param string $id
     *
     * @return AddressInterface|null
     */
    public function findOneByCustomerAndId(CustomerInterface $customer, $id);
}

Remove an address from book

[Address] Remove an address from book


<!DOCTYPE html>

    <title>Event RSVP | MyRoboJackets</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="{{ mix('/css/app.css') }}" rel="stylesheet">

    @include('favicon')

This event has ended!

                We would have loved to see you at {{ $event->name }}, but unfortunately, that event has already ended.

Click here to see our upcoming events.

Add link to upcoming events on the ended RSVP page


<?php
/**
 * Default template for displaying post content
 *
 * @package ZnWP Bootstrap Theme
 */

global $znwp_theme;
?>

            <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

                <?php if (is_single()): ?>
                  <?php the_title(); ?>
                <?php else: ?>
                  <a href="<?php the_permalink(); ?>"><?php the_title(); ?>
                <?php endif; ?>

              <time> <?php the_date(); ?></time>

              <?php if (is_single()): ?>
                <?php the_content(); ?>

                <?php
                previous_post_link(
                    '
%link
',
                    ' %title'
                );
                next_post_link(
                    '
%link
',
                    '%title '
                );
                ?>
              <?php else: ?>
                <?php the_excerpt(); ?>
              <?php endif; ?>

Add div.clearfix to ensure links work in phone mode


<?php
/**
 * @Author	Freek Lijten
 */
require_once(__DIR__ . '/../../lib/AutoLoader.php');
new AutoLoader();

//generate random keys
$handle = fopen('/dev/urandom', 'rb');
$random = fread($handle, 200);
fclose($handle);
$consumerKey = sha1(substr($random, 0, 100));
$consumerSecret = sha1(substr($random, 100, 100));

//create consumer model
$Consumer = new OAuthConsumerModel(Configuration::getDataStore());
$Consumer->setConsumerCreateDate(time());
$Consumer->setConsumerKey($consumerKey);
$Consumer->setConsumerSecret($consumerSecret);
$Consumer->save();

echo "Consumer key: $consumerKey <br />Consumer secret: $consumerSecret";

<?php
/**
 * @Author	Freek Lijten
 */
require_once(__DIR__ . '/../../lib/AutoLoader.php');
new AutoLoader();

//create consumer model
$Consumer = new OAuthConsumerModel(Configuration::getDataStore());
$Consumer->setConsumerCreateDate(time());
$Consumer->setConsumerKey(OAuthProviderWrapper::generateToken());
$Consumer->setConsumerSecret(OAuthProviderWrapper::generateToken());
$Consumer->save();

echo "Consumer key: $consumerKey <br />Consumer secret: $consumerSecret";

Use the generate token function from the wrapper while creating a new consumer


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

namespace ZendTest\Db\Sql\Ddl\Column;

use Zend\Db\Sql\Ddl\Column\Boolean;

class BooleanTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Zend\Db\Sql\Ddl\Column\Boolean::getExpressionData
     */
    public function testGetExpressionData()
    {
        $column = new Boolean('foo');
        $this->assertEquals(
            array(array('%s %s NOT NULL', array('foo', 'TINYINT'), array($column::TYPE_IDENTIFIER, $column::TYPE_LITERAL))),
            $column->getExpressionData()
        );
    }

    /**
     * @covers Zend\Db\Sql\Ddl\Column\Boolean
     *
     * @group 6257
     */
    public function testIsAlwaysNotNullable()
    {
        $column = new Boolean('foo', true);

        $this->assertFalse($column->isNullable());

        $column->setNullable(true);

        $this->assertFalse($column->isNullable());
    }
}

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

namespace ZendTest\Db\Sql\Ddl\Column;

use Zend\Db\Sql\Ddl\Column\Boolean;

class BooleanTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Zend\Db\Sql\Ddl\Column\Boolean::getExpressionData
     */
    public function testGetExpressionData()
    {
        $column = new Boolean('foo');
        $this->assertEquals(
            array(array('%s %s NOT NULL', array('foo', 'BOOLEAN'), array($column::TYPE_IDENTIFIER, $column::TYPE_LITERAL))),
            $column->getExpressionData()
        );
    }

    /**
     * @covers Zend\Db\Sql\Ddl\Column\Boolean
     *
     * @group 6257
     */
    public function testIsAlwaysNotNullable()
    {
        $column = new Boolean('foo', true);

        $this->assertFalse($column->isNullable());

        $column->setNullable(true);

        $this->assertFalse($column->isNullable());
    }
}

Change expected from `TINYINT` to `BOOLEAN`

The value of Boolean::$type was changed from `TINYINT` to `BOOLEAN` in a [commit](The https://github.com/zendframework/zf2/commit/e287ebfc9935e0fbc74998fe138aba67764250db) made by @SlayerBirden. It appears the tests were not changed to account for the new value.


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Inventory\Model;

class InventoryUnit implements InventoryUnitInterface
{
    /** @var mixed */
    protected $id;

    protected ?StockableInterface $stockable = null;

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

    public function getStockable(): ?StockableInterface
    {
        return $this->stockable;
    }

    public function setStockable(StockableInterface $stockable): void
    {
        $this->stockable = $stockable;
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Inventory\Model;

class InventoryUnit implements InventoryUnitInterface
{
    /** @var mixed */
    protected $id;

    /**
     * @var StockableInterface|null
     */
    protected $stockable;

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

    public function getStockable(): ?StockableInterface
    {
        return $this->stockable;
    }

    public function setStockable(StockableInterface $stockable): void
    {
        $this->stockable = $stockable;
    }
}

Remove types in public and protected properies in not final classes (in components)


<?php

namespace Spatie\Backup\Notifications\Senders;

use Illuminate\Contracts\Config\Repository;
use Spatie\Backup\Notifications\BaseSender;

class Pushover extends BaseSender
{
    /** @var array */
    protected $config;

    /**
     * @param Repository $config
     */
    public function __construct(Repository $config)
    {
        $this->config = $config->get('laravel-backup.notifications.pushover');
    }

    /**
     * Sends the message to the Pushover API
     * @return void
     */
    public function send()
    {
        curl_setopt_array($ch = curl_init(), [
            CURLOPT_URL => 'https://api.pushover.net/1/messages.json',
            CURLOPT_POSTFIELDS => [
                'token' => $this->config['token'],
                'user' => $this->config['user'],
                'title' => $this->subject,
                'message' => $this->message,
                'sound' => $this->getSound(),
            ],
            CURLOPT_SAFE_UPLOAD => true,
        ]);
        curl_exec($ch);
        curl_close($ch);
    }

    /**
     * @return string
     */
    protected function getSound()
    {
        return $this->type === static::TYPE_SUCCESS
            ? $this->config['sounds']['success']
            : $this->config['sounds']['error'];
    }

}

<?php

namespace Spatie\Backup\Notifications\Senders;

use Illuminate\Contracts\Config\Repository;
use Spatie\Backup\Notifications\BaseSender;

class Pushover extends BaseSender
{
    /** @var array */
    protected $config;

    /**
     * @param Repository $config
     */
    public function __construct(Repository $config)
    {
        $this->config = $config->get('laravel-backup.notifications.pushover');
    }

    /**
     * Sends the message to the Pushover API
     * @return void
     */
    public function send()
    {
        curl_setopt_array($ch = curl_init(), [
            CURLOPT_URL => 'https://api.pushover.net/1/messages.json',
            CURLOPT_POSTFIELDS => [
                'token' => $this->config['token'],
                'user' => $this->config['user'],
                'title' => $this->subject,
                'message' => $this->message,
                'sound' => $this->getSound(),
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SAFE_UPLOAD => true,
        ]);
        curl_exec($ch);
        curl_close($ch);
    }

    /**
     * @return string
     */
    protected function getSound()
    {
        return $this->type === static::TYPE_SUCCESS
            ? $this->config['sounds']['success']
            : $this->config['sounds']['error'];
    }

}

Remove unnecessary output from curl when using pushover