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

	public function __construct($id, $name, $description, $score, $cPath, $content) {
		$this->cID = $id;
		$this->cName = $name;
		$this->cDescription = $description;
		$this->score = $score;
		$this->cPath = $cPath;
		$this->content = $content;
		$this->nh = Loader::helper('navigation');
	}

	public function getID() {return $this->cID;}
	public function getName() {return $this->cName;}
	public function getDescription() {return $this->cDescription;}
	public function getScore() {return $this->score;}
	public function getCollectionPath() {return $this->cPath;}
	public function getCpath() {return $this->cPath;}
	public function getBodyContent() {return $this->content;}
	public function getDate($mask = '') {
		if ($mask == '') {
			$mask = t('Y-m-d H:i:s');
		}
		return date($mask, strtotime($this->cDate));
	}
	public function getPath() {
		$c = Page::getByID($this->cID);
		return $this->nh->getLinkToCollection($c, true);
	}

	public function setDate($date) { $this->cDate = $date;}
}

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

	public function __construct($id, $name, $description, $score, $cPath, $content, $cDatePublic = false) {
		$this->cID = $id;
		$this->cName = $name;
		$this->cDescription = $description;
		$this->score = $score;
		$this->cPath = $cPath;
		$this->content = $content;
		if ($cDatePublic) {
			$this->setDate($cDatePublic);
		}
		$this->nh = Loader::helper('navigation');
	}

	public function getID() {return $this->cID;}
	public function getName() {return $this->cName;}
	public function getDescription() {return $this->cDescription;}
	public function getScore() {return $this->score;}
	public function getCollectionPath() {return $this->cPath;}
	public function getCpath() {return $this->cPath;}
	public function getBodyContent() {return $this->content;}
	public function getDate($mask = '') {
		if ($mask == '') {
			$mask = t('Y-m-d H:i:s');
		}
		return date($mask, strtotime($this->cDate));
	}
	public function getPath() {
		$c = Page::getByID($this->cID);
		return $this->nh->getLinkToCollection($c, true);
	}

	public function setDate($date) { $this->cDate = $date;}
}

Add cDatePublic to indexed search result constructor

Former-commit-id: 5c4c6da19612c683470a11ed997e515bed375b7f


<?php

namespace MageTest\Manager\Attributes\Provider\Loader;

use Symfony\Component\Yaml\Yaml;

/**
 * Class YmlLoader
 *
 * @package MageTest\Manager\Attributes\Provider\Loader
 */
class YmlLoader implements Loader, ParseFields
{

    /**
     * @var \Symfony\Component\Yaml\Yaml
     */
    private $yaml;

    /**
     * @param Yaml $yaml
     */
    public function __construct(Yaml $yaml = null)
    {
        $this->yaml = $yaml ? : new Yaml;
    }

    /**
     * @param $file
     * @return array
     */
    public function load($file)
    {
        return $this->yaml->parse($file);
    }

    /**
     * @param $model
     * @return array
     */
    public function parseFields($model)
    {
        return array(
            $this->parseModel(key($model)) => array(
                'depends' => $this->parseDependencies(key($model)),
                'attributes' => reset($model)
            )
        );
    }

    /**
     * @param $key
     * @return mixed
     */
    private function parseModel($key)
    {
        preg_match("/[^ (]+/", $key, $matches);
        return reset($matches);
    }

    /**
     * @param $key
     * @return mixed
     */
    private function parseDependencies($key)
    {
        preg_match("/ \((.*)\)/", $key, $matches);
        return end($matches);
    }

}

<?php

namespace MageTest\Manager\Attributes\Provider\Loader;

use Symfony\Component\Yaml\Yaml;

/**
 * Class YmlLoader
 *
 * @package MageTest\Manager\Attributes\Provider\Loader
 */
class YmlLoader implements Loader, ParseFields
{

    /**
     * @var \Symfony\Component\Yaml\Yaml
     */
    private $yaml;

    /**
     * @param Yaml $yaml
     */
    public function __construct(Yaml $yaml = null)
    {
        $this->yaml = $yaml ? : new Yaml;
    }

    /**
     * @param $file
     * @return array
     */
    public function load($file)
    {
        return $this->yaml->parse($file);
    }

    /**
     * @param $model
     * @return array
     */
    public function parseFields($model)
    {
        return array(
            $this->parseModel(key($model)) => array(
                'depends' => $this->parseDependencies(key($model)),
                'attributes' => reset($model)
            )
        );
    }

    /**
     * @param $key
     * @return mixed
     */
    private function parseModel($key)
    {
        preg_match("/[^ (]+/", $key, $matches);
        return reset($matches);
    }

    /**
     * @param $key
     * @return mixed
     */
    private function parseDependencies($key)
    {
        preg_match("/ \((.*)\)/", $key, $matches);
        if (strstr(end($matches), ' ')) {
            return explode(" ", end($matches));
        }
        return end($matches);
    }

}

Fix broken Yaml fixture dependences parsing


<div class="backdrop_box <?php echo isset($medium_backdrop) && $medium_backdrop == 1 ? 'medium' : 'large'; ?>" id="reportissue_container">

        <?php echo __('Report an issue'); ?>
        <?= fa_image_tag('times'); ?>

        <?php include_component('main/reportissue', compact('selected_project', 'issue', 'issuetypes', 'selected_issuetype', 'selected_milestone', 'selected_build', 'parent_issue', 'errors', 'permission_errors', 'board', 'locked_issuetype')); ?>

<div class="backdrop_box <?php echo isset($medium_backdrop) && $medium_backdrop == 1 ? 'medium' : 'large'; ?>" id="reportissue_container">

        <?php echo __('Report an issue'); ?>
        <?= fa_image_tag('times'); ?>

        <?php
            $params = array();
            if (isset($selected_project))
            {
                $params['selected_project'] = $selected_project;
            }
            if (isset($issue))
            {
                $params['issue'] = $issue;
            }
            if (isset($issuetypes))
            {
                $params['issuetypes'] = $issuetypes;
            }
            if (isset($selected_issuetype))
            {
                $params['selected_issuetype'] = $selected_issuetype;
            }
            if (isset($selected_milestone))
            {
                $params['selected_milestone'] = $selected_milestone;
            }
            if (isset($selected_build))
            {
                $params['selected_build'] = $selected_build;
            }
            if (isset($parent_issue))
            {
                $params['parent_issue'] = $parent_issue;
            }
            if (isset($errors))
            {
                $params['errors'] = $errors;
            }
            if (isset($permission_errors))
            {
                $params['permission_errors'] = $permission_errors;
            }
            if (isset($board))
            {
                $params['board'] = $board;
            }
            if (isset($locked_issuetype))
            {
                $params['locked_issuetype'] = $locked_issuetype;
            }
            include_component('main/reportissue', $params);
        ?>

Check if every param is set

Check if every param is set


<?php

namespace Bolt\Nut;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Bolt\Translation\Translator as Trans;

class ExtensionsEnable extends BaseCommand
{
    protected function configure()
    {
        $this
            ->setName('extensions:enable')
            ->setAliases(array('extensions:install'))
            ->setDescription('Installs an extension by name and version.')
            ->addArgument('name', InputArgument::REQUIRED, 'Name of the extension to enable')
            ->addArgument('version', InputArgument::REQUIRED, 'Version of the extension to enable');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $name = $input->getArgument('name');
        $version = $input->getArgument('version');
        if (!isset($name) || !isset($version)) {
            $output->writeln(
                '<error>' .
                Trans::trans('You must specify both a name and a version to install!') .
                '</error>'
            );

            return;
        }

        $result = $this->app['extend.runner']->install($name, $version);

        $output->writeln("<info>[Done]</info> ");
        $output->writeln($result, OutputInterface::OUTPUT_PLAIN);

    }
}

<?php

namespace Bolt\Nut;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Bolt\Translation\Translator as Trans;

class ExtensionsEnable extends BaseCommand
{
    protected function configure()
    {
        $this
            ->setName('extensions:enable')
            ->setAliases(array('extensions:install'))
            ->setDescription('Installs an extension by name and version.')
            ->addArgument('name', InputArgument::REQUIRED, 'Name of the extension to enable')
            ->addArgument('version', InputArgument::REQUIRED, 'Version of the extension to enable');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $name = $input->getArgument('name');
        $version = $input->getArgument('version');
        if (!isset($name) || !isset($version)) {
            $output->writeln(
                '<error>' .
                Trans::__('You must specify both a name and a version to install!') .
                '</error>'
            );

            return;
        }

        $result = $this->app['extend.runner']->install($name, $version);

        $output->writeln("<info>[Done]</info> ");
        $output->writeln($result, OutputInterface::OUTPUT_PLAIN);

    }
}

Convert Trans::trans() to use __() instead


<?php
/*
 * This file is part of Yolk - Gamer Network's PHP Framework.
 *
 * Copyright (c) 2015 Gamer Network Ltd.
 *
 * Distributed under the MIT License, a copy of which is available in the
 * LICENSE file that was bundled with this package, or online at:
 * https://github.com/gamernetwork/yolk-application
 */

namespace yolk\contracts\support;

interface Config extends collections\Dictionary {

	/**
	 * Loads and parses a configuration file.
	 * The file must define an array variable $config from which the data will be loaded.
	 *
	 * @param string file   location of the configuration file.
	 * @return self
	 * @throws \LogicException if $config is not defined or not an array
	 */
	public function load( $file );

	/**
	 * Merge an array into the current configuration.
	 * @param  array  $data
	 * @return self
	 */
	public function merge( array $data );

}

// EOF

<?php
/*
 * This file is part of Yolk - Gamer Network's PHP Framework.
 *
 * Copyright (c) 2015 Gamer Network Ltd.
 *
 * Distributed under the MIT License, a copy of which is available in the
 * LICENSE file that was bundled with this package, or online at:
 * https://github.com/gamernetwork/yolk-application
 */

namespace yolk\contracts\support;

interface Config extends collections\Dictionary {

	/**
	 * Loads and parses a configuration file.
	 * The file must define an array variable $config from which the data will be loaded.
	 *
	 * @param string file   location of the configuration file.
	 * @return self
	 * @throws \LogicException if $config is not defined or not an array
	 */
	public function load( $file, $key = '' );

	/**
	 * Merge an array into the current configuration.
	 * @param  array  $data
	 * @return self
	 */
	public function merge( array $data );

}

// EOF

Support for loading a config file into a specific key


<?php

/**
 * Do not edit anything in this file unless you know what you're doing
 */

/**
 * Here's what's happening with these hooks:
 * 1. WordPress detects theme in themes/sage
 * 2. When we activate, we tell WordPress that the theme is actually in themes/sage/templates
 * 3. When we call get_template_directory() or get_template_directory_uri(), we point it back to themes/sage
 *
 * We do this so that the Template Hierarchy will look in themes/sage/templates for core WordPress themes
 * But functions.php, style.css, and index.php are all still located in themes/sage
 *
 * themes/sage/index.php also contains some self-correcting code, just in case the template option gets reset
 */
add_filter('template', function ($template) {
    return dirname($template);
});
add_action('after_switch_theme', function () {
    update_option('template', get_option('template') . '/templates');
});

/**
 * Require composer autoloader
 */
require_once __DIR__ . '/vendor/autoload.php';

<?php

/**
 * Do not edit anything in this file unless you know what you're doing
 */

/**
 * Here's what's happening with these hooks:
 * 1. WordPress detects theme in themes/sage
 * 2. When we activate, we tell WordPress that the theme is actually in themes/sage/templates
 * 3. When we call get_template_directory() or get_template_directory_uri(), we point it back to themes/sage
 *
 * We do this so that the Template Hierarchy will look in themes/sage/templates for core WordPress themes
 * But functions.php, style.css, and index.php are all still located in themes/sage
 *
 * themes/sage/index.php also contains some self-correcting code, just in case the template option gets reset
 */
add_filter('stylesheet', function ($stylesheet) {
  return dirname($stylesheet);
});
add_action('after_switch_theme', function () {
  $stylesheet = get_option('stylesheet');
  basename($stylesheet) == 'templates' || update_option('stylesheet', $stylesheet . '/templates');
});

/**
 * Require composer autoloader
 */
require_once __DIR__ . '/vendor/autoload.php';

Fix issue with WP loading wrong index.php


<?php

namespace Roots\Sage;

/**
 * Utility class which takes an array of conditional tags (or any function which returns a boolean)
 * and returns `true` if *any* of them are `true`, and `false` otherwise.
 *
 * @param array list of conditional tags (http://codex.wordpress.org/Conditional_Tags)
 *        or custom function which returns a boolean
 *
 * @return boolean
 */
class ConditionalTagCheck {
  private $conditionals;

  public $result = true;

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

    $conditionals = array_map([$this, 'checkConditionalTag'], $this->conditionals);

    if (in_array(true, $conditionals)) {
      $this->result = false;
    }
  }

  private function checkConditionalTag($conditional) {
    if (is_array($conditional)) {
      list($tag, $args) = $conditional;
    } else {
      $tag = $conditional;
      $args = false;
    }

    if (function_exists($tag)) {
      return $args ? $tag($args) : $tag();
    } else {
      return false;
    }
  }
}

<?php

namespace Roots\Sage;

/**
 * Utility class which takes an array of conditional tags (or any function which returns a boolean)
 * and returns `false` if *any* of them are `true`, and `true` otherwise.
 *
 * @param array list of conditional tags (http://codex.wordpress.org/Conditional_Tags)
 *        or custom function which returns a boolean
 *
 * @return boolean
 */
class ConditionalTagCheck {
  private $conditionals;

  public $result = true;

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

    $conditionals = array_map([$this, 'checkConditionalTag'], $this->conditionals);

    if (in_array(true, $conditionals)) {
      $this->result = false;
    }
  }

  private function checkConditionalTag($conditional) {
    if (is_array($conditional)) {
      list($tag, $args) = $conditional;
    } else {
      $tag = $conditional;
      $args = false;
    }

    if (function_exists($tag)) {
      return $args ? $tag($args) : $tag();
    } else {
      return false;
    }
  }
}

Adjust comments on ConditionalTagCheck to match actual functionality.

The check returns false, if any of it's tags are true, not vise versa.


<?php
class Secondary_Walker extends Walker_Nav_Menu{
  // Tell Walker where to inherit it's parent and id values
    var $db_fields = array(
        'parent' => 'menu_item_parent',
        'id'     => 'db_id'
    );

    /**
     * At the start of each element, output a
 and  tag structure.
     *
     * Note: Menu objects include url and title properties, so we will use those.
     */
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
      $id = (isset( $args->post_id )) ? (int)$args->post_id : false;
      $name = (isset( $args->post_title )) ? trim( $args->post_title ) : false;
      $byID = $id ? ($id != $item->object_id) : false;

      if ($name) $regex = '/'.$args->post_title.'/i';
      $byNAME = $name ? !preg_match($regex, $item->title) : false;

      if ($byID || $byNAME){
        $output .= sprintf( "\n
%s
\n",
            $item->url,
            ( $item->object_id === get_the_ID() ) ? ' class="current"' : '',
            $item->title
        );
      }

    }
}

<?php
class Secondary_Walker extends Walker_Nav_Menu{
  // Tell Walker where to inherit it's parent and id values
    var $db_fields = array(
        'parent' => 'menu_item_parent',
        'id'     => 'db_id'
    );

    /**
     * At the start of each element, output a
 and  tag structure.
     *
     * Note: Menu objects include url and title properties, so we will use those.
     */
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
      $id = (isset( $args->post_id )) ? (int)$args->post_id : false;
      $name = (isset( $args->post_title )) ? trim( $args->post_title ) : false;
      $byID = $id ? ($id != $item->object_id) : false;

      if ($name) $regex = '/'.$args->post_title.'/i';
      $byNAME = $name ? !preg_match($regex, utf8_encode($item->title)) : false;

      if ($byID || $byNAME){
        $output .= sprintf( "\n
%s
\n",
            $item->url,
            ( $item->object_id === get_the_ID() ) ? ' class="current"' : '',
            $item->title
        );
      }

    }
}

Fix character encode to utf8

Walker: Fix character encode to utf8


<?php
/**
 * Base controller for all authenticated applicants controllers
 * @author Jon Johnson <jon.johnson@ucsf.edu>
 * @package jazzee
 * @subpackage admin
 * @subpackage applicants
 */
abstract class ApplicantsController extends AdminController{
  public static function isAllowed($controller, $action, $user, $programID, $cycleID, $actionParams){
    if($programID AND $cycleID AND $user)  return $user->isAllowed($controller, $action, $programID);
    return false;
  }
}

?>

<?php
/**
 * Base controller for all authenticated applicants controllers
 * @author Jon Johnson <jon.johnson@ucsf.edu>
 * @package jazzee
 * @subpackage admin
 * @subpackage applicants
 */
abstract class ApplicantsController extends AdminController{
  public static function isAllowed($controller, $action, $user, $programID, $cycleID, $actionParams){
    if($programID AND $cycleID AND $user)  return $user->isAllowed($controller, $action, $programID);
    return false;
  }

  /**
   * Notify and applicant that their status has changed
   * Several controllers (ApplicantsView, ApplicantsDecisions) can change an applicants status (decisions, sir, answer status)
   * Use this method to send them notifications
   * @param Applicant $applicant
   */
  protected function notifyApplicantStatusUpdate(Applicant $applicant){
    $mail = JazzeeMail::getInstance();
    $message = new EmailMessage;
    $message->to($applicant->email, "{$applicant->firstName} {$applicant->lastName}");
    $message->from($applicant->Application->contactEmail, $applicant->Application->contactName);
    $message->subject = 'Application Status';
    $message->body = "We have updated your application status.  In order to protect your privacy you must login to see these changes.  " . $mail->path("apply/{$applicant->Application->Program->shortName}/{$applicant->Application->Cycle->name}/applicant/login");
    $mail->send($message);
  }
}

?>

Add method to ApplicantsController to send applicants a notification email when their status changed.


<?php

namespace Oro\Bundle\LayoutBundle\Tests\Unit\Layout\DataProvider;

use Oro\Bundle\LayoutBundle\Layout\DataProvider\PropertyAccessDataProvider;
use Symfony\Component\PropertyAccess\PropertyAccessor;

class PropertyAccessDataProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testGetValue()
    {
        $object = new \stdClass();
        $propertyPath = 'foo.bar["fee"]';
        $result = 'result';
        $propertyAccess = $this->createMock(PropertyAccessor::class);
        $propertyAccess->expects($this->once())
            ->method('getValue')
            ->with($object, $propertyPath)
            ->willReturn($result);
        $provider = new PropertyAccessDataProvider($propertyAccess);
        $actual = $provider->getValue($object, $propertyPath);
        $this->assertEquals($result, $actual);
    }
}

<?php

namespace Oro\Bundle\LayoutBundle\Tests\Unit\Layout\DataProvider;

use Symfony\Component\PropertyAccess\PropertyAccessor;

use Oro\Bundle\LayoutBundle\Layout\DataProvider\PropertyAccessDataProvider;

class PropertyAccessDataProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testGetValue()
    {
        $object = new \stdClass();
        $propertyPath = 'foo.bar["fee"]';
        $result = 'result';
        $propertyAccess = $this->createMock(PropertyAccessor::class);
        $propertyAccess->expects($this->once())
            ->method('getValue')
            ->with($object, $propertyPath)
            ->willReturn($result);
        $provider = new PropertyAccessDataProvider($propertyAccess);
        $actual = $provider->getValue($object, $propertyPath);
        $this->assertEquals($result, $actual);
    }
}

BB-6622: Create PropertyAccess data provider
- cs fix


<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / User / Controller
 */
namespace PH7;

class SearchController extends Controller
{

    public function index()
    {
        Framework\Url\Header::redirect(Framework\Mvc\Router\Uri::get('user', 'search', 'quick'));
    }

    public function quick()
    {
        $this->view->page_title = t('Search Quick Profiles');
        $this->view->h1_title = t('The Search Members | Quick Search');
        $this->output();
    }

    public function advanced()
    {
        $this->view->page_title = t('Search Advanced Profiles');
        $this->view->h1_title = t('The Search Members | Advanced Search');
        $this->output();
    }

}

<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / User / Controller
 */
namespace PH7;

class SearchController extends Controller
{

    public function index()
    {
        Framework\Url\Header::redirect(Framework\Mvc\Router\Uri::get('user', 'search', 'quick'));
    }

    public function quick()
    {
        $this->view->page_title = $this->view->h1_title = t('Quick Search');
        $this->output();
    }

    public function advanced()
    {
        $this->view->page_title = $this->view->h1_title = t('Advanced Search');
        $this->output();
    }

}

Remove unseless title/wrong English, etc


<?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\Form;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
interface DataMapperInterface
{
    /**
     * Maps properties of some data to a list of forms.
     *
     * @param mixed           $data  Structured data
     * @param FormInterface[] $forms A list of {@link FormInterface} instances
     *
     * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported.
     */
    public function mapDataToForms($data, $forms);

    /**
     * Maps the data of a list of forms into the properties of some data.
     *
     * @param FormInterface[] $forms A list of {@link FormInterface} instances
     * @param mixed           $data  Structured data
     *
     * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported.
     */
    public function mapFormsToData($forms, &$data);
}

<?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\Form;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
interface DataMapperInterface
{
    /**
     * Maps properties of some data to a list of forms.
     *
     * @param mixed                        $data  Structured data
     * @param FormInterface[]|\Traversable $forms A list of {@link FormInterface} instances
     *
     * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported.
     */
    public function mapDataToForms($data, $forms);

    /**
     * Maps the data of a list of forms into the properties of some data.
     *
     * @param FormInterface[]|\Traversable $forms A list of {@link FormInterface} instances
     * @param mixed                        $data  Structured data
     *
     * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported.
     */
    public function mapFormsToData($forms, &$data);
}

Add \Traversable typehint to phpdoc

Add \Traversable typehint to phpdoc


<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;

class APIController extends Controller
{
    /**
     * @param $request Request
     * @throws NotFoundHttpException - if the webservice is not found (status code 404)
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     * @Route("/api/{namespace}/{classname}", name="api", options={"expose" = true})
     */
    public function apiAction(Request $request, $namespace, $classname){
        try{
            $service = $this->get('app.api.webservice')->factory($namespace, $classname);
        } catch (Exception $e){
            throw $this->createNotFoundException('Webservice not found in the API');
        }
        $queryData = new ParameterBag(array_merge($request->query->all(), $request->request->all()));
        $user = null;
//        if($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){
//            $user = $this->get('security.token_storage')->getToken()->getUser();
//        }
        $result = $service->execute($queryData, $user);
        $response = $this->json($result);
        $response->headers->set('Access-Control-Allow-Origin', '*');
        return $response;
    }

}

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;

class APIController extends Controller
{
    /**
     * @param $request Request
     * @throws NotFoundHttpException - if the webservice is not found (status code 404)
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     * @Route("/api/{namespace}/{classname}", name="api", options={"expose" = true})
     */
    public function apiAction(Request $request, $namespace, $classname){
        try{
            $service = $this->get('app.api.webservice')->factory($namespace, $classname);
        } catch (Exception $e){
            throw $this->createNotFoundException('Webservice not found in the API');
        }
        $queryData = new ParameterBag(array_merge($request->query->all(), $request->request->all()));
        $user = null;
        if($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){
            $user = $this->get('security.token_storage')->getToken()->getUser();
        }
        $result = $service->execute($queryData, $user);
        $response = $this->json($result);
        $response->headers->set('Access-Control-Allow-Origin', '*');
        return $response;
    }

}

Add code in order to get the current user


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

namespace Darvin\ContentBundle\DependencyInjection\Compiler;

use Knp\DoctrineBehaviors\EventSubscriber\TranslatableEventSubscriber;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Disable KNP translatable event subscriber compiler pass
 */
class DisableKnpTranslatableSubscriberPass implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container): void
    {
        if ($container->hasDefinition(TranslatableEventSubscriber::class)) {
            $container->getDefinition(TranslatableEventSubscriber::class)->clearTag('doctrine.event_subscriber');
        }
    }
}

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

namespace Darvin\ContentBundle\DependencyInjection\Compiler;

use Knp\DoctrineBehaviors\EventSubscriber\TranslatableEventSubscriber;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Disable KNP translatable event subscriber compiler pass
 */
class DisableKnpTranslatableSubscriberPass implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container): void
    {
        if ($container->hasDefinition(TranslatableEventSubscriber::class)) {
            $container->getDefinition('darvin_content.translatable.event_subscriber.map')
                ->setDecoratedService(TranslatableEventSubscriber::class);
        }
    }
}

Fix disabling KNP translatable event subscriber compiler pass.


<?php

namespace SilverStripe\IFrame;

use SilverStripe\CMS\Controllers\ContentController;
use SilverStripe\Control\Director;
use SilverStripe\View\Requirements;

class IFramePageController extends ContentController
{
    protected function init()
    {
        parent::init();

        if ($this->ForceProtocol) {
            if ($this->ForceProtocol == 'http://' && Director::protocol() != 'http://') {
                return $this->redirect(preg_replace('#https://#', 'http://', $this->AbsoluteLink()));
            } elseif ($this->ForceProtocol == 'https://' && Director::protocol() != 'https://') {
                return $this->redirect(preg_replace('#http://#', 'https://', $this->AbsoluteLink()));
            }
        }

        if ($this->IFrameURL) {
            Requirements::javascript('iframe/javascript/iframe_page.js');
        }
    }
}

<?php

namespace SilverStripe\IFrame;

use SilverStripe\CMS\Controllers\ContentController;
use SilverStripe\Control\Director;
use SilverStripe\View\Requirements;

class IFramePageController extends ContentController
{
    protected function init()
    {
        parent::init();
        $currentProtocol = Director::protocol();
        $desiredProtocol = $this->ForceProtocol;
        if ($desiredProtocol && $currentProtocol !== $desiredProtocol) {
            $enforcedLocation = preg_replace(
                "#^${currentProtocol}#",
                $desiredProtocol,
                $this->AbsoluteLink()
            );
            return $this->redirect($enforcedLocation);
        }

        if ($this->IFrameURL) {
            Requirements::javascript('silverstripe/iframe: javascript/iframe_page.js');
        }
    }
}

FIX: Use new resource loading syntax for javascript

SilverStripe 4 vendormodule types make use of an 'expose' composer
directive to allow assets they provide to be accessed by a web request.
Previously the javascript for the iFrame resizing business tried to load
from a static path that no longer exists (referenced inside PHP), which
caused a fatal error. This has been fixed along with making the
conditional code for enforcing a protocol on the page's request a bit more
readable & easily digestable to developers.


<!DOCTYPE html>
<html <?php language_attributes(); ?>>

    <link href="http://gmpg.org/xfn/11" rel="profile">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

    <title><?php wp_title( '|', true, 'right' ); ?></title>

    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ site.baseurl }}public/apple-touch-icon-precomposed.png">
    <link rel="shortcut icon" href="{{ site.baseurl }}public/favicon.ico">

    <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

    <?php wp_head(); ?>

    <?php get_sidebar(); ?>

            <a href="<?php bloginfo('url'); ?>" title="Home"><?php bloginfo('name' ); ?>
            <?php bloginfo('description') ?>

<!DOCTYPE html>
<html <?php language_attributes(); ?>>

    <link href="http://gmpg.org/xfn/11" rel="profile">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

    <title><?php wp_title( '|', true, 'right' ); ?></title>

    <?php wp_head(); ?>

    <?php get_sidebar(); ?>

            <a href="<?php bloginfo('url'); ?>" title="Home"><?php bloginfo('name' ); ?>
            <?php bloginfo('description') ?>

Remove RSS and icon links in head.

Remove RSS and icon links in head.


<?php

class SV_OptimizedListQueries_XenForo_Model_Post extends XFCP_SV_OptimizedListQueries_XenForo_Model_Post
{
    public function preparePostJoinOptions(array $fetchOptions)
    {
        if (SV_OptimizedListQueries_Globals::$slimPostFetchForSearch)
        {
            $fetchOptions['skip_wordcount'] = true;
            if (!empty($fetchOptions['join']) && class_exists('Sidane_Threadmarks_Model_Post', false))
            {
                $fetchOptions['join'] &= ~Sidane_Threadmarks_Model_Post::FETCH_THREADMARKS;
            }
        }

        $sqlOptions = parent::preparePostJoinOptions($fetchOptions);

        if (SV_OptimizedListQueries_Globals::$slimPostFetchForSearch)
        {
            $sqlOptions['selectFields'] .= ", '' as message ";
        }

        return $sqlOptions;
    }
}

// ******************** FOR IDE AUTO COMPLETE ********************
if (false)
{
    class XFCP_SV_OptimizedListQueries_XenForo_Model_Post extends XenForo_Model_Post {}
}

<?php

class SV_OptimizedListQueries_XenForo_Model_Post extends XFCP_SV_OptimizedListQueries_XenForo_Model_Post
{
    public function preparePostJoinOptions(array $fetchOptions)
    {
        if (SV_OptimizedListQueries_Globals::$slimPostFetchForSearch)
        {
            $fetchOptions['skip_wordcount'] = true;
            if (class_exists('Sidane_Threadmarks_XenForo_Model_Post', false))
            {
                $fetchOptions['includeThreadmark'] = false;
            }
            else if (!empty($fetchOptions['join']) && class_exists('Sidane_Threadmarks_Model_Post', false))
            {
                /** @noinspection PhpUndefinedClassInspection */
                $fetchOptions['join'] &= ~Sidane_Threadmarks_Model_Post::FETCH_THREADMARKS;
            }
        }

        $sqlOptions = parent::preparePostJoinOptions($fetchOptions);

        if (SV_OptimizedListQueries_Globals::$slimPostFetchForSearch)
        {
            $sqlOptions['selectFields'] .= ", '' as message ";
        }

        return $sqlOptions;
    }
}

// ******************** FOR IDE AUTO COMPLETE ********************
if (false)
{
    class XFCP_SV_OptimizedListQueries_XenForo_Model_Post extends XenForo_Model_Post {}
}

Fix threadmark slim search results

Fix threadmark slim search results


<?php
namespace Neos\Flow\Tests\Functional\Reflection\Fixtures\Model;

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

use Neos\Flow\Annotations as Flow;

/**
 * A model fixture which is used for testing the class schema building
 *
 * @Flow\Entity
 */
class SuperEntity extends AbstractSuperEntity
{
    /**
     * Just a normal string
     *
     * @var string|null
     */
    protected $someString;
}

<?php
namespace Neos\Flow\Tests\Functional\Reflection\Fixtures\Model;

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

use Neos\Flow\Annotations as Flow;

/**
 * A model fixture which is used for testing the class schema building
 *
 * @Flow\Entity
 */
class SuperEntity extends AbstractSuperEntity
{
    /**
     * Just a normal string
     *
     * @var string|null
     */
    protected $someString;

    /**
     * Just an int that can be null
     *
     * @var null|int
     */
    protected $someNullableInt;
}

Add case for `null|...` type

TASK: Add case for `null|...` type


<?php

namespace haqqi\storm\controllers;

use haqqi\storm\Storm;
use yii\web\Controller;

/**
 * Class StormController
 *
 * Main controller that implements the layout of Storm Template
 *
 * @package haqqi\storm\controllers
 */
class StormController extends Controller {

  public function init() {
    parent::init();

    $this->layout = Storm::getComponent()->getLayoutPath();
  }
}

<?php

namespace haqqi\storm\controllers;

use haqqi\storm\Storm;
use yii\filters\ContentNegotiator;
use yii\web\Controller;

/**
 * Class StormController
 *
 * Main controller that implements the layout of Storm Template
 *
 * @package haqqi\storm\controllers
 */
class StormController extends Controller {

  public function init() {
    parent::init();

    $this->layout = Storm::getComponent()->getLayoutPath();
  }

  public function behaviors() {
    $behaviors = parent::behaviors();

    // make the response json according to the request
    $behaviors['contentNegotiator'] = [
      'class'   => ContentNegotiator::className(),
      'formats' => [
        'application/json' => Response::FORMAT_JSON,
        'text/html'        => Response::FORMAT_HTML
      ],
    ];

    return $behaviors;
  }
}

Add content negotiator for ajax

Add content negotiator for ajax


    WDI Paste
    <button class="navbar-toggler" aria-expanded="false" aria-controls="navbarCollapse" aria-label="Toggle navigation" type="button" data-toggle="collapse" data-target="#navbarCollapse">

    </button>

                Linguaggi

        Crea nuovo paste

Add fancy button on navbar

Add fancy button on navbar


@if ($trendingHashtags)

United States trends

                #Laravel

                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est.

            @foreach ($trendingHashtags as $key => $value)

                    #{{ $key }}

                        {{ $value }} {{ str_plural('post', $value) }}

            @endforeach

@endif

@if ($trendingHashtags)

United States trends

            @foreach ($trendingHashtags as $key => $value)

                    #{{ $key }}

                        {{ $value }} {{ str_plural('post', $value) }}

            @endforeach

@endif

Remove unused Trending Hashtag placeholder


<?php
try {
    // Send `204 No Content` status code
    http_response_code(204);

    // Get the raw POST data
    $data = file_get_contents('php://input');

    // Only continue if it’s valid JSON that is not just `null`, `0`, `false` or an empty string, i.e. if it could be a CSP violation report.
    if (json_decode($data)) {
        require_once('./global_functions.php');
        require_once('./connections/parameters.php');

        $db = new dbWrapper($hostname_gds_site, $username_gds_site, $password_gds_site, $database_gds_site, true);
        if ($db) {
            $headers = json_encode(getallheaders());

            $remoteIP = empty($_SERVER['REMOTE_ADDR'])
                ? NULL
                : $_SERVER['REMOTE_ADDR'];

            $db->q(
                "INSERT INTO `reports_csp`(`reportContent`, `reportHeaders`, `reportIP`) VALUES (?, ?, ?);",
                'sss',
                $data, $headers, $remoteIP
            );
        } else {
            echo 'No DB!';
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}

<?php
try {
    // Send `204 No Content` status code
    http_response_code(204);

    // Get the raw POST data
    $data = file_get_contents('php://input');

    // Only continue if it’s valid JSON that is not just `null`, `0`, `false` or an empty string, i.e. if it could be a CSP violation report.
    if (json_decode($data)) {
        require_once('./global_functions.php');
        require_once('./connections/parameters.php');

        $db = new dbWrapper($hostname_gds_site, $username_gds_site, $password_gds_site, $database_gds_site, true);
        if ($db) {
            $headers = json_encode(getallheaders());

            $remoteIP = empty($_SERVER['REMOTE_ADDR'])
                ? NULL
                : $_SERVER['REMOTE_ADDR'];

            $reportURI = empty($_SERVER["REQUEST_URI"])
                ? NULL
                : htmlentities($_SERVER["REQUEST_URI"]);

            $db->q(
                "INSERT INTO `reports_csp`(`reportContent`, `reportHeaders`, `reportIP`, `reportURI`) VALUES (?, ?, ?, ?);",
                'ssss',
                $data, $headers, $remoteIP, $reportURI
            );
        } else {
            echo 'No DB!';
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}

Update CSP report to try and capture offending page


<?php

/*
|--------------------------------------------------------------------------
| Authentication Filters
|--------------------------------------------------------------------------
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/

Route::filter('sentry_check', function() {
  if (!Sentry::check()) return Redirect::to('/');
});

Route::filter('project_check', function($route) {
  $user       = Sentry::getUser();
  $project_id = $route->getParameter('project_id');
  $project    = Project::where('user_id', $user->id)->where('id', $project_id)->first();
  if(null === $project) {
    return Redirect::to('404');
  }
});

/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
|--------------------------------------------------------------------------
|
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/

Route::filter('csrf', function() {
  if (Session::token() != Input::get('_token')) {
    throw new Illuminate\Session\TokenMismatchException;
  }
});

<?php

/*
|--------------------------------------------------------------------------
| Authentication Filters
|--------------------------------------------------------------------------
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/

Route::filter('sentry_check', function() {
  if (!Sentry::check()) return Redirect::to('/');
});

Route::filter('project_check', function($route) {
  $user       = Sentry::getUser();
  $project_id = $route->getParameter('project_id');
  $project    = Project::where('user_id', $user->id)->where('id', $project_id)->first();
  if(null === $project) {
    return Redirect::to('404');
  }
});

/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
|--------------------------------------------------------------------------
|
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/

Route::filter('csrf', function() {
  if (Session::token() !== Input::get('_token')) {
    throw new Illuminate\Session\TokenMismatchException;
  }
});

Fix for non-strict token check

Fix for non-strict token check


<?php

namespace Oro\Bundle\EntityBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;

use Oro\Bundle\EntityBundle\Entity\EntityFieldFallbackValue;

class EntityFieldFallbackTransformer implements DataTransformerInterface
{
    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (!$value instanceof EntityFieldFallbackValue) {
            return $value;
        }

        if (is_null($value->getFallback())) {
            return $value->setScalarValue($value->getOwnValue());
        }

        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (!$value instanceof EntityFieldFallbackValue) {
            return $value;
        }

        // set entity value to null, so entity will use fallback value
        $fallbackId = $value->getFallback();
        if (isset($fallbackId)) {
            $value->setScalarValue(null);
            $value->setArrayValue(null);

            return $value;
        }

        // not fallback, so make sure we clean fallback field
        $value->setFallback(null);

        if (is_array($value->getScalarValue())) {
            return $value
                ->setArrayValue($value->getScalarValue())
                ->setScalarValue(null);
        }

        return $value->setArrayValue(null);
    }
}

<?php

namespace Oro\Bundle\EntityBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;

use Oro\Bundle\EntityBundle\Entity\EntityFieldFallbackValue;

class EntityFieldFallbackTransformer implements DataTransformerInterface
{
    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        if (!$value instanceof EntityFieldFallbackValue) {
            return $value;
        }

//        if (is_null($value->getFallback())) {
//            return $value->setScalarValue($value->getOwnValue());
//        }

        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (!$value instanceof EntityFieldFallbackValue) {
            return $value;
        }

        // set entity value to null, so entity will use fallback value
        $fallbackId = $value->getFallback();
        if (isset($fallbackId)) {
            $value->setScalarValue(null);
            $value->setArrayValue(null);

            return $value;
        }

        // not fallback, so make sure we clean fallback field
        $value->setFallback(null);

        if (is_array($value->getScalarValue())) {
            return $value
                ->setArrayValue($value->getScalarValue())
                ->setScalarValue(null);
        }

        return $value->setArrayValue(null);
    }
}

BB-7487: Add Design section to edit product page
- added “pageTemplate” Entity fallback field to product
- added “Design” section
- added drop-down to set product pageTemplate to product edit page at admin section
- added pageTemplate to context in Frontend Product View page
- if  there is no page templates available, showed message (No page template)


<?php
/**
 * @package plugins.businessProcessNotification
 * @subpackage model
 */
class BusinessProcessStartNotificationTemplate extends BusinessProcessNotificationTemplate
{
	public function __construct()
	{
		$this->setType(BusinessProcessNotificationPlugin::getBusinessProcessNotificationTemplateTypeCoreValue(BusinessProcessNotificationTemplateType::BPM_START));
		parent::__construct();
	}

	/* (non-PHPdoc)
	 * @see BatchEventNotificationTemplate::dispatch()
	 */
	public function abort($scope)
	{
		$abortCaseJobType = BusinessProcessNotificationPlugin::getBusinessProcessNotificationTemplateTypeCoreValue(BusinessProcessNotificationTemplateType::BPM_ABORT);
		return $this->dispatchPerCase($scope, $abortCaseJobType);
	}
}

<?php
/**
 * @package plugins.businessProcessNotification
 * @subpackage model
 */
class BusinessProcessStartNotificationTemplate extends BusinessProcessNotificationTemplate
{
	private $disableParameters = false;

	public function __construct()
	{
		$this->setType(BusinessProcessNotificationPlugin::getBusinessProcessNotificationTemplateTypeCoreValue(BusinessProcessNotificationTemplateType::BPM_START));
		parent::__construct();
	}

	/* (non-PHPdoc)
	 * @see EventNotificationTemplate::getContentParameters()
	 */
	public function getContentParameters()
	{
		return $this->disableParameters ? array() : parent::getContentParameters();
	}

	/* (non-PHPdoc)
	 * @see EventNotificationTemplate::getUserParameters()
	 */
	public function getUserParameters()
	{
		return $this->disableParameters ? array() : parent::getUserParameters();
	}

	/* (non-PHPdoc)
	 * @see BatchEventNotificationTemplate::dispatch()
	 */
	public function abort($scope)
	{
		$abortCaseJobType = BusinessProcessNotificationPlugin::getBusinessProcessNotificationTemplateTypeCoreValue(BusinessProcessNotificationTemplateType::BPM_ABORT);
		$this->disableParameters = true;
		try
		{
			$ret = $this->dispatchPerCase($scope, $abortCaseJobType);
		}
		catch (Exception $e)
		{
			$this->disableParameters = false;
			throw $e;
		}
		$this->disableParameters = false;
		return $ret;
	}
}

Disable parameters for abort actions

Disable parameters for abort actions


@if (isset($message))

        <button type="button" class="close js-hide-alert">
            ×
            Close
        </button>

@endif

Use raw output for alert message (so that quotes are not escaped).


<?php

namespace Korobi\WebBundle\Controller;

use Korobi\WebBundle\Util\Akio;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class SecurityController extends BaseController {

    /**
     * @var Akio
     */
    private $akio;

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

    /**
     * @param Request $req
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function reportCspAction(Request $req) {
        $payload = json_decode($req->getContent(), true);
        $uri = $payload['csp-report']['document-uri'];
        $resource = $payload['csp-report']['blocked-uri'];
        $message = $this->akio->startMessage()->insertRed()->insertText("[!! CSP !!]")->insertAquaLight()->insertText(" Request to $resource on page $uri blocked.");
        $this->akio->sendMessage($message);
        return new JsonResponse("Thanks, browser.");
    }

    public function showRedirectAction(Request $req) {
        $response = new Response($this->renderView("KorobiWebBundle::error-redirect.html.twig", ["url" => $req->get("redirUrl")]), 403);
        return $response;
    }
}

<?php

namespace Korobi\WebBundle\Controller;

use Korobi\WebBundle\Util\Akio;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class SecurityController extends BaseController {

    /**
     * @var Akio
     */
    private $akio;

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

    /**
     * @param Request $req
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function reportCspAction(Request $req) {
        $payload = json_decode($req->getContent(), true);
        $uri = $payload['csp-report']['document-uri'];
        $resource = $payload['csp-report']['blocked-uri'];
        $ip = $req->getClientIp();
        $message = $this->akio->startMessage()->insertRed()->insertText("[!! CSP !!]")->insertAquaLight()->insertText(" Request to $resource on page $uri blocked via $ip.");
        $this->akio->sendMessage($message);
        return new JsonResponse("Thanks, browser.");
    }

    public function showRedirectAction(Request $req) {
        $response = new Response($this->renderView("KorobiWebBundle::error-redirect.html.twig", ["url" => $req->get("redirUrl")]), 403);
        return $response;
    }
}

Add IP address to CSP alerts.

Add IP address to CSP alerts.

I hope you've set up this properly for CloudFlare Kashike


<?php
namespace wcf\system\sitemap\object;
use wcf\data\DatabaseObject;

/**
 * Interface for sitemap objects.
 *
 * @author	Joshua Ruesweg
 * @copyright	2001-2017 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Sitemap\Object
 * @since	3.1
 */
interface ISitemapObjectObjectType {
	/**
	 * Returns the DatabaseObject class name for the sitemap object.
	 *
	 * @return 	string
	 */
	public function getObjectClass();

	/**
	 * Returns the DatabaseObjectList class name for the sitemap object.
	 *
	 * @return 	string
	 */
	public function getObjectListClass();

	/**
	 * Returns the DatabaseObjectList for the sitemap object.
	 *
	 * @return 	string
	 */
	public function getObjectList();

	/**
	 * Returns the database column, which represents the last modified date.
	 * If there isn't any column, this method should return `null`.
	 *
	 * @return 	string|null
	 */
	public function getLastModifiedColumn();

	/**
	 * Returns the permission for a guest to view a certain object for this object type.
	 *
	 * @param 	DatabaseObject 	$object
	 * @return 	boolean
	 */
	public function canView(DatabaseObject $object);
}

<?php
namespace wcf\system\sitemap\object;
use wcf\data\DatabaseObject;
use wcf\data\DatabaseObjectList;

/**
 * Interface for sitemap objects.
 *
 * @author	Joshua Ruesweg
 * @copyright	2001-2017 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Sitemap\Object
 * @since	3.1
 */
interface ISitemapObjectObjectType {
	/**
	 * Returns the DatabaseObject class name for the sitemap object.
	 *
	 * @return 	string
	 */
	public function getObjectClass();

	/**
	 * Returns the DatabaseObjectList class name for the sitemap object.
	 *
	 * @return 	string
	 */
	public function getObjectListClass();

	/**
	 * Returns the DatabaseObjectList for the sitemap object.
	 *
	 * @return 	DatabaseObjectList
	 */
	public function getObjectList();

	/**
	 * Returns the database column, which represents the last modified date.
	 * If there isn't any column, this method should return `null`.
	 *
	 * @return 	string|null
	 */
	public function getLastModifiedColumn();

	/**
	 * Returns the permission for a guest to view a certain object for this object type.
	 *
	 * @param 	DatabaseObject 	$object
	 * @return 	boolean
	 */
	public function canView(DatabaseObject $object);
}

Fix return type in sitemap object type interface


<?php

namespace League\ColorExtractor\Laravel;

use Illuminate\Support\ServiceProvider;
use League\ColorExtractor\Client;

/**
 * @author Antoine Corcy <contact@sbin.dk>
 */
class ColorExtractorServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bindShared('color-extractor', function ($app) {
            return new Client();
        });

        $this->app->alias('color-extractor', 'League\ColorExtractor\Client');
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array('color-extractor', 'League\ColorExtractor\Client');
    }
}

<?php

namespace League\ColorExtractor\Laravel;

use Illuminate\Support\ServiceProvider;
use League\ColorExtractor\Client;

/**
 * @author Antoine Corcy <contact@sbin.dk>
 */
class ColorExtractorServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('color-extractor', function ($app) {
            return new Client();
        });

        $this->app->alias('color-extractor', 'League\ColorExtractor\Client');
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array('color-extractor', 'League\ColorExtractor\Client');
    }
}

Switch to singleton method for Laravel 5.2.


<?php

class WPMessagePresenter implements MessagePresenter {

	/**
	 * @var string[]
	 */
	protected $messages;

	public function register_hooks() {
		add_action( 'admin_notices', array( $this, 'renderMessage' ) );
	}

	/**
	 * Shows a message to the user
	 *
	 * @param string $message The message to show to the user
	 */
	public function show( $message ) {
		$this->messages[] = $message;
	}

	public function renderMessage() {
		?>
			<div class="error">
				<?php echo $this->kses( $this->messages[0] ); ?>
			</div>
		<?php
	}

	public function kses( $message ) {
		return wp_kses( $message, array(
			'a' => array(
				'href' => true,
			),
			'strong' => true,
			'p' => true,
		) );
	}
}

<?php

class WPMessagePresenter implements MessagePresenter {

	/**
	 * @var string[]
	 */
	protected $messages;

	/**
	 * Registers hooks to WordPress. This is a seperate function so you can control when the hooks are registered.
	 */
	public function register_hooks() {
		add_action( 'admin_notices', array( $this, 'renderMessage' ) );
	}

	/**
	 * Shows a message to the user
	 *
	 * @param string $message The message to show to the user
	 */
	public function show( $message ) {
		$this->messages[] = $message;
	}

	public function renderMessage() {
		?>
			<div class="error">
				<?php echo $this->kses( $this->messages[0] ); ?>
			</div>
		<?php
	}

	public function kses( $message ) {
		return wp_kses( $message, array(
			'a' => array(
				'href' => true,
			),
			'strong' => true,
			'p' => true,
		) );
	}
}

Add some docs to register_hooks

Add some docs to register_hooks


<?php

/*
 * This is part of the symfonette/neon-integration package.
 *
 * (c) Martin Hasoň <martin.hason@gmail.com>
 * (c) Webuni s.r.o. <info@webuni.cz>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfonette\NeonIntegration\HttpKernel;

use Symfonette\NeonIntegration\DependencyInjection\NeonFileLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Config\FileLocator;

trait NeonContainerLoaderTrait
{
    protected function getContainerLoader(ContainerBuilder $container)
    {
        /* @var $loader \Symfony\Component\Config\Loader\Loader */
        $loader = parent::getContainerLoader($container);
        $resolver = $loader->getResolver();
        $resolver->addLoader(new NeonFileLoader($container, new FileLocator($this)));

        return $loader;
    }
}

<?php

/*
 * This is part of the symfonette/neon-integration package.
 *
 * (c) Martin Hasoň <martin.hason@gmail.com>
 * (c) Webuni s.r.o. <info@webuni.cz>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfonette\NeonIntegration\HttpKernel;

use Symfonette\NeonIntegration\DependencyInjection\NeonFileLoader;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Config\FileLocator;

trait NeonContainerLoaderTrait
{
    protected function getContainerLoader(ContainerInterface $container)
    {
        /* @var $loader \Symfony\Component\Config\Loader\Loader */
        $loader = parent::getContainerLoader($container);
        $resolver = $loader->getResolver();
        $resolver->addLoader(new NeonFileLoader($container, new FileLocator($this)));

        return $loader;
    }
}

Fix type hint in neon loader trait

Fix type hint in neon loader trait


<?php
/**
 * Spigot Timings Parser
 *
 * Written by Aikar <aikar@aikar.co>
 *
 * @license MIT
 */

class Cache {
	private static $base = '/tmp/timings_';

	public static function get($key) {
		$file = self::getFile($key);
		if (file_exists("$file.gz")) {
			return trim(gzdecode(file_get_contents("$file.gz")));
		} else if (file_exists($file)) {
			$data = trim(file_get_contents($file));
			self::put($key, $data);
			//unlink($file); // Disabled for now while legacy code is the primary code
		}
		return null;
	}
	public static function put($key, $data) {
		if (strlen($data) < MAX_CACHE_BYTES) {
			file_put_contents(self::getFile($key).".gz", gzencode($data));
		}
	}
	private static function getFile($key) {
		return self::$base . md5($key);
	}
}

<?php
/**
 * Spigot Timings Parser
 *
 * Written by Aikar <aikar@aikar.co>
 *
 * @license MIT
 */

class Cache {
	private static $base = '/tmp/timings_';

	public static function get($key) {
		$file = self::getFile($key);
		if (file_exists("$file.gz")) {
			return trim(gzdecode(file_get_contents("$file.gz")));
		} else if (file_exists($file)) {
			$data = trim(file_get_contents($file));
			self::put($key, $data);
			unlink($file);
		}
		return null;
	}
	public static function put($key, $data) {
		if (strlen($data) < MAX_CACHE_BYTES) {
			file_put_contents(self::getFile($key).".gz", gzencode($data));
		}
	}
	private static function getFile($key) {
		return self::$base . md5($key);
	}
}

Delete the unzipped cache file

Delete the unzipped cache file


<?php
/**
 * @title            Birthday Cron Class
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / App / System / Core / Asset / Cron / 24H
 * @version          1.0
 */

namespace PH7;

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

class BirthdayCoreCron extends Cron
{
    public function __construct()
    {
        parent::__construct();

        $this->send();
    }

    protected function send()
    {
        $iNum = (new BirthdayCore)->sendMails();

        if ($iNum === 0) {
            echo t('No birthday today.');
        } else {
            echo nt('%n% email sent.', '%n% emails sent.', $iNum);
        }
    }
}

// Go!
new BirthdayCoreCron;

<?php
/**
 * @title            Birthday Cron Class
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / App / System / Core / Asset / Cron / 24H
 * @version          1.0
 */

namespace PH7;

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

class BirthdayCoreCron extends Cron
{
    /** @var int */
    private $iNum;

    public function __construct()
    {
        parent::__construct();

        $this->send();
    }

    protected function send()
    {
        $$this->iNum = (new BirthdayCore)->sendMails();

        if ($this->hasBirthdays()) {
            echo t('No birthday today.');
        } else {
            echo nt('%n% email sent.', '%n% emails sent.', $iNum);
        }
    }

    /**
     * @return bool
     */
    private function hasBirthdays()
    {
        return $this->iNum === 0;
    }
}

// Go!
new BirthdayCoreCron;

Refactoring: Move code into function for better readability


<?php

namespace Northstar\Services;

use DoSomething\Gateway\Common\RestApiClient;

class Fastly extends RestApiClient
{
    /**
     * Create a new Fastly API client.
     */
    public function __construct()
    {
        $url = config('services.fastly.url');

        $options = [
            'headers' => [
                'Fastly-Key' => config('services.fastly.key'),
                'Accept'     => 'application/json',
            ],
        ];

        parent::__construct($url, $options);
    }

    /**
     * Purge object from Fastly cache based on give cache key
     *
     * @param $cacheKey String
     */
    public function purgeKey($cacheKey)
    {
        $fastlyConfigured = config('features.glide') &&
            ! is_null(config('services.fastly.url')) &&
            ! is_null(config('services.fastly.key')) &&
            ! is_null(config('services.fastly.service_id')) &&
            isset($cacheKey);

        if (! $fastlyConfigured) {
            info('image_cache_purge_failed', ['response' => 'Fastly not configured correctly on this environment.']);

            return null;
        }

        $service = config('services.fastly.service_id');

        $purgeResponse = $this->post('service/'.$service.'/purge/'.$cacheKey);

        info('image_cache_purge_successful', ['response' => $purgeResponse]);

        return $purgeResponse;
    }
}

<?php

namespace Northstar\Services;

use DoSomething\Gateway\Common\RestApiClient;

class Fastly extends RestApiClient
{
    /**
     * Create a new Fastly API client.
     */
    public function __construct()
    {
        $url = config('services.fastly.url');

        $options = [
            'headers' => [
                'Fastly-Key' => config('services.fastly.key'),
                'Accept'     => 'application/json',
            ],
        ];

        parent::__construct($url, $options);
    }

    /**
     * Purge object from Fastly cache based on give cache key
     *
     * @param $cacheKey String
     */
    public function purgeKey($cacheKey)
    {
        $fastlyConfigured = ! is_null(config('services.fastly.url')) &&
            ! is_null(config('services.fastly.key')) &&
            ! is_null(config('services.fastly.service_id')) &&
            isset($cacheKey);

        if (! $fastlyConfigured) {
            info('image_cache_purge_failed', ['response' => 'Fastly not configured correctly on this environment.']);

            return null;
        }

        $service = config('services.fastly.service_id');

        $purgeResponse = $this->post('service/'.$service.'/purge/'.$cacheKey);

        info('image_cache_purge_successful', ['response' => $purgeResponse]);

        return $purgeResponse;
    }
}

Remove glide, she doesn't even go here

Remove glide, she doesn't even go here


@section('content')

{{ trans('panichd::lang.attachment-edit') }}

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">{{ trans('panichd::lang.flash-x') }}</button>

                @include('panichd::tickets.partials.attachment_form_fields')

                {!! CollectiveForm::hidden(null, 'modal-attachment-edit', ['id'=>'hide_modal_id']) !!}

                    {!! CollectiveForm::button( trans('panichd::lang.update'), [
                        'type' => 'button',
                        'class' => 'btn btn-primary attachment_form_submit'
                    ]) !!}

@append

@section('content')

{{ trans('panichd::lang.attachment-edit') }}

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">{{ trans('panichd::lang.flash-x') }}</button>

				<fieldset id="edit_ticket_attachment">
                    @include('panichd::tickets.partials.attachment_form_fields')

                    {!! CollectiveForm::hidden(null, 'modal-attachment-edit', ['id'=>'hide_modal_id']) !!}

                        {!! CollectiveForm::button( trans('panichd::lang.update'), [
                            'type' => 'button',
                            'class' => 'btn btn-primary attachment_form_submit',
                            'data-back-div' => 'ticket_attached'
                        ]) !!}

				</fieldset>

@append

Bug: Edit ticket attachment and show changes before update


<?php
namespace Grav\Plugin;

use Grav\Common\Page\Collection;
use Grav\Common\Plugin;
use Grav\Common\Registry;
use Grav\Common\Uri;
use Grav\Common\Taxonomy;

class RandomPlugin extends Plugin
{
    /**
     * @var bool
     */
    protected $active = false;

    /**
     * @var Uri
     */
    protected $uri;

    /**
     * @var array
     */
    protected $filters = array();

    /**
     * Activate plugin if path matches to the configured one.
     */
    public function onAfterInitPlugins()
    {
        $this->uri = Registry::get('Uri');
        $route = $this->config->get('plugins.random.route');

        if ($route && $route == $this->uri->path()) {
            $this->active = true;
        }
    }

    /**
     * Display random page.
     */
    public function onAfterGetPage()
    {
        if ($this->active) {
            /** @var Taxonomy $taxonomy_map */
            $taxonomy_map = Registry::get('Taxonomy');

            $filters = (array) $this->config->get('plugins.random.filters');

            if (count($filters) > 0) {
                $collection = new Collection();
                foreach ($filters as $taxonomy => $items) {
                    if (isset($items)) {
                        $collection->append($taxonomy_map->findTaxonomy([$taxonomy => $items])->toArray());
                    }
                }

                $grav = Registry::get('Grav');
                $grav->page = $collection->random()->current();
            }
        }
    }
}

<?php
namespace Grav\Plugin;

use Grav\Common\Page\Collection;
use Grav\Common\Plugin;
use Grav\Common\Uri;
use Grav\Common\Taxonomy;

class RandomPlugin extends Plugin
{
    /**
     * @return array
     */
    public static function getSubscribedEvents() {
        return [
            'onAfterInitPlugins' => ['onAfterInitPlugins', 0],
        ];
    }

    /**
     * Activate plugin if path matches to the configured one.
     */
    public function onAfterInitPlugins()
    {
        /** @var Uri $uri */
        $uri = $this->grav['uri'];
        $route = $this->config->get('plugins.random.route');

        if ($route && $route == $uri->path()) {
            $this->enable([
                'onAfterGetPage' => ['onAfterGetPage', 0]
            ]);
        }
    }

    /**
     * Display random page.
     */
    public function onAfterGetPage()
    {
        /** @var Taxonomy $taxonomy_map */
        $taxonomy_map = $this->grav['taxonomy'];

        $filters = (array) $this->config->get('plugins.random.filters');

        if (count($filters) > 0) {
            $collection = new Collection();
            foreach ($filters as $taxonomy => $items) {
                if (isset($items)) {
                    $collection->append($taxonomy_map->findTaxonomy([$taxonomy => $items])->toArray());
                }
            }

            $this->grav['page'] = $collection->random()->current();
        }
    }
}

Convert plugin to use Symfony events

Convert plugin to use Symfony events


<?php

namespace VGMdb\Component\Swiftmailer;

use VGMdb\Component\Swiftmailer\EventListener\EmailSenderListener;
use Silex\Application;
use Silex\Provider\SwiftmailerServiceProvider as BaseSwiftmailerServiceProvider;

/**
 * Swiftmailer Provider.
 *
 * @author Gigablah <gigablah@vgmdb.net>
 */
class SwiftmailerServiceProvider extends BaseSwiftmailerServiceProvider
{
    public function boot(Application $app)
    {
        $app['dispatcher']->addSubscriber(new EmailSenderListener($app));
    }
}

<?php

namespace VGMdb\Component\Swiftmailer;

use VGMdb\Component\Swiftmailer\EventListener\EmailSenderListener;
use Silex\Application;
use Silex\Provider\SwiftmailerServiceProvider as BaseSwiftmailerServiceProvider;

/**
 * Swiftmailer Provider.
 *
 * @author Gigablah <gigablah@vgmdb.net>
 */
class SwiftmailerServiceProvider extends BaseSwiftmailerServiceProvider
{
    public function register(Application $app)
    {
        parent::register($app);

        $app['mailer'] = $app->share($app->extend('mailer', function ($mailer) use ($app) {
            if (isset($app['swiftmailer.redirect'])) {
                $redirectPlugin = new \Swift_Plugins_RedirectingPlugin($app['swiftmailer.redirect']);
                $mailer->registerPlugin($redirectPlugin);
            }

            return $mailer;
        }));
    }

    public function boot(Application $app)
    {
        $app['dispatcher']->addSubscriber(new EmailSenderListener($app));
    }
}

Add redirection option to swiftmailer config


<?php

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

class Munkireport extends Migration
{
    public function up()
    {
        $capsule = new Capsule();
        $capsule::schema()->create('munkireport', function (Blueprint $table) {
            $table->increments('id');

            $table->string('serial_number')->unique();
            $table->string('runtype');
            $table->string('version');
            $table->integer('errors');
            $table->integer('warnings');
            $table->string('manifestname')->nullable();
            $table->binary('error_json')->nullable();
            $table->binary('warning_json')->nullable();
            $table->string('starttime');
            $table->string('endtime');
            $table->string('timestamp');

            $table->index('errors','munkireport_errors');
            $table->index('manifestname','munkireport_manifestname');
            $table->index('runtype','munkireport_runtype');
            $table->index('timestamp','munkireport_timestamp');
            $table->index('version','munkireport_version');
            $table->index('warnings','munkireport_warnings');

//            $table->timestamps();
        });
    }

    public function down()
    {
        $capsule = new Capsule();
        $capsule::schema()->dropIfExists('munkireport');
    }
}

<?php

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

class Munkireport extends Migration
{
    public function up()
    {
        $capsule = new Capsule();
        $capsule::schema()->create('munkireport', function (Blueprint $table) {
            $table->increments('id');

            $table->string('serial_number')->unique();
            $table->string('runtype');
            $table->string('version');
            $table->integer('errors');
            $table->integer('warnings');
            $table->string('manifestname')->nullable();
            $table->longText('error_json')->nullable();
            $table->longText('warning_json')->nullable();
            $table->string('starttime');
            $table->string('endtime');
            $table->string('timestamp');

            $table->index('errors','munkireport_errors');
            $table->index('manifestname','munkireport_manifestname');
            $table->index('runtype','munkireport_runtype');
            $table->index('timestamp','munkireport_timestamp');
            $table->index('version','munkireport_version');
            $table->index('warnings','munkireport_warnings');

//            $table->timestamps();
        });
    }

    public function down()
    {
        $capsule = new Capsule();
        $capsule::schema()->dropIfExists('munkireport');
    }
}

Change column type in munkireport migration


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

namespace ZendTest\Code\Generator\TestAsset;

class ClassWithNamespace
{
}

<?php
namespace ZendTest\Code\Generator\TestAsset;

class ClassWithNamespace
{
}

Revert addition of docblock to test asset

- Broke test, as test was not expecting/generating docblock


@extends('layout')

@section('content')
    @component('partials.header')
        @slot('theme')
            is-dark
        @endslot
        @slot('subtitle')
            About section
        @endslot
    @endcomponent

    <Notification v-show="showNotifcation" type="info" :timer="false" @close="showNotifcation = false">
        This is a render of the current readme file from the Github repo.
    </Notification>

                {!! $markdown !!}

@stop

@extends('layout')

@section('content')
    @component('partials.header')
        @slot('theme')
            is-dark
        @endslot
        @slot('subtitle')
            About section
        @endslot
    @endcomponent

                {!! $markdown !!}

    <Notification v-show="showNotifcation" type="info" :timer="false" @close="showNotifcation = false">
        This is a render of the current readme file from the Github repo.
    </Notification>

@stop

Move the notification on the about page below the text so that when the page loads, the text gets loaded first, then the notification content and then Vue renders it as a notification


<?php

namespace Korobi\WebBundle\Util;

use GuzzleHttp\Client as GuzzleClient;

/**
 * Class to talk to Akio.
 * @package Korobi\WebBundle\Util
 */
class Akio {

    protected $guzzle;
    private $host;
    private $port;
    private $key;

    /**
     * Initialize the class.
     * @param string $host The instance host
     * @param int $port The instance port
     * @param string $key The auth key
     */
    public function __construct($host, $port, $key) {
        $this->guzzle = new GuzzleClient();
        $this->host = $host;
        $this->port = $port;
        $this->key = $key;
    }

    public function startMessage() {
        return new AkioMessageBuilder();
    }

    public function sendMessage(AkioMessageBuilder $message) {
        $text = $message->getRawText();
        $this->guzzle->get("http://" . $this->host . ":" . $this->port, [
            'query' => ['message' => $text],
            'headers' => ['X-Akio-Korobi' => $this->key]
        ]);
    }

}

<?php

namespace Korobi\WebBundle\Util;

use GuzzleHttp\Client as GuzzleClient;

/**
 * Class to talk to Akio.
 * @package Korobi\WebBundle\Util
 */
class Akio {

    protected $guzzle;
    private $host;
    private $port;
    private $key;

    /**
     * Initialize the class.
     * @param string $host The instance host
     * @param int $port The instance port
     * @param string $key The auth key
     */
    public function __construct($host, $port, $key) {
        $this->guzzle = new GuzzleClient();
        $this->host = $host;
        $this->port = $port;
        $this->key = $key;
    }

    public function startMessage() {
        return new AkioMessageBuilder();
    }

    public function sendMessage(AkioMessageBuilder $message) {
        $text = $message->getRawText();
        $this->guzzle->post("http://" . $this->host . ":" . $this->port, [
            'query' => ['message' => $text],
            'headers' => ['X-Akio-Korobi' => $this->key]
        ]);
    }

}

Make it a POST req.

Make it a POST req.


<?php

function Places_areas_response_data()
{
	Q_Valid::requireFields(array('location'), $_REQUEST, true);

	$location = $_REQUEST["location"];
	Q_Valid::requireFields(array('latitude', 'longitude', 'venue'), $location, true);

	$app = Q::app();

	$stream = new Streams_Stream();
	$stream->publisherId = $app;
	$stream->type = "Places/location";
	$stream->title = $location["venue"];
	$stream->setAttribute("latitude", $location["latitude"]);
	$stream->setAttribute("longitude", $location["longitude"]);

	if(!$stream->retrieve()) {
		$stream->save();
	}

	return $stream;
}

<?php

function Places_areas_response_data()
{
	Q_Valid::requireFields(array('location'), $_REQUEST, true);

	$location = $_REQUEST["location"];
	Q_Valid::requireFields(array('latitude', 'longitude', 'venue'), $location, true);

	$appId = Q::app();

	$stream = Places_Location::stream($appId, $location['placeId'], true);

	return $stream;
}

Use Places_location::stream to get/create Places/location stream and use appId as publisherId


  Blogue -
  Política de Privacidade -
  Contacto

Add contact page to footer

Add contact page to footer


<?php

namespace Laravel\Lumen\Testing;

trait DatabaseMigrations
{
    /**
     * Run the dabase migrations for the application.
     *
     * @return void
     */
    public function runDatabaseMigrations()
    {
        $this->artisan('migrate');

        $this->beforeApplicationDestroyed(function () {
            $this->artisan('migrate:rollback');
        });
    }
}

<?php

namespace Laravel\Lumen\Testing;

trait DatabaseMigrations
{
    /**
     * Run the database migrations for the application.
     *
     * @return void
     */
    public function runDatabaseMigrations()
    {
        $this->artisan('migrate');

        $this->beforeApplicationDestroyed(function () {
            $this->artisan('migrate:rollback');
        });
    }
}

Fix typo in database migrations trait

Fix typo in database migrations trait


<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id'); // User ID
            $table->string('name'); // Username
            $table->string('email')->unique(); // Email address
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();

            $table->string('icon'); // Users avatar. Can be filename, "$gravatar" or "$default".
        });
    }

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

Add avatar to the database schema

Add avatar to the database schema


<?php

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

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('slug')->unique();
            $table->jsonb('permissions');
            $table->timestamps();
        });
    }

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

<?php

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

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('slug')->unique();
            $table->text('permissions');
            $table->timestamps();
        });
    }

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

Fix migration to run on mysql 5.6 version


<?php

namespace Symfony\Component\Cache\Tests\Fixtures;

use Doctrine\Common\Cache\CacheProvider;

class ArrayCache extends CacheProvider
{
    private $data = [];

    protected function doFetch($id)
    {
        return $this->doContains($id) ? $this->data[$id][0] : false;
    }

    protected function doContains($id): bool
    {
        if (!isset($this->data[$id])) {
            return false;
        }

        $expiry = $this->data[$id][1];

        return !$expiry || microtime(true) < $expiry || !$this->doDelete($id);
    }

    protected function doSave($id, $data, $lifeTime = 0): bool
    {
        $this->data[$id] = [$data, $lifeTime ? microtime(true) + $lifeTime : false];

        return true;
    }

    protected function doDelete($id): bool
    {
        unset($this->data[$id]);

        return true;
    }

    protected function doFlush(): bool
    {
        $this->data = [];

        return true;
    }

    protected function doGetStats(): ?array
    {
        return null;
    }
}

<?php

namespace Symfony\Component\Cache\Tests\Fixtures;

use Doctrine\Common\Cache\CacheProvider;

class ArrayCache extends CacheProvider
{
    private $data = [];

    protected function doFetch($id): mixed
    {
        return $this->doContains($id) ? $this->data[$id][0] : false;
    }

    protected function doContains($id): bool
    {
        if (!isset($this->data[$id])) {
            return false;
        }

        $expiry = $this->data[$id][1];

        return !$expiry || microtime(true) < $expiry || !$this->doDelete($id);
    }

    protected function doSave($id, $data, $lifeTime = 0): bool
    {
        $this->data[$id] = [$data, $lifeTime ? microtime(true) + $lifeTime : false];

        return true;
    }

    protected function doDelete($id): bool
    {
        unset($this->data[$id]);

        return true;
    }

    protected function doFlush(): bool
    {
        $this->data = [];

        return true;
    }

    protected function doGetStats(): ?array
    {
        return null;
    }
}

Add return type unions to private/internal/final/test methods


<?php
class Kwc_Favourites_Box_Component extends Kwc_Abstract
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['assets']['files'][] = 'web/components/Favourites/Box/Component.js';
        $ret['favouritesPageComponent'] = 'KWC_FAVOURITES_PAGE'; //TODO set to kwc-favourites-page
        $ret['viewCache'] = false;
        $ret['placeholder']['linkText'] = trlStatic('FAVORITEN ({0})');
        return $ret;
    }

    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        $user = Kwf_Model_Abstract::getInstance('Users')->getAuthedUser();
        if ($user) {
            $model = Kwf_Model_Abstract::getInstance('Kwc_Favourites_Model');
            $select = new Kwf_Model_Select();
            $select->whereEquals('user_id', $user->id);
            $count = $model->countRows($select);
            $ret['linkText'] = str_replace('{0}', "$count", $this->_getPlaceholder('linkText'));
        }
        $ret['favourite'] = Kwf_Component_Data_Root::getInstance()
            ->getComponentByClass(Kwc_Abstract::getSetting($this->getData()->getComponentClass(), 'favouritesPageComponent'));
        return $ret;
    }
}

<?php
class Kwc_Favourites_Box_Component extends Kwc_Abstract
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['assets']['files'][] = 'kwf/Kwc/Favourites/Box/Component.js';
        $ret['favouritesPageComponent'] = 'KWC_FAVOURITES_PAGE'; //TODO set to kwc-favourites-page
        $ret['viewCache'] = false;
        $ret['placeholder']['linkText'] = trlStatic('FAVORITEN ({0})');
        return $ret;
    }

    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        $user = Kwf_Model_Abstract::getInstance('Users')->getAuthedUser();
        if ($user) {
            $model = Kwf_Model_Abstract::getInstance('Kwc_Favourites_Model');
            $select = new Kwf_Model_Select();
            $select->whereEquals('user_id', $user->id);
            $count = $model->countRows($select);
            $ret['linkText'] = str_replace('{0}', "$count", $this->_getPlaceholder('linkText'));
        }
        $ret['favourite'] = Kwf_Component_Data_Root::getInstance()
            ->getComponentByClass(Kwc_Abstract::getSetting($this->getData()->getComponentClass(), 'favouritesPageComponent'));
        return $ret;
    }
}

Change path to correct location

Change path to correct location


<?php
/**
 * Snippet for displaying a Campaign's creator property, which is an array.
 *
 * For available variables:
 * @see dosomething_campaign_load().
 */
?>

<?php print t('Created by'); ?>

      <img src="<?php print $picture['src_square']; ?>" />

    ×

The Creator

        <img src="<?php print $picture['src_square']; ?>" />

<?php print $first_name; ?> <?php print $last_initial; ?>

<?php print $city; ?>, <?php print $state; ?>

<?php print $copy; ?>

        Back to main page

Update modal creator with new heading markup.


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

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

abstract class Import
{

    protected $db;

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

    }

}

Fix indentation (remove blank line + add blank line after namespace declaration


<?php

namespace Itkg\DelayEventBundle\EventListener;

use Doctrine\Common\Persistence\ObjectManager;
use Itkg\DelayEventBundle\Event\ProcessedEvents;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class ClearMemoryEventSubscriber
 */
class ClearMemoryEventSubscriber implements EventSubscriberInterface
{
    /**
     * @var ObjectManager
     */
    private $objectManager;

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

    /**
     * @param Event $event
     */
    public function onFinish(Event $event)
    {
        $this->objectManager->flush();
        $this->objectManager->clear();
    }

    /**
     * {@inheritDoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            ProcessedEvents::FINISH  => 'onFinish',
        );
    }
}

<?php

namespace Itkg\DelayEventBundle\EventListener;

use Doctrine\Common\Persistence\ObjectManager;
use Itkg\DelayEventBundle\Event\ProcessedEvents;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class ClearMemoryEventSubscriber
 */
class ClearMemoryEventSubscriber implements EventSubscriberInterface
{
    /**
     * @var ObjectManager
     */
    private $objectManager;

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

    /**
     * @param Event $event
     */
    public function onFinish(Event $event)
    {
        $this->objectManager->flush();
    }

    /**
     * {@inheritDoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            ProcessedEvents::FINISH  => 'onFinish',
        );
    }
}

Remove doctrine manager clear due to side effect


<?php

namespace Hyperized\WeFact;

use Illuminate\Support\ServiceProvider;

class WefactServiceProvider extends ServiceProvider {

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

  /**
   * Bootstrap the application services.
   *
   * @return void
   */
  public function boot()
  {
    // Configuration file
    $configPath = __DIR__.'/config/wefact.php';
    $this->mergeConfigFrom($configPath, 'Wefact');
    $this->publishes([
      $configPath => config_path('wefact.php'),
    ]);
  }

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

  /**
   * Register the application services.
   *
   * @return void
   */
  public function register()
  {
    $this->app->bind('Wefact', function($app) {
        return new Hyperized\WeFact;
    });
  }

}

<?php

namespace Hyperized\WeFact;

use Illuminate\Support\ServiceProvider;

class WefactServiceProvider extends ServiceProvider {

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

  /**
   * Bootstrap the application services.
   *
   * @return void
   */
  public function boot()
  {
    // Configuration file
    $configPath = __DIR__.'/config/wefact.php';
    $this->mergeConfigFrom($configPath, 'Wefact');
    $this->publishes([
      $configPath => config_path('Wefact.php'),
    ]);
  }

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

  /**
   * Register the application services.
   *
   * @return void
   */
  public function register()
  {
    $this->app->bind('Wefact', function($app) {
        return new Hyperized\WeFact;
    });
  }

}

Fix config path difference (W vs w)

Fix config path difference (W vs w)


<?php

namespace Oro\Bundle\LayoutBundle\Twig;

use Symfony\Bridge\Twig\Form\TwigRendererEngineInterface;
use Symfony\Bridge\Twig\Form\TwigRendererInterface;

use Oro\Component\Layout\Renderer;

/**
 * Heavily inspired by FormRenderer class
 *
 * @see \Symfony\Bridge\Twig\Form\TwigRenderer
 */
class TwigRenderer extends Renderer implements TwigRendererInterface
{
    /**
     * @var TwigRendererEngineInterface
     */
    protected $engine;

    /**
     * @param TwigRendererEngineInterface $engine
     */
    public function __construct(TwigRendererEngineInterface $engine)
    {
        parent::__construct($engine);
    }

    /**
     * {@inheritdoc}
     */
    public function setEnvironment(\Twig_Environment $environment)
    {
        $this->engine->setEnvironment($environment);
    }
}

<?php

namespace Oro\Bundle\LayoutBundle\Twig;

use Symfony\Bridge\Twig\Form\TwigRendererEngineInterface;
use Symfony\Bridge\Twig\Form\TwigRendererInterface;

use Oro\Component\Layout\Renderer;

/**
 * Heavily inspired by TwigRenderer class
 *
 * @see \Symfony\Bridge\Twig\Form\TwigRenderer
 */
class TwigRenderer extends Renderer implements TwigRendererInterface
{
    /**
     * @var TwigRendererEngineInterface
     */
    protected $engine;

    /**
     * @param TwigRendererEngineInterface $engine
     */
    public function __construct(TwigRendererEngineInterface $engine)
    {
        parent::__construct($engine);
    }

    /**
     * {@inheritdoc}
     */
    public function setEnvironment(\Twig_Environment $environment)
    {
        $this->engine->setEnvironment($environment);
    }
}

BB-2229: Implement template based loop
 - fixed typo