<?php

namespace Rcm\Controller;
use Rcm\Controller\EntityMgrAwareController;

class StateApiController extends EntityMgrAwareController
{
    /**
     * Returns states as JSON. 404's if country not found.
     */
    function listStatesAction()
    {
        $countryIso3 = $this->getEvent()->getRouteMatch()->getParam('country');
        $stateEntities = $this->entityMgr->getRepository('\Rcm\Entity\State')
            ->findBy(
                array('country' => $countryIso3),
                array('name' => 'ASC')
            );

        $states = array();
        foreach ($stateEntities as $state) {
            $name = $state->getName();
            if (empty($name)) {
                $name = $state->getState();
            }
            $states[$state->getState()] = $name;
        }

        if (!count($states)) {
            $httpCode = '404 Not Found';
            header('HTTP/1.0 ' . $httpCode);
            exit($httpCode);
        }

        exit(json_encode($states));
    }
}

<?php

namespace Rcm\Controller;
use Rcm\Controller\EntityMgrAwareController;

class StateApiController extends EntityMgrAwareController
{
    /**
     * Returns states as JSON. 404's if country not found.
     */
    function listStatesAction()
    {
        $countryIso3 = $this->getEvent()->getRouteMatch()->getParam('country');
        $stateEntities = $this->entityMgr->getRepository('\Rcm\Entity\State')
            ->findBy(
                array('country' => $countryIso3),
                array('name' => 'ASC')
            );

        $states = array();
        foreach ($stateEntities as $state) {
            $name = $state->getName();
            if (empty($name)) {
                $name = $state->getState();
            }
            $states[$state->getState()] = utf8_encode($name);
        }

        if (!count($states)) {
            $httpCode = '404 Not Found';
            header('HTTP/1.0 ' . $httpCode);
            exit($httpCode);
        }

        exit(json_encode($states));
    }
}

Fix for VIP Pricing, French State Display, VIP Links to LoginLink, Fixes for UTF8 display of states.


<?php

declare(strict_types=1);

namespace SimpleSAML\SAML2\XML\md;

use SimpleSAML\Assert\Assert;
use SimpleSAML\SAML2\Exception\ProtocolViolationException;

use function filter_var;

/**
 * Abstract class implementing LocalizedURIType.
 *
 * @package simplesamlphp/saml2
 */
abstract class AbstractLocalizedURI extends AbstractLocalizedName
{
    /**
     * Validate the content of the element.
     *
     * @param string $content  The value to go in the XML textContent
     * @throws \Exception on failure
     * @return void
     */
    protected function validateContent(string $content): void
    {
        parent::validateContent($content);

        Assert::false(
            !empty($content) && !filter_var($content, FILTER_VALIDATE_URL),
            $this->getQualifiedName() . ' is not a valid URL.',
            ProtocolViolationException::class,
        );
    }
}

<?php

declare(strict_types=1);

namespace SimpleSAML\SAML2\XML\md;

use SimpleSAML\Assert\Assert;
use SimpleSAML\SAML2\Exception\ProtocolViolationException;

use function filter_var;

/**
 * Abstract class implementing LocalizedURIType.
 *
 * @package simplesamlphp/saml2
 */
abstract class AbstractLocalizedURI extends AbstractLocalizedName
{
    /**
     * Validate the content of the element.
     *
     * @param string $content  The value to go in the XML textContent
     * @throws \Exception on failure
     * @return void
     */
    protected function validateContent(string $content): void
    {
        parent::validateContent($content);

        Assert::false(
            !filter_var($content, FILTER_VALIDATE_URL),
            $this->getQualifiedName() . ' is not a valid URL.',
            ProtocolViolationException::class,
        );
    }
}

Simplify assertion; testing for empty content is done by the parent


<?php

namespace OpenOrchestra\ModelBundle\Tests\Functional\Repository;

use OpenOrchestra\ModelInterface\Repository\ContentTypeRepositoryInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * Class ContentTypeRepositoryTest
 *
 * @group integrationTest
 */
class ContentTypeRepositoryTest extends KernelTestCase
{
    /**
     * @var ContentTypeRepositoryInterface
     */
    protected $repository;

    /**
     * Set up the test
     */
    public function setUp()
    {
        parent::setUp();

        static::bootKernel();
        $this->repository = static::$kernel->getContainer()->get('open_orchestra_model.repository.content_type');
    }

    /**
     * @param string $contentType
     * @param int    $version
     *
     * @dataProvider provideContentTypeAndVersionNumber
     */
    public function testFindOneByContentTypeIdInLastVersion($contentType, $version)
    {
        $contentTypeElement = $this->repository->findOneByContentTypeIdInLastVersion($contentType);

        $this->assertEquals($version, $contentTypeElement->getVersion());
    }

    /**
     * @return array
     */
    public function provideContentTypeAndVersionNumber()
    {
        return array(
            array('news', 2),
            array('customer', 1),
        );
    }
}

<?php

namespace OpenOrchestra\ModelBundle\Tests\Functional\Repository;

use OpenOrchestra\ModelInterface\Repository\ContentTypeRepositoryInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * Class ContentTypeRepositoryTest
 *
 * @group integrationTest
 */
class ContentTypeRepositoryTest extends KernelTestCase
{
    /**
     * @var ContentTypeRepositoryInterface
     */
    protected $repository;

    /**
     * Set up the test
     */
    public function setUp()
    {
        parent::setUp();

        static::bootKernel();
        $this->repository = static::$kernel->getContainer()->get('open_orchestra_model.repository.content_type');
    }

    /**
     * @param string $contentType
     * @param int    $version
     *
     * @dataProvider provideContentTypeAndVersionNumber
     */
    public function testFindOneByContentTypeIdInLastVersion($contentType, $version)
    {
        $contentTypeElement = $this->repository->findOneByContentTypeIdInLastVersion($contentType);

        $this->assertEquals($version, $contentTypeElement->getVersion());
    }

    /**
     * @return array
     */
    public function provideContentTypeAndVersionNumber()
    {
        return array(
            array('car', 2),
            array('customer', 1),
        );
    }
}

Update test depending on environment (BO or FO)


@extends('layout')

@section('body')

Settings

 {{ __('general.profile') }}

 {{ __('general.account') }}

 {{ __('general.preferences') }}

 {{ __('models.spaces') }}

                @yield('settings_title')
                <form method="POST" action="/settings" enctype="multipart/form-data">
                    {{ csrf_field() }}
                    @yield('settings_body')
                </form>

@endsection

@extends('layout')

@section('body')

{{ __('pages.settings') }}

 {{ __('general.profile') }}

 {{ __('general.account') }}

 {{ __('general.preferences') }}

 {{ __('models.spaces') }}

                @yield('settings_title')
                <form method="POST" action="/settings" enctype="multipart/form-data">
                    {{ csrf_field() }}
                    @yield('settings_body')
                </form>

@endsection

Replace hard-coded English at top of settings menu


<?php
if ( ! function_exists('format_money')) {
    /**
     * Formats a price. Adds the currency if provided.
     *
     * @param string $value
     * @param null   $currency
     *
     * @return string
     */
    function format_money($value, $currency = null)
    {
        $number = money_format('%.2n', (float)$value);

        if ($currency) {
            $number = "${currency} ${number}";
        }

        return $number;
    }
}

<?php
if ( ! function_exists('format_money')) {
    /**
     * Formats a price. Adds the currency if provided.
     *
     * @param string $value
     * @param null   $currency
     *
     * @return string
     */
    function format_money($value, $currency = null)
    {
        setlocale(LC_ALL, '');
        $locale = localeconv();

        $number = number_format((float)$value, 2, $locale['decimal_point'], $locale['thousands_sep']);

        if ($currency) {
            $number = "${currency} ${number}";
        }

        return $number;
    }
}

Replace money_format since it is not available on Windows (!2)


<?php
declare(strict_types = 1);

namespace Embed\Detectors;

class Languages extends Detector
{
    /**
     * @return \Psr\Http\Message\UriInterface[]
     */
    public function detect(): array
    {
        $document = $this->extractor->getDocument();
        $languages = [];

        foreach ($document->select('.//link[@hreflang]')->nodes() as $node) {
            $language = $node->getAttribute('hreflang');
            $href = $node->getAttribute('href');

            if (isEmpty()) {
                continue;
            }

            $languages[$language] = $this->extractor->resolveUri($href);
        }

        return $languages;
    }

    private function isEmpty($value): boolval
    {
        $skipValues = array(
            'undefined',
        );

        return empty($value) || in_array($value, $skipValues);
    }
}

<?php
declare(strict_types = 1);

namespace Embed\Detectors;

class Languages extends Detector
{
    /**
     * @return \Psr\Http\Message\UriInterface[]
     */
    public function detect(): array
    {
        $document = $this->extractor->getDocument();
        $languages = [];

        foreach ($document->select('.//link[@hreflang]')->nodes() as $node) {
            $language = $node->getAttribute('hreflang');
            $href = $node->getAttribute('href');

            if (self::isEmpty($language) || self::isEmpty($href)) {
                continue;
            }

            $languages[$language] = $this->extractor->resolveUri($href);
        }

        return $languages;
    }

    private function isEmpty(string $value): bool
    {
        $skipValues = array(
            'undefined',
        );

        return empty($value) || in_array($value, $skipValues);
    }
}

Fix undefined function without parameter


<?php namespace Modules\Dashboard\Sidebar;

use Maatwebsite\Sidebar\Group;
use Maatwebsite\Sidebar\Item;
use Maatwebsite\Sidebar\Menu;
use Modules\Core\Contracts\Authentication;

class SidebarExtender implements \Maatwebsite\Sidebar\SidebarExtender
{
    /**
     * @var Authentication
     */
    protected $auth;

    /**
     * @param Authentication $auth
     *
     * @internal param Guard $guard
     */
    public function __construct(Authentication $auth)
    {
        $this->auth = $auth;
    }

    /**
     * @param Menu $menu
     *
     * @return Menu
     */
    public function extendWith(Menu $menu)
    {
        $menu->group(trans('dashboard::dashboard.name'), function (Group $group) {
            $group->weight(0);
            $group->hideHeading();

            $group->item(trans('dashboard::dashboard.name'), function (Item $item) {
                $item->icon('fa fa-dashboard');
                $item->route('dashboard.index');
                $item->authorize(
                    $this->auth->hasAccess('dashboard.index')
                );
            });
        });

        return $menu;
    }
}

<?php namespace Modules\Dashboard\Sidebar;

use Maatwebsite\Sidebar\Group;
use Maatwebsite\Sidebar\Item;
use Maatwebsite\Sidebar\Menu;
use Modules\Core\Contracts\Authentication;

class SidebarExtender implements \Maatwebsite\Sidebar\SidebarExtender
{
    /**
     * @var Authentication
     */
    protected $auth;

    /**
     * @param Authentication $auth
     *
     * @internal param Guard $guard
     */
    public function __construct(Authentication $auth)
    {
        $this->auth = $auth;
    }

    /**
     * @param Menu $menu
     *
     * @return Menu
     */
    public function extendWith(Menu $menu)
    {
        $menu->group(trans('dashboard::dashboard.name'), function (Group $group) {
            $group->weight(0);
            $group->hideHeading();

            $group->item(trans('dashboard::dashboard.name'), function (Item $item) {
                $item->icon('fa fa-dashboard');
                $item->route('dashboard.index');
                $item->isActiveWhen(route('dashboard.index', null, false));
                $item->authorize(
                    $this->auth->hasAccess('dashboard.index')
                );
            });
        });

        return $menu;
    }
}

Add an isActiveWhen on the dashbaord sidebar class


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

namespace Zend\Mvc\Service;

use Zend\Form\FormElementManager;
use Zend\ServiceManager\ServiceLocatorInterface;

class FormElementManagerFactory extends AbstractPluginManagerFactory
{
    const PLUGIN_MANAGER_CLASS = 'Zend\Form\FormElementManager';

    /**
     * Create and return the MVC controller plugin manager
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return FormElementManager
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $plugins = parent::createService($serviceLocator);
        return $plugins;
    }
}

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

namespace Zend\Mvc\Service;

use Zend\Form\Form;
use Zend\Form\FormElementManager;
use Zend\ServiceManager\ServiceLocatorInterface;

class FormElementManagerFactory extends AbstractPluginManagerFactory
{
    const PLUGIN_MANAGER_CLASS = 'Zend\Form\FormElementManager';

    /**
     * Create and return the MVC controller plugin manager
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return FormElementManager
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $plugins = parent::createService($serviceLocator);
        if ($serviceLocator->has('Di')) {
            $di = $serviceLocator->get('Di');
            $im = $di->instanceManager();
            if (!$im->getTypePreferences('Zend\Form\FormInterface')) {
                $form = new Form;
                $im->setTypePreference('Zend\Form\FormInterface', array($form));
            }
            $plugins->addPeeringServiceManager($serviceLocator);
            $plugins->setRetrieveFromPeeringManagerFirst(true);
        }
        return $plugins;
    }
}

Fix conflict AbstractPluginManager::valdatePlugin with DiAbstractFactory


<?php

namespace ajax\listing;

use \PDO as PDO;

/**
 * Web Service.
 * Returns Organisms with given ids
 */
class Organisms extends \WebService {

    /**
     * @param $querydata[ids] array of organism ids
     * @returns array of organisms
     */
    public function execute($querydata) {
        global $db;

        $organism_ids = $querydata['ids'];

        $place_holders = implode(',', array_fill(0, count($organism_ids), '?'));

        $query_get_organisms = <<<EOF
SELECT *
    FROM organism
    WHERE organism_id IN ($place_holders)
EOF;

        $stm_get_organisms = $db->prepare($query_get_organisms);

        $data = array();

        $stm_get_organisms->execute($organism_ids);

        while ($row = $stm_get_organisms->fetch(PDO::FETCH_ASSOC)) {
            $data[] = $row;
        }

        return $data;
    }

}

?>

<?php

namespace ajax\listing;

use \PDO as PDO;

/**
 * Web Service.
 * Returns Organisms with given ids
 */
class Organisms extends \WebService {

    /**
     * @param $querydata[ids] array of organism ids
     * @returns array of organisms
     */
    public function execute($querydata) {
        global $db;

        $limit = 5;
        if(in_array('limit', $querydata)){
            $limit = $querydata['limit'];
        }
        $query_get_organisms = <<<EOF
SELECT *
    FROM organism LIMIT $limit
EOF;

        $stm_get_organisms = $db->prepare($query_get_organisms);

        $data = array();

        $stm_get_organisms->execute($limit);

        while ($row = $stm_get_organisms->fetch(PDO::FETCH_ASSOC)) {
            $data[] = $row;
        }

        return $data;
    }

}

?>

Change Webservice in order to limit the entrys


<?php
namespace Craft;

class AssetRevPlugin extends BasePlugin
{
	/**
	 * @return string
	 */
	public function getName()
	{
		return 'Asset Rev';
	}

	/**
	 * Returns the plugin’s version number.
	 *
	 * @return string The plugin’s version number.
	 */
	public function getVersion()
	{
		return '2.0.1';
	}

	/**
	 * Returns the plugin developer’s name.
	 *
	 * @return string The plugin developer’s name.
	 */
	public function getDeveloper()
	{
		return 'Club Studio Ltd';
	}

	/**
	 * Returns the plugin developer’s URL.
	 *
	 * @return string The plugin developer’s URL.
	 */
	public function getDeveloperUrl()
	{
		return 'https://clubstudio.co.uk';
	}

	/**
	 * Add Twig Extension
	 *
	 * @return AssetRevTwigExtension
	 * @throws \Exception
	 */
	public function addTwigExtension()
	{
		Craft::import('plugins.assetrev.twigextensions.AssetRevTwigExtension');

		return new AssetRevTwigExtension();
	}

	/**
	 * Define plugin settings
	 *
	 * @return array
	 */
	protected function defineSettings()
	{
		return array(
			'manifestPath' => array(AttributeType::String, 'required' => true),
		);
	}

	/**
	 * Get settings html
	 *
	 * @return string
	 */
	public function getSettingsHtml()
	{
		return craft()->templates->render('assetrev/_settings', array(
			'settings' => $this->getSettings(),
			'basePath' => CRAFT_BASE_PATH,
		));
	}
}

<?php
namespace Craft;

class AssetRevPlugin extends BasePlugin
{
	/**
	 * @return string
	 */
	public function getName()
	{
		return 'Asset Rev';
	}

	/**
	 * Returns the plugin’s version number.
	 *
	 * @return string The plugin’s version number.
	 */
	public function getVersion()
	{
		return '3.0.0';
	}

	/**
	 * Returns the plugin developer’s name.
	 *
	 * @return string The plugin developer’s name.
	 */
	public function getDeveloper()
	{
		return 'Club Studio Ltd';
	}

	/**
	 * Returns the plugin developer’s URL.
	 *
	 * @return string The plugin developer’s URL.
	 */
	public function getDeveloperUrl()
	{
		return 'https://clubstudio.co.uk';
	}

	/**
	 * @return string
	 */
	public function getDocumentationUrl()
	{
		return 'https://github.com/clubstudioltd/craft-asset-rev';
	}

	/**
	 * Add Twig Extension
	 *
	 * @return AssetRevTwigExtension
	 * @throws \Exception
	 */
	public function addTwigExtension()
	{
		Craft::import('plugins.assetrev.twigextensions.AssetRevTwigExtension');

		return new AssetRevTwigExtension();
	}
}

Add documentation url and update version number


<?php

namespace App;

trait LogsToConsole
{
    public function alert(string $message)
    {
        app('console')->alert($message);
    }

    public function warn(string $message)
    {
        app('console')->warn($message);
    }

    public function error(string $message)
    {
        app('console')->error($message);
    }

    protected function line(string $message)
    {
        app('console')->line($message);
    }

    protected function info(string $message)
    {
        app('console')->info($message);
    }
}

<?php

namespace App;

trait LogsToConsole
{
    public function alert(string $message)
    {
        app('console')->alert($message);
    }

    public function warn(string $message)
    {
        app('console')->warn($message);
    }

    public function error(string $message)
    {
        app('console')->error($message);
    }

    public function line(string $message)
    {
        app('console')->line($message);
    }

    public function info(string $message)
    {
        app('console')->info($message);
    }
}

Use public methods as per tighten coding standards.


<?php

namespace Rogue\Services;

use Softonic\GraphQL\ClientBuilder;

class GraphQL
{
    /**
     * Build a new GraphQL client.
     */
    public function __construct()
    {
        $this->client = ClientBuilder::build(config('services.graphql.url'));
    }

    /**
     * Run a GraphQL query using the client.
     *
     * @param  $query     String
     * @param  $variables Array
     * @return \Softonic\GraphQL\Response
     */
    public function query($query, $variables)
    {
        return $this->client->query($query, $variables);
    }
}

<?php

namespace Rogue\Services;

use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;

class GraphQL
{
    /**
     * Build a new GraphQL client.
     */
    public function __construct()
    {
        $this->client = ClientBuilder::build(config('services.graphql.url'));
    }

    /**
     * Run a GraphQL query using the client
     * and parse the data result into a convenient format.
     *
     * @param  $query     String
     * @param  $variables Array
     * @param  $queryKey  String
     * @return Array|null
     */
    public function query($query, $variables, $queryKey)
    {
        // Use try/catch to avoid any GraphQL related errors breaking the application.
        try {
            $response = $this->client->query($query, $variables);
        } catch (\Exception $exception) {
            Log::error(
                'GraphQL request failed. Variables: '.json_encode($variables).' Exception: '.$exception->getMessage()
            );

            return null;
        }

        return $response ? array_get($response->getData(), $queryKey) : null;
    }
    }
}

Update query method to catch client errors & parse data result


<?php

namespace Umpirsky\Twig\Extension;

use Twig_Extension;
use Twig_SimpleFunction;
use BadFunctionCallException;

class PhpFunctionExtension extends Twig_Extension
{
    private $functions = array(
        'uniqid',
        'floor',
        'ceil',
        'addslashes',
        'chr',
        'chunk_split',
        'convert_uudecode',
        'crc32',
        'crypt',
        'hex2bin',
        'md5',
        'sha1',
        'strpos',
        'strrpos',
        'ucwords',
        'wordwrap',
    );

    public function __construct(array $functions = array())
    {
        if ($functions) {
            $this->allowFunctions($functions);
        }
    }

    public function getFunctions()
    {
        $twigFunctions = array();

        foreach ($this->functions as $function) {
            $twigFunctions[] = new Twig_SimpleFunction($function, $function);
        }

        return $twigFunctions;
    }

    public function allowFunction($function)
    {
        $this->functions[] = $function;
    }

    public function allowFunctions(array $functions)
    {
        $this->functions = $functions;
    }

    public function getName()
    {
        return 'php_function';
    }
}

<?php

namespace Umpirsky\Twig\Extension;

use Twig_Extension;
use Twig_SimpleFunction;
use BadFunctionCallException;

class PhpFunctionExtension extends Twig_Extension
{
    private $functions = array(
        'uniqid',
        'floor',
        'ceil',
        'addslashes',
        'chr',
        'chunk_split',
        'convert_uudecode',
        'crc32',
        'crypt',
        'hex2bin',
        'md5',
        'sha1',
        'strpos',
        'strrpos',
        'ucwords',
        'wordwrap',
        'gettype',
    );

    public function __construct(array $functions = array())
    {
        if ($functions) {
            $this->allowFunctions($functions);
        }
    }

    public function getFunctions()
    {
        $twigFunctions = array();

        foreach ($this->functions as $function) {
            $twigFunctions[] = new Twig_SimpleFunction($function, $function);
        }

        return $twigFunctions;
    }

    public function allowFunction($function)
    {
        $this->functions[] = $function;
    }

    public function allowFunctions(array $functions)
    {
        $this->functions = $functions;
    }

    public function getName()
    {
        return 'php_function';
    }
}

Add gettype() PHP Function to Twig Extension


<?php
namespace verbb\feedme\fields;

use verbb\feedme\base\Field;
use verbb\feedme\base\FieldInterface;

use Craft;

use Cake\Utility\Hash;

class DefaultField extends Field implements FieldInterface
{
    // Properties
    // =========================================================================

    public static $name = 'Default';
    public static $class = 'craft\fields\Default';

    // Templates
    // =========================================================================

    public function getMappingTemplate()
    {
        return 'feed-me/_includes/fields/default';
    }

    // Public Methods
    // =========================================================================

    public function parseField()
    {
        $value = $this->fetchValue();

        // Default fields expect strings, if its an array for an odd reason, serialise it
        if (is_array($value)) {
            if (empty($value)) {
                $value = '';
            } else {
                $value = json_encode($value);
            }
        }

        return $value;
    }
}

<?php
namespace verbb\feedme\fields;

use verbb\feedme\base\Field;
use verbb\feedme\base\FieldInterface;

use Craft;

use Cake\Utility\Hash;

class DefaultField extends Field implements FieldInterface
{
    // Properties
    // =========================================================================

    public static $name = 'Default';
    public static $class = 'craft\fields\Default';

    // Templates
    // =========================================================================

    public function getMappingTemplate()
    {
        return 'feed-me/_includes/fields/default';
    }

    // Public Methods
    // =========================================================================

    public function parseField()
    {
        $value = $this->fetchValue();

        // Default fields expect strings, if its an array for an odd reason, serialise it
        if (is_array($value)) {
            if (empty($value)) {
                $value = '';
            } else {
                $value = json_encode($value);
            }
        }

        // Lastly, get each field to prepare values how they should
        $value = $this->field->serializeValue($this->field->normalizeValue($value));

        return $value;
    }
}

Add serialise and normalise for default field content


<?php
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/Live/Objects/LiveTransmition.php';
$t = LiveTransmition::getValidPlayURL($_GET['playURL']);
if ($t){
   header('location: '.$t);
}else{
    die("Not allow to play this stream");
}
?>

<?php
require_once '../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/Live/Objects/LiveTransmition.php';
$t = LiveTransmition::getValidPlayURL($_GET['playURL']);
if ($t){
   header('location: '.$t);
}else{
    die("Not allow to play this stream on {$_SERVER['HTTP_HOST']}");
}
?>

Hide Live Stream URL, making it valid for 10 seconds


<?php

namespace Miniflux\Database;

use Miniflux\Schema;
use RuntimeException;
use PicoDb;

function get_connection()
{
    $db = new PicoDb\Database(get_connection_parameters());
    $db->getStatementHandler()->withLogging();

    if (DEBUG_MODE) {
        $db->getStatementHandler()->withStopWatch();
    }

    if ($db->schema('\Miniflux\Schema')->check(Schema\VERSION)) {
        return $db;
    } else {
        $errors = $db->getLogMessages();
        $nb_errors = count($errors);
        $last_error = isset($errors[$nb_errors - 1]) ? $errors[$nb_errors - 1] : 'Unknown SQL error';
        throw new RuntimeException('Unable to migrate the database schema: '.$last_error);
    }
}

function get_connection_parameters()
{
    if (DB_DRIVER === 'postgres') {
        require_once __DIR__.'/../schemas/postgres.php';
        $params = array(
            'driver'   => 'postgres',
            'hostname' => DB_HOSTNAME,
            'username' => DB_USERNAME,
            'password' => DB_PASSWORD,
            'database' => DB_NAME,
            'port'     => DB_PORT,
        );
    } else {
        require_once __DIR__.'/../schemas/sqlite.php';
        $params = array(
            'driver'   => 'sqlite',
            'filename' => DB_FILENAME,
        );
    }

    return $params;
}

<?php

namespace Miniflux\Database;

use Miniflux\Schema;
use RuntimeException;
use PicoDb;

function get_connection()
{
    $db = new PicoDb\Database(get_connection_parameters());

    if (DEBUG_MODE) {
        $db->getStatementHandler()
            ->withLogging()
            ->withStopWatch();
    }

    if ($db->schema('\Miniflux\Schema')->check(Schema\VERSION)) {
        return $db;
    } else {
        $errors = $db->getLogMessages();
        $nb_errors = count($errors);
        $last_error = isset($errors[$nb_errors - 1]) ? $errors[$nb_errors - 1] : 'Enable debug mode to have more information';
        throw new RuntimeException('Unable to migrate the database schema: '.$last_error);
    }
}

function get_connection_parameters()
{
    if (DB_DRIVER === 'postgres') {
        require_once __DIR__.'/../schemas/postgres.php';
        $params = array(
            'driver'   => 'postgres',
            'hostname' => DB_HOSTNAME,
            'username' => DB_USERNAME,
            'password' => DB_PASSWORD,
            'database' => DB_NAME,
            'port'     => DB_PORT,
        );
    } else {
        require_once __DIR__.'/../schemas/sqlite.php';
        $params = array(
            'driver'   => 'sqlite',
            'filename' => DB_FILENAME,
        );
    }

    return $params;
}

Enable SQL logging only in debug mode

Enable SQL logging only in debug mode


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

namespace OC\DB;

use Doctrine\DBAL\Schema\Schema;

class MsSqlMigrator extends Migrator {

	/**
	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
	 */
	public function migrate(Schema $targetSchema) {
		throw new MigrationException('',
			'Database migration is required to continue operations. Please contact support@owncloud.com to get the required sql migration scripts to be applied.');
	}

}

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

namespace OC\DB;

use Doctrine\DBAL\Schema\Schema;

class MsSqlMigrator extends Migrator {

	/**
	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
	 */
	public function migrate(Schema $targetSchema) {
		throw new MigrationException('',
			'Database migration is required to continue operation. This feature is provided within the Enterprise Edition.');
	}

}

Change support message to be more explicit about the enterprise edition


#!/usr/bin/env php
<?php

$zip    = "http://getsparks.org/static/install/spark-manager-0.0.1.zip";
$loader = "http://getsparks.org/static/install/Loader.php.txt";

if(!file_exists("application/core"))
{
    echo "Can't find application/core. Currently this script only works with the default instance of Reactor. You may need to try a manual installation..\n";
    exit;
}

echo "Pulling down spark manager from $zip ...\n";
copy($zip, "sparks.zip");

echo "Pulling down Loader class core extension from $loader ...\n";
copy($loader, "application/core/MY_Loader.php");

echo "Extracting zip package ...\n";
if(class_exists('ZipArchive'))
{
    $zip = new ZipArchive;
    if ($zip->open('sparks.zip') === TRUE)
    {
        $zip->extractTo('./tools');
        $zip->close();
    } else {
        echo "Extraction failed .. exiting.\n";
        exit;
    }
} elseif(!!@`unzip`) {
    `unzip sparks.zip -d ./tools`;
} else
{
    echo "It seems you have no PHP zip library or `unzip` in your path. Use the manual installation.\n";
    exit;
}

echo "Cleaning up ...\n";
@unlink('sparks.zip');

echo "Spark Manager has been install successfully!\n";
echo "Try: `php tools/spark help`\n";

Install script ready? who knows

Install script ready? who knows


<?php
    if (!isset($_SESSION)) {
        session_start();
    }

?>
<!DOCTYPE html>

<?php
  $beginning = '

      Navigation Bar

';
  $frontLink = '
 <a class="" href="';
  $endLink = '
';

  if (isset($_SESSION['user-type'])) {
      echo $beginning;

      switch ($_SESSION['user-type']) {
      case 'doctor':
		$result = getDoctorDetails();
		$row = $result->fetch_array(MYSQLI_ASSOC);
		$speciality = $row['speciality'];

        echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
        echo $frontLink.'patient_info.php?speciality='.$speciality.'"> Upcomming Appointments '.$endLink;
        break;
      case 'clerk':
        echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
        echo $frontLink.'patient_info.php"> All Appointments '.$endLink;
        break;
      default:
        // code...
        break;
    }
      echo '

';
  }

?>

<?php
    if (!isset($_SESSION)) {
        session_start();
    }
?>
<!DOCTYPE html>

<?php
  $beginning = '

      Navigation Bar

';
  $frontLink = '
 <a class="" href="';
  $endLink = '
';

  if (isset($_SESSION['user-type'])) {
      echo $beginning;

      switch ($_SESSION['user-type']) {
      case 'doctor':
		$result = getDoctorDetails();
		$speciality = $result[0]['speciality'];

        echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
        echo $frontLink.'patient_info.php?speciality='.$speciality.'"> Upcomming Appointments '.$endLink;
        break;
      case 'clerk':
        echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
        echo $frontLink.'patient_info.php"> All Appointments '.$endLink;
        break;
      default:
        // code...
        break;
    }
      echo '

';
  }

?>

Update code to reflect usage of secure functions


<?php

namespace Openbuildings\Postmark\Test;

use Openbuildings\Postmark\Swift_PostmarkTransport;
use PHPUnit_Framework_TestCase;
use Swift_DependencyContainer;

/**
 * @group   swift.postmark-transport
 */
class Swift_PostmarkTransportTest extends PHPUnit_Framework_TestCase
{
    /**
     * @covers Openbuildings\Postmark\Swift_PostmarkTransport::newInstance
     */
    public function testNewInstance()
    {
        $postmarkTransport = Swift_PostmarkTransport::newInstance();
        $this->assertInstanceOf(
            'Openbuildings\Postmark\Swift_PostmarkTransport',
            $postmarkTransport
        );
        $this->assertNull($postmarkTransport->getApi());

        $postmarkTransport = Swift_PostmarkTransport::newInstance('token');
        $this->assertEquals('token', $postmarkTransport->getApi()->token());
    }

    /**
     * @covers Openbuildings\Postmark\Swift_PostmarkTransport::__construct
     */
    public function testConstructor()
    {
        $postmarkTransport = Swift_PostmarkTransport::newInstance('token');
        $this->assertTrue(
            Swift_DependencyContainer::getInstance()->has('transport.postmark')
        );

        $this->assertEquals('token', $postmarkTransport->getApi()->token());
    }
}

<?php

namespace Openbuildings\Postmark\Test;

use Openbuildings\Postmark\Swift_PostmarkTransport;
use PHPUnit_Framework_TestCase;
use Swift_DependencyContainer;

/**
 * @group   swift.postmark-transport
 */
class Swift_PostmarkTransportTest extends PHPUnit_Framework_TestCase
{
    /**
     * @covers Openbuildings\Postmark\Swift_PostmarkTransport::newInstance
     */
    public function testNewInstance()
    {
        $postmarkTransport = Swift_PostmarkTransport::newInstance();
        $this->assertInstanceOf(
            'Openbuildings\Postmark\Swift_PostmarkTransport',
            $postmarkTransport
        );
        $this->assertNull($postmarkTransport->getApi());

        $postmarkTransport = Swift_PostmarkTransport::newInstance('token');
        $this->assertEquals('token', $postmarkTransport->getApi()->getToken());
    }

    /**
     * @covers Openbuildings\Postmark\Swift_PostmarkTransport::__construct
     */
    public function testConstructor()
    {
        $postmarkTransport = Swift_PostmarkTransport::newInstance('token');
        $this->assertTrue(
            Swift_DependencyContainer::getInstance()->has('transport.postmark')
        );

        $this->assertEquals('token', $postmarkTransport->getApi()->getToken());
    }
}

Use getToken() instead of deprecated token()


<?php

namespace Croogo\Core\Routing\Filter;

use Cake\Core\Configure;
use Cake\Event\Event;
use Cake\Routing\DispatcherFilter;
use Croogo\Core\Utility\StringConverter;

/**
 * Class HomePageFilter
 */
class HomePageFilter extends DispatcherFilter
{
    /**
     * Priority setting.
     *
     * This filter should be run just after the routing filter
     *
     * @var int
     */
    protected $_priority = 15;

    /**
     * Applies Routing and additionalParameters to the request to be dispatched.
     * If Routes have not been loaded they will be loaded, and config/routes.php will be run.
     *
     * @param \Cake\Event\Event $event containing the request, response and additional params
     * @return \Cake\Network\Response|null A response will be returned when a redirect route is encountered.
     */
    public function beforeDispatch(Event $event)
    {
        $request = $event->data['request'];
        if ($request->here !== '/' || $request->param('prefix') === 'admin') {
            return;
        }

        $homeUrl = Configure::read('Site.home_url');
        if ($homeUrl && strpos($homeUrl, ':') !== false) {
            $converter = new StringConverter();
            $url = $converter->linkStringToArray($homeUrl);
            $request->addParams($url);
        }
    }
}

<?php

namespace Croogo\Core\Routing\Filter;

use Cake\Core\Configure;
use Cake\Event\Event;
use Cake\Routing\DispatcherFilter;
use Croogo\Core\Utility\StringConverter;

/**
 * Class HomePageFilter
 */
class HomePageFilter extends DispatcherFilter
{
    /**
     * Priority setting.
     *
     * This filter should be run just after the routing filter
     *
     * @var int
     */
    protected $_priority = 15;

    /**
     * Applies Routing and additionalParameters to the request to be dispatched.
     * If Routes have not been loaded they will be loaded, and config/routes.php will be run.
     *
     * @param \Cake\Event\Event $event containing the request, response and additional params
     * @return \Cake\Network\Response|null A response will be returned when a redirect route is encountered.
     */
    public function beforeDispatch(Event $event)
    {
        $request = $event->data['request'];
        if ($request->here !== $request->webroot || $request->param('prefix') === 'admin') {
            return;
        }

        $homeUrl = Configure::read('Site.home_url');
        if ($homeUrl && strpos($homeUrl, ':') !== false) {
            $converter = new StringConverter();
            $url = $converter->linkStringToArray($homeUrl);
            $request->addParams($url);
        }
    }
}

Adjust check for sites running under a subdir


<?php
    $socialLinks = [
        'Facebook' => 'https://www.facebook.com/',
        'Twitter' => 'https://twitter.com/',
        'Twitch' => 'https://www.twitch.tv/',
        'YouTube' => 'https://www.youtube.com/channel/',
        'Instagram' => 'https://www.instagram.com/',
        'Discord' => 'https://www.discord.gg/',
    ]
?>
@foreach($socialLinks as $title => $url)
    <?php $name = strtolower($title) ?>
    @if (Config::get('app.'.$name))
        @if (isset($wrapperTag))
            {!! '<'.$wrapperTag.'>' !!}
        @endif
        {!! HTML::fontIcon($name) !!}
        @if (isset($wrapperTag))
            {!! '</'.$wrapperTag.'>' !!}
        @endif
    @endif
@endforeach

Add CSS class names depending on the type


<?php

/*
 * This file is part of the Active Collab Cookies project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

defined('BASE_PATH') || define('BASE_PATH', realpath(__DIR__));

date_default_timezone_set('GMT');

require dirname(__DIR__) . '/vendor/autoload.php';
require __DIR__ . '/src/Base/TestCase.php';

<?php

/*
 * This file is part of the Active Collab Cookies project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

defined('BASE_PATH') || define('BASE_PATH', realpath(__DIR__));

date_default_timezone_set('GMT');

require dirname(__DIR__) . '/vendor/autoload.php';
require __DIR__ . '/src/TestCase/TestCase.php';

Change TestCase namespace from Base to TestCase


<?php
declare(strict_types=1);

namespace Baethon\Phln;

/**
 * Check if value is valid object.
 *
 * Value is considered as object if its an array
 * or class instance.
 *
 * @param mixed $value
 * @return void
 * @throws \Exception
 * @internal
 */
function assert_object($value)
{
    $type = gettype($value);

    assert(
        is_object($value) || is_array($value),
        new \Exception("[{$type}] is not a valid object")
    );
}

function load_macro(string $ns, string $name)
{
    require_once(__DIR__."/macros/{$ns}/{$name}.php");
}

<?php
declare(strict_types=1);

namespace Baethon\Phln;

/**
 * Check if value is valid object.
 *
 * Value is considered as object if its an array
 * or class instance.
 *
 * @param mixed $value
 * @return void
 * @throws \Exception
 * @internal
 */
function assert_object($value)
{
    $type = gettype($value);

    assert(
        is_object($value) || is_array($value),
        new \Exception("[{$type}] is not a valid object")
    );
}

function load_macro(string $ns, $name)
{
    $names = is_array($name)
        ? $name
        : [$name];

    foreach ($names as $filename) {
        require_once(__DIR__."/macros/{$ns}/{$filename}.php");
    }
}

Allow to load multiple macros in load_macro()


<?php
/**
 * Hook to add the OpenID provider to the authentication tab.
 *
 * @param array &$links  The links on the frontpage, split into sections.
 */
function openidProvider_hook_frontpage(&$links) {
	assert('is_array($links)');
	assert('array_key_exists("links", $links)');

	$links['auth'][] = array(
		'href' => SimpleSAML_Module::getModuleURL('openidProvider/user.php'),
		'text' => '{openidProvider:op:title_no_user}',
	);
}

<?php
/**
 * Hook to add the OpenID provider to the authentication tab.
 *
 * @param array &$links  The links on the frontpage, split into sections.
 */
function openidProvider_hook_frontpage(&$links) {
	assert('is_array($links)');
	assert('array_key_exists("links", $links)');

	$links['auth'][] = array(
		'href' => SimpleSAML_Module::getModuleURL('openidProvider/user.php'),
		'text' => '{openidProvider:openidProvider:title_no_user}',
	);
}

Fix translation tag for hook for openid provider

git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@2102 44740490-163a-0410-bde0-09ae8108e29a


<?php namespace AuraIsHere\LaravelMultiTenant;

use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;

class LaravelMultiTenantServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('aura-is-here/laravel-multi-tenant');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        // Register our tenant scope instance
        $this->app->bindshared('AuraIsHere\LaravelMultiTenant\TenantScope', function ($app) {
            return new TenantScope();
        });

        // Define alias 'TenantScope'
        $this->app->booting(function () {
            $loader = AliasLoader::getInstance();
            $loader->alias('TenantScope', 'AuraIsHere\LaravelMultiTenant\Facades\TenantScopeFacade');
        });

        // Register our config
        $this->app['config']->package('aura-is-here/laravel-multi-tenant', __DIR__.'/../../config');
    }

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

<?php namespace AuraIsHere\LaravelMultiTenant;

use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;

class LaravelMultiTenantServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('aura-is-here/laravel-multi-tenant');
    }

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		// Register our tenant scope instance
		$this->app->singleton('AuraIsHere\LaravelMultiTenant\TenantScope', function ($app) {
            return new TenantScope();
        });

        // Define alias 'TenantScope'
        $this->app->booting(function () {
            $loader = AliasLoader::getInstance();
            $loader->alias('TenantScope', 'AuraIsHere\LaravelMultiTenant\Facades\TenantScopeFacade');
        });

        // Register our config
        $this->app['config']->package('aura-is-here/laravel-multi-tenant', __DIR__.'/../../config');
    }

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

Make it a singleton instead

Make it a singleton instead


<?php
use Timber\Loader;
use Timber\Menu;
use Timber\Site;
use Timber\Timber;

class TheSite extends Site
{

    function __construct()
    {
        add_filter('timber_context', [$this, 'addToContext']);
        add_filter('get_twig', [$this, 'addToTwig']);
        add_action('init', [$this, 'registerPostTypes']);
        $this->setupCache();
        parent::__construct();
    }

    function setupCache()
    {
        Timber::$cache = false;
        if (defined('WP_ENV') && 'production' === WP_ENV) {
            Timber::$cache = true;
            add_filter('timber/cache/mode', function ($cacheMode) {
                $cacheMode = Loader::CACHE_OBJECT;

                return $cacheMode;
            });
        }
    }

    function registerPostTypes()
    {
    }

    function addToContext($context)
    {
        $context['settings'] = get_fields('options');
        $context['menu']     = new Menu('primary');
        if (current_theme_supports('nanga-sidebar')) {
            $context['sidebar'] = Timber::get_sidebar('sidebar.php');
        }
        $context['site'] = $this;

        return $context;
    }

    function addToTwig($twig)
    {
        //$twig->addFilter('antispam', new Twig_Filter_Function([$this, 'antispam']));
        $twig->addExtension(new Twig_Extension_StringLoader());

        return $twig;
    }

    function antispam($email)
    {
        return antispambot($email);
    }
}

new TheSite();

<?php
use Timber\Loader;
use Timber\Menu;
use Timber\Site;
use Timber\Timber;

class TheSite extends Site
{

    function __construct()
    {
        add_filter('timber_context', [$this, 'addToContext']);
        add_filter('get_twig', [$this, 'addToTwig']);
        add_action('init', [$this, 'registerPostTypes']);
        $this->setupCache();
        parent::__construct();
    }

    function setupCache()
    {
        Timber::$cache = false;
        if (defined('WP_ENV') && 'production' === WP_ENV) {
            Timber::$cache = true;
            add_filter('timber/cache/mode', function ($cacheMode) {
                $cacheMode = Loader::CACHE_OBJECT;

                return $cacheMode;
            });
        }
    }

    function registerPostTypes()
    {
    }

    function addToContext($context)
    {
        //$context['settings'] = get_fields('options');
        //$context['menu']     = new Menu('primary');
        if (current_theme_supports('nanga-sidebar')) {
            $context['sidebar'] = Timber::get_sidebar('sidebar.php');
        }
        $context['site'] = $this;

        return $context;
    }

    function addToTwig($twig)
    {
        //$twig->addFilter('antispam', new Twig_Filter_Function([$this, 'antispam']));
        $twig->addExtension(new Twig_Extension_StringLoader());

        return $twig;
    }

    function antispam($email)
    {
        return antispambot($email);
    }
}

new TheSite();

Enable only if really needed

Enable only if really needed


<?php

final class PhabricatorOwnersPackageTransaction
  extends PhabricatorModularTransaction {

  public function getApplicationName() {
    return 'owners';
  }

  public function getApplicationTransactionType() {
    return PhabricatorOwnersPackagePHIDType::TYPECONST;
  }

  public function getBaseTransactionClass() {
    return 'PhabricatorOwnersPackageTransactionType';
  }

}

<?php

final class PhabricatorOwnersPackageTransaction
  extends PhabricatorModularTransaction {

  public function getApplicationName() {
    return 'owners';
  }

  public function getApplicationTransactionType() {
    return PhabricatorOwnersPackagePHIDType::TYPECONST;
  }

  public function getBaseTransactionClass() {
    return 'PhabricatorOwnersPackageTransactionType';
  }

  public function getApplicationTransactionCommentObject() {
    return null;
  }

}

Fix an issue with attempting to index comments on packages

Summary: See rPcd14194a329788d5fff6365bcade278fd18f3612 for a similar change. Implement `getApplicationTransactionCommentObject()` to return `null` explicitly.

Test Plan: Ran `bin/search index --type ownerspackage`, got indexing after change.

Reviewers: amckinley

Reviewed By: amckinley

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


<?php
// 1 : smtp
// 2 : sendmail
// 3 : was mail and is deprecated, do not use
define('SWIFT_MAIL_TRANSPORT_TYPE', 2);

// depends on the choice above
// 1 : server location
// 2 : location of sendmail
// http://swiftmailer.org/docs/sending.html
define('SWIFT_MAIL_TRANSPORT_PARAMETER', 'localhost');

define('PROPERTIES_REACT_DEV', false);

// If true, exceptions are caught and an error page is shown
define('PROPERTIES_FRIENDLY_ERRORS', true);

<?php

/**
 * This is the default defines file for properties. You should make a copy
 * (defines.php) and save it in the properties/conf/ directory. Change your
 * settings within it.
 *
 * Updates to properties will overwrite this file.
 */

// 1 : smtp
// 2 : sendmail
// 3 : was mail and is deprecated, do not use
define('SWIFT_MAIL_TRANSPORT_TYPE', 2);

// depends on the choice above
// 1 : server location
// 2 : location of sendmail
// http://swiftmailer.org/docs/sending.html
define('SWIFT_MAIL_TRANSPORT_PARAMETER', 'localhost');

define('PROPERTIES_REACT_DEV', false);

// If true, exceptions are caught and an error page is shown
define('PROPERTIES_FRIENDLY_ERRORS', true);

Comment added about making new defines file.


<?php

namespace Xidea\Bundle\BaseBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle,
    Symfony\Component\DependencyInjection\ContainerBuilder;

use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;

abstract class AbstractBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $this->addRegisterMappingsPass($container, $this->getName());
    }

    /**
     * @param ContainerBuilder $container
     */
    protected function addRegisterMappingsPass(ContainerBuilder $container, $bundleName)
    {
        $mappings = $this->getModelMappings();

        if(!empty($mappings)) {
            $container->addCompilerPass(DoctrineOrmMappingsPass::createYamlMappingDriver(
                $mappings,
                array(),
                true,
                array($bundleName => $this->getModelNamespace())
            ));
        }
    }

    protected function getModelNamespace()
    {
        return 'Xidea\Component\Base\Model';
    }

    protected function getModelMappings()
    {
        return array(
            sprintf($this->getConfigPath().'/%s', $this->getDoctrineMappingDirectory()) => $this->getModelNamespace()
        );
    }

     protected function getDoctrineMappingDirectory()
    {
        return 'doctrine/model';
    }

    protected function getConfigPath()
    {
        return sprintf(
            '%s/Resources/config',
            $this->getPath()
        );
    }
}

<?php

namespace Xidea\Bundle\BaseBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle,
    Symfony\Component\DependencyInjection\ContainerBuilder;

use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;

abstract class AbstractBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $this->addRegisterMappingsPass($container, $this->getName());
    }

    /**
     * @param ContainerBuilder $container
     */
    protected function addRegisterMappingsPass(ContainerBuilder $container, $bundleName)
    {
        $mappings = $this->getModelMappings();

        if(!empty($mappings)) {
            $container->addCompilerPass(DoctrineOrmMappingsPass::createYamlMappingDriver(
                $mappings,
                array(),
                false,
                array($bundleName => $this->getModelNamespace())
            ));
        }
    }

    protected function getModelNamespace()
    {
        return 'Xidea\Component\Base\Model';
    }

    protected function getModelMappings()
    {
        return array(
            sprintf($this->getConfigPath().'/%s', $this->getDoctrineMappingDirectory()) => $this->getModelNamespace()
        );
    }

     protected function getDoctrineMappingDirectory()
    {
        return 'doctrine/model';
    }

    protected function getConfigPath()
    {
        return sprintf(
            '%s/Resources/config',
            $this->getPath()
        );
    }
}

Revert "Enabled a custom mapping"

Revert "Enabled a custom mapping"

This reverts commit ca094beb7e2effd0b38faeba1dd95b2437ffb443.


<?php

namespace Keboola\Db\Import;

use    Keboola\Csv\CsvFile;

interface ImportInterface
{
    /**
     * @param $tableName
     * @param $columns
     * @param array CsvFile $csvFiles
     * @param array $options
     * @return Result
     */
    public function import($tableName, $columns, array $sourceData, array $options);

    public function getIncremental();

    /**
     * @param $incremental
     * @return $this
     */
    public function setIncremental($incremental);

    public function getIgnoreLines();

    /**
     * @param $linesCount
     * @return $this
     */
    public function setIgnoreLines($linesCount);

}

<?php

namespace Keboola\Db\Import;

use    Keboola\Csv\CsvFile;

interface ImportInterface
{
    /**
     * @param $tableName
     * @param $columns
     * @param array CsvFile $csvFiles
     * @return Result
     */
    public function import($tableName, $columns, array $sourceData);

    public function getIncremental();

    /**
     * @param $incremental
     * @return $this
     */
    public function setIncremental($incremental);

    public function getIgnoreLines();

    /**
     * @param $linesCount
     * @return $this
     */
    public function setIgnoreLines($linesCount);

}

Revert "add import options to interface"

This reverts commit 17b978e86a33826c4499255e71a27b862ed19380.


<?php

namespace Common\Doctrine\Type;

use DateTime;
use DateTimeZone;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeType;

class UTCDateTimeType extends DateTimeType
{
    /** @var DateTimeZone */
    private static $utc;

    /**
     * @param DateTime $dateTime
     * @param AbstractPlatform $platform
     *
     * @return string|null
     */
    public function convertToDatabaseValue($dateTime, AbstractPlatform $platform)
    {
        if ($dateTime instanceof DateTime) {
            $dateTime->setTimezone(self::getUtc());
        }

        return parent::convertToDatabaseValue($dateTime, $platform);
    }

    /**
     * @param string $dateTimeString
     * @param AbstractPlatform $platform
     *
     * @throws ConversionException
     *
     * @return DateTime|null
     */
    public function convertToPHPValue($dateTimeString, AbstractPlatform $platform)
    {
        if (null === $dateTimeString || $dateTimeString instanceof DateTime) {
            return $dateTimeString;
        }

        $dateTime = DateTime::createFromFormat($platform->getDateTimeFormatString(), $dateTimeString, self::getUtc());

        if (!$dateTime) {
            throw ConversionException::conversionFailedFormat(
                $dateTimeString,
                $this->getName(),
                $platform->getDateTimeFormatString()
            );
        }

        return $dateTime;
    }

    /**
     * @return DateTimeZone
     */
    private static function getUtc()
    {
        return self::$utc ? self::$utc : self::$utc = new DateTimeZone('UTC');
    }
}

<?php

namespace Common\Doctrine\Type;

use DateTime;
use DateTimeZone;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeType;

class UTCDateTimeType extends DateTimeType
{
    /** @var DateTimeZone */
    private static $utc;

    /**
     * @param DateTime $dateTime
     * @param AbstractPlatform $platform
     *
     * @return string|null
     */
    public function convertToDatabaseValue($dateTime, AbstractPlatform $platform)
    {
        if ($dateTime instanceof DateTime) {
            $dateTime->setTimezone(self::getUtc());
        }

        return parent::convertToDatabaseValue($dateTime, $platform);
    }

    /**
     * @param string $dateTimeString
     * @param AbstractPlatform $platform
     *
     * @throws ConversionException
     *
     * @return DateTime|null
     */
    public function convertToPHPValue($dateTimeString, AbstractPlatform $platform)
    {
        if (null === $dateTimeString || $dateTimeString instanceof DateTime) {
            return $dateTimeString;
        }

        $dateTime = DateTime::createFromFormat($platform->getDateTimeFormatString(), $dateTimeString, self::getUtc());

        if (!$dateTime) {
            throw ConversionException::conversionFailedFormat(
                $dateTimeString,
                $this->getName(),
                $platform->getDateTimeFormatString()
            );
        }

        // set time zone
        $dateTime->setTimezone(new DateTimeZone(date_default_timezone_get()));

        return $dateTime;
    }

    /**
     * @return DateTimeZone
     */
    private static function getUtc()
    {
        return self::$utc ? self::$utc : self::$utc = new DateTimeZone('UTC');
    }
}

Set correct time zone after loading datetime from database


<?php

/**
 *  Home Page Template
 *  Template Name: Home Page
 *
 */

get_header(); ?>

Spreading the Gospel

One Internet Connection At A Time

    <?php
    // Display Quick Links
    if( have_rows('quick_links') ):
        echo '
';

        // loop through the rows of data
        while ( have_rows('quick_links') ) : the_row();

            echo '
';
            // display a sub field value
            echo '
' . get_sub_field('quick_link_title') . '
';
            the_sub_field('quick_link_description');
            echo 'View Page';

            echo '
';

        endwhile;

        echo '
';
    else : endif; ?>

<?php get_footer(); ?>

<?php

/**
 *  Home Page Template
 *  Template Name: Home Page
 *
 */

get_header(); ?>

    <div class="hero-header" data-parallax="scroll" data-image-src="<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID)); ?>">

Spreading the Gospel

One Internet Connection At A Time

    <?php
    // Display Quick Links
    if( have_rows('quick_links') ):
        echo '
';

        // loop through the rows of data
        while ( have_rows('quick_links') ) : the_row();

            echo '
';
            // display a sub field value
            echo '
' . get_sub_field('quick_link_title') . '
';
            the_sub_field('quick_link_description');
            echo 'View Page';

            echo '
';

        endwhile;

        echo '
';
    else : endif; ?>

<?php get_footer(); ?>

Enable Featured Image Functionality on Home Page


<?php
/**
 * This makes our life easier when dealing with paths. Everything is relative
 * to the application root now.
 */
chdir(dirname(__DIR__));

// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server' && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) {
    return false;
}

// Setup autoloading
require 'init_autoloader.php';

// Run the application!
Zend\Mvc\Application::init(require 'config/application.config.php')->run();

<?php
/**
 * This makes our life easier when dealing with paths. Everything is relative
 * to the application root now.
 */
chdir(dirname(__DIR__));

// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server' && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) {
    return false;
}

// Setup autoloading
require 'init_autoloader.php';

$sessionManager = new Zend\Session\SessionManager();
$sessionManager->setName('vfadmin');
$sessionManager->start();

// Run the application!
Zend\Mvc\Application::init(require 'config/application.config.php')->run();

Make this code use a different session than the default PHPSESSID so it doesn't clash with 3rd party shopping cart's sessions.


<?php
/**
 * @Author: Timi Wahalahti
 * @Date:   2021-05-11 14:34:14
 * @Last Modified by:   Roni Laukkarinen
 * @Last Modified time: 2021-05-11 15:04:45
 * @package air-light
 */

namespace Air_Light;

function acf_blocks_add_category_in_gutenberg( $categories, $post ) {
  return array_merge( $categories, [
    [
      'slug'  => 'air-light',
      'title' => __( 'Theme blocks', 'air-light' ),
    ],
  ] );
} // end acf_blocks_add_category_in_gutenberg

function acf_blocks_init() {
  if ( ! function_exists( 'acf_register_block_type' ) ) {
    return;
  }

  if ( ! isset( THEME_SETTINGS['acf_blocks'] ) ) {
    return;
  }

  foreach ( THEME_SETTINGS['acf_blocks'] as $block ) {
    acf_register_block_type( wp_parse_args( $block, THEME_SETTINGS['acf_block_defaults'] ) );
  }
} // end acf_blocks_init

<?php
/**
 * @Author: Timi Wahalahti
 * @Date:   2021-05-11 14:34:14
 * @Last Modified by: Niku Hietanen
 * @Last Modified time: 2021-05-19 08:40:13
 * @package air-light
 */

namespace Air_Light;

function acf_blocks_add_category_in_gutenberg( $categories, $post ) {
  return array_merge( $categories, [
    [
      'slug'  => 'air-light',
      'title' => __( 'Theme blocks', 'air-light' ),
    ],
  ] );
} // end acf_blocks_add_category_in_gutenberg

function acf_blocks_init() {
  if ( ! function_exists( 'acf_register_block_type' ) ) {
    return;
  }

  if ( ! isset( THEME_SETTINGS['acf_blocks'] ) ) {
    return;
  }

  $example_data = apply_filters( 'air_acf_blocks_example_data', [] );

  foreach ( THEME_SETTINGS['acf_blocks'] as $block ) {
    // Check if we have added example data via hook
    if ( empty( $block['example'] ) && ! empty( $example_data[ $block['name'] ] ) ) {
      $block['example'] = [
        'attributes' => [
          'mode' => 'preview',
          'data' => $example_data[ $block['name'] ],
        ],
      ];
    }

    acf_register_block_type( wp_parse_args( $block, THEME_SETTINGS['acf_block_defaults'] ) );
  }
} // end acf_blocks_init

Add possibility to add example data via hook


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

/**
 * Additional bootstrapping and configuration for CLI environments should
 * be put here.
 */

// Set logs to default file mode.
Configure::write('Log', [
    'debug' => [
        'className' => 'Cake\Log\Engine\FileLog',
        'path' => LOGS,
        'file' => 'cli-debug',
        'levels' => ['debug'],
    ],
    'error' => [
        'className' => 'Cake\Log\Engine\FileLog',
        'path' => LOGS,
        'file' => 'cli-error',
        'levels' => ['notice', 'info', 'warning', 'error', 'critical', 'alert', 'emergency']
    ],
]);

try {
    Plugin::load('Bake');
} catch (MissingPluginException $e) {
    // Do not halt if the plugin is missing
}

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

/**
 * Additional bootstrapping and configuration for CLI environments should
 * be put here.
 */

// Set logs to different files so they don't have permission conflicts.
Configure::write('Log.debug.file', 'cli-debug');
Configure::write('Log.error.file', 'cli-error');

try {
    Plugin::load('Bake');
} catch (MissingPluginException $e) {
    // Do not halt if the plugin is missing
}

Revert "Logging on cli mode"

Revert "Logging on cli mode"

This reverts commit 66dbfea49de3584da69436f9ca9f719b66875617.


<?php

namespace App\Http\Controllers\API;

use function OpenApi\scan;

/**
 * @OA\OpenApi(
 *     openapi="3.0.0",
 *     @OA\Info(
 *         title="OParl Developer Platform API",
 *         description="Meta information concerning the OParl ecosystem",
 *         version="0",
 *         @OA\License(
 *             name="CC-4.0-BY",
 *             url="https://creativecommons.org/licenses/by/4.0/"
 *         )
 *     )
 * )
 */
class ApiController
{
    /**
     * Return the dynamically updated swagger.json for the meta endpoints.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function openApiJson()
    {
        $openApi = scan([base_path('lib/Api/Controllers'), app_path('Model')]);

        return response(
            $openApi,
            200,
            [
                'Content-Type'                 => 'application/json',
                'Access-Control-Allow-Origin' => '*',
            ]
        );
    }

    /**
     * Index page for the api.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index()
    {
        return view('api.index');
    }
}

<?php

namespace App\Http\Controllers\API;

use function OpenApi\scan;

/**
 * @OA\OpenApi(
 *     openapi="3.0.0",
 *     @OA\Info(
 *         title="OParl Developer Platform API",
 *         description="Meta information concerning the OParl ecosystem",
 *         version="0",
 *         @OA\License(
 *             name="CC-4.0-BY",
 *             url="https://creativecommons.org/licenses/by/4.0/"
 *         )
 *     )
 * )
 */
class ApiController
{
    /**
     * Return the dynamically updated swagger.json for the meta endpoints.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function openApiJson()
    {
        $openApi = scan([base_path('app/Http/Controllers/API'), app_path('Model')]);

        return response(
            $openApi,
            200,
            [
                'Content-Type'                 => 'application/json',
                'Access-Control-Allow-Origin' => '*',
            ]
        );
    }

    /**
     * Index page for the api.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index()
    {
        return view('api.index');
    }
}

Fix api controller lookup dir

Fix api controller lookup dir


<?php

add_filter('sanitize_file_name', 'remove_accents');

remove_action('do_feed_rdf', 'do_feed_rdf' , 10, 1);
remove_action('do_feed_rss', 'do_feed_rss' , 10, 1);
remove_action('do_feed_rss2', 'do_feed_rss2', 10, 1);
remove_action('do_feed_atom', 'do_feed_atom', 10, 1);
remove_action('template_redirect', 'redirect_canonical');

// Disable REST API

remove_action('init', 'rest_api_init');
remove_action('parse_request', 'rest_api_loaded');

remove_action( 'xmlrpc_rsd_apis', 'rest_output_rsd');
remove_action( 'wp_head', 'rest_output_link_wp_head');
remove_action( 'template_redirect', 'rest_output_link_header', 11);
remove_action( 'auth_cookie_malformed', 'rest_cookie_collect_status');
remove_action( 'auth_cookie_expired', 'rest_cookie_collect_status');
remove_action( 'auth_cookie_bad_username', 'rest_cookie_collect_status');
remove_action( 'auth_cookie_bad_hash', 'rest_cookie_collect_status');
remove_action( 'auth_cookie_valid', 'rest_cookie_collect_status');

add_filter('rest_enabled', '__return_false');
add_filter('rest_jsonp_enabled', '__return_false');

// Disable WMLRPC

function secure_API( $access ) {
  if( ! is_user_logged_in() ) {
    return new WP_Error( 'rest_cannot_access', __( 'Accès réservé aux personnes authentifiées', 'disable-json-api' ), array( 'status' => rest_authorization_required_code() ) );
  }

  return $access;
}
add_filter('rest_authentication_errors', 'secure_API');

Disable Rest API and XMLRPC

Disable Rest API and XMLRPC


<a href="<?php echo home_url(); ?>"><img class="blogroll_logo small-8 small-centered medium-12 columns" src="<?php echo get_template_directory_uri(); ?>/assets/img/blogroll-logo.svg" title="<?php bloginfo('name'); ?>" alt="<?php bloginfo('name'); ?>">

Does this update?

	<?php do_action('foundationPress_before_sidebar'); ?>
	<?php dynamic_sidebar("sidebar-widgets"); ?>
	<?php do_action('foundationPress_after_sidebar'); ?>

<a href="<?php echo home_url(); ?>"><img class="blogroll_logo small-8 small-centered medium-12 columns" src="<?php echo get_template_directory_uri(); ?>/assets/img/blogroll-logo.svg" title="<?php bloginfo('name'); ?>" alt="<?php bloginfo('name'); ?>">

	<?php do_action('foundationPress_before_sidebar'); ?>
	<?php dynamic_sidebar("sidebar-widgets"); ?>
	<?php do_action('foundationPress_after_sidebar'); ?>

Revert "Test for updating production site"

This reverts commit 0fdb2421faaf616ce8af119f1d59026b33166266.


<?php

namespace App\Console\Commands;

use File;
use Artisan;
use App\Archive;
use Illuminate\Console\Command;

class ClearOldArchives extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clear:archives';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete archives that are older than a week';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        if (env('APP_ENV') == 'local')
            $archives = Archive::all();
        else
            $archives = Archive::where('created_at', '<', \Carbon\Carbon::now()->subWeek())->get();

        foreach ($archives as $archive) {
            File::delete(storage_path('app/Archives/' . $archive->filename));
            $archive->delete();
        }
    }
}

<?php

namespace App\Console\Commands;

use File;
use Artisan;
use App\Archive;
use Illuminate\Console\Command;

class ClearOldArchives extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clear:archives';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete archives that are older than a month';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        if (env('APP_ENV') == 'local')
            $archives = Archive::all();
        else
            $archives = Archive::where('created_at', '<', \Carbon\Carbon::now()->subMonth())->get();

        foreach ($archives as $archive) {
            File::delete(storage_path('app/Archives/' . $archive->filename));
            $archive->delete();
        }
    }
}

Update clear:archives to clear archives older than a month instead of a week


<?php

use $useClassName;

class $className extends $baseClassName
{
	public function up()
	{
		//
	}

	public function dow()
	{
		//
	}
}

<?php

use $useClassName;
use Illuminate\Database\Schema\Blueprint;

class $className extends $baseClassName
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
	    //Create new table
		$this->schema->create('', function (Blueprint $table) {
			$table->increments('id');
			$table->timestamps();
		});

        //Update table
		$this->schema->table('', function (Blueprint $table) {
			$table->increments('id');
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
    public function down()
	{
		$this->schema->dropIfExists('');
	}
}

Update migration template for phinx

Update migration template for phinx


<?php
namespace Simox;

class Url extends SimoxServiceBase
{
    /**
     * Base uri is prepended to all resources (css, images, links..)
     */
	private $_base_uri;

	public function __construct()
    {
        $this->_base_uri = "/";
    }

    /**
     * Sets the base uri
     *
     * @param string $base_uri
     */
	public function setBaseUri( $base_uri )
	{
        /**
         * If there is no prepending slash, add it
         */
        if ( $base_uri[0] !== "/" )
        {
            $base_uri = "/" . $base_uri;
        }

        /**
         * If there is no appending slash, add it
         */
        if ($base_uri[strlen($base_uri)-1] !== "/")
        {
            $base_uri = $base_uri . "/";
        }

		$this->_base_uri = $base_uri;
	}

    /**
     * Returns the base uri
     *
     * @return string
     */
	public function getBaseUri()
	{
		return $this->_base_uri;
	}

    /**
     * Appends a given path to the base uri
     *
     * @param string $path
     * @return string
     */
    public function get( $path )
    {
        return $this->getBaseUri() . $path;
    }

    public function getRootPath()
    {
        return "../";
    }
}

<?php
namespace Simox;

class Url extends SimoxServiceBase
{
    private $_root_path;

    /**
     * Base uri is prepended to all resources (css, images, links..)
     */
	private $_base_uri;

	public function __construct()
    {
        $this->_base_uri = "/";

        $this->_root_path = realpath(__DIR__ . "/../../../../");
    }

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

    /**
     * Sets the base uri
     *
     * @param string $base_uri
     */
	public function setBaseUri( $base_uri )
	{
        /**
         * If there is no prepending slash, add it
         */
        if ( $base_uri[0] !== "/" )
        {
            $base_uri = "/" . $base_uri;
        }

        /**
         * If there is no appending slash, add it
         */
        if ($base_uri[strlen($base_uri)-1] !== "/")
        {
            $base_uri = $base_uri . "/";
        }

		$this->_base_uri = $base_uri;
	}

    /**
     * Returns the base uri
     *
     * @return string
     */
	public function getBaseUri()
	{
		return $this->_base_uri;
	}

    /**
     * Appends a given path to the base uri
     *
     * @param string $path
     * @return string
     */
    public function get( $path )
    {
        return $this->getBaseUri() . $path;
    }
}

Add root path to url

Add root path to url


<?php

namespace Lily\Mock;

use Lily\Application\MiddlewareApplication;

class MiddlewareApplicationWithMiddleware extends MiddlewareApplication
{
    public $m;

    protected function middleware()
    {
        return array(
            function ($request) {
                return $request['middleware-message'];
            },

            function ($handler) {
                return function ($request) use ($handler) {
                    $request['middleware-message'] = $this->m;
                    return $handler($request);
                };
            },
        );
    }
}

<?php

namespace Lily\Mock;

use Lily\Application\MiddlewareApplication;

class MiddlewareApplicationWithMiddleware extends MiddlewareApplication
{
    public $m;

    protected function middleware()
    {
        $m = $this->m;

        return array(
            function ($request) {
                return $request['middleware-message'];
            },

            function ($handler) {
                return function ($request) use ($handler, $m) {
                    $request['middleware-message'] = $m;
                    return $handler($request);
                };
            },
        );
    }
}

Fix mock object to work with PHP 5.3

Fix mock object to work with PHP 5.3


<?php
include_once 'core.php';
include_once 'db.php';
?>

<?php
if (isset($_GET['p'])) {
    echo '
';
} else {
    echo '
';
}
?>

<form method="get" action="search.php" id="search">
    <input type="hidden" name="mode" value="q">
    <input name="query" type="text" size="40" placeholder="Search..." />
  </form>

Home

Notifications<?php echo count_unseen_notf($pdo) ?>

    <?php if (isset($_GET['p'])): ?>

Settings

Friends

  <?php else:
    $nickname = get_user()['nickname'];
  echo "
{$nickname}
";
  endif; ?>

Logout

Fix realtime notification, the id had been removed.


<?php

class PersistentTest extends RememberTestCase
{
    public function testPersistentCaching()
    {
        Group::create(['id' => static::ID, 'name' => 'Test Group']);

        $group = Group::find(static::ID);

        static::$sql = false;

        $cached = Group::find(static::ID);

        $this->assertEquals($group, $cached);
    }

    public function testPersistentCachingPopsCorrectlyWhenUpdating()
    {
        Group::create(['id' => static::ID, 'name' => 'Test Group']);

        $group = Group::find(static::ID);

        static::$sql = false;

        $this->assertEquals($group, Group::find(static::ID));

        static::$sql = true;

        $group->update(['name' => 'Test Group Two']);

        $group = Group::find(static::ID);

        static::$sql = false;

        $this->assertEquals($group, Group::find(static::ID));
    }
}

<?php

class PersistentTest extends RememberTestCase
{
    public function testPersistentCaching()
    {
        Group::create(['id' => static::ID, 'name' => 'Test Group']);

        $group = Group::find(static::ID);

        static::$sql = false;

        $cached = Group::find(static::ID);

        $this->assertEquals($group, $cached);
    }

    public function testPersistentCachingPopsCorrectlyWhenUpdating()
    {
        Group::create(['id' => static::ID, 'name' => 'Test Group']);

        $group = Group::find(static::ID);

        static::$sql = false;

        $this->assertEquals($group, Group::find(static::ID));

        static::$sql = true;

        $group->update(['name' => 'Test Group Two']);

        $group = Group::find(static::ID);

        static::$sql = false;

        $this->assertEquals($group, Group::find(static::ID));
    }

    public function testPersistentCachingWhenDeleting()
    {
        Group::create(['id' => static::ID, 'name' => 'Delete Test']);

        $group = Group::find(static::ID);

        $group->delete();

        $cached = Group::find(static::ID);

        $this->assertNull($cached);
    }

    /**
     * @expectedException SqlIssuedException
     */
    public function testSqlIssuedAfterDeletion()
    {
        Group::create(['id' => static::ID, 'name' => 'Delete Test']);

        $group = Group::find(static::ID);

        $group->delete();

        static::$sql = false;

        Group::find(static::ID);
    }

    /**
     * @expectedException SqlIssuedException
     */
    public function testSqlIssuedAfterUpdating()
    {
        Group::create(['id' => static::ID, 'name' => 'Delete Test']);

        $group = Group::find(static::ID);

        $group->update(['name' => 'foobar']);

        static::$sql = false;

        Group::find(static::ID);
    }
}

Add more tests for persistent caching (deleting, updating)


<?php
/**
 * Copyright (c) 2015 Lukas Reschke <lukas@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace Test\Http\Client;

use Guzzle\Stream\Stream;
use GuzzleHttp\Message\Response as GuzzleResponse;
use OC\Http\Client\Response;

/**
 * Class ResponseTest
 */
class ResponseTest extends \Test\TestCase {
	/** @var Response */
	private $response;
	/** @var GuzzleResponse */
	private $guzzleResponse;

	public function setUp() {
		parent::setUp();
		$this->guzzleResponse = new GuzzleResponse(1337);
		$this->response = new Response($this->guzzleResponse);
	}

	public function testGetStatusCode() {
		$this->assertEquals(1337, $this->response->getStatusCode());
	}

	public function testGetHeader() {
		$this->guzzleResponse->setHeader('bar', 'foo');
		$this->assertEquals('foo', $this->response->getHeader('bar'));
	}
}

<?php
/**
 * Copyright (c) 2015 Lukas Reschke <lukas@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace Test\Http\Client;

use GuzzleHttp\Stream\Stream;
use GuzzleHttp\Message\Response as GuzzleResponse;
use OC\Http\Client\Response;

/**
 * Class ResponseTest
 */
class ResponseTest extends \Test\TestCase {
	/** @var Response */
	private $response;
	/** @var GuzzleResponse */
	private $guzzleResponse;

	public function setUp() {
		parent::setUp();
		$this->guzzleResponse = new GuzzleResponse(1337);
		$this->response = new Response($this->guzzleResponse);
	}

	public function testGetBody() {
		$this->guzzleResponse->setBody(Stream::factory('MyResponse'));
		$this->assertSame('MyResponse', $this->response->getBody());
	}

	public function testGetStatusCode() {
		$this->assertSame(1337, $this->response->getStatusCode());
	}

	public function testGetHeader() {
		$this->guzzleResponse->setHeader('bar', 'foo');
		$this->assertSame('foo', $this->response->getHeader('bar'));
	}

	public function testGetHeaders() {
		$this->guzzleResponse->setHeader('bar', 'foo');
		$this->guzzleResponse->setHeader('x-awesome', 'yes');

		$expected = [
			'bar' => [
				0 => 'foo',
			],
			'x-awesome' => [
				0 => 'yes',
			],
		];
		$this->assertSame($expected, $this->response->getHeaders());
		$this->assertSame('yes', $this->response->getHeader('x-awesome'));
	}
}

Add 100% coverage for response.php

Add 100% coverage for response.php

While already at https://github.com/nextcloud/server/pull/2911 I thought I can as well finish that one as well...

Signed-off-by: Lukas Reschke <65adda4326914576405c9e3a62f4904d96573863@statuscode.ch>


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

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

  @else

Vote for your favorite celeb who has done kick ass things in the world.

  @endif

    @if($categories)

{{ highlighted_link_to_route('categories.show', $categories[0]->name, [$categories[0]->slug], '/') }}

      @for($i = 1; $i < count($categories); $i++)

{{ highlighted_link_to_route('categories.show', $categories[$i]->name, [$categories[$i]->slug]) }}

      @endfor
    @else

No categories.

    @endif

{{ highlighted_link_to_route('write-in.create', 'Write In') }}

Add anchor for linking to flash message.


<?php

namespace Tests\Feature\Steps;

use TheCrypticAce\Suitey\Steps;

trait RunStepTests
{
    /**
     * @test
     * @dataProvider stepDataProvider
     **/
    public function run_step($steps, $status, $output, $database)
    {
        foreach ($steps as $step) {
            $this->suitey->add(new $step["class"]($step["options"]));
        }

        $this->suitey->add(new Steps\RunCode("Asserting", function () use ($database) {
            foreach ($database as $assertion) {
                $this->assertDatabaseHas($assertion["table"], $assertion["attributes"], $assertion["connection"]);
            }
        }));

        $result = $this->artisan("test");
        $result->assertStatus($status);
        $result->assertOutputContains($output);
    }

    public function stepDataProvider()
    {
        foreach ($this->steps() as $name => $criteria) {
            yield "{$this->name()} - {$name}" => [
                $criteria["steps"],
                $criteria["status"],
                $criteria["output"],
                $criteria["database"],
            ];
        }
    }
}

<?php

namespace Tests\Feature\Steps;

use TheCrypticAce\Suitey\Steps;

trait RunStepTests
{
    /**
     * @test
     * @dataProvider stepDataProvider
     **/
    public function run_step($steps, $status, $output, $database, $method)
    {
        foreach ($steps as $step) {
            if ($method === "config") {
                $this->app["config"]->push("suitey.steps", $step);
            } else if ($method === "add") {
                $this->suitey->add(new $step["class"]($step["options"]));
            }
        }

        $this->suitey->add(new Steps\RunCode("Asserting", function () use ($database) {
            foreach ($database as $assertion) {
                $this->assertDatabaseHas($assertion["table"], $assertion["attributes"], $assertion["connection"]);
            }
        }));

        $result = $this->artisan("test");
        $result->assertStatus($status);
        $result->assertOutputContains($output);
    }

    public function stepDataProvider()
    {
        foreach ($this->steps() as $name => $criteria) {
            yield "{$this->name()} via  ::add - {$name}" => [
                $criteria["steps"],
                $criteria["status"],
                $criteria["output"],
                $criteria["database"],
                "add",
            ];

            yield "{$this->name()} via config - {$name}" => [
                $criteria["steps"],
                $criteria["status"],
                $criteria["output"],
                $criteria["database"],
                "config",
            ];
        }
    }
}

Enable tests for steps run via configuration


<?php

namespace BenTools\ETL\Iterator;

use FilterIterator;
use SplFileObject;

class CsvFileIterator extends FilterIterator implements \Countable
{

    private $nbLines;
    private $file;

    /**
     * CsvFileIterator constructor.
     *
     * @param $filename
     * @param string $delimiter
     * @param string $enclosure
     */
    public function __construct(SplFileObject $file, $delimiter = ',', $enclosure = '"', $escapeString = '\\')
    {
        $this->file = $file;
        $this->file->setCsvControl($delimiter, $enclosure, $escapeString);
        $this->file->setFlags(SplFileObject::READ_CSV);
        parent::__construct($this->file);
    }

    /**
     * @inheritDoc
     */
    public function accept()
    {
        $current = $this->getInnerIterator()->current();
        return !empty(array_filter(
            $current,
            function ($cell) {
                return null !== $cell;
            }
        ));
    }

    /**
     * @inheritdoc
     */
    public function count()
    {
        if (null === $this->nbLines) {
            $flags   = $this->file->getFlags();
            $current = $this->file->key();
            $this->file->setFlags(null);
            $this->file->seek(PHP_INT_MAX);
            $this->nbLines = $this->file->key() + 1;
            $this->file->seek($current);
            $this->file->setFlags($flags);
        }

        return $this->nbLines;
    }
}

<?php

namespace BenTools\ETL\Iterator;

use FilterIterator;
use SplFileObject;

class CsvFileIterator extends FilterIterator implements \Countable
{

    private $nbLines;
    private $file;

    /**
     * CsvFileIterator constructor.
     *
     * @param $filename
     * @param string $delimiter
     * @param string $enclosure
     */
    public function __construct(SplFileObject $file, $delimiter = ',', $enclosure = '"', $escapeString = '\\')
    {
        $this->file = $file;
        $this->file->setCsvControl($delimiter, $enclosure, $escapeString);
        $this->file->setFlags(SplFileObject::READ_CSV);
        parent::__construct($this->file);
    }

    /**
     * @inheritDoc
     */
    public function accept()
    {
        $current = $this->getInnerIterator()->current();
        return !empty(array_filter(
            $current,
            function ($cell) {
                return null !== $cell;
            }
        ));
    }

    /**
     * @inheritdoc
     */
    public function count()
    {
        if (null === $this->nbLines) {
            $this->rewind();
            $this->nbLines = count(iterator_to_array($this));
        }

        return $this->nbLines;
    }
}

Fix count() method that might not return a relevant result


<?php

// MOODLE VERSION INFORMATION

// This file defines the current version of the core Moodle code being used.
// This is compared against the values stored in the database to determine
// whether upgrades should be performed (see lib/db/*.php)

    $version = 2007100903;  // YYYYMMDD = date
                            //       XY = increments within a single day

    $release = '1.9 Beta +';   // Human-friendly version name

?>

<?php

// MOODLE VERSION INFORMATION

// This file defines the current version of the core Moodle code being used.
// This is compared against the values stored in the database to determine
// whether upgrades should be performed (see lib/db/*.php)

    $version = 2007101000;  // YYYYMMDD = date
                            //       XY = increments within a single day

    $release = '1.9 Beta 2';   // Human-friendly version name

?>

Bump to Beta 2 level

Bump to Beta 2 level


<?php
require_once "../../config.php";
require_once $CFG->dirroot."/pdo.php";

// Sanity checks
$LTI = requireData(array('user_id', 'link_id', 'role','context_id'));
$instructor = isInstructor($LTI);
$user_id = $LTI['user_id'];

$grade = 1.0;

$code = $_POST['code'];
$json = json_encode(array("code" => $code));

$retval = updateGradeJSON($pdo, $json);

$retval = Array("status" => "success");
echo json_encode($retval);

<?php
require_once "../../config.php";
require_once $CFG->dirroot."/pdo.php";

// Sanity checks
$LTI = requireData(array('user_id', 'link_id', 'role','context_id'));
$instructor = isInstructor($LTI);
$user_id = $LTI['user_id'];

$grade = 1.0;

if ( ! isset($_POST['code']) ) {
    echo(json_encode(array("error" => "Missing code")));
    return;
}
$code = $_POST['code'];
$json = json_encode(array("code" => $code));

$retval = updateGradeJSON($pdo, $json);

$retval = Array("status" => "success");
echo json_encode($retval);

Check for missing code variable.

Check for missing code variable.


<?php

require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

//$kernel = new AppCache(new AppKernel('prod', false));
$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();

// if you want to use the SonataPageBundle with multisite
// using different relative paths, you must change the request
// object to use the SiteRequest
use Sonata\PageBundle\Request\SiteRequest as Request;

//use Symfony\Component\HttpFoundation\Request;

$kernel->handle(Request::createFromGlobals())->send();

<?php

require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

//$kernel = new AppCache(new AppKernel('prod', false));
$kernel = new AppKernel('prod', false);
//$kernel->loadClassCache();

// if you want to use the SonataPageBundle with multisite
// using different relative paths, you must change the request
// object to use the SiteRequest
use Sonata\PageBundle\Request\SiteRequest as Request;

//use Symfony\Component\HttpFoundation\Request;

$kernel->handle(Request::createFromGlobals())->send();

Fix 'Cannot redeclare class Sonata\PageBundle\Request\SiteRequestInterface'


<?php

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

namespace Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper;

use ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator as BaseGenerator;
use Zend\Code\Generator\ClassGenerator;

/**
 * @internal
 */
class LazyLoadingValueHolderGenerator extends BaseGenerator
{
    /**
     * {@inheritdoc}
     */
    public function generate(\ReflectionClass $originalClass, ClassGenerator $classGenerator)
    {
        parent::generate($originalClass, $classGenerator);

        if ($classGenerator->hasMethod('__destruct')) {
            $destructor = $classGenerator->getMethod('__destruct');
            $body = $destructor->getBody();
            $newBody = preg_replace('/^(\$this->initializer[a-zA-Z0-9]++) && .*;\n\nreturn (\$this->valueHolder)/', '$1 || $2', $body);

            if ($body === $newBody) {
                throw new \UnexpectedValueException(sprintf('Unexpected lazy-proxy format generated for method %s::__destruct()', $originalClass->name));
            }

            $destructor->setBody($newBody);
        }
    }
}

<?php

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

namespace Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper;

use ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator as BaseGenerator;
use Zend\Code\Generator\ClassGenerator;

/**
 * @internal
 */
class LazyLoadingValueHolderGenerator extends BaseGenerator
{
    /**
     * {@inheritdoc}
     */
    public function generate(\ReflectionClass $originalClass, ClassGenerator $classGenerator)
    {
        parent::generate($originalClass, $classGenerator);

        if ($classGenerator->hasMethod('__destruct')) {
            $destructor = $classGenerator->getMethod('__destruct');
            $body = $destructor->getBody();
            $newBody = preg_replace('/^(\$this->initializer[a-zA-Z0-9]++) && .*;\n\nreturn (\$this->valueHolder)/', '$1 || $2', $body);

            if ($body === $newBody) {
                throw new \UnexpectedValueException(sprintf('Unexpected lazy-proxy format generated for method %s::__destruct().', $originalClass->name));
            }

            $destructor->setBody($newBody);
        }
    }
}

Add missing dots at the end of exception messages


<?php namespace Plugins\October\User\Facades;

use October\Rain\Support\Facade;

class Auth extends Facade
{
    /**
     * Get the class name this facade is acting on behalf of.
     * @return string
     */
    protected static function getFacadeClass() { return 'Plugins\October\User\Classes\AuthManager'; }
}

<?php namespace Plugins\October\User\Facades;

use October\Rain\Support\Facade;

class Auth extends Facade
{
    /**
     * Get the class name this facade is acting on behalf of.
     * @return string
     */
    protected static function getFacadeAccessor() { return 'Plugins\October\User\Classes\AuthManager'; }
}

Switch to new Facade implementation

Switch to new Facade implementation