<?php if (0 < count($creators)): ?>
  <?php foreach($events as $date): ?>
    <?php $creator = QubitActor::getById($date->actorId); ?>

    <?php if (($value = $creator->getHistory(array('cultureFallback' => true))) || $creator->datesOfExistence): ?>
      <bioghist id="<?php echo 'md5-' . md5(url_for(array($creator, 'module' => 'actor'), true)) ?>" encodinganalog="<?php echo $ead->getMetadataParameter('bioghist') ?>">
        <?php if ($value): ?>
          <note>
<?php echo escape_dc(esc_specialchars($value)) ?>
</note>
        <?php endif; ?>
        <?php if ($creator->datesOfExistence): ?>
          <note>
<date type="existence"><?php echo escape_dc(esc_specialchars($creator->datesOfExistence)) ?></date>
</note>
        <?php endif; ?>
      </bioghist>
    <?php endif; ?>

  <?php endforeach; ?>
<?php endif; ?>

<?php if (0 < count($creators)): ?>
  <?php foreach($events as $date): ?>
    <?php $creator = QubitActor::getById($date->actorId); ?>

    <?php if (($value = $creator->getHistory(array('cultureFallback' => true))) || $creator->datesOfExistence): ?>
      <bioghist id="<?php echo 'md5-' . md5(url_for(array($creator, 'module' => 'actor'), true)) ?>" encodinganalog="<?php echo $ead->getMetadataParameter('bioghist') ?>">
        <?php if ($value): ?>
          <note>
<?php echo escape_dc(esc_specialchars($value)) ?>
</note>
        <?php endif; ?>
      </bioghist>
    <?php endif; ?>

  <?php endforeach; ?>
<?php endif; ?>

Remove dates of existence from bioghist

Remove dates of existence from bioghist


<?php

// give the name of php file associated with routename
function getPhpFile($routeName='') {
	// read global var $app
	global $app;

	// check if page exists in file
	if(array_key_exists($routeName, $app['pages'])) {
		$file = $app['pages'][$routeName];
	} else {
		throw new Exception("Error processing getPhpFile($routeName)", 1);
	}

	return $file;
}

// return actual routeName
function getActualRoute() {
	// if route not defined
	if(!isset($_GET['p'])) {
		// equivalent to homepage
		$page = 'accueil';
	} else {
		// given page
		$page = $_GET['p'];
	}
	return $page;
}

// redirect user to given routeName
function redirect($routeName='') {
	// redirect to generate url
	redirectUrl(generateUrl($routeName));
}

// redirect user to given routeName
function redirectUrl($url) {
	// redirect to generate url
	header('Location:' . $url );
}

// generate url by routeName
function generateUrl($routeName=''){
	$url = 'index.php';
	if($routeName != '' && !is_null($routeName)){
		// concate get variable
		$url = $url . '?p=' . $routeName;
	}
	return $url;
}

<?php

// give the name of php file associated with routename
function getPhpFile($routeName='') {
	// read global var $app
	global $app;

	// check if page exists in file
	if(array_key_exists($routeName, $app['pages'])) {
		$file = $app['pages'][$routeName];
	} else {
		throw new Exception("Error processing getPhpFile($routeName)", 1);
	}

	return $file;
}

// return actual routeName
function getActualRoute() {
	// if route not defined
	if(!isset($_GET['p'])) {
		// equivalent to homepage
		$page = 'accueil';
	} else {
		// given page
		$page = $_GET['p'];
	}
	return $page;
}

// redirect user to given routeName
function redirect($routeName='') {
	// redirect to generate url
	redirectUrl(generateUrl($routeName));
}

// redirect user to given routeName
function redirectUrl($url) {
	// redirect to generate url
	header('Location:' . $url );
	die("Redirected");
}

// generate url by routeName
function generateUrl($routeName=''){
	$url = 'index.php';
	if($routeName != '' && !is_null($routeName)){
		// concate get variable
		$url = $url . '?p=' . $routeName;
	}
	return $url;
}

Fix deleting when not connected

Fix deleting when not connected


<?php namespace Milkyway\SS\FlashMessage;

use Controller as Original;

class Controller extends Original
{
    private static $allowed_actions = [
        'refresh',
    ];

    private static $url_handlers = [
        '$Area!' => 'refresh',
    ];

    /**
     * Grab available notifications
     *
     * @param $request
     * @return array|\SS_HTTPResponse|void
     * @throws \SS_HTTPResponse_Exception
     */
    public function refresh($request) {
        // Only available via AJAX
        if(!$request->isAjax()) {
            return $this->httpError(404);
        }

        $area = $request->param('Area');
        singleton('require')->clear();

        // If no area specified, do nothing
        if(!$area) {
            return [];
        }

        $response = $this->getResponse();
        $response->addHeader('Content-type', 'application/json');
        $response->setBody(json_encode(singleton('message')->$area()->get()));
        return $response;
    }

    public function Link($area = '') {
        return $this->join_links('notifications', $area);
    }
}

<?php namespace Milkyway\SS\FlashMessage;

use Controller as Original;

class Controller extends Original
{
    private static $allowed_actions = [
        'refresh',
    ];

    private static $url_handlers = [
        '$Area!' => 'refresh',
    ];

    /**
     * Grab available notifications
     *
     * @param $request
     * @return array|\SS_HTTPResponse|void
     * @throws \SS_HTTPResponse_Exception
     */
    public function refresh($request) {
        // Only available via AJAX
        if(!$request->isAjax()) {
            return $this->httpError(404);
        }

        $area = $request->param('Area');
        singleton('require')->clear();

        // If no area specified, do nothing
        if(!$area) {
            return [];
        }

        // Add additional messages via an extension (if you want to call an API etc.)
        $this->extend('onRefresh', $area, $request);

        $response = $this->getResponse();
        $response->addHeader('Content-type', 'application/json');
        $response->setBody(json_encode(singleton('message')->$area()->get()));
        return $response;
    }

    public function Link($area = '') {
        return $this->join_links('notifications', $area);
    }
}

FIX: Add an extension point to the notify controller, to allow messages to be added


<?php namespace Hybrid;

/**
 * Auth class
 *
 * @package    Hybrid
 * @category   Auth
 * @author     Laravel Hybrid Development Team
 */

use \Auth as Laravel_Auth, \Event;

class Auth extends Laravel_Auth
{
	protected static $user_roles = null;
	/**
	 * Get the current user's roles of the application.
	 *
	 * If the user is a guest, empty array should be returned.
	 *
	 * @static
	 * @access  public
	 * @return  array
	 */
	public static function roles()
	{
		$user    = static::user();
		$roles   = array();
		$user_id = 0;

		// only search for roles when user is logged
		if ( ! is_null($user)) $user_id = $user->id;

		if (is_null(static::$user_roles[$user_id]))
		{

			static::$user_roles[$user_id] = Event::until('hybrid.auth.roles', array($user, $roles));
		}

		return static::$user_roles[$user_id];
	}
}

<?php namespace Hybrid;

/**
 * Auth class
 *
 * @package    Hybrid
 * @category   Auth
 * @author     Laravel Hybrid Development Team
 */

use \Auth as Laravel_Auth, \Event;

class Auth extends Laravel_Auth
{
	/**
	 * Cached user to roles relationship
	 *
	 * @var array
	 */
	protected static $user_roles = null;

	/**
	 * Get the current user's roles of the application.
	 *
	 * If the user is a guest, empty array should be returned.
	 *
	 * @static
	 * @access  public
	 * @return  array
	 */
	public static function roles()
	{
		$user    = static::user();
		$roles   = array();
		$user_id = 0;

		// only search for roles when user is logged
		if ( ! is_null($user)) $user_id = $user->id;

		if (is_null(static::$user_roles[$user_id]))
		{
			static::$user_roles[$user_id] = Event::until('hybrid.auth.roles', array($user, $roles));
		}

		return static::$user_roles[$user_id];
	}

	/**
	 * Determine if current user has the given role
	 *
	 * @static
	 * @access public
	 * @param  string   $role
	 * @return boolean
	 */
	public static function is($role)
	{
		$roles = static::roles();

		return in_array($role, $roles);
	}
}

Add Hybrid\Auth::is() to check if user has a given role

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


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

function normalizeShortcode($shortcode) {
    return str_replace('-', '_', strtolower($shortcode));
}

$data = json_decode(file_get_contents(__DIR__ . '/../vendor/milesj/emojibase/packages/data/en/raw.json'), true);
$emoji_array = require(__DIR__ . '/../src/shortcodes-array.php');
$existing_shortcodes = array_map('normalizeShortcode', array_keys($emoji_array));

foreach ($data as $emoji) {
    foreach ($emoji['shortcodes'] as $shortcode) {

        if (in_array(normalizeShortcode($shortcode), $existing_shortcodes)) {
            continue;
        }

        $emoji_array[ (string) $shortcode] = $emoji['hexcode'];
    }
}

ksort($emoji_array, SORT_NATURAL);
$output = "<?php\nreturn [\n";
foreach ($emoji_array as $shortcode => $codepoints) {
    $output .= "  '$shortcode' => '$codepoints',\n";
};
$output .= '];';
file_put_contents('src/shortcodes-array.php', $output);

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

function normalizeShortcode($shortcode) {
    return str_replace('-', '_', strtolower($shortcode));
}

$data = json_decode(file_get_contents(__DIR__ . '/../vendor/milesj/emojibase/packages/data/en/data.raw.json'), true);
$shortcodes = json_decode(file_get_contents(__DIR__ . '/../vendor/milesj/emojibase/packages/data/en/shortcodes/emojibase.raw.json'), true);

$emoji_array = require(__DIR__ . '/../src/shortcodes-array.php');
$existing_shortcodes = array_map('normalizeShortcode', array_keys($emoji_array));

foreach ($data as $emoji) {

    if (!isset($shortcodes[$emoji['hexcode']])) {
        continue;
    }

    if (!is_array($shortcodes[$emoji['hexcode']])) {
        $shortcodes[$emoji['hexcode']] = [$shortcodes[$emoji['hexcode']]];
    }

    foreach ($shortcodes[$emoji['hexcode']] as $shortcode) {

        if (in_array(normalizeShortcode($shortcode), $existing_shortcodes)) {
            continue;
        }

        $emoji_array[ (string) $shortcode] = $emoji['hexcode'];
    }
}

ksort($emoji_array, SORT_NATURAL);
$output = "<?php\nreturn [\n";
foreach ($emoji_array as $shortcode => $codepoints) {
    $output .= "  '$shortcode' => '$codepoints',\n";
};
$output .= '];';
file_put_contents('src/shortcodes-array.php', $output);

Rebuild generation of shortcodes araay

Rebuild generation of shortcodes araay


<?php

/*
 * This file is part of the Blackfire SDK package.
 *
 * (c) Blackfire <support@blackfire.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Blackfire\Bridge\Laravel;

use Dotenv\Dotenv;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;

class LoadBlackfireEnvironmentVariables
{
    /**
     * Bootstrap the given application.
     *
     * @return void
     */
    public function bootstrap(Application $app)
    {
        $request = Request::capture();
        if (!($request->headers->has('X-BLACKFIRE-LARAVEL-TESTS') && $request->headers->has('X-BLACKFIRE-QUERY'))) {
            return;
        }

        $dotenv = Dotenv::createImmutable(base_path(), '.env.testing');
        $dotenv->safeload();
    }
}

<?php

/*
 * This file is part of the Blackfire SDK package.
 *
 * (c) Blackfire <support@blackfire.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Blackfire\Bridge\Laravel;

use Dotenv\Dotenv;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;

class LoadBlackfireEnvironmentVariables
{
    /**
     * Bootstrap the given application.
     *
     * @return void
     */
    public function bootstrap(Application $app)
    {
        $request = Request::capture();
        if (!($request->headers->has('X-BLACKFIRE-LARAVEL-TESTS') && $request->headers->has('X-BLACKFIRE-QUERY'))) {
            return;
        }

        $dotenv = Dotenv::createImmutable(base_path(), '.env.testing');
        $dotenv->load();

        if (env('APP_ENV') !== 'testing') {
            throw new \RuntimeException('The .env.testing file should contain APP_ENV=testing');
        }
    }
}

Increase security loading the .env.testing file


<?php

$base = dirname(__FILE__) . "/..";

set_include_path(
    $base . "/config:" .
    $base . "/system/config:" .
    $base . "/system:" .
    $base . "/tests:" .
    $base . "/tests/system:" .
    $base . "/application/libraries/enums:" .
    $base . "/application/libraries/core:" .
    $base . "/application/libraries/db:" .
    $base . "/application/controllers:" .
    $base . "/application/models:" .
    $base . "/application/libraries:" .
    $base . "/application/views:" .
    get_include_path()
);

// Load and setup class file autloader
include_once("libraries/core/class.autoloader.inc.php");
spl_autoload_register("Lunr\Libraries\Core\Autoloader::load");

?>

<?php

$base = dirname(__FILE__) . "/..";

set_include_path(
    $base . "/config:" .
    $base . "/system/config:" .
    $base . "/system:" .
    $base . "/tests:" .
    $base . "/tests/system:" .
    $base . "/application/libraries/enums:" .
    $base . "/application/libraries/core:" .
    $base . "/application/libraries/db:" .
    $base . "/application/controllers:" .
    $base . "/application/models:" .
    $base . "/application/libraries:" .
    $base . "/application/views:" .
    get_include_path()
);

// Load and setup class file autloader
include_once("libraries/core/class.autoloader.inc.php");
spl_autoload_register(array(new Lunr\Libraries\Core\Autoloader(), 'load'));

?>

test: Adjust test bootstrap file for new autoloader structure


<?php

class CRM_Monetico_Page_Monetico extends CRM_Core_Page {
  function run() {
    /**
     * NEEDS REVIEW
     *
     * The CMC_IC extension used this class to generate a mini-form,
     * which Monetico does not seem to support. Using this instead to
     * declare a webhook and process the IPN.
     *
     * CiviCRM normally has another entry-point to validate IPNs,
     * but could not understand the documentation on the issue.
     */

    $ipn = new CRM_Core_Payment_MoneticoIPN(array_merge($_REQUEST, array('exit_mode' => TRUE)));
    $ipn->main();

    die();
  }

}

<?php

class CRM_Monetico_Page_Monetico extends CRM_Core_Page {
  function run() {
    /**
     * NEEDS REVIEW
     *
     * The CMC_IC extension used this class to generate a mini-form,
     * which Monetico does not seem to support. Using this instead to
     * declare a webhook and process the IPN.
     *
     * CiviCRM normally has another entry-point to validate IPNs,
     * but could not understand the documentation on the issue.
     */

    $ipn = new CRM_Core_Payment_MoneticoIPN(array_merge($_REQUEST, array('exit_mode' => TRUE)));
    $ipn->main();

    CRM_Utils_System::civiExit();
  }

}

Use civiExit() instead of die.

Use civiExit() instead of die.


<?php

namespace Swm\Bundle\MailHookBundle\ApiService;

use Swm\Bundle\MailHookBundle\Hook\DefaultHook;
use Swm\Bundle\MailHookBundle\SwmMailHookEvent;

class MailgunApiService extends BaseApiService
{
    private $eventAssoc = array(
        'delivered'     => SwmMailHookEvent::MAILHOOK_SEND,
        'opened'        => SwmMailHookEvent::MAILHOOK_OPEN,
        'clicked'       => SwmMailHookEvent::MAILHOOK_CLICK,
        'complained'    => SwmMailHookEvent::MAILHOOK_SPAM,
        'unsubscribed'  => SwmMailHookEvent::MAILHOOK_UNSUB,
        'failed'        => SwmMailHookEvent::MAILHOOK_REJECT,
    );

    /**
     * @param  array  $hook
     * @return HookInterface
     */
    private function bindHook(array $hook)
    {
        return new DefaultHook($hook['event'], $hook['recipient'], 'mailgun', $hook, $this->eventAssoc[$hook['event']]);
    }

    /**
     * @return array<HookInterface>
     */
    public function bind()
    {
        $metaData = json_decode($this->request->getContent(), true);

        return array($this->bindHook($metaData));
    }
}

<?php

namespace Swm\Bundle\MailHookBundle\ApiService;

use Swm\Bundle\MailHookBundle\Hook\DefaultHook;
use Swm\Bundle\MailHookBundle\SwmMailHookEvent;

class MailgunApiService extends BaseApiService
{
    private $eventAssoc = array(
        'delivered'     => SwmMailHookEvent::MAILHOOK_SEND,
        'opened'        => SwmMailHookEvent::MAILHOOK_OPEN,
        'clicked'       => SwmMailHookEvent::MAILHOOK_CLICK,
        'complained'    => SwmMailHookEvent::MAILHOOK_SPAM,
        'unsubscribed'  => SwmMailHookEvent::MAILHOOK_UNSUB,
        'failed'        => SwmMailHookEvent::MAILHOOK_REJECT,
    );

    /**
     * @param  array  $hook
     * @return HookInterface
     */
    private function bindHook(array $hook)
    {
        return new DefaultHook($hook['event'], $hook['recipient'], 'mailgun', $hook, $this->eventAssoc[$hook['event']]);
    }

    /**
     * @return array<HookInterface>
     */
    public function bind()
    {
        $metaData = json_decode($this->request->getContent(), true);

        return array($this->bindHook($metaData['event-data']));
    }
}

Fix data field for Mailgun

Fix data field for Mailgun


<?php
namespace HomoChecker\Model;

use GuzzleHttp\Promise;
use GuzzleHttp\ClientInterface;

class Icon implements IconInterface
{
    public static $default = 'https://abs.twimg.com/sticky/default_profile_images/default_profile_0_200x200.png';

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

    public function getAsync(string $screen_name): Promise\PromiseInterface
    {
        return Promise\coroutine(function () use ($screen_name) {
            try {
                $target = "https://twitter.com/intent/user?screen_name={$screen_name}";
                $response = yield $this->client->getAsync($target);
                $body = (string)$response->getBody();

                if (!preg_match('/src=(?:\"|\')(https:\/\/[ap]bs\.twimg\.com\/[^\"\']+)/', $body, $matches)) {
                    throw new \RuntimeException('No URL found');
                }
                [, $url] = $matches;
            } catch (\RuntimeException $e) {
                $url = static::$default;
            }

            return yield $url ?? static::$default;
        });
    }
}

<?php
namespace HomoChecker\Model;

use GuzzleHttp\Promise;
use GuzzleHttp\ClientInterface;

class Icon implements IconInterface
{
    public static $default = 'https://abs.twimg.com/sticky/default_profile_images/default_profile_200x200.png';

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

    public function getAsync(string $screen_name): Promise\PromiseInterface
    {
        return Promise\coroutine(function () use ($screen_name) {
            try {
                $target = "https://twitter.com/intent/user?screen_name={$screen_name}";
                $response = yield $this->client->getAsync($target);
                $body = (string)$response->getBody();

                if (!preg_match('/src=(?:\"|\')(https:\/\/[ap]bs\.twimg\.com\/[^\"\']+)/', $body, $matches)) {
                    throw new \RuntimeException('No URL found');
                }
                [, $url] = $matches;
            } catch (\RuntimeException $e) {
                $url = static::$default;
            }

            return yield $url ?? static::$default;
        });
    }
}

Update default icon for Twitter

Update default icon for Twitter


<?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\Component\HttpKernel;

/**
 * Client simulates a browser and makes requests to an HttpKernel instance.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @method Request  getRequest()  A Request instance
 * @method Response getResponse() A Response instance
 */
class HttpKernelBrowser extends Client
{
}

<?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\Component\HttpKernel;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Client simulates a browser and makes requests to an HttpKernel instance.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @method Request  getRequest()  A Request instance
 * @method Response getResponse() A Response instance
 */
class HttpKernelBrowser extends Client
{
}

[HttpKernel] Fix missing use for request and response classes


Search results for <?php the_search_query(); ?>

<?php if (have_posts()) { ?>

  <?php while (have_posts()) : the_post() ?>
    <article <?php post_class() ?>>

<a href="<?php the_permalink() ?>"><?php the_title() ?>

        <?php get_template_part('templates/entry-meta') ?>
        <?php if (has_post_thumbnail()) {
    the_post_thumbnail('large');
} ?>

      <?php the_excerpt() ?>
      <?php get_template_part('templates/entry-footer') ?>

  <?php endwhile ?>

<?php } else { ?>

No results found on <?php echo get_bloginfo('name'); ?>.

Please try searching again using different words or try this search on GOV.UK.

<?php } ?>

Add horizontal line element to header

Add horizontal line element to header


@extends('larapress.layouts.master')

@section('head.extension')
    {{ HTML::style('larapress/assets/css/pages/home/login.css') }}
@stop

@section('body')

            {{-- Messages --}}
            @if ( Session::has('error') )

                    @lang('messages.Error')!
                    @lang('messages.' . Session::get('error'))

            @endif

            @yield('content')

            © {{{ $now->year }}} Martin Hettiger |
            Powered by Laravel

@stop

@extends('larapress.layouts.master')

@section('head.extension')
    {{ HTML::style('larapress/assets/css/pages/home/login.css') }}
@stop

@section('body')

            {{-- Messages --}}
            @if ( Session::has('error') )

                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    @lang('messages.Error')!
                    @lang('messages.' . Session::get('error'))

            @endif

            @yield('content')

            © {{{ $now->year }}} Martin Hettiger |
            Powered by Laravel

@stop

Add a dismiss button to the alert

Add a dismiss button to the alert


<?php

namespace SilverLeague\LogViewer\Task;

use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\BuildTask;

/**
 * This is purely for demo purposes, and will log a message at every level for local testing or demo purposes.
 *
 * @package silverstripe-logviewer
 * @author  Robbie Averill <robbie@averill.co.nz>
 */
class CreateLogsTask extends BuildTask
{
    /**
     * {@inheritDoc}
     */
    private static $segment = 'CreateLogsTask';

    /**
     * {@inheritDoc}
     */
    public function run($request)
    {
        $logger = Injector::inst()->get('Logger');
        $logger->addDebug('Detailed debug information');
        $logger->addInfo('Interesting events. Examples: User logs in, SQL logs.');
        $logger->addNotice('Uncommon events');
        $logger->addWarning(
            'Exceptional occurrences that are not errors. Examples: Use of deprecated APIs, poor use of an API, '
            . 'undesirable things that are not necessarily wrong.'
        );
        $logger->addError('Runtime errors');
        $logger->addCritical('Critical conditions. Example: Application component unavailable, unexpected exception.');
        $logger->addAlert(
            'Action must be taken immediately. Example: Entire website down, database unavailable, etc. '
            . 'This should trigger the SMS alerts and wake you up.'
        );
        $logger->addEmergency('Urgent alert.');
        echo 'Finito.', PHP_EOL;
    }
}

<?php

namespace SilverLeague\LogViewer\Task;

use Psr\Log\LoggerInterface;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\BuildTask;

/**
 * This is purely for demo purposes, and will log a message at every level for local testing or demo purposes.
 *
 * @package silverstripe-logviewer
 * @author  Robbie Averill <robbie@averill.co.nz>
 */
class CreateLogsTask extends BuildTask
{
    /**
     * {@inheritDoc}
     */
    private static $segment = 'CreateLogsTask';

    /**
     * {@inheritDoc}
     */
    public function run($request)
    {
        $logger = Injector::inst()->get(LoggerInterface::class);
        $logger->addDebug('Detailed debug information');
        $logger->addInfo('Interesting events. Examples: User logs in, SQL logs.');
        $logger->addNotice('Uncommon events');
        $logger->addWarning(
            'Exceptional occurrences that are not errors. Examples: Use of deprecated APIs, poor use of an API, '
            . 'undesirable things that are not necessarily wrong.'
        );
        $logger->addError('Runtime errors');
        $logger->addCritical('Critical conditions. Example: Application component unavailable, unexpected exception.');
        $logger->addAlert(
            'Action must be taken immediately. Example: Entire website down, database unavailable, etc. '
            . 'This should trigger the SMS alerts and wake you up.'
        );
        $logger->addEmergency('Urgent alert.');
        echo 'Finito.', PHP_EOL;
    }
}

FIX Update logger injector alias in example code


Hi {{ $envelope->signedBy->preferred_first_name }},

We received your Travel Authority Request for {{ $envelope->signable->travel->name }}. Once everyone has submitted their documents, we'll forward all of them to Georgia Tech for review and approval.

You can view your completed form within DocuSign at {{ $envelope->sender_view_url }}.

@if(!$envelope->signable->is_paid)
You still need to make a ${{ intval($envelope->signable->travel->fee_amount) }} payment for the travel fee.

You can pay online with a credit or debit card at {{ route('pay.travel') }}. Note that we add an additional ${{ number_format(\App\Models\Payment::calculateSurcharge($envelope->signable->travel->fee_amount * 100) / 100, 2) }} surcharge for online payments.

If you would prefer to pay by cash or check, make arrangements with {{ $envelope->signable->travel->primaryContact->full_name }}.

Write checks to Georgia Tech, with RoboJackets on the memo line. Don't forget to sign it!
@endif

For more information, visit {{ route('travel.index') }}. If you have any questions, please contact {{ $envelope->signable->travel->primaryContact->full_name }}.

----

To stop receiving emails from {{ config('app.name') }}, visit @{{{ pm:unsubscribe }}}.

Tweak whitespace for DocuSign acknowledgement email


<?php

namespace Doctrine\Instantiator\Exception;

use InvalidArgumentException as BaseInvalidArgumentException;
use ReflectionClass;
use const PHP_VERSION_ID;
use function interface_exists;
use function sprintf;
use function trait_exists;

/**
 * Exception for invalid arguments provided to the instantiator
 */
class InvalidArgumentException extends BaseInvalidArgumentException implements ExceptionInterface
{
    public static function fromNonExistingClass(string $className) : self
    {
        if (interface_exists($className)) {
            return new self(sprintf('The provided type "%s" is an interface, and can not be instantiated', $className));
        }

        if (PHP_VERSION_ID >= 50400 && trait_exists($className)) {
            return new self(sprintf('The provided type "%s" is a trait, and can not be instantiated', $className));
        }

        return new self(sprintf('The provided class "%s" does not exist', $className));
    }

    public static function fromAbstractClass(ReflectionClass $reflectionClass) : self
    {
        return new self(sprintf(
            'The provided class "%s" is abstract, and can not be instantiated',
            $reflectionClass->getName()
        ));
    }
}

<?php

namespace Doctrine\Instantiator\Exception;

use InvalidArgumentException as BaseInvalidArgumentException;
use ReflectionClass;
use function interface_exists;
use function sprintf;
use function trait_exists;

/**
 * Exception for invalid arguments provided to the instantiator
 */
class InvalidArgumentException extends BaseInvalidArgumentException implements ExceptionInterface
{
    public static function fromNonExistingClass(string $className) : self
    {
        if (interface_exists($className)) {
            return new self(sprintf('The provided type "%s" is an interface, and can not be instantiated', $className));
        }

        if (trait_exists($className)) {
            return new self(sprintf('The provided type "%s" is a trait, and can not be instantiated', $className));
        }

        return new self(sprintf('The provided class "%s" does not exist', $className));
    }

    public static function fromAbstractClass(ReflectionClass $reflectionClass) : self
    {
        return new self(sprintf(
            'The provided class "%s" is abstract, and can not be instantiated',
            $reflectionClass->getName()
        ));
    }
}

Remove unnecessary check of php version

Remove unnecessary check of php version

The minimum php version required in composer is 7.1 and the code
was checking with version 5


<?php

namespace Joli\JoliCi;

use org\bovigo\vfs\vfsStream;
use Joli\JoliCi\BuildStrategy\TravisCiBuildStrategy;

class TravisCiBuildStrategyTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->buildPath = vfsStream::setup('build-path');
        $this->strategy = new TravisCiBuildStrategy(vfsStream::url('build-path'));
    }

    public function testSupportTrue()
    {
        $support = $this->strategy->supportProject(__DIR__.DIRECTORY_SEPARATOR."fixtures".DIRECTORY_SEPARATOR."travisci".DIRECTORY_SEPARATOR."project1");

        $this->assertTrue($support);
    }

    public function testSupportFalse()
    {
        $support = $this->strategy->supportProject(__DIR__.DIRECTORY_SEPARATOR."fixtures".DIRECTORY_SEPARATOR."travisci".DIRECTORY_SEPARATOR."project2");

        $this->assertFalse($support);
    }
}

<?php

namespace Joli\JoliCi\BuildStrategy;

use org\bovigo\vfs\vfsStream;
use Joli\JoliCi\BuildStrategy\TravisCiBuildStrategy;

class TravisCiBuildStrategyTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->buildPath = vfsStream::setup('build-path');
        $this->strategy = new TravisCiBuildStrategy(vfsStream::url('build-path'), __DIR__."/../../../../resources/travisci");
    }

    public function testSupportTrue()
    {
        $support = $this->strategy->supportProject(__DIR__.DIRECTORY_SEPARATOR."fixtures".DIRECTORY_SEPARATOR."travisci".DIRECTORY_SEPARATOR."project1");

        $this->assertTrue($support);
    }

    public function testSupportFalse()
    {
        $support = $this->strategy->supportProject(__DIR__.DIRECTORY_SEPARATOR."fixtures".DIRECTORY_SEPARATOR."travisci".DIRECTORY_SEPARATOR."project2");

        $this->assertFalse($support);
    }
}

Fix test for TravisCi Strategy

Fix test for TravisCi Strategy


<?php
/**
 * Created by PhpStorm.
 * User: Catalin
 * Date: 03-Jun-17
 * Time: 13:59
 */

include ("../../BACK/conectare_db.php");

$username = $_SESSION["username"];
$stid = oci_parse($connection, 'SELECT LINK FROM player WHERE username = :username');
oci_bind_by_name($stid, ':username', $username);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_BOTH);
$link = $row[0];
oci_free_statement($stid);

if (strcmp($link,'k') == 0)
    echo '';
else
    echo '';

Update avatar when is changed

Update avatar when is changed


<?php
/*
 * This could be loaded on a very old version of PHP so no syntax/methods over 5.2 in this file.
 */
use Bolt\Exception\BootException;

if (version_compare(PHP_VERSION, '5.5.9', '<')) {
    require dirname(dirname(__FILE__)) . '/src/Exception/BootException.php';

    BootException::earlyExceptionVersion();
}

if (PHP_SAPI === 'cli-server') {
    if (is_file($_SERVER['DOCUMENT_ROOT'] . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']))) {
        return false;
    }
}

return require dirname(__FILE__) . '/bootstrap.php';

<?php
/*
 * This could be loaded on a very old version of PHP so no syntax/methods over 5.2 in this file.
 */
use Bolt\Exception\BootException;

if (version_compare(PHP_VERSION, '5.5.9', '<')) {
    require dirname(dirname(__FILE__)) . '/src/Exception/BootException.php';

    BootException::earlyExceptionVersion();
}

if (PHP_SAPI === 'cli-server') {
    if (is_file($_SERVER['DOCUMENT_ROOT'] . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']))) {
        return false;
    }

    // Fix server variables for PHP built-in server so base path is correctly determined.
    $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
    $frame = end($trace);
    // Absolute path to entry file
    $_SERVER['SCRIPT_FILENAME'] = $frame['file'];
    // Relative path to entry file from document root (dir the server is point to)
    $_SERVER['SCRIPT_NAME'] = preg_replace("#^{$_SERVER['DOCUMENT_ROOT']}#", '', $_SERVER['SCRIPT_FILENAME']);
}

return require dirname(__FILE__) . '/bootstrap.php';

Fix base path for file-like urls (i.e. thumbnails, file viewing/editing on backend UI, etc.) for built-in php server.


<?php

namespace App\Providers;

use App\Post;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        // Using Closure based composers...
        View::composer('_partials._aside_recent_articles', function ($view) {
            return $view->with('latestPosts', Post::latest()->take(5)->get());
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

<?php

namespace App\Providers;

use App\Post;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        // Using Closure based composers...
        View::composer('_partials._aside_recent_articles', function ($view) {
            return $view->with('latestPosts', Post::published()->latest()->take(5)->get());
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Remove unpublished posts from latest posts list sidebar


<?php

namespace Phosphorum\Markdown;

use Ciconia\Common\Text;
use Ciconia\Extension\ExtensionInterface;
use Ciconia\Markdown;

/**
 * Class MentionExtension
 *
 * @package Phosphorum\Markdown
 */
class MentionExtension implements ExtensionInterface
{

    /**
     * {@inheritdoc}
     */
    public function register(Markdown $markdown)
    {
        $markdown->on('inline', [$this, 'processMentions']);
    }

    /**
     * @param Text $text
     */
    public function processMentions(Text $text)
    {
        // Turn @username into [@username](http://example.com/user/username)
        $text->replace('/(?:^|[^a-zA-Z0-9.])@([A-Za-z]+[A-Za-z0-9]+)/', function (Text $w, Text $username) {
            return ' [@' . $username . '](http://forum.phalconphp.com/user/0/' . $username . ')';
        });
    }

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

<?php

namespace Phosphorum\Markdown;

use Ciconia\Common\Text;
use Ciconia\Extension\ExtensionInterface;
use Ciconia\Markdown;
use Phalcon\DI\Injectable;

/**
 * Class MentionExtension
 *
 * @package Phosphorum\Markdown
 */
class MentionExtension extends Injectable implements ExtensionInterface
{

    /**
     * {@inheritdoc}
     */
    public function register(Markdown $markdown)
    {
        $markdown->on('inline', [$this, 'processMentions']);
    }

    /**
     * @param Text $text
     */
    public function processMentions(Text $text)
    {
        // Turn @username into [@username](http://example.com/user/username)
        $text->replace('/(?:^|[^a-zA-Z0-9.])@([A-Za-z]+[A-Za-z0-9]+)/', function (Text $w, Text $username) {
            return ' [@' . $username . '](' . $this->config->site->url . '/user/0/' . $username . ')';
        });
    }

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

Fix hard coded site URL in @username mention


<?php
namespace Nubs\PwMan;

use RandomLib\Factory as RandomFactory;

/**
 * Generate random passwords.
 */
class PasswordGenerator
{
    /** @type string The characters to use in the password. */
    private $_characters;

    /** @type int The length of the password. */
    private $_length;

    /**
     * Construct the password generator with the desired settings.
     *
     * @api
     */
    public function __construct()
    {
        $this->_characters = join(range(chr(32), chr(126)));
        $this->_length = 32;
    }

    /**
     * Generate a password.
     *
     * @api
     * @return string The random password.
     */
    public function __invoke()
    {
        $generator = (new RandomFactory())->getMediumStrengthGenerator();
        return $generator->generateString($this->_length, $this->_characters);
    }
}

<?php
namespace Nubs\PwMan;

use RandomLib\Factory as RandomFactory;

/**
 * Generate random passwords.
 */
class PasswordGenerator
{
    /** @type string The characters to use in the password. */
    private $_characters;

    /** @type int The length of the password. */
    private $_length;

    /**
     * Construct the password generator with the desired settings.
     *
     * @api
     * @param string $characters The characters to use in the password.
     * @param int $length The length of the password to generate.
     */
    public function __construct($characters = null, $length = 32)
    {
        $this->_characters = $characters ?: join(range(chr(32), chr(126)));
        $this->_length = $length;
    }

    /**
     * Generate a password.
     *
     * @api
     * @return string The random password.
     */
    public function __invoke()
    {
        $generator = (new RandomFactory())->getMediumStrengthGenerator();
        return $generator->generateString($this->_length, $this->_characters);
    }
}

Allow characters/length to be overriden in the generator.


<?php

namespace App\Console\Commands\Bulk;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class BulkAll extends BaseCommand
{

    protected $signature = 'bulk:all';

    protected $description = "Reset database and import everything";

    public function handle()
    {
        // Import all bulkable resources from compliant data services
        foreach (config('resources.inbound') as $source => $endpoints) {
            foreach ($endpoints as $endpoint => $resource) {
                dump("$source >> $endpoint");
                $this->call('bulk:import', [
                    'source' => $source,
                    'endpoint' => $endpoint,
                ]);
            }
        }

        /*

        // TODO: Use bulking for import:images
        // TODO: Use upserts for import:analytics

        // Import non-standard data
        $this->call('import:mobile');
        $this->call('import:sites', ['--yes' => 'default']);
        $this->call('import:ulan');
        $this->call('import:analytics');

        // EventOccurrence is not included in import:web to avoid duplication
        $this->call('import:web-full', ['--yes' => 'default', 'endpoint' => 'event-occurrences']);

        */

    }

}

<?php

namespace App\Console\Commands\Bulk;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class BulkAll extends BaseCommand
{

    protected $signature = 'bulk:all {skip?}';

    protected $description = "Reset database and import everything";

    public function handle()
    {
        $shouldSkipTo = $this->argument('skip') ?? false;

        // Import all bulkable resources from compliant data services
        foreach (config('resources.inbound') as $source => $endpoints) {
            foreach ($endpoints as $endpoint => $resource) {
                dump("$source >> $endpoint");

                if ($shouldSkipTo && $source !== $shouldSkipTo) {
                    dump("Skipping...");
                    continue;
                }

                $this->call('bulk:import', [
                    'source' => $source,
                    'endpoint' => $endpoint,
                ]);

                $shouldSkipTo = false;
            }
        }

        /*

        // TODO: Use bulking for import:images
        // TODO: Use upserts for import:analytics

        // Import non-standard data
        $this->call('import:mobile');
        $this->call('import:sites', ['--yes' => 'default']);
        $this->call('import:ulan');
        $this->call('import:analytics');

        // EventOccurrence is not included in import:web to avoid duplication
        $this->call('import:web-full', ['--yes' => 'default', 'endpoint' => 'event-occurrences']);

        */

    }

}

Add skip argument to `bulk:all`

Add skip argument to `bulk:all`


<?php

namespace Concrete\Core\Updater\Migrations\Migrations;

use Concrete\Core\Updater\Migrations\AbstractMigration;

class Version20181112211702 extends AbstractMigration
{

    public function upgradeDatabase()
    {
        $this->refreshEntities([
            'Concrete\Core\Entity\Express\Control\AssociationControl',
        ]);
    }
}

<?php

namespace Concrete\Core\Updater\Migrations\Migrations;

use Concrete\Core\Updater\Migrations\AbstractMigration;
use Concrete\Core\Updater\Migrations\RepeatableMigrationInterface;

class Version20181112211702 extends AbstractMigration implements RepeatableMigrationInterface
{
    public function upgradeDatabase()
    {
        $this->refreshEntities([
            'Concrete\Core\Entity\Express\Control\AssociationControl',
        ]);
    }
}

Mark migration 20181112211702 as repeatable


<?php

declare(strict_types=1);

namespace phpDocumentor\Reflection\Php;

use phpDocumentor\Reflection\Exception;

trait MetadataContainerTest
{
    /**
     * @covers ::addMetadata
     * @covers ::getMetadata
     */
    public function testSetMetaDataForNonExistingKey(): void
    {
        $stub = new MetadataStub('stub');

        $this->getFixture()->addMetadata($stub);

        self::assertSame(['stub' => $stub], $this->getFixture()->getMetadata());
    }

    /**
     * @covers ::addMetadata
     */
    public function testSetMetaDataWithExistingKeyThrows(): void
    {
        self::expectException(Exception::class);

        $stub = new MetadataStub('stub');

        $this->getFixture()->addMetadata($stub);
        $this->getFixture()->addMetadata($stub);
    }

    abstract public function getFixture(): MetadataContainer;
}

<?php

declare(strict_types=1);

namespace phpDocumentor\Reflection\Php;

use phpDocumentor\Reflection\Exception;
use phpDocumentor\Reflection\Metadata\MetaDataContainer as MetaDataContainerInterface;

trait MetadataContainerTest
{
    /**
     * @covers ::addMetadata
     * @covers ::getMetadata
     */
    public function testSetMetaDataForNonExistingKey(): void
    {
        $stub = new MetadataStub('stub');

        $this->getFixture()->addMetadata($stub);

        self::assertSame(['stub' => $stub], $this->getFixture()->getMetadata());
    }

    /**
     * @covers ::addMetadata
     */
    public function testSetMetaDataWithExistingKeyThrows(): void
    {
        self::expectException(Exception::class);

        $stub = new MetadataStub('stub');

        $this->getFixture()->addMetadata($stub);
        $this->getFixture()->addMetadata($stub);
    }

    abstract public function getFixture(): MetaDataContainerInterface;
}

Use interface as return type

Use interface as return type


<?php

require_once APP_LIB_PATH . '/AppResponse.php';

$app->group('/nannies', function() use ($app, $nannyDB) {

});

<?php

require_once APP_LIB_PATH . '/AppResponse.php';

$app->group('/nannies', function() use ($app, $nannyDB) {
	$app->get('/:id', function() use ($app) {
		// TODO: Get nanny data for :id
	});
});

Add API routes for Nanny

Add API routes for Nanny

#57


<?
defined('C5_EXECUTE') or die("Access Denied.");

$c = Page::getCurrentPage();
if (is_object($c)) {
    $cp = new Permissions($c);
    Loader::element('page_controls_footer', array('cp' => $cp, 'c' => $c));
}

$_trackingCodePosition = Config::get('concrete.seo.tracking.code_position');
if (empty($disableTrackingCode) && (empty($_trackingCodePosition) || $_trackingCodePosition === 'bottom')) {
	echo Config::get('concrete.seo.tracking.code');
}

$v = View::getInstance();
print $v->markFooterAssetPosition();

// user profile menu
Loader::element('account/menu');

<?
defined('C5_EXECUTE') or die("Access Denied.");

$c = Page::getCurrentPage();
if (is_object($c)) {
    $cp = new Permissions($c);
    View::element('page_controls_footer', array('cp' => $cp, 'c' => $c));
}

$_trackingCodePosition = Config::get('concrete.seo.tracking.code_position');
if (empty($disableTrackingCode) && (empty($_trackingCodePosition) || $_trackingCodePosition === 'bottom')) {
	echo Config::get('concrete.seo.tracking.code');
}

View::getInstance()->markFooterAssetPosition();

// user profile menu
View::element('account/menu');

Remove deprecated calls (Loader --> View)


<?php

$lines = array(
    'User-agent: *',
    'Allow: /',
    'Disallow: '.URL_BASE.'rest/',
);

foreach (WebModule::getAllModules() as $module) {
    if (!$module->allowRobots()) {
        $lines[] = 'Disallow: '.URL_BASE.$module->getConfigModule().'/';
    }
}

$output = implode("\n", $lines)."\n";

header('Content-type: text/plain');
print $output;

<?php

$lines = array(
    'User-agent: *',
    'Allow: '.URL_BASE,
    'Disallow: '.URL_BASE.'rest/',
);

foreach (WebModule::getAllModules() as $module) {
    if (!$module->allowRobots()) {
        $lines[] = 'Disallow: '.URL_BASE.$module->getConfigModule().'/';
    }
}

$output = implode("\n", $lines)."\n";

header('Content-type: text/plain');
print $output;

[KGO-788]
Make sure to set allow statement on URL_BASE


<?php

namespace PragmaRX\Google2FALaravel\Support;

use Illuminate\Support\MessageBag;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;

trait ErrorBag
{
    /**
     * Create an error bag and store a message on int.
     *
     * @param $message
     *
     * @return MessageBag
     */
    protected function createErrorBagForMessage($message)
    {
        return new MessageBag([
            'message' => $message,
        ]);
    }

    /**
     * Get a message bag with a message for a particular status code.
     *
     * @param $statusCode
     *
     * @return MessageBag
     */
    protected function getErrorBagForStatusCode($statusCode)
    {
        $errorMap = [
            SymfonyResponse::HTTP_UNPROCESSABLE_ENTITY => 'google2fa.error_messages.wrong_otp',
            SymfonyResponse::HTTP_BAD_REQUEST          => 'google2fa.error_messages.cannot_be_empty',
        ];

        return $this->createErrorBagForMessage(
            trans(
                config(
                    array_key_exists($statusCode, $errorMap) ? $errorMap[$statusCode] : 'google2fa.error_messages.unknown'
                )
            )
        );
    }
}

<?php

namespace PragmaRX\Google2FALaravel\Support;

use Illuminate\Support\MessageBag;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;

trait ErrorBag
{
    /**
     * Create an error bag and store a message on int.
     *
     * @param $message
     *
     * @return MessageBag
     */
    protected function createErrorBagForMessage($message)
    {
        return new MessageBag([
            'message' => $message,
        ]);
    }

    /**
     * Get a message bag with a message for a particular status code.
     *
     * @param $statusCode
     *
     * @return MessageBag
     */
    protected function getErrorBagForStatusCode($statusCode)
    {
        $errorMap = [
            SymfonyResponse::HTTP_UNPROCESSABLE_ENTITY => 'google2fa.error_messages.wrong_otp',
            SymfonyResponse::HTTP_BAD_REQUEST          => 'google2fa.error_messages.cannot_be_empty',
        ];

        return $this->createErrorBagForMessage(
            trans(
                config(
                    array_key_exists($statusCode, $errorMap) ? $errorMap[$statusCode] : 'google2fa.error_messages.unknown',
                    'google2fa.error_messages.unknown'
                )
            )
        );
    }
}

Fix crash if config value is not set

Fix crash if config value is not set


<?php

function startswith($haystack, $needle) {
  return substr($haystack, 0, strlen($needle)) === $needle;
}

function endswith($haystack, $needle) {
  return substr($haystack, -strlen($needle)) === $needle;
}

function get_r($x) {
  ob_start();
  print_r($x);
  return ob_get_clean();
}

function parse_strptime($a) {
  date_default_timezone_set('UTC');
  return mktime($a['tm_hour'], $a['tm_min'], $a['tm_sec'], $a['tm_mon']+1, $a['tm_mday'], $a['tm_year'] + 1900);
}

<?php

function startswith($haystack, $needle) {
  return substr($haystack, 0, strlen($needle)) === $needle;
}

function endswith($haystack, $needle) {
  return substr($haystack, -strlen($needle)) === $needle;
}

function array_flatten($array) {
  $return = array();
  array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
  return $return;
}

function parse_strptime($a) {
  date_default_timezone_set('UTC');
  return mktime($a['tm_hour'], $a['tm_min'], $a['tm_sec'], $a['tm_mon']+1, $a['tm_mday'], $a['tm_year'] + 1900);
}

Remove get_r => print_r(..., true). Add array_flatten.


@extends('layouts.default')

@section('content')

Login

					@if (count($errors) > 0)

							Whoops! There were some problems with your input.

								@foreach ($errors->all() as $error)

{{ $error }}

								@endforeach

					@endif

					<form class="form-horizontal" role="form" method="POST" action="/auth/login">
						<input type="hidden" name="_token" value="{{ csrf_token() }}">

							E-Mail Address

								<input type="email" class="form-control" name="email" value="{{ old('email') }}">

							Password

								<input type="password" class="form-control" name="password">

										<input type="checkbox" name="remember"> Remember Me

								<button type="submit" class="btn btn-primary" style="margin-right: 15px;">
									Login
								</button>

								Forgot Your Password?

					</form>

@endsection

Copy our login page to the auth endpoints


<?php

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

class CreateParticipantsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('participants', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('draw_id');
            $table->text('santa');
            $table->text('challenge');

            $table->foreign('draw_id')->references('id')->on('draws')->onDelete('cascade');
        });
    }

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

<?php

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

class CreateParticipantsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('participants', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('draw_id')->unsigned();
            $table->text('santa');
            $table->text('challenge');

            $table->foreign('draw_id')->references('id')->on('draws')->onDelete('cascade');
        });
    }

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

Fix migration refering to different column type (unsigned/signed)


<?php

namespace Yajra\CMS\Console;

use Illuminate\Console\Command;
use Yajra\CMS\Repositories\Extension\Repository;

class WidgetPublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'widget:install {name}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Install YajraCMS widget extension.';

    /**
     * @var \Yajra\CMS\Repositories\Extension\Repository
     */
    private $extensions;

    /**
     * Create a new command instance.
     *
     * @param \Yajra\CMS\Repositories\Extension\Repository $extensions
     */
    public function __construct(Repository $extensions)
    {
        parent::__construct();
        $this->extensions = $extensions;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $path = app_path('Widgets') . DIRECTORY_SEPARATOR . $this->argument('name') . '.json';

        $this->extensions->registerManifest($path);
        $this->laravel->make('cache.store')->forget('extensions.widgets');
        $this->laravel->make('cache.store')->forget('extensions.all');

        $this->info($this->argument('name') . ' widget extension installed!');
    }
}

<?php

namespace Yajra\CMS\Console;

use Illuminate\Console\Command;
use Yajra\CMS\Repositories\Extension\Repository;

class WidgetPublishCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'widget:install {name} {--path}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Install YajraCMS widget extension.';

    /**
     * @var \Yajra\CMS\Repositories\Extension\Repository
     */
    private $extensions;

    /**
     * Create a new command instance.
     *
     * @param \Yajra\CMS\Repositories\Extension\Repository $extensions
     */
    public function __construct(Repository $extensions)
    {
        parent::__construct();
        $this->extensions = $extensions;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $path = app_path('Widgets') . DIRECTORY_SEPARATOR . $this->argument('name') . '.json';

        if ($this->option('path')) {
            $path = base_path($this->argument('name'));
        }

        $this->extensions->registerManifest($path);
        $this->laravel->make('cache.store')->forget('extensions.widgets');
        $this->laravel->make('cache.store')->forget('extensions.all');

        $this->info($this->argument('name') . ' widget extension installed!');
    }
}

Allow widget installation using the path.


<?php
namespace Slack;

/**
 * An object fetched from the Slack API.
 */
abstract class ClientObject
{
    /**
     * @var ApiClient The API client the object belongs to.
     */
    protected $client;

    /**
     * @var array The object's data cached from the remote server.
     */
    protected $data = [];

    /**
     * Creates a client object from a data array.
     *
     * @param ApiClient $client The API client the object belongs to.
     * @param array     $data   An array of model data.
     */
    public function __construct(ApiClient $client, array $data)
    {
        $this->client = $client;
        $this->data = $data;
    }
}

<?php
namespace Slack;

/**
 * An object fetched from the Slack API.
 */
abstract class ClientObject
{
    /**
     * @var ApiClient The API client the object belongs to.
     */
    protected $client;

    /**
     * @var array The object's data cached from the remote server.
     */
    protected $data = [];

    /**
     * Creates a client object from a data array.
     *
     * @param ApiClient $client The API client the object belongs to.
     * @param array     $data   An array of model data.
     */
    public function __construct(ApiClient $client, array $data)
    {
        $this->client = $client;
        $this->data = $data;
    }

    /**
     * Gets the client object that created the object.
     *
     * @return ApiClient The client object that created the object.
     */
    public function getClient()
    {
        return $this->client;
    }
}

Add ability to get an object's creating client


<?php

class SassHandlerTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var SassHandler
     */
    private $sassHandler;

    /**
     * Path to the directory with fixture files
     * @var string
     */
    private $fixturesDirectory;

    protected function setUp()
    {
        $this->sassHandler = new SassHandler;
        $this->sassHandler->compilerPath =
            __DIR__ . '/../vendor/leafo/scssphp/scss.inc.php';

        // Use "compressed" formatting to simplify code with assertions
        $this->sassHandler->compilerOutputFormatting = 'compressed';

        $this->fixturesDirectory = __DIR__ . '/fixtures/';
    }

    /**
     * Test integration with scssphp compiler
     */
    public function testCompile()
    {
        $scssFile = $this->fixturesDirectory . 'compile.scss';
        $this->assertEquals(
            'body a{color:red;}',
            $this->sassHandler->compile($scssFile)
        );
    }
}

<?php

class SassHandlerTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var SassHandler
     */
    private $sassHandler;

    /**
     * Path to the directory with fixture files
     * @var string
     */
    private $fixturesDirectory;

    protected function setUp()
    {
        $this->sassHandler = new SassHandler;
        $this->sassHandler->compilerPath =
            __DIR__ . '/../vendor/leafo/scssphp/scss.inc.php';

        // Use "compressed" formatting to simplify code with assertions
        $this->sassHandler->compilerOutputFormatting = SassHandler::OUTPUT_FORMATTING_COMPRESSED;

        $this->fixturesDirectory = __DIR__ . '/fixtures/';
    }

    /**
     * Test integration with scssphp compiler
     */
    public function testCompile()
    {
        $scssFile = $this->fixturesDirectory . 'compile.scss';
        $this->assertEquals(
            'body a{color:red;}',
            $this->sassHandler->compile($scssFile)
        );
    }
}

Update compilerOutputFormatting value in the unit test


<?php

// Autofind the first available app environment
$sf_root_dir = realpath(dirname(__FILE__).'/../../../');
$apps_dir = glob($sf_root_dir.'/apps/*', GLOB_ONLYDIR);
$app = substr($apps_dir[0],
              strrpos($apps_dir[0], DIRECTORY_SEPARATOR) + 1,
              strlen($apps_dir[0]));
if (!$app)
{
  throw new Exception('No app has been detected in this project');
}

// -- path to the symfony project where the plugin resides
$sf_path = dirname(__FILE__).'/../../..';

// bootstrap
include($sf_path . '/test/bootstrap/functional.php');

// create a new test browser
$browser = new sfTestBrowser();
$browser->initialize();

// initialize database manager
$databaseManager = new sfDatabaseManager();
$databaseManager->initialize();

<?php

// Autofind the first available app environment
$sf_root_dir = realpath(dirname(__FILE__).'/../../../');
$apps_dir = glob($sf_root_dir.'/apps/*', GLOB_ONLYDIR);
$app = substr($apps_dir[0],
              strrpos($apps_dir[0], DIRECTORY_SEPARATOR) + 1,
              strlen($apps_dir[0]));
if (!$app)
{
  throw new Exception('No app has been detected in this project');
}

// -- path to the symfony project where the plugin resides
$sf_path = dirname(__FILE__).'/../../..';

// bootstrap
include($sf_path . '/test/bootstrap/functional.php');

// create a new test browser
$browser = new sfTestBrowser();
$browser->initialize();

// initialize database manager
if(method_exists('sfDatabaseManager', 'loadConfiguration'))
{
  // symfony 1.1 style
  new sfDatabaseManager($configuration);
}
else
{
  // symfony 1.0 style
  $databaseManager = new sfDatabaseManager();
  $databaseManager->initialize();
}

Allow for easier testing with sf 1.1

[wiki:DbFinderPlugin] Allow for easier testing with sf 1.1


<?php

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

// avoiding of Yii Framework class autoloader warnings
spl_autoload_unregister(array('YiiBase','autoload'));
spl_autoload_register(function ($classname) { @YiiBase::autoload($classname); });

Fix php warnings on phpunit test failures.


<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\Search\Mapping\Annotations;

use Doctrine\Common\Annotations\Annotation;

/**
 * @Annotation
 * @Target("PROPERTY")
 */
final class Field {}

/**
 * @Annotation
 * @Target("CLASS")
 */
final class Searchable {}

Add Field and Searchable to annotations

Add Field and Searchable to annotations


<?php
declare(strict_types=1);

namespace Moka\Traits;

use Moka\Moka;

/**
 * Trait MokaCleanerTrait
 * @package Moka\Traits
 */
trait MokaCleanerTrait
{
    /**
     * @return void
     */
    public function tearDown()
    {
        Moka::clean();
    }
}

<?php
declare(strict_types=1);

namespace Moka\Traits;

use Moka\Moka;

/**
 * Trait MokaCleanerTrait
 * @package Moka\Traits
 */
trait MokaCleanerTrait
{
    /**
     * @return void
     */
    public function tearDown()
    {
        Moka::reset();
    }
}

Use reset() instead of clean()

Use reset() instead of clean()


<?php

namespace R\Hive\Commands;

use Illuminate\Console\GeneratorCommand;

class MakeValidatorCommand extends GeneratorCommand
{
    protected function getPath($name)
    {
        $name = str_replace($this->laravel->getNamespace(), '', $name);

        // Add the class type to the file name.
        return $this->laravel['path'].'/'.str_replace('\\', '/', $name).$this->type.'.php';
    }
}

<?php

namespace R\Hive\Commands;

use Illuminate\Console\GeneratorCommand;

class HiveGeneratorCommand extends GeneratorCommand
{
    protected function getPath($name)
    {
        $name = str_replace($this->laravel->getNamespace(), '', $name);

        // Add the class type to the file name.
        return $this->laravel['path'].'/'.str_replace('\\', '/', $name).$this->type.'.php';
    }

    protected function getStub()
    {
        return;
    }
}

Fix invalid class name, and implement abstract method.


<?php
namespace TYPO3\Eel\FlowQuery\Operations;

/*                                                                        *
 * This script belongs to the TYPO3 Flow package "TYPO3.Eel".             *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License, either version 3   *
 * of the License, or (at your option) any later version.                 *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

use TYPO3\Eel\FlowQuery\FlowQuery;
use TYPO3\Flow\Annotations as Flow;

/**
 * Get a random element index from the context.
 *
 * This operation randomizes the order of elements contained
 * in the context.
 */
class ShuffleOperation extends AbstractOperation {

	/**
	 * {@inheritdoc}
	 *
	 * @var string
	 */
	static protected $shortName = 'shuffle';

	/**
	 * {@inheritdoc}
	 *
	 * @var boolean
	 */
	static protected $final = TRUE;

	/**
	 * {@inheritdoc}
	 *
	 * @param FlowQuery $flowQuery the FlowQuery object
	 * @param array $arguments the arguments for this operation
	 * @return mixed
	 */
	public function evaluate(FlowQuery $flowQuery, array $arguments) {
		$context = $flowQuery->getContext();
		if (count($context) > 0) {
			shuffle($context);
			$flowQuery->setContext($context);
		}
	}
}

<?php
namespace TYPO3\Eel\FlowQuery\Operations;

/*                                                                        *
 * This script belongs to the TYPO3 Flow package "TYPO3.Eel".             *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License, either version 3   *
 * of the License, or (at your option) any later version.                 *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

use TYPO3\Eel\FlowQuery\FlowQuery;
use TYPO3\Flow\Annotations as Flow;

/**
 * Get a random element index from the context.
 *
 * This operation randomizes the order of elements contained
 * in the context.
 */
class ShuffleOperation extends AbstractOperation {

	/**
	 * {@inheritdoc}
	 *
	 * @var string
	 */
	static protected $shortName = 'shuffle';

	/**
	 * {@inheritdoc}
	 *
	 * @param FlowQuery $flowQuery the FlowQuery object
	 * @param array $arguments the arguments for this operation
	 * @return mixed
	 */
	public function evaluate(FlowQuery $flowQuery, array $arguments) {
		$context = $flowQuery->getContext();
		if (count($context) > 0) {
			shuffle($context);
			$flowQuery->setContext($context);
		}
	}
}

Make shuffle() a non-final operation

[BUGFIX] Make shuffle() a non-final operation

Change-Id: I675ee102d9f799c023c07f7abcbf839b48656429
Releases: master
Reviewed-on: https://review.typo3.org/27584
Reviewed-by: Karsten Dambekalns
Tested-by: Karsten Dambekalns
Reviewed-by: Christopher Hlubek
Original-Commit-Hash: cdc83573e41778089143dc5cdb2413b825e9c200


<?php

namespace Jstewmc\Rtf\Element\HeaderTable;

/**
 * Declares fonts for use throughout the document
 */
class FontTable extends HeaderTable
{
    public function __construct(array $children = [])
    {
        $this->children = $children;
    }
}

<?php

namespace Jstewmc\Rtf\Element\HeaderTable;

/**
 * Declares fonts for use throughout the document
 */
class FontTable extends HeaderTable
{
    public function __construct(array $children = [])
    {
        $this->setChildren($children);
    }
}

Fix font table to set parent of child elements


<?php

namespace Phug\Util\Partial;

trait OptionTrait
{

    private $options = [];

    public function getOptions()
    {

        return $this->options;
    }

    public function setOptions(array $options)
    {

        $this->options = array_replace($this->options, $options);

        return $this;
    }

    public function setOptionsRecursive(array $options)
    {

        $this->options = array_replace_recursive($this->options, $options);

        return $this;
    }

    public function getOption($name)
    {

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

    public function setOption($name, $value)
    {

        $this->options[$name] = $value;

        return $this;
    }
}

<?php

namespace Phug\Util\Partial;

trait OptionTrait
{

    protected $options = [];

    public function getOptions()
    {

        return $this->options;
    }

    public function setOptions(array $options)
    {

        $this->options = array_replace($this->options, $options);

        return $this;
    }

    public function setOptionsRecursive(array $options)
    {

        $this->options = array_replace_recursive($this->options, $options);

        return $this;
    }

    public function getOption($name)
    {

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

    public function setOption($name, $value)
    {

        $this->options[$name] = $value;

        return $this;
    }
}

Allow extended class to access $options

Allow extended class to access $options


<?php

namespace Stati\Tests;

use PHPUnit_Framework_TestCase;

abstract class TestCase extends PHPUnit_Framework_TestCase
{
}

<?php

namespace Stati\Tests;

use PHPUnit\Framework\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
}

Update test for phpunit 6.*

Update test for phpunit 6.*


<?php

$config = SimpleSAML_Configuration::getInstance();
$sconfig = SimpleSAML_Configuration::getConfig('config-sanitycheck.php');

$info = array();
$errors = array();
$hookinfo = array(
	'info' => &$info,
	'errors' => &$errors,
);
SimpleSAML_Module::callHooks('sanitycheck', $hookinfo);

if (isset($_REQUEST['output']) && $_REQUEST['output'] == 'text') {

	if (count($errors) === 0) {
		echo 'OK';
	} else {
		echo 'FAIL';
	}
	exit;
}

$t = new SimpleSAML_XHTML_Template($config, 'sanitycheck:check-tpl.php');
$t->data['pageid'] = 'statistics';
$t->data['errors'] = $errors;
$t->data['info'] = $info;
$t->data['jquery'] = $jquery;
$t->show();

<?php

$config = SimpleSAML_Configuration::getInstance();
$sconfig = SimpleSAML_Configuration::getConfig('config-sanitycheck.php');

$info = array();
$errors = array();
$hookinfo = array(
	'info' => &$info,
	'errors' => &$errors,
);
SimpleSAML_Module::callHooks('sanitycheck', $hookinfo);

if (isset($_REQUEST['output']) && $_REQUEST['output'] == 'text') {

	if (count($errors) === 0) {
		echo 'OK';
	} else {
		echo 'FAIL';
	}
	exit;
}

$t = new SimpleSAML_XHTML_Template($config, 'sanitycheck:check-tpl.php');
$t->data['pageid'] = 'sanitycheck';
$t->data['errors'] = $errors;
$t->data['info'] = $info;
$t->data['jquery'] = $jquery;
$t->show();

Fix page ID for sanity check page...

Fix page ID for sanity check page...

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


<?php declare(strict_types=1);
namespace Onion\Framework\Http\Middleware\Factory;

use Onion\Framework\Router\Route;
use Psr\Container\ContainerInterface;
use Onion\Framework\Router\Interfaces\RouterInterface;
use Onion\Framework\Dependency\Interfaces\FactoryInterface;
use Onion\Framework\Http\Middleware\RequestHandler;

class RequestHandlerFactory implements FactoryInterface
{
    /** @var Router */
    private $router;

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

    public function build(ContainerInterface $container)
    {
        if (!$container->has('middleware')) {
            throw new \RuntimeException(
                'Unable to initialize RequestHandler without defined middleware'
            );
        }

        $middlewareGenerator = function () use ($container) {
            $middleware = $container->get('middleware');

            foreach ($middleware as $identifier) {
                $instance = $container->get($identifier);
                assert(
                    is_object($instance) && $instance instanceof MiddlewareInterface,
                    new \TypeError("'{$identifier}' must implement MiddlewareInterface")
                );

                yield $instance;
            }
        };
        return new RequestHandler($middlewareGenerator());
    }
}

<?php declare(strict_types=1);
namespace Onion\Framework\Http\Middleware\Factory;

use Onion\Framework\Router\Route;
use Psr\Container\ContainerInterface;
use Onion\Framework\Dependency\Interfaces\FactoryInterface;
use Onion\Framework\Http\Middleware\RequestHandler;

class RequestHandlerFactory implements FactoryInterface
{
    public function build(ContainerInterface $container)
    {
        if (!$container->has('middleware')) {
            throw new \RuntimeException(
                'Unable to initialize RequestHandler without defined middleware'
            );
        }

        $middlewareGenerator = function () use ($container) {
            $middleware = $container->get('middleware');

            foreach ($middleware as $identifier) {
                $instance = $container->get($identifier);
                assert(
                    is_object($instance) && $instance instanceof MiddlewareInterface,
                    new \TypeError("'{$identifier}' must implement MiddlewareInterface")
                );

                yield $instance;
            }
        };
        return new RequestHandler($middlewareGenerator());
    }
}

Remove obsolete reference to RouterInterface


<?php

namespace Backend\Modules\ContentBlocks\Api;

use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlock;
use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlockRepository;
use FOS\RestBundle\Controller\Annotations as Rest;
use JMS\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

final class ApiController
{
    /** @var ContentBlockRepository */
    private $blockRepository;

    /** @var SerializerInterface */
    private $serializer;

    public function __construct(ContentBlockRepository $blockRepository, SerializerInterface $serializer)
    {
        $this->blockRepository = $blockRepository;
        $this->serializer = $serializer;
    }

    /**
     * @Rest\Get("/content-blocks")
     */
    public function getContentblocksAction(): JsonResponse
    {
        return JsonResponse::create(
            json_decode(
                $this->serializer->serialize($this->blockRepository->findAll(), 'json'),
                true
            )
        );
    }

    /**
     * @Rest\Get("/content-blocks/{language}/{id}")
     *
     * @param string $language
     * @param int $id
     * @return JsonResponse
     */
    public function getContentblockAction($language, $id): JsonResponse
    {
        $contentBlock = $this->blockRepository->findOneBy(['locale' => $language, 'id' => $id]);

        if (!$contentBlock instanceof ContentBlock) {
            throw new NotFoundHttpException();
        }

        return JsonResponse::create(
            json_decode(
                $this->serializer->serialize($contentBlock, 'json'),
                true
            )
        );
    }
}

<?php

namespace Backend\Modules\ContentBlocks\Api;

use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlock;
use Backend\Modules\ContentBlocks\Domain\ContentBlock\ContentBlockRepository;
use FOS\RestBundle\Controller\Annotations as Rest;
use JMS\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

final class ApiController
{
    /** @var ContentBlockRepository */
    private $blockRepository;

    /** @var SerializerInterface */
    private $serializer;

    public function __construct(ContentBlockRepository $blockRepository, SerializerInterface $serializer)
    {
        $this->blockRepository = $blockRepository;
        $this->serializer = $serializer;
    }

    /**
     * @Rest\Get("/content-blocks")
     */
    public function getContentblocksAction(): JsonResponse
    {
        return JsonResponse::create(
            json_decode(
                $this->serializer->serialize($this->blockRepository->findAll(), 'json'),
                true
            )
        );
    }

    /**
     * @Rest\Get("/content-blocks/{language}/{id}")
     */
    public function getContentblockAction(string $language, int $id): JsonResponse
    {
        $contentBlock = $this->blockRepository->findOneBy(['locale' => $language, 'id' => $id]);

        if (!$contentBlock instanceof ContentBlock) {
            throw new NotFoundHttpException();
        }

        return JsonResponse::create(
            json_decode(
                $this->serializer->serialize($contentBlock, 'json'),
                true
            )
        );
    }
}

Add type safety to the url parameters

Add type safety to the url parameters


<?php
$showBannerOnNetwork = get_site_option('banner_setting');
$showBannerBySite = get_field('show_banner', 'options');
if ($showBannerOnNetwork == true && ($showBannerBySite == true || $showBannerBySite === null)) {
    $bannerTitle = get_site_option('banner_title');
    $bannerLinkText = get_site_option('banner_link_text');
    $bannerLink = get_site_option('banner_link'); ?>

<?php echo esc_html($bannerTitle) ?>

<a href="<?php echo esc_url($bannerLink)?>" id="take-survey" target="_blank"><?php echo esc_html($bannerLinkText) ?>

No thanks

    <?php
}
?>

Replace out-of-place h3 with a p styled as heading

Resolves: https://trello.com/c/ZpypHwAa/526-fix-banner-styling


<?php if ($offset > 0): ?>
    <a id="previous-page" href="?action=<?= $menu ?>&offset=<?= ($offset - $items_per_page) ?>&order=<?= $order ?>&direction=<?= $direction ?><?= isset($feed_id) ? '&feed_id='.$feed_id : '' ?>">« <?= t('Previous page') ?>
<?php endif ?>

<?php if (($nb_items - $offset) > $items_per_page): ?>
    <a id="next-page" href="?action=<?= $menu ?>&offset=<?= ($offset + $items_per_page) ?>&order=<?= $order ?>&direction=<?= $direction ?><?= isset($feed_id) ? '&feed_id='.$feed_id : '' ?><?= isset($group_id) ? '&group_id='.$group_id : '' ?>"><?= t('Next page') ?> »
<?php endif ?>

<?php if ($offset > 0): ?>
    <a id="previous-page" href="?action=<?= $menu ?>&offset=<?= ($offset - $items_per_page) ?>&order=<?= $order ?>&direction=<?= $direction ?><?= isset($feed_id) ? '&feed_id='.$feed_id : '' ?><?= isset($group_id) ? '&group_id='.$group_id : '' ?>">« <?= t('Previous page') ?>
<?php endif ?>

<?php if (($nb_items - $offset) > $items_per_page): ?>
    <a id="next-page" href="?action=<?= $menu ?>&offset=<?= ($offset + $items_per_page) ?>&order=<?= $order ?>&direction=<?= $direction ?><?= isset($feed_id) ? '&feed_id='.$feed_id : '' ?><?= isset($group_id) ? '&group_id='.$group_id : '' ?>"><?= t('Next page') ?> »
<?php endif ?>

Add group_id to the previous page link

Add group_id to the previous page link


<?php

class EngineBlock_Corto_ProxyServer_UnknownRemoteEntityException extends EngineBlock_Corto_ProxyServer_Exception
{
    protected $_entityId;

    public function __construct($entityId)
    {
        $this->_entityId = $entityId;
        $message = "Unknown remote entity with entityid '$entityId'";
        parent::__construct($message, self::CODE_NOTICE);
    }

    public function setEntityId($entityId)
    {
        $this->_entityId = $entityId;
        return $this;
    }

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

<?php

class EngineBlock_Corto_ProxyServer_UnknownRemoteEntityException extends EngineBlock_Corto_ProxyServer_Exception
{
    /**
     * @var string
     */
    protected $_entityId;

    /**
     * @param string         $entityId
     * @param Exception|null $previous
     */
    public function __construct($entityId, \Exception $previous = null)
    {
        $this->_entityId = $entityId;
        $message = "Unknown remote entity with entityid '$entityId'";

        parent::__construct($message, self::CODE_NOTICE, $previous);
    }

    /**
     * @param string $entityId
     * @return $this
     */
    public function setEntityId($entityId)
    {
        $this->_entityId = $entityId;
        return $this;
    }

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

Allow UnkonwRemoteEntityException to be thrown based on previous


<?php

namespace Common\Doctrine\Entity;

use Doctrine\DBAL\Exception\TableExistsException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\ORM\Tools\ToolsException;

class CreateSchema
{
    /** @var EntityManager */
    private $entityManager;

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

    /**
     * Adds a new doctrine entity in the database
     *
     * @param string $entityClass
     */
    public function forEntityClass($entityClass)
    {
        $this->forEntityClasses([$entityClass]);
    }

    /**
     * Adds new doctrine entities in the database
     *
     * @param array $entityClasses
     *
     * @throws ToolsException
     */
    public function forEntityClasses(array $entityClasses)
    {
        // create the database table for the given class using the doctrine SchemaTool
        $schemaTool = new SchemaTool($this->entityManager);

        try {
            $schemaTool->createSchema(
                array_map(
                    [$this->entityManager, 'getClassMetadata'],
                    $entityClasses
                )
            );
        } catch (TableExistsException $tableExists) {
            // do nothing
        } catch (ToolsException $toolsException) {
            if (!$toolsException->getPrevious() instanceof TableExistsException) {
                throw $toolsException;
            }
            // do nothing
        }
    }
}

<?php

namespace Common\Doctrine\Entity;

use Doctrine\DBAL\Exception\TableExistsException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\ORM\Tools\ToolsException;

class CreateSchema
{
    /** @var EntityManager */
    private $entityManager;

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

    /**
     * Adds a new doctrine entity in the database
     *
     * @param string $entityClass
     */
    public function forEntityClass($entityClass)
    {
        $this->forEntityClasses([$entityClass]);
    }

    /**
     * Adds new doctrine entities in the database
     *
     * @param array $entityClasses
     *
     * @throws ToolsException
     */
    public function forEntityClasses(array $entityClasses)
    {
        $schemaTool = new SchemaTool($this->entityManager);

        $schemaTool->updateSchema(
            array_map(
                [$this->entityManager, 'getClassMetadata'],
                $entityClasses
            ),
            true
        );
    }
}

Make sure the relations are also created when we install a module


<?php
namespace Composer\Installers;

class RadPHPInstaller extends BaseInstaller
{
    protected $locations = [
        'bundle' => 'bundles/{$name}/'
    ];

    /**
     * Format package name to CamelCase
     */
    public function inflectPackageVars($vars)
    {
        $nameParts = explode('/', $vars['name']);
        foreach ($nameParts as &$value) {
            $value = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $value));
            $value = str_replace(array('-', '_'), ' ', $value);
            $value = str_replace(' ', '', ucwords($value));
        }
        $vars['name'] = implode('/', $nameParts);
        return $vars;
    }
}

<?php
namespace Composer\Installers;

class RadPHPInstaller extends BaseInstaller
{
    protected $locations = array(
        'bundle' => 'bundles/{$name}/'
    );

    /**
     * Format package name to CamelCase
     */
    public function inflectPackageVars($vars)
    {
        $nameParts = explode('/', $vars['name']);
        foreach ($nameParts as &$value) {
            $value = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $value));
            $value = str_replace(array('-', '_'), ' ', $value);
            $value = str_replace(' ', '', ucwords($value));
        }
        $vars['name'] = implode('/', $nameParts);
        return $vars;
    }
}

Convert array to traditional syntax

Convert array to traditional syntax


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Console\Commands;

use Illuminate\Console\Command;

class CoreInstallCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:install {--f|force : Force the operation to run when in production.} {--r|resource=* : Specify which resources to publish.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Install Cortex Project.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $this->alert($this->description);

        $this->call('cortex:publish', ['--force' => $this->option('force'), '--resource' => $this->option('resource') ?: ['config']]);
        $this->call('cortex:migrate', ['--force' => $this->option('force')]);
        $this->call('cortex:seed');

        $this->call('cortex:autoload');
        $this->call('cortex:activate');
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Foundation\Console\Commands;

use Illuminate\Console\Command;

class CoreInstallCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:install {--f|force : Force the operation to run when in production.} {--r|resource=* : Specify which resources to publish.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Install Cortex Project.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $this->alert($this->description);

        $this->call('cortex:publish', ['--force' => $this->option('force'), '--resource' => $this->option('resource') ?: ['config']]);
        $this->call('cortex:migrate', ['--force' => $this->option('force')]);
        $this->call('cortex:seed');

        $this->call('cortex:autoload', ['--force' => $this->option('force')]);
        $this->call('cortex:activate', ['--force' => $this->option('force')]);
    }
}

Add 'force' option to core autoload & activate artisan command calls


<?php

namespace Yajra\CMS\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Yajra\CMS\Entities\Category;
use Yajra\CMS\Events\CategoryWasViewed;

class CategoryController extends Controller
{
    /**
     * Display an article.
     *
     * @param \Yajra\CMS\Entities\Category $category
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(Category $category, Request $request)
    {
        $category->increment('hits');

        $layout   = $request->query('layout', 'blog');
        $limit    = $request->get('limit', $layout == 'list' ? 10 : 5);
        /** @var \Illuminate\Contracts\Pagination\Paginator $articles */
        $articles = $category->articles()->published()->isNotPage()->latest()->paginate($limit);

        if ($layout === 'list') {
            $articles->appends('layout', 'list');
        }

        if ($request->has('limit')) {
            $articles->appends('limit', $limit);
        }

        event(new CategoryWasViewed($category));

        return view("category.$layout", compact('category', 'articles', 'limit'));
    }
}

<?php

namespace Yajra\CMS\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Yajra\CMS\Entities\Category;
use Yajra\CMS\Events\CategoryWasViewed;

class CategoryController extends Controller
{
    /**
     * Display an article.
     *
     * @param \Yajra\CMS\Entities\Category $category
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(Category $category, Request $request)
    {
        $category->increment('hits');

        $layout   = $request->query('layout', 'blog');
        $limit    = $request->get('limit', $layout == 'list' ? 10 : 6);
        /** @var \Illuminate\Contracts\Pagination\Paginator $articles */
        $articles = $category->articles()->published()->isNotPage()->latest()->paginate($limit);

        if ($layout === 'list') {
            $articles->appends('layout', 'list');
        }

        if ($request->has('limit')) {
            $articles->appends('limit', $limit);
        }

        event(new CategoryWasViewed($category));

        return view("category.$layout", compact('category', 'articles', 'limit'));
    }
}

Set default limit for blog to 6.

Set default limit for blog to 6.


<?php

declare(strict_types=1);

namespace Ray\Aop;

use PhpParser\NodeTraverser;
use PhpParser\Parser;
use Ray\Aop\Exception\InvalidSourceClassException;
use ReflectionClass;
use RuntimeException;

use function file_get_contents;
use function get_class;
use function is_array;
use function is_bool;

final class VisitorFactory
{
    /** @var Parser */
    private $parser;

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

    /**
     * @param ReflectionClass<object> $class
     */
    public function __invoke(ReflectionClass $class): CodeVisitor
    {
        $traverser = new NodeTraverser();
        $visitor = new CodeVisitor();
        $traverser->addVisitor($visitor);
        $fileName = $class->getFileName();
        if (is_bool($fileName)) {
            throw new InvalidSourceClassException(get_class($class));
        }

        $file = file_get_contents($fileName);
        if ($file === false) {
            throw new RuntimeException($fileName); // @codeCoverageIgnore
        }

        $stmts = $this->parser->parse($file);
        if (is_array($stmts)) {
            $traverser->traverse($stmts);
        }

        return $visitor;
    }
}

<?php

declare(strict_types=1);

namespace Ray\Aop;

use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor\NameResolver;
use PhpParser\Parser;
use Ray\Aop\Exception\InvalidSourceClassException;
use ReflectionClass;
use RuntimeException;

use function file_get_contents;
use function get_class;
use function is_array;
use function is_bool;

final class VisitorFactory
{
    /** @var Parser */
    private $parser;

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

    /**
     * @param ReflectionClass<object> $class
     */
    public function __invoke(ReflectionClass $class): CodeVisitor
    {
        $traverser = new NodeTraverser();
        $nameResolver = new NameResolver();
        $visitor = new CodeVisitor();
        $traverser->addVisitor($nameResolver);
        $traverser->addVisitor($visitor);
        $fileName = $class->getFileName();
        if (is_bool($fileName)) {
            throw new InvalidSourceClassException(get_class($class));
        }

        $file = file_get_contents($fileName);
        if ($file === false) {
            throw new RuntimeException($fileName); // @codeCoverageIgnore
        }

        $stmts = $this->parser->parse($file);
        if (is_array($stmts)) {
            $traverser->traverse($stmts);
        }

        return $visitor;
    }
}

Use NameResolver for including namespace


<?php

namespace TwinDigital\WPTools;

/**
 * Class Filter
 */
class Filter {

  /**
   * Remove active filter from $wp_filter
   * @param string $hook   Hook on which the original filter was applied.
   * @param string $class  Classname.
   * @param string $method Method.
   *
   * @todo Create tests.
   *
   * @SuppressWarnings(PHPMD.Superglobals) Don't worry, I know what I'm doing.
   * @return void
   */
  public static function remove(string $hook, string $class, string $method) {
    $filters = [];
    if (array_key_exists($hook, $GLOBALS['wp_filter']) === true) {
      $filters = $GLOBALS['wp_filter'][$hook];
    }
    if (empty($filters) === true) {
      return;
    }

    foreach ($filters as $priority => $filter) {
      foreach ($filter as $function) {
        if (is_array($function) === true
            && is_a($function['function'][0], $class) === true
            && $method === $function['function'][1]
        ) {
          remove_filter(
            $hook,
            [
              $function['function'][0],
              $method,
            ],
            $priority
          );
        }
      }
    }
  }
}

<?php

namespace TwinDigital\WPTools;

/**
 * Class Filter
 */
class Filter {

  /**
   * Remove active filter from $wp_filter
   *
   * @param string $hook   Hook on which the original filter was applied.
   * @param string $class  Classname.
   * @param string $method Method.
   *
   * @SuppressWarnings(PHPMD.Superglobals) Don't worry, I know what I'm doing.
   * @return boolean
   */
  public static function remove(string $hook, string $class, string $method): bool {
    if (array_key_exists($hook, $GLOBALS['wp_filter']) === true) {
      $filters = $GLOBALS['wp_filter'][$hook];
    } else {
      return false;
    }
    $return = false;
    foreach ($filters as $priority => $filter) {
      foreach ($filter as $function) {
        if (is_array($function) === true
            && is_a($function['function'][0], $class) === true
            && $method === $function['function'][1]
        ) {
          $return = remove_filter(
            $hook,
            [
              $function['function'][0],
              $method,
            ],
            $priority
          );
        }
      }
    }

    return $return;
  }
}

Simplify and add boolean return

Simplify and add boolean return


<?php

namespace KeyCDN;

use Illuminate\Support\ServiceProvider;
use KeyCDN\Facades\KeyCDN;
use KeyCDN\Facades\KeyCDNFacade;

/**
 * Class KeyCDNServiceProvider
 * @package KeyCDN
 */
class KeyCDNServiceProvider extends ServiceProvider
{
    /**
     * Register config files
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../config/keycdn.php' => config_path('keycdn.php'),
        ], 'keycdn');
    }

    /**
     * Register Service
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../config/keycdn.php', 'keycdn'
        );

        $this->app->bind(KeyCDN::class, function() {
            return KeyCDN::create(config('keycdn.key'));
        });
    }

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

<?php

namespace KeyCDN;

use Illuminate\Support\ServiceProvider;
use KeyCDN\Facades\KeyCDNFacade;

/**
 * Class KeyCDNServiceProvider
 * @package KeyCDN
 */
class KeyCDNServiceProvider extends ServiceProvider
{
    /**
     * Register config files
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../config/keycdn.php' => config_path('keycdn.php'),
        ], 'keycdn');
    }

    /**
     * Register Service
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../config/keycdn.php', 'keycdn'
        );

        $this->app->bind(KeyCDN::class, function() {
            return KeyCDN::create(config('keycdn.key'));
        });
    }

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

Fix issue with Service Provider

Fix issue with Service Provider


<?php
namespace Scat;

use OE\Lukas\Parser\QueryParser;
use OE\Lukas\Visitor\QueryItemPrinter;

class SearchService
{
  public function __construct() {
  }

  public function search($q) {
    $scanner= new \OE\Lukas\Parser\QueryScanner();
    $parser= new \OE\Lukas\Parser\QueryParser($scanner);
    $parser->readString($q);
    $query= $parser->parse();

    $v= new \Scat\SearchVisitor();
    $query->accept($v);

    $items= \Model::factory('Item')->select('item.*')
                                   ->left_outer_join('brand',
                                                     array('brand.id', '=',
                                                           'item.brand'))
                                   ->left_outer_join('barcode',
                                                     array('barcode.item', '=',
                                                           'item.id'))
                                   ->where_raw($v->where_clause())
                                   ->where_gte('item.active', 1)
                                   ->order_by_asc('code')
                                   ->find_many();

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

<?php
namespace Scat;

class SearchService
{
  public function __construct() {
  }

  public function search($q) {
    return [
      'items' => $this->searchItems($q),
      'products' => $this->searchProducts($q)
    ];
  }

  public function searchItems($q) {
    $scanner= new \OE\Lukas\Parser\QueryScanner();
    $parser= new \OE\Lukas\Parser\QueryParser($scanner);
    $parser->readString($q);
    $query= $parser->parse();

    $v= new \Scat\SearchVisitor();
    $query->accept($v);

    $items= \Model::factory('Item')->select('item.*')
                                   ->left_outer_join('brand',
                                                     array('brand.id', '=',
                                                           'item.brand'))
                                   ->left_outer_join('barcode',
                                                     array('barcode.item', '=',
                                                           'item.id'))
                                   ->where_raw($v->where_clause())
                                   ->where_gte('item.active', 1)
                                   ->order_by_asc('code')
                                   ->find_many();

    return $items;
  }

  public function searchProducts($q) {
    return [];
  }
}

Split item search into its own function

Split item search into its own function


<script type="text/javascript">
    jQuery(document).ready(function () {
        // dynamic table
        oTable = jQuery('#{{ $id }}').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": "/",
            "columns": [
                @foreach($columns as $name => $label)
                { 'data': '{{ $label }}' },
                @endforeach
            ]
        });
    });
</script>

<script type="text/javascript">
    jQuery(document).ready(function () {
        // dynamic table
        oTable = jQuery('#{{ $id }}').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": "{{ isset($options['route']) ? $options['route'] : '/' }}",
            "columns": [
                @foreach($columns as $name => $label)
                { 'data': '{{ $label }}' },
                @endforeach
            ]
        });
    });
</script>

Allow route option when creating a table 110