<?php namespace Mja\Mail\Controllers;

use BackendMenu;
use Backend\Classes\Controller;
use Mja\Mail\Models\Email;
use Mja\Mail\Models\EmailOpens;

/**
 * Back-end Controller
 */
class Mail extends Controller
{
    public $hide_hints = false;

    public $implement = [
        'Backend.Behaviors.FormController',
        'Backend.Behaviors.ListController',
        'Backend.Behaviors.RelationController',
    ];

    public $formConfig = 'config_form.yaml';
    public $listConfig = 'config_list.yaml';
    public $relationConfig = 'config_relation.yaml';

    public $requiredPermissions = ['mja.mail.mail'];

    public $bodyClass = 'compact-container';

    /**
     * Ensure that by default our menu sidebar is active
     */
    public function __construct()
    {
        parent::__construct();
        BackendMenu::setContext('Mja.Mail', 'mail', 'mail');
    }

    public function index()
    {
        $this->vars['opens'] = EmailOpens::count();
        $this->vars['sent'] = Email::whereSent(true)->count();
        $this->vars['bounced'] = Email::whereSent(false)->count();
        $this->vars['emails'] = Email::groupBy('code')->get();

        $this->asExtension('ListController')->index();
    }
}

<?php namespace Mja\Mail\Controllers;

use BackendMenu;
use Backend\Classes\Controller;
use Mja\Mail\Models\Email;
use Mja\Mail\Models\EmailOpens;

/**
 * Back-end Controller
 */
class Mail extends Controller
{
    public $hide_hints = false;

    public $implement = [
        'Backend.Behaviors.FormController',
        'Backend.Behaviors.ListController',
        'Backend.Behaviors.RelationController',
    ];

    public $formConfig = 'config_form.yaml';
    public $listConfig = 'config_list.yaml';
    public $relationConfig = 'config_relation.yaml';

    public $requiredPermissions = ['mja.mail.mail'];

    public $bodyClass = 'compact-container';

    /**
     * Ensure that by default our menu sidebar is active
     */
    public function __construct()
    {
        parent::__construct();
        BackendMenu::setContext('Mja.Mail', 'mail', 'mail');
    }

    public function index()
    {
        $this->vars['opens'] = EmailOpens::count();
        $this->vars['sent'] = Email::whereSent(true)->count();
        $this->vars['bounced'] = Email::whereSent(false)->count();
        $this->vars['emails'] = Email::select('code')->groupBy('code')->get();

        $this->asExtension('ListController')->index();
    }
}

Fix group by for mysql 5.7

Fix group by for mysql 5.7


<?php

/**
 * This file is part of lcms.
 *
 * Plugin Manager.
 *
 * @author Mikołaj Pich <m.pich@outlook.com>
 * @package lcms\Plugins
 * @version 0.1
 */

namespace lcms\Plugins;

class PluginsManager {

	/**
	 * Run plugin manager service
	 *
	 * @param string $path from-root path to plugins directory
	 *
	 * @return void
	 */
	public static function run($path = 'content/plugins') {

	}
}

<?php

/**
 * This file is part of lcms.
 *
 * Plugins Manager.
 *
 * @author Mikołaj Pich <m.pich@outlook.com>
 * @package lcms\Plugins
 * @version 0.1
 */

namespace lcms\Plugins;

class PluginsManager {

	/**
	 * Run plugin manager service
	 *
	 * @param string $path from-root path to plugins directory
	 *
	 * @return void
	 */
	public static function run($path = 'content/plugins') {

	}
}

Add new line at the end

Add new line at the end


<?php

/**
 * Collection of upgrade steps.
 */
class CRM_Expertapplication_Upgrader extends CRM_Expertapplication_Upgrader_Base {

  public function upgrade_1001() {
    $this->executeCustomDataFile('xml/expert_data_agree_privacy_scheme.xml');
    return TRUE;
  }

}

<?php

/**
 * Collection of upgrade steps.
 */
class CRM_Expertapplication_Upgrader extends CRM_Expertapplication_Upgrader_Base {

  public function upgrade_1001() {
    $this->executeCustomDataFile('xml/expert_data_agree_privacy_scheme.xml');
    return TRUE;
  }

  public function upgrade_1003() {
    $activity_type_group_id = civicrm_api3('OptionGroup', 'getvalue', array(
      'name' => 'activity_type',
      'return' => 'id',
    ));
    CRM_Core_DAO::executeQuery("UPDATE civicrm_option_value SET label = 'Filled Out PUM CV' WHERE name = 'Fill Out PUM CV' AND option_group_id = %1", array(
      1 => array($activity_type_group_id, 'Integer')
    ));
    return TRUE;
  }

}

Update changed activity type Fill out pum CV label


<?php
namespace App\Middlewares;

use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;

/**
 * Class InlineDataMiddleware
 * @package App\Gitter\Middleware
 */
class InlineDataMiddleware implements MiddlewareInterface
{
    /**
     * @param Message $message
     * @return mixed
     */
    public function handle(Message $message)
    {
        $isImage = preg_match(
            sprintf('/([^`]%s|^%1$s)/iu', 'http(?:s)?:\/\/.*?\.(?:jpg|png|jpeg|svg|bmp|gif)')
        , $message->text);

        $isVideo = preg_match(
            sprintf('/([^`]%s|^%1$s)/iu', 'http(?:s)?:\/\/(?:www\.)?(?:youtube\.com|youtu\.be)')
        , $message->text);

        if ($isImage || $isVideo) {
            // Move to lang files
            $answer = sprintf('@%s, просьба оборачивать в кавычки ссылки на видео и изображения.', $message->user->login);
            $message->italic($answer);
        }

        return $message;
    }
}

<?php
namespace App\Middlewares;

use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;

/**
 * Class InlineDataMiddleware
 * @package App\Gitter\Middleware
 */
class InlineDataMiddleware implements MiddlewareInterface
{
    /**
     * @param Message $message
     * @return mixed
     */
    public function handle(Message $message)
    {
        $isImage = preg_match(
            sprintf('/([^`]%s|^%1$s)/iu', 'http(?:s)?:\/\/.*?\.(?:jpg|png|jpeg|svg|bmp|gif)')
        , $message->text);

        $isVideo = preg_match(
            sprintf('/([^`]%s|^%1$s)/iu', 'http(?:s)?:\/\/(?:www\.)?(?:youtube\.com|youtu\.be)')
        , $message->text);

        if (($isImage || $isVideo) && $message->user->login !== \Auth::user()->login) {
            // Move to lang files
            $answer = sprintf('@%s, просьба оборачивать в кавычки ссылки на видео и изображения.', $message->user->login);
            $message->italic($answer);
        }

        return $message;
    }
}

Add karma bot to inline data whitelist

Add karma bot to inline data whitelist


<?php

namespace WPAL\Wordpress;

class Helpers
{
	public function stripSlashesDeep($value)
	{
		return stripslashes_deep($value);
	}

	public function numberFormatI18n($number, $decimals = 0)
	{
		return number_format_i18n($number, $decimals);
	}

	public function wptexturize($text)
	{
		return wptexturize($text);
	}

	public function wpParseArgs($args, $defaults = '')
	{
		return wp_parse_args($args, $defaults);
	}

	public function sanitizeTitle($title, $fallback_title = '', $context = 'save')
	{
		return sanitize_title($title, $fallback_title, $context);
	}

	public function wpautop($pee, $br = true)
	{
		return wpautop($pee, $br);
	}
}

<?php

namespace WPAL\Wordpress;

class Helpers
{
	public function stripSlashesDeep($value)
	{
		return stripslashes_deep($value);
	}

	public function numberFormatI18n($number, $decimals = 0)
	{
		return number_format_i18n($number, $decimals);
	}

	public function wptexturize($text)
	{
		return wptexturize($text);
	}

	public function wpParseArgs($args, $defaults = '')
	{
		return wp_parse_args($args, $defaults);
	}

	public function sanitizeTitle($title, $fallback_title = '', $context = 'save')
	{
		return sanitize_title($title, $fallback_title, $context);
	}

	public function wpautop($pee, $br = true)
	{
		return wpautop($pee, $br);
	}

	/**
	 * Parses post body with HTML parser.
	 *
	 * Calls `wptexturize` and `wpautop` functions.
	 *
	 * @param $text string Text to parse.
	 * @return string HTML result.
	 */
	public function parsePostBody($text)
	{
		return $this->wpautop($this->wptexturize($text));
	}
}

Add helper method for parsing post text

Add helper method for parsing post text


<?php

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

class ModifyChargeIdType extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('charges', function (Blueprint $table) {
            $table->bigInteger('charge_id')->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('charges', function (Blueprint $table) {
            $table->integer('charge_id')->change();
        });
    }
}

Add newline for migration of charges type


<?php

/**
 * Returns the extension of the filename (path or URI) or an empty string.
 * @return string Extension of the filename starting with a dot.
 */
function getExtension($filename, $isURI = false) {

	// If $filename is an URI, get only the path component
	if ($isURI===true) $filename = parse_url($filename, PHP_URL_PATH);

	$extension = pathinfo($filename, PATHINFO_EXTENSION);

	// Special cases
	// https://github.com/electerious/Lychee/issues/482
	list($extension) = explode(':', $extension, 2);

	if (empty($extension)===false) $extension = '.' . $extension;

	return $extension;

}

?>

<?php

/**
 * Returns the extension of the filename (path or URI) or an empty string.
 * @return string Extension of the filename starting with a dot.
 */
function getExtension($filename, $isURI = false) {

	// If $filename is an URI, get only the path component
	if ($isURI===true) $filename = parse_url($filename, PHP_URL_PATH);

	$extension = pathinfo($filename, PATHINFO_EXTENSION);

	// Special cases
	// https://github.com/electerious/Lychee/issues/482
	list($extension) = explode(':', $extension, 2);
	list($extension) = explode('?', $extension, 2);

	if (empty($extension)===false) $extension = '.' . $extension;

	return $extension;

}

?>

Allow URL import of photos containing a question mark


<?php

namespace MyBB\Core\Presenters;

use Illuminate\Support\Facades\App;
use McCool\LaravelAutoPresenter\BasePresenter;

class ProfileFieldGroup extends BasePresenter
{
    public function fields()
    {
        $profileFields = $this->getWrappedObject()->getProfileFields()->get();
        $decorated = [];

        $decorator = App::make('autopresenter');
        foreach ($profileFields as $profileField) {
            $decorated[] = $decorator->decorate($profileField);
        }

        return $decorated;
    }
}

<?php

namespace MyBB\Core\Presenters;

use Illuminate\Support\Facades\App;
use McCool\LaravelAutoPresenter\BasePresenter;

class ProfileFieldGroup extends BasePresenter
{
    public function fields()
    {
        $profileFields = $this->getWrappedObject()->getProfileFields()->get();
        $profileFields = $profileFields->sortBy('display_order');
        $decorated = [];

        $decorator = App::make('autopresenter');
        foreach ($profileFields as $profileField) {
            $decorated[] = $decorator->decorate($profileField);
        }

        return $decorated;
    }
}

Sort using the display_order when we present the fields from a group


<?php

class SourceController extends BaseController {

    public function show($path = null)
    {
        if(is_dir(base_path() . "/query/" . $path)) // Check if it's a folder
            return View::make('folder')->with('path', $path);
        else
        {
            return View::make('file')
            	->with('file', $path)
            	->with('path', $path);
        }
    }

    public static function getDir($path)
    {
    	$elements = scandir(base_path() . "/" . $path);
  		unset($elements[0]);
  		unset($elements[1]);
  		return array_values($elements);
    }

    public static function linkedPath($path)
    {
    	$array = explode("/", $path);
    	$out = "";
    	$last = "/lists";
    	$lastElementKey = sizeof($array) - 1;

    	foreach ($array as $k => $v) {
    		if ($k < $lastElementKey) {
    			$url = $last . "/" . $v;
	    		$out .= "" . $v . "/";
    			$last = $url;
    		}
    	}

    	$out .= $array[$lastElementKey];
    	return $out;

    }
}

<?php

class SourceController extends BaseController {

    public function show($path = null)
    {
        if(is_dir(base_path() . "/query/" . $path)) // Check if it's a folder
            return View::make('folder')->with('path', $path);
        else
        {
            return View::make('file')
            	->with('file', $path)
            	->with('path', $path);
        }
    }

    public static function getDir($path)
    {
        if (!is_dir(base_path() . "/" . $path))
            return array();
    	$elements = scandir(base_path() . "/" . $path);
  		unset($elements[0]);
  		unset($elements[1]);
  		return array_values($elements);
    }

    public static function linkedPath($path)
    {
    	$array = explode("/", $path);
    	$out = "";
    	$last = "/lists";
    	$lastElementKey = sizeof($array) - 1;

    	foreach ($array as $k => $v) {
    		if ($k < $lastElementKey) {
    			$url = $last . "/" . $v;
	    		$out .= "" . $v . "/";
    			$last = $url;
    		}
    	}

    	$out .= $array[$lastElementKey];
    	return $out;

    }
}

Make possible to have no folder without returnig weird errors


<?php
class Kwc_Basic_Link_Trl_Component extends Kwc_Abstract_Composite_Trl_Component
{
    public static function getSettings($mainComponentClass)
    {
        $ret = parent::getSettings($mainComponentClass);
        $ret['ownModel'] = Kwc_Abstract::getSetting($mainComponentClass, 'ownModel');
        $ret['assets']['dep'][] = 'ExtFormFields';
        $ret['assets']['files'][] = 'kwf/Kwc/Basic/Link/Trl/CopyButton.js';
        $ret['throwHasContentChangedOnRowColumnsUpdate'] = 'text';
        return $ret;
    }

    public function getTemplateVars(Kwf_Component_Renderer_Abstract $renderer = null)
    {
        $ret = parent::getTemplateVars($renderer);
        $ret['text'] = $this->_getRow()->text;
        return $ret;
    }

    public function hasContent()
    {
        if (!$this->_getRow()->text) return false;
        return parent::hasContent();
    }
}

<?php
class Kwc_Basic_Link_Trl_Component extends Kwc_Abstract_Composite_Trl_Component
{
    public static function getSettings($mainComponentClass)
    {
        $ret = parent::getSettings($mainComponentClass);
        $ret['ownModel'] = Kwc_Abstract::getSetting($mainComponentClass, 'ownModel');
        $ret['assetsAdmin']['dep'][] = 'ExtFormFields';
        $ret['assetsAdmin']['files'][] = 'kwf/Kwc/Basic/Link/Trl/CopyButton.js';
        $ret['throwHasContentChangedOnRowColumnsUpdate'] = 'text';
        return $ret;
    }

    public function getTemplateVars(Kwf_Component_Renderer_Abstract $renderer = null)
    {
        $ret = parent::getTemplateVars($renderer);
        $ret['text'] = $this->_getRow()->text;
        return $ret;
    }

    public function hasContent()
    {
        if (!$this->_getRow()->text) return false;
        return parent::hasContent();
    }
}

Change dependencies to load only in backend


<?php

	namespace ChickenWire;

	use ChickenWire\Core\Mime;

	class Layout
	{

		private $_content;

		protected $controller;

		public function __construct($layout, $controller, $content)
		{

			// Localize
			$this->_content = $content;
			$this->controller = $controller;

			// Create translation functions
			$t = I18n::translateClosure();

			// Load the file
			require $layout;

		}

		protected function yield($block = 'main')
		{

			// Any content?
			if (!array_key_exists($block, $this->_content)) return;

			// Output the content
			echo $this->_content[$block];

		}

	}

?>

<?php

	namespace ChickenWire;

	use ChickenWire\Core\Mime;

	class Layout
	{

		private $_content;

		protected $controller;

		protected $config;

		public function __construct($layout, $controller, $content)
		{

			// Localize
			$this->_content = $content;
			$this->controller = $controller;

			// Get config
			$this->config = Application::getConfiguration();

			// Create translation functions
			$t = I18n::translateClosure();

			// Load the file
			require $layout;

		}

		protected function yield($block = 'main')
		{

			// Any content?
			if (!array_key_exists($block, $this->_content)) return;

			// Output the content
			echo $this->_content[$block];

		}

	}

?>

Make configuration available in layout

Make configuration available in layout


<?php

/*
 * This file is part of the Sonata project.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\PageBundle\Page\Service;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;

use Sonata\PageBundle\Model\PageInterface;

/**
 * Abstract page service that provides a basic implementation
 *
 * @author Olivier Paradis <paradis.olivier@gmail.com>
 */
abstract class BasePageService implements PageServiceInterface
{
    /**
     * Page service name used in the admin
     *
     * @var string
     */
    protected $name;

    /**
     * Constructor
     *
     * @param string $name Page service name
     */
    public function __construct($name)
    {
        $this->name = $name;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * {@inheritdoc}
     */
    abstract public function execute(PageInterface $page, Request $request, array $parameters = array(), Response $response = null);
}

<?php

/*
 * This file is part of the Sonata project.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\PageBundle\Page\Service;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;

use Sonata\PageBundle\Model\PageInterface;

/**
 * Abstract page service that provides a basic implementation
 *
 * @author Olivier Paradis <paradis.olivier@gmail.com>
 */
abstract class BasePageService implements PageServiceInterface
{
    /**
     * Page service name used in the admin
     *
     * @var string
     */
    protected $name;

    /**
     * Constructor
     *
     * @param string $name Page service name
     */
    public function __construct($name)
    {
        $this->name = $name;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->name;
    }
}

Remove unneeded abstract method implementation


<?php
/**
 * Class for a dice session
 *
 * Encapsulates the saving and restoring of dice
 */
class CDiceSession
{
  const SESS_VAR = 'dice';

  private $dice;

  public function __construct() {
    $this->dice = new CSessionVar(self::SESS_VAR, array());
  }

  public function getDice() {
    return $this->dice->get();
  }

  public function addDice(CDice $dice) {
    // Possible because CSessionVar->get() returns a reference
    array_push($this->dice->get(), $dice);
  }

  public function clearDice() {
    $this->dice->clear();
  }
}

<?php
/**
 * Class for a dice session
 *
 * Encapsulates the saving and restoring of dice
 */
class CDiceSession
{
  const SESS_VAR = 'dice';

  private $dice;

  public function __construct() {
    $this->dice = new CSessionVar($this::SESS_VAR, array());
  }

  public function getDice() {
    return $this->dice->get();
  }

  public function addDice(CDice $dice) {
    // Possible because CSessionVar->get() returns a reference
    array_push($this->dice->get(), $dice);
  }

  public function clearDice() {
    $this->dice->clear();
  }
}

Use $this instead of self when accessing const


<?php

namespace Ketmo\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class AcmeCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('acme')
            ->setDescription('Hack me')
            ->addArgument('name', InputArgument::OPTIONAL)
            ->addOption('yell', null, InputOption::VALUE_NONE)
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $text = '<info>Hello</info>';

        $name = $input->getArgument('name');
        if ($name) {
            $text .= ' <comment>'.$name.'</comment>';
        }

        if ($input->getOption('yell')) {
            $text .= ' !!!';
        }

        $output->writeln($text);
    }
}

<?php

namespace Ketmo\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class AcmeCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('acme')
            ->setDescription('Hack me')
            ->addArgument('name', InputArgument::OPTIONAL)
            ->addOption('yell', null, InputOption::VALUE_NONE)
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $text = '<info>Hi</info>';

        $name = $input->getArgument('name');
        if ($name) {
            $text .= ' <comment>'.$name.'</comment>';
        }

        if ($input->getOption('yell')) {
            $text .= ' !!!';
        }

        $output->writeln($text);
    }
}

Change in the acme command

Change in the acme command


<?php
/**
 * Single Re Google Review
 *
 * @package Google Review
 */

get_header();

$google_review   = get_post_meta( $post->ID, 're-google-review-google-place-id', true );
$facebook_review = get_post_meta( $post->ID, 're-google-review-facebook', true );
?>

Use Google
to leave your review?

	<a href="http://search.google.com/local/writereview?placeid=<?php echo esc_html( $google_review ); ?>" class="button"><?php esc_html_e( 'Yes', 'domain' ); ?>

	<?php if ( $facebook_review ) { ?>

<?php esc_html_e( '- OR -', 'domain' ); ?>

		<a href="<?php echo esc_url( $facebook_review ); ?>" class="button"><?php esc_html_e( 'Facebook', 'domain' ); ?>
	<?php } ?>

<?php get_footer(); ?>

<?php
/**
 * Single Re Google Review
 *
 * @package Google Review
 */

get_header();

$google_review          = get_post_meta( $post->ID, 're-google-review-google-place-id', true );
$facebook_review        = get_post_meta( $post->ID, 're-google-review-facebook', true );
$healthy_hearing_review = get_post_meta( $post->ID, 're-google-review-healthy-hearing', true );
?>

Use Google
to leave your review?

	<a href="http://search.google.com/local/writereview?placeid=<?php echo esc_html( $google_review ); ?>" class="button"><?php esc_html_e( 'Yes', 'domain' ); ?>

	<?php if ( $facebook_review ) { ?>

<?php esc_html_e( '- OR -', 'domain' ); ?>

		<a href="<?php echo esc_url( $facebook_review ); ?>" class="button"><?php esc_html_e( 'Facebook', 'domain' ); ?>
	<?php } ?>

<?php get_footer(); ?>

Add new meta field for healthy hearing, add id attribute to heading.


<?php
define('ENVIRONMENT_LOCAL', 0);
define('ENVIRONMENT_CURRENT', ENVIRONMENT_LOCAL);

define('DOMAIN', getenv('MULTISITE_DOMAIN'));
define('BASE_URL','http://movies.'.DOMAIN.'/');
define('SUPER_SEARCH_URL', 'http://search.'.DOMAIN.'/index.php?q=');
define('ROOT_PATH', dirname(__FILE__, 2).'/');

define('API_URL', BASE_URL.'api/');
define('HOME_URL', BASE_URL.'index.php');
define('RATED_URL', BASE_URL.'rated.php');
define('SUGGESTIONS_URL', BASE_URL.'suggestions.php');
define('STYLES_URL', BASE_URL.'styles/');
define('SCRIPTS_URL', BASE_URL.'scripts/');

define('INC_PATH', ROOT_PATH.'inc/');
define('VIEWS_PATH', INC_PATH.'views/');
define('CONTROLLERS_PATH', INC_PATH.'controllers/');

<?php
define('ENVIRONMENT_LOCAL', 0);
define('ENVIRONMENT_CURRENT', ENVIRONMENT_LOCAL);

define('DOMAIN', getenv('MULTISITE_DOMAIN'));
define('BASE_URL','http://movies.'.DOMAIN.'/');
define('SUPER_SEARCH_URL', 'http://search.'.DOMAIN.'/index.php?q=');
define('ROOT_PATH', dirname(__FILE__, 2).'/');

define('API_URL', BASE_URL.'api/');
define('HOME_URL', BASE_URL.'');
define('RATED_URL', BASE_URL.'rated/');
define('SUGGESTIONS_URL', BASE_URL.'suggestions/');
define('STYLES_URL', BASE_URL.'styles/');
define('SCRIPTS_URL', BASE_URL.'scripts/');

define('INC_PATH', ROOT_PATH.'inc/');
define('VIEWS_PATH', INC_PATH.'views/');
define('CONTROLLERS_PATH', INC_PATH.'controllers/');

Edit page urls to remove .php

Edit page urls to remove .php


@extends('home.master')

@section('title')
        Login
@stop

@section('content')

        		<form action="" method="POST" class="form-horizontal" id="loginForm">
                                {!! csrf_field() !!}

                                <input type="text" name="username" class="form-control" id="inputUsername" placeholder="Username" {{{ (Session::has('username') ? 'value=' . Session::get('username') : '') }}}>

                                <input type="password" name="password" class="form-control" id="inputPassword" placeholder="Password">

                                <button type="submit" class="btn btn-primary btn-block">Sign in</button>
                        </form>

@stop

@extends('home.master')

@section('title')
        Login
@stop

@section('content')

        		<form action="" method="POST" class="form-horizontal" id="loginForm">
                                {!! csrf_field() !!}

                                        Login
                                        <input type="text" name="username" class="form-control" id="inputUsername" placeholder="Username" {{{ (Session::has('username') ? 'value=' . Session::get('username') : '') }}}>

                                        Password
                                        <input type="password" name="password" class="form-control" id="inputPassword" placeholder="Password">

                                <button type="submit" class="btn btn-primary btn-block">Sign in</button>
                        </form>

@stop

Add labels to input fields

Add labels to input fields


<?php
namespace Aluc\Views;

use Aluc\Service\Laboratorio;
use Aluc\Service\Moderador;
use Aluc\Tools\TemplateGenerator;

class ModeradoresView {
    private $data;
    private $template;
    private static $instance = null;

    protected function __construct() {

    }

    public static function getInstance() {
        if (static::$instance == null) {
            static::$instance = new static();
        }
        return static::$instance;
    }

    public function render() {
        TemplateGenerator::generate($this->data, $this->template);
    }

    public function listAll() {
        $moderadores = Moderador::getAll();
        $this->data = array(
            'moderadores' => $moderadores
        );
        $this->template = 'moderadores.php';
        return $this;
    }
}

<?php
namespace Aluc\Views;

use Aluc\Service\Laboratorio;
use Aluc\Service\Moderador;
use Aluc\Tools\TemplateGenerator;

class ModeradoresView {
    private $data;
    private $template;
    private static $instance = null;

    protected function __construct() {

    }

    public static function getInstance() {
        if (static::$instance == null) {
            static::$instance = new static();
        }
        return static::$instance;
    }

    public function render() {
        TemplateGenerator::generate($this->data, $this->template);
        return $this;
    }

    public function listAll() {
        $moderadores = Moderador::getAll();
        $this->data = array(
            'moderadores' => $moderadores
        );
        $this->template = 'moderadores.php';
        return $this;
    }
}

Return this for chaining methods

Return this for chaining methods


<?php

namespace CtiDigital\Configurator\Model\Configurator\Config;

use Magento\Framework\Config\SchemaLocatorInterface;
use Magento\Framework\Module\Dir;

class SchemaLocator implements SchemaLocatorInterface
{

    protected $schema;

    public function __construct(\Magento\Framework\Module\Dir\Reader $reader)
    {
        $this->schema =
            $reader->getModuleDir(Dir::MODULE_ETC_DIR, 'CtiDigital_Configurator')
            . '/'
            . 'configurator.xsd';
    }

    /**
     * {@inheritdoc}
     */
    public function getSchema()
    {
        $this->schema;
    }

    /**
     * Only one schema will every be required once merged.
     *
     * @return null
     */
    public function getPerFileSchema()
    {
        return null;
    }
}

<?php

namespace CtiDigital\Configurator\Model\Configurator\Config;

use Magento\Framework\Config\SchemaLocatorInterface;
use Magento\Framework\Module\Dir;

class SchemaLocator implements SchemaLocatorInterface
{

    protected $schema;

    public function __construct(\Magento\Framework\Module\Dir\Reader $reader)
    {
        $this->schema =
            $reader->getModuleDir(Dir::MODULE_ETC_DIR, 'CtiDigital_Configurator')
            . '/'
            . 'configurator.xsd';
    }

    /**
     * {@inheritdoc}
     */
    public function getSchema()
    {
        return $this->schema;
    }

    /**
     * Only one schema will every be required once merged.
     *
     * @return null
     */
    public function getPerFileSchema()
    {
        return null;
    }
}

Fix null xsd schema on config xml reading


<?php if ($skill): ?>

    <?php foreach ($skill['photos'] as $photo): ?>
        <img src="<?php echo h($photo['thumbnail']); ?>_small" class="img-responsive" alt="">
        <?php break; ?>
    <?php endforeach; ?>

<?php echo h($skill['name']['text']); ?>

<?php echo $skill['description']['text']; ?>

<?php else: ?>

<?php echo t('Empty skill block.')?>

<?php endif; ?>

<?php if ($skill && isset($skill['name'])): ?>

    <?php foreach ($skill['photos'] as $photo): ?>
        <img src="<?php echo h($photo['thumbnail']); ?>_small" class="img-responsive" alt="">
        <?php break; ?>
    <?php endforeach; ?>

<?php echo h($skill['name']['text']); ?>

<?php echo $skill['description']['text']; ?>

<?php else: ?>

<?php echo t('Empty skill block.')?>

<?php endif; ?>

Check if Skill is found in Skill block

Check if Skill is found in Skill block


<?php

namespace PhlyMongo;

use Mongo;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class MongoConnectionFactory implements FactoryInterface
{
    protected $server  = 'mongodb://localhost:27017';
    protected $options = array('connect' => true);

    public function __construct($server = null, array $options = null)
    {
        if (null !== $server) {
            $this->server = $server;
        }
        if (null !== $options) {
            $this->options = $options;
        }
    }

    public function createService(ServiceLocatorInterface $services)
    {
        return new Mongo($this->server, $this->options);
    }
}

<?php
namespace PhlyMongo;

use Mongo;
use MongoClient;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class MongoConnectionFactory implements FactoryInterface
{

    protected $server = 'mongodb://localhost:27017';

    protected $options = array(
        'connect' => true
    );

    public function __construct($server = null, array $options = null)
    {
        if (null !== $server) {
            $this->server = $server;
        }
        if (null !== $options) {
            $this->options = $options;
        }
    }

    public function createService(ServiceLocatorInterface $services)
    {
        if (class_exists('MongoClient')) {
            return new MongoClient($this->server, $this->options);
        } else {
            return new Mongo($this->server, $this->options);
        }
    }
}

Connect with MongoClient if exists. Class found in driver >=1.3.0. Mongo class deprecated


<?php
/**
 * mbc-logging-gateway
 *
 * Collect user import activity from the userImportExistingLoggingQueue. Update
 * the LoggingAPI / database with import activity via mb-logging.
 */

date_default_timezone_set('America/New_York');
define('CONFIG_PATH',  __DIR__ . '/messagebroker-config');

// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\MBC_LoggingGateway\MBC_LoggingGateway;

// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-logging-gateway.config.inc';

echo '------- mbc-impoert-logging START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

// Kick off
$mb = new MessageBroker($credentials, $config);
$mb->consumeMessage(array(new MBC_LoggingGateway($mb, $settings), 'consumeQueue'));

echo '------- mbc-impoert-logging END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

<?php
/**
 * mbc-logging-gateway
 *
 * Collect user import activity from the userImportExistingLoggingQueue. Update
 * the LoggingAPI / database with import activity via mb-logging.
 */

date_default_timezone_set('America/New_York');
define('CONFIG_PATH',  __DIR__ . '/messagebroker-config');
// The number of messages for the consumer to reserve with each callback
// See consumeMwessage for further details.
// Necessary for parallel processing when more than one consumer is running on the same queue.
define('QOS_SIZE', 1);

// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\MBC_LoggingGateway\MBC_LoggingGateway;

// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-logging-gateway.config.inc';

echo '------- mbc-impoert-logging START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

// Kick off
$mb = new MessageBroker($credentials, $config);
$mb->consumeMessage(array(new MBC_LoggingGateway($mb, $settings), 'consumeQueue'), QOS_SIZE);

echo '------- mbc-impoert-logging END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

Add QOS setting to blocking call to support parallel processing


<?php

namespace Stratedge\PassportFacebook\Console;

use Illuminate\Console\Command;

class FacebookCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'passport:facebook {client_id : ID of the client}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Grant a client access to the Facebook grant';

    /**
     * Execute the console command.
     *
     * @param  \Laravel\Passport\ClientRepository  $clients
     * @return void
     */
    public function handle(ClientRepository $clients)
    {
        $client = Client::find($this->argument("client_id"));

        if (!$client) {
            throw new Exception("Could not find client with ID " . $this->argument("client_id"));
        }

        $client->facebook_client = true;

        $client->save();

        $this->info("Client " . $this->argument("client_id") . " has been granted access to the Facebook grant.");
    }
}

<?php

namespace Stratedge\PassportFacebook\Console;

use Illuminate\Console\Command;
use Laravel\Passport\Client;

class FacebookCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'passport:facebook {client_id : ID of the client}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Grant a client access to the Facebook grant';

    /**
     * Execute the console command.
     *
     * @param  \Laravel\Passport\ClientRepository  $clients
     * @return void
     */
    public function handle()
    {
        $client = Client::find($this->argument("client_id"));

        if (!$client) {
            throw new Exception("Could not find client with ID " . $this->argument("client_id"));
        }

        $client->facebook_client = true;

        $client->save();

        $this->info("Client " . $this->argument("client_id") . " has been granted access to the Facebook grant.");
    }
}

Fix dependency injection in Facebook command


<?php

namespace League\Glide\Manipulators;

use Intervention\Image\Image;
use League\Glide\Manipulators\Helpers\Color;

/**
 * @property string $bg
 */
class Background extends BaseManipulator
{
    /**
     * Perform blur image manipulation.
     * @param  Image $image The source image.
     * @return Image The manipulated image.
     */
    public function run(Image $image)
    {
        if (is_null($this->bg)) {
            return $image;
        }

        $color = (new Color($this->bg))->formatted();

        if ($color) {
            $new = $image->getDriver()->newImage($image->width(), $image->height(), $color);
            $new->mime = $image->mime;
            $image = $new->insert($image, 'top-left', 0, 0);
        }

        return $image;
    }
}

<?php

namespace League\Glide\Manipulators;

use Intervention\Image\Image;
use League\Glide\Manipulators\Helpers\Color;

/**
 * @property string $bg
 */
class Background extends BaseManipulator
{
    /**
     * Perform background image manipulation.
     * @param  Image $image The source image.
     * @return Image The manipulated image.
     */
    public function run(Image $image)
    {
        if (is_null($this->bg)) {
            return $image;
        }

        $color = (new Color($this->bg))->formatted();

        if ($color) {
            $new = $image->getDriver()->newImage($image->width(), $image->height(), $color);
            $new->mime = $image->mime;
            $image = $new->insert($image, 'top-left', 0, 0);
        }

        return $image;
    }
}

Correct background image manipulation doc


<?php

use Illuminate\Contracts\Console\Kernel;
use Symfony\Component\Console\Output\ConsoleOutput;

require __DIR__ . '/autoload.php';

$app = require __DIR__ . '/app.php';

/** @var \Pterodactyl\Console\Kernel $kernel */
$kernel = $app->make(Kernel::class);

/**
 * Bootstrap the kernel and prepare application for testing.
 */
$kernel->bootstrap();

$output = new ConsoleOutput;

/**
 * Perform database migrations and reseeding before continuing with
 * running the tests.
 */
$output->writeln(PHP_EOL . '<comment>Refreshing database for Integration tests...</comment>');
$kernel->call('migrate:fresh', ['--database' => 'testing']);

$output->writeln('<comment>Seeding database for Integration tests...</comment>' . PHP_EOL);
$kernel->call('db:seed', ['--database' => 'testing']);

<?php

use Illuminate\Contracts\Console\Kernel;
use Symfony\Component\Console\Output\ConsoleOutput;

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

$app = require __DIR__ . '/app.php';

/** @var \Pterodactyl\Console\Kernel $kernel */
$kernel = $app->make(Kernel::class);

/**
 * Bootstrap the kernel and prepare application for testing.
 */
$kernel->bootstrap();

$output = new ConsoleOutput;

/**
 * Perform database migrations and reseeding before continuing with
 * running the tests.
 */
$output->writeln(PHP_EOL . '<comment>Refreshing database for Integration tests...</comment>');
$kernel->call('migrate:fresh', ['--database' => 'testing']);

$output->writeln('<comment>Seeding database for Integration tests...</comment>' . PHP_EOL);
$kernel->call('db:seed', ['--database' => 'testing']);

Fix path to autoload file

Fix path to autoload file


<?php

namespace SearchApi\Models;

/**
 * Class SearchTerm - A search term is a basic unit that will be used to build a query for
 * Search providers.
 */
class SearchTerm {
  public $value;          // (string)     This will be a keyword from NerTagger, location from ReverseGeocoder, etc.
  public $category;       // (string)     Category as string: 'location', 'person', 'organization', etc.
  public $related;        // (string[])   Array of related keywords
  public $count;          // (int)        Occurences of keyword
  public $isUserInput;    // (bool)       TRUE if term is a user-specified keyword, FALSE if it is not

  function __construct( $value, $category, $related, $count, $isUserInput ) {
    $this->value = $value;
    $this->category = $category;
    $this->related = $related;
    $this->count = $count;
    $this->isUserInput = $isUserInput;
  }
}

<?php

namespace SearchApi\Models;

/**
 * Class SearchTerm - A search term is a basic unit that will be used to build a query for
 * Search providers.
 *
 * @var $value       string      This will be a keyword from NerTagger, location from ReverseGeocoder, etc.
 * @var $category    string      'location', 'person', 'organization', etc.
 * @var $related     string[]    Array of related keywords
 * @var $count       int         Occurences of keyword
 * @var $isUserInput bool        TRUE if term is a user-specified keyword, FALSE if it is not
 */
class SearchTerm {
  public $value;
  public $category;
  public $related;
  public $count;
  public $isUserInput;

  function __construct( $value, $category, $related, $count, $isUserInput ) {
    $this->value = $value;
    $this->category = $category;
    $this->related = $related;
    $this->count = $count;
    $this->isUserInput = $isUserInput;
  }
}

Add phpdoc-style comments to SearchTerm

Add phpdoc-style comments to SearchTerm


<?php
// (c) Copyright 2002-2010 by authors of the Tiki Wiki/CMS/Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

// Wiki plugin to output superscript ...
// based on sub plugin

function wikiplugin_sup_help() {
        return tra("Displays text in superscript.").":
~np~{SUP()}text{SUP}~/np~";
}

function wikiplugin_sup_info() {
	return array(
		'name' => tra( 'Superscript' ),
		'documentation' => 'PluginSup',
		'description' => tra('Displays text in superscript (exponent).'),
		'prefs' => array( 'wikiplugin_sup' ),
		'body' => tra('text'),
		'icon' => 'pics/icons/text_superscript.png',
		'params' => array(
		),
	);
}

function wikiplugin_sup($data, $params)
{
        global $tikilib;

        extract ($params,EXTR_SKIP);
	return "$data";
}

<?php
// (c) Copyright 2002-2010 by authors of the Tiki Wiki/CMS/Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

// Wiki plugin to output superscript ...
// based on sub plugin

function wikiplugin_sup_help() {
        return tra("Displays text in superscript.").":
~np~{SUP()}text{SUP}~/np~";
}

function wikiplugin_sup_info() {
	return array(
		'name' => tra( 'Superscript' ),
		'documentation' => tra('PluginSup'),
		'description' => tra('Displays text in superscript (exponent).'),
		'prefs' => array( 'wikiplugin_sup' ),
		'body' => tra('text'),
		'icon' => 'pics/icons/text_superscript.png',
		'params' => array(
		),
	);
}

function wikiplugin_sup($data, $params)
{
        global $tikilib;

        extract ($params,EXTR_SKIP);
	return "$data";
}

Add tra to plugin info

Add tra to plugin info

git-svn-id: 9bac41f8ebc9458fc3e28d41abfab39641e8bd1c@31052 b456876b-0849-0410-b77d-98878d47e9d5


<?php

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

namespace Symfony\Bridge\Doctrine\Logger;

use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Doctrine\DBAL\Logging\DebugStack;

/**
 * DbalLogger.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class DbalLogger extends DebugStack
{
    protected $logger;

    /**
     * Constructor.
     *
     * @param LoggerInterface $logger A LoggerInterface instance
     */
    public function __construct(LoggerInterface $logger = null)
    {
        $this->logger = $logger;
    }

    /**
     * {@inheritdoc}
     */
    public function startQuery($sql, array $params = null, array $types = null)
    {
        parent::startQuery($sql, $params, $types);

        if (null !== $this->logger) {
            $this->log($sql.' ('.json_encode($params).')');
        }
    }

    /**
     * Logs a message.
     *
     * @param string $message A message to log
     */
    public function log($message)
    {
        $this->logger->debug($message);
    }
}

<?php

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

namespace Symfony\Bridge\Doctrine\Logger;

use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Doctrine\DBAL\Logging\DebugStack;

/**
 * DbalLogger.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class DbalLogger extends DebugStack
{
    protected $logger;

    /**
     * Constructor.
     *
     * @param LoggerInterface $logger A LoggerInterface instance
     */
    public function __construct(LoggerInterface $logger = null)
    {
        $this->logger = $logger;
    }

    /**
     * {@inheritdoc}
     */
    public function startQuery($sql, array $params = null, array $types = null)
    {
        parent::startQuery($sql, $params, $types);

        if (null !== $this->logger) {
            $this->log($sql.' ('.@json_encode($params).')');
        }
    }

    /**
     * Logs a message.
     *
     * @param string $message A message to log
     */
    public function log($message)
    {
        $this->logger->debug($message);
    }
}

Fix log of non utf8 data

[DoctrineBridge] Fix log of non utf8 data


<Response>
    <Say voice="woman" language="fr" >
        Ne quittez pas, s'il vous plaît.
    </Say>
    <Dial>
        <Conference
            waitUrl="http://twimlets.com/holdmusic?Bucket=com.twilio.music.classical">
            my room
        </Conference>
    </Dial>
</Response>

<Response>
    <Say voice="woman" language="en" >
        Please hold the line, your conference will begin shortly.
    </Say>
    <Dial>
        <Conference
            waitUrl="http://twimlets.com/holdmusic?Bucket=com.twilio.music.classical">
            my room
        </Conference>
    </Dial>
</Response>

Change Twilio message from French to English.


<?php

namespace Chromabits\Illuminated\Database\Articulate;

use Chromabits\Nucleus\Foundation\BaseObject;
use Chromabits\Nucleus\Meditation\Exceptions\FailedCheckException;

/**
 * Class ValidatingObserver
 *
 * Originally from: https://github.com/AltThree/Validator/
 *
 * @author Eduardo Trujillo <ed@chromabits.com>
 * @package Chromabits\Illuminated\Database\Articulate
 */
class ValidatingObserver extends BaseObject
{
    /**
     * Validate the model on saving.
     *
     * @param Model $model
     */
    public function saving(Model $model)
    {
        $this->validate($model);
    }

    /**
     * Validate the model on saving.
     *
     * @param Model $model
     */
    public function restoring(Model $model)
    {
        $this->validate($model);
    }

    protected function validate(Model $model)
    {
        $attributes = $model->getAttributes();
        $checkable = $model->getCheckable();

        if ($checkable === null) {
            return;
        }

        $result = $checkable->check($attributes);

        if ($result->failed()) {
            throw new FailedCheckException($checkable, $result);
        }
    }
}

<?php

namespace Chromabits\Illuminated\Database\Articulate;

use Chromabits\Nucleus\Foundation\BaseObject;
use Chromabits\Nucleus\Meditation\Exceptions\FailedCheckException;

/**
 * Class ValidatingObserver
 *
 * Originally from: https://github.com/AltThree/Validator/
 *
 * @author Eduardo Trujillo <ed@chromabits.com>
 * @package Chromabits\Illuminated\Database\Articulate
 */
class ValidatingObserver extends BaseObject
{
    /**
     * Validate the model on saving.
     *
     * @param Model $model
     */
    public function saving(Model $model)
    {
        $this->validate($model);
    }

    /**
     * Validate the model on saving.
     *
     * @param Model $model
     */
    public function restoring(Model $model)
    {
        $this->validate($model);
    }

    protected function validate(Model $model)
    {
        $attributes = $model->attributesToArray();
        $checkable = $model->getCheckable();

        if ($checkable === null) {
            return;
        }

        $result = $checkable->check($attributes);

        if ($result->failed()) {
            throw new FailedCheckException($checkable, $result);
        }
    }
}

Use attributesToArray instead of getAttributes


<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePhpdebugbarStorageTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('phpdebugbar', function (Blueprint $table) {
                $table->increments('id');

                $table->text('data');
                $table->string('meta_utime');
                $table->dateTime('meta_datetime');
                $table->string('meta_uri');
                $table->string('meta_ip');
                $table->string('meta_method');

                $table->index('meta_utime');
                $table->index('meta_datetime');
                $table->index('meta_uri');
                $table->index('meta_ip');
                $table->index('meta_method');
            });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('phpdebugbar');
    }
}

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePhpdebugbarStorageTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('phpdebugbar', function (Blueprint $table) {
                $table->string('id');
                $table->text('data');
                $table->string('meta_utime');
                $table->dateTime('meta_datetime');
                $table->string('meta_uri');
                $table->string('meta_ip');
                $table->string('meta_method');

                $table->primary('id');
                $table->index('meta_utime');
                $table->index('meta_datetime');
                $table->index('meta_uri');
                $table->index('meta_ip');
                $table->index('meta_method');
            });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('phpdebugbar');
    }
}

Fix id column in migration

Fix id column in migration


<?php

/**
 * Testcase_Promotions definition
 *
 * @package Functest
 * @author Ivan Kerin
 * @author Yasen Yanev
 * @copyright  (c) 2011-2013 Despark Ltd.
 */
abstract class Testcase_Promotions extends \PHPUnit\Framework\TestCase {

	public function setUp()
	{
		parent::setUp();
		Database::instance()->begin();
		Jam_Association_Creator::current(1);
	}

	public function tearDown()
	{
		Database::instance()->rollback();
		parent::tearDown();
	}

	public function ids(array $items)
	{
		return array_values(array_map(function($item){ return $item->id(); }, $items));
	}
}

<?php

/**
 * Testcase_Promotions definition
 *
 * @package Functest
 * @author Ivan Kerin
 * @author Yasen Yanev
 * @copyright  (c) 2011-2013 Despark Ltd.
 */
abstract class Testcase_Promotions extends \PHPUnit\Framework\TestCase {

	public function setUp(): void
	{
		parent::setUp();
		Database::instance()->begin();
		Jam_Association_Creator::current(1);
	}

	public function tearDown(): void
	{
		Database::instance()->rollback();
		parent::tearDown();
	}

	public function ids(array $items)
	{
		return array_values(array_map(function($item){ return $item->id(); }, $items));
	}
}

Add setUP and tearDown return type

Add setUP and tearDown return type


@extends('layouts.app')

@section('title', 'Leaderboard')

@section('content')

Leaderboard

	@foreach ($users as $user)

						{!! avatar($user)->medium()->link() !!}

{{ $user->name }}

{{ number_format($user->countBestAnswers()) }} Best Answer {{ str_plural('Award', $user->countBestAnswers()) }}

{{ number_format($user->points) }} Experience

	@endforeach

@endsection

Add a link to the user profile

Add a link to the user profile


<?php namespace Flarum\Core\Notifications;

use Flarum\Core\Users\User;

class NotificationRepository
{
    /**
     * Find a user's notifications.
     *
     * @param User $user
     * @param int|null $limit
     * @param int $offset
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function findByUser(User $user, $limit = null, $offset = 0)
    {
        $primaries = Notification::select(
            app('flarum.db')->raw('MAX(id) AS id'),
            app('flarum.db')->raw('SUM(is_read = 0) AS unread_count')
        )
            ->where('user_id', $user->id)
            ->whereIn('type', $user->getAlertableNotificationTypes())
            ->where('is_deleted', false)
            ->groupBy('type', 'subject_id')
            ->orderByRaw('MAX(time) DESC')
            ->skip($offset)
            ->take($limit);

        return Notification::select('notifications.*', 'p.unread_count')
            ->mergeBindings($primaries->getQuery())
            ->join(app('flarum.db')->raw('('.$primaries->toSql().') p'), 'notifications.id', '=', 'p.id')
            ->latest('time')
            ->get();
    }
}

<?php namespace Flarum\Core\Notifications;

use Flarum\Core\Users\User;

class NotificationRepository
{
    /**
     * Find a user's notifications.
     *
     * @param User $user
     * @param int|null $limit
     * @param int $offset
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function findByUser(User $user, $limit = null, $offset = 0)
    {
        $primaries = Notification::select(
            app('flarum.db')->raw('MAX(id) AS id'),
            app('flarum.db')->raw('SUM(is_read = 0) AS unread_count')
        )
            ->where('user_id', $user->id)
            ->whereIn('type', $user->getAlertableNotificationTypes())
            ->where('is_deleted', false)
            ->groupBy('type', 'subject_id')
            ->orderByRaw('MAX(time) DESC')
            ->skip($offset)
            ->take($limit);

        return Notification::select('notifications.*', app('flarum.db')->raw('p.unread_count'))
            ->mergeBindings($primaries->getQuery())
            ->join(app('flarum.db')->raw('('.$primaries->toSql().') p'), 'notifications.id', '=', app('flarum.db')->raw('p.id'))
            ->latest('time')
            ->get();
    }
}

Support table custom table prefix

Support table custom table prefix

Laravel automatically adds a table prefix to any table names, so we
need to wrap our aliased table in DB::raw.


@extends('layout')

@section('title', __('general.earnings'))

@section('body')

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

            @if (count($earnings))
                @foreach ($earnings as $earning)

{{ $earning->description }}

{{ $earning->formatted_happened_on }}

{!! $currency !!} {{ $earning->formatted_amount }}

                            <form method="POST" action="/earnings/{{ $earning->id }}">
                                {{ method_field('DELETE') }}
                                {{ csrf_field() }}
                                <button class="button link">

                                </button>
                            </form>

                @endforeach
            @else

You don't have any earnings

            @endif

@endsection

@extends('layout')

@section('title', __('general.earnings'))

@section('body')

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

                Create Earning

            @if (count($earnings))
                @foreach ($earnings as $earning)

{{ $earning->description }}

{{ $earning->formatted_happened_on }}

{!! $currency !!} {{ $earning->formatted_amount }}

                            <form method="POST" action="/earnings/{{ $earning->id }}">
                                {{ method_field('DELETE') }}
                                {{ csrf_field() }}
                                <button class="button link">

                                </button>
                            </form>

                @endforeach
            @else

You don't have any earnings

            @endif

@endsection

Add button for creating earning to earnings' index view


@foreach (session('flash_notification', collect())->toArray() as $message)
  @if ($loop->first)

  @endif
  @if ($message['overlay'])
  @include('partials.flashModal', [
    'modalClass' => 'flash-modal',
    'title'      => $message['title'],
    'body'       => $message['message']
  ])
  @else

    {!! $message['message'] !!}
    <button class="close" aria-label="Dismiss alert" data-dismiss="alert" type="button" data-close>
      ×
    </button>

  @endif
  @if ($loop->last)

  @endif
@endforeach
{{ session()->forget('flash_notification') }}

View: Remove array_key_exists from flash partial


<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

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

Route::resource('task', 'TaskController');
Route::resource('tag', 'TagController');

Create resource Tag and Task

Create resource Tag and  Task


<?php namespace App\Models;

use App\Bases\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

/**
 * Class User
 * @package App\Models
 */
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    /* ------------------------------------------------------------------------------------------------
     |  Traits
     | ------------------------------------------------------------------------------------------------
     */
    use Authenticatable, CanResetPassword;

    /* ------------------------------------------------------------------------------------------------
     |  Properties
     | ------------------------------------------------------------------------------------------------
     */
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];
}

<?php namespace App\Models;

use App\Bases\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

/**
 * Class User
 * @package App\Models
 */
class User
    extends Model
    implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
    /* ------------------------------------------------------------------------------------------------
     |  Traits
     | ------------------------------------------------------------------------------------------------
     */
    use Authenticatable, Authorizable, CanResetPassword;

    /* ------------------------------------------------------------------------------------------------
     |  Properties
     | ------------------------------------------------------------------------------------------------
     */
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];
}

Implement interface & Adding Authorizable Trait.


<?php

namespace Spatie\MediaLibrary;

use Spatie\MediaLibrary\Models\Media;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\MediaLibrary\Filesystem\Filesystem;

class MediaObserver
{
    public function creating(Media $media)
    {
        $media->setHighestOrderNumber();
    }

    public function updating(Media $media)
    {
        if ($media->file_name !== $media->getOriginal('file_name')) {
            app(Filesystem::class)->syncFileNames($media);
        }
    }

    public function updated(Media $media)
    {
        if (is_null($media->getOriginal('model_id'))) {
            return;
        }

        if ($media->manipulations !== json_decode($media->getOriginal('manipulations'), true)) {
            app(FileManipulator::class)->createDerivedFiles($media);
        }
    }

    public function deleted(Media $media)
    {
        if (in_array(SoftDeletes::class, class_uses_recursive($media))) {
            if (! $media->isForceDeleting()) {
                return;
            }
        }

        app(Filesystem::class)->removeAllFiles($media);
    }
}

<?php

namespace Spatie\MediaLibrary;

use Spatie\MediaLibrary\Models\Media;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\MediaLibrary\Filesystem\Filesystem;

class MediaObserver
{
    public function creating(Media $media)
    {
        $media->setHighestOrderNumber();
    }

    public function updating(Media $media)
    {
        if ($media->file_name !== $media->getOriginal('file_name')) {
            app(Filesystem::class)->syncFileNames($media);
        }
    }

    public function updated(Media $media)
    {
        if (is_null($media->getOriginal('model_id'))) {
            return;
        }

        if ($media->manipulations !== json_decode($media->getOriginal('manipulations'), true)) {
            $eventDispatcher = Media::getEventDispatcher();
            Media::unsetEventDispatcher();

            app(FileManipulator::class)->createDerivedFiles($media);

            Media::setEventDispatcher($eventDispatcher);
        }
    }

    public function deleted(Media $media)
    {
        if (in_array(SoftDeletes::class, class_uses_recursive($media))) {
            if (! $media->isForceDeleting()) {
                return;
            }
        }

        app(Filesystem::class)->removeAllFiles($media);
    }
}

Disable model events when saving extra properties in Media::updated event


<?php
return [
    'class' => '\blink\server\SwServer',
    'bootstrap' => __DIR__ . '/../bootstrap.php',
    'host' => '0.0.0.0',
    'port' => 7788,
];

<?php
return [
    'class' => '\blink\server\SwServer',
    'bootstrap' => __DIR__ . '/../bootstrap.php',
    'host' => '0.0.0.0',
    'port' => 9812,
];

Change default listening port to 9812

Change default listening port to 9812


<?php

Route::post('laralytics', function (\Bsharp\Laralytics\Laralytics $laralytics) {

    dd(Input::all());
    $laralytics->payload();

    return response()->json($_POST);
});

<?php

Route::post('laralytics', function (\Bsharp\Laralytics\Laralytics $laralytics, Illuminate\Http\Request $request) {

    $payload = $request->only('infos', 'click', 'custom');

    $laralytics->payload($payload);

    return response()->json($_POST);
});

Use request dependency injection instead of Input facade to retrieve request POST parameters


<?php

/*
 * This file is part of Phraseanet SDK.
 *
 * (c) Alchemy <info@alchemy.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PhraseanetSDK\Entity;

use PhraseanetSDK\EntityManager;

abstract class AbstractEntity implements EntityInterface
{
    /** @var EntityManager */
    protected $em;

    final public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }
}

<?php

/*
 * This file is part of Phraseanet SDK.
 *
 * (c) Alchemy <info@alchemy.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PhraseanetSDK\Entity;

use PhraseanetSDK\EntityManager;

abstract class AbstractEntity implements EntityInterface
{
    /** @var EntityManager */
    protected $em;

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

Remove final to constructor to allow constructor overloading


@extends('master')

@section('title')
Bookmarks «
@stop

@section('content')

@foreach($bookmarks as $bookmark)

    <a class="u-bookmark-of<?php if ($bookmark->name !== null) { echo ' h-cite'; } ?>" href="{{ $bookmark->url }}">
      @isset($bookmark->name)
        {{ $bookmark->name }}
      @endisset

      @empty($bookmark->name)
        {{ $bookmark->url }}
      @endempty

@endforeach

@stop

@extends('master')

@section('title')
Bookmarks «
@stop

@section('content')

@foreach($bookmarks as $bookmark)

    <a class="u-bookmark-of<?php if ($bookmark->name !== null) { echo ' h-cite'; } ?>" href="{{ $bookmark->url }}">
      @isset($bookmark->name)
        {{ $bookmark->name }}
      @endisset

      @empty($bookmark->name)
        {{ $bookmark->url }}
      @endempty
       id }}">🔗

@endforeach

@stop

Add a link icon to the individual bookmark


<?php

namespace FireDIY\PrivateMessageBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ConversationType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('subject')
            ->add('firstMessage', PrivateMessageType::class)
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'FireDIY\PrivateMessageBundle\Entity\Conversation'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'firediy_privatemessagebundle_conversation';
    }

}

<?php

namespace FireDIY\PrivateMessageBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ConversationType extends AbstractType
{

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('recipients')
            ->add('subject')
            ->add('firstMessage', PrivateMessageType::class);
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'FireDIY\PrivateMessageBundle\Entity\Conversation'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'firediy_privatemessagebundle_conversation';
    }

}

Update Conversation's form : add field recipients


<?php

namespace K10rProject\Helpers;

use Shopware\Bundle\PluginInstallerBundle\Service\PluginLicenceService;
use Shopware\Components\Model\ModelManager;
use Shopware\Models\Plugin\License;

class LicenseHelper
{
    /** @var PluginLicenceService */
    private $licenseService;

    /** @var ModelManager */
    private $modelManager;

    public function __construct(PluginLicenceService $licenseService, ModelManager $modelManager)
    {
        $this->licenseService = $licenseService;
        $this->modelManager   = $modelManager;
    }

    /**
     * Add a license key using SwagLicense
     *
     * @param string $licenseKey
     */
    public function addLicenseKey($licenseKey)
    {
        if (method_exists($this->licenseService, 'importLicence')) { // SW 5.5 compatibility
            $this->licenseService->importLicence($licenseKey);
        }
    }

    /**
     * Removes a license for a Plugin or Module, given by name.
     *
     * @param string $pluginName
     *
     * @return bool
     */
    public function removeLicenseByPluginName($pluginName)
    {
        $license = $this->modelManager->getRepository(License::class)->findOneBy(['module' => $pluginName]);

        if (!$license instanceof License) {
            return false;
        }

        $this->modelManager->remove($license);
        $this->modelManager->flush();

        return true;
    }
}

<?php

namespace K10rProject\Helpers;

use Shopware\Bundle\PluginInstallerBundle\Service\PluginLicenceService;
use Shopware\Components\Model\ModelManager;
use Shopware\Models\Plugin\License;

class LicenseHelper
{
    /** @var PluginLicenceService */
    private $licenseService;

    /** @var ModelManager */
    private $modelManager;

    public function __construct(PluginLicenceService $licenseService, ModelManager $modelManager)
    {
        $this->licenseService = $licenseService;
        $this->modelManager   = $modelManager;
    }

    /**
     * Add a license key using SwagLicense
     *
     * @param string $licenseKey
     */
    public function addLicenseKey($licenseKey)
    {
        if (method_exists($this->licenseService, 'importLicence')) { // SW 5.5 compatibility
            $this->licenseService->importLicence($licenseKey);
        } else {
            trigger_error('There is no plugin license management after Shopware 5.5', E_USER_DEPRECATED);
        }
    }

    /**
     * Removes a license for a Plugin or Module, given by name.
     *
     * @param string $pluginName
     *
     * @return bool
     */
    public function removeLicenseByPluginName($pluginName)
    {
        $license = $this->modelManager->getRepository(License::class)->findOneBy(['module' => $pluginName]);

        if (!$license instanceof License) {
            return false;
        }

        $this->modelManager->remove($license);
        $this->modelManager->flush();

        return true;
    }
}

[INT-205] Add deprecation error for using `addLicenseKey` after Shopware 5.5.


<?php

use Bausch\LaravelCornerstone\Http\Controllers\KeepAliveController;

$router->get('lbausch/laravel-cornerstone/keepalive', KeepAliveController::class.'@keepalive');

<?php

use Bausch\LaravelCornerstone\Http\Controllers\KeepAliveController;

Route::get('lbausch/laravel-cornerstone/keepalive', KeepAliveController::class.'@keepalive');

Use Route instead of $router

Use Route instead of $router


<?php
namespace MangoPay;
/**
 * Class represents PayPal type for mean of payment in PayIn entity
 */
class PayInPaymentDetailsPaypal extends Libraries\Dto implements PayInPaymentDetails
{
    /**
     * Address used instead of the user's PayPal account address.
     * @var ShippingAddress
     */
    public $ShippingAddress;

    public function GetSubObjects()
    {
        $subObjects = parent::GetSubObjects();

        $subObjects['ShippingAddress'] = '\Mangopay\ShippingAddress';

        return $subObjects;
    }
}

<?php
namespace MangoPay;
/**
 * Class represents PayPal type for mean of payment in PayIn entity
 */
class PayInPaymentDetailsPaypal extends Libraries\Dto implements PayInPaymentDetails
{
    /**
     * Address used instead of the user's PayPal account address.
     * @var ShippingAddress
     */
    public $ShippingAddress;

    public function GetSubObjects()
    {
        $subObjects = parent::GetSubObjects();

        $subObjects['ShippingAddress'] = '\MangoPay\ShippingAddress';

        return $subObjects;
    }
}

Fix class mapping for ShippingAddress field in PayPal entity


<?php

/*
 * X-editable extension for Yii2
 *
 * @link      https://github.com/hiqdev/yii2-x-editable
 * @package   yii2-x-editable
 * @license   BSD-3-Clause
 * @copyright Copyright (c) 2015, HiQDev (https://hiqdev.com/)
 */

namespace hiqdev\xeditable\widgets;

use hiqdev\xeditable\traits\XEditableTrait;
use yii\base\Widget;

class XEditable extends Widget
{
    use XEditableTrait;

    public $value;

    public $model;

    public $attribute;

    public function run()
    {
        return $this->prepareHtml([
            'value'         => $this->value,
            'model'         => $this->model,
            'attribute'     => $this->attribute,
            'pluginOptions' => $this->pluginOptions,
        ]);
    }
}

<?php

/*
 * X-editable extension for Yii2
 *
 * @link      https://github.com/hiqdev/yii2-x-editable
 * @package   yii2-x-editable
 * @license   BSD-3-Clause
 * @copyright Copyright (c) 2015, HiQDev (https://hiqdev.com/)
 */

namespace hiqdev\xeditable\widgets;

use hiqdev\xeditable\traits\XEditableTrait;
use yii\base\Widget;

class XEditable extends Widget
{
    use XEditableTrait;

    public $value;

    public $model;

    public $attribute;

    public function init()
    {
        parent::init();
        $this->registerAssets();
        $this->pluginOptions['url'] = (isset($this->pluginOptions['url']) && mb_strlen($this->pluginOptions['url']) > 0) ? : $this->model->getScenario();
    }

    public function run()
    {
        return $this->prepareHtml([
            'value'         => $this->value,
            'model'         => $this->model,
            'attribute'     => $this->attribute,
            'pluginOptions' => $this->pluginOptions,
        ]);
    }
}

Add auto detedt url from model scenario

Add auto detedt url from model scenario


<?php
class com_meego_planet_controllers_top
{
    public function __construct(midgardmvc_core_request $request)
    {
        $this->request = $request;
    }

    public function get_items(array $args)
    {
        $this->data['title'] = 'MeeGo Planet: Top Voted Posts';
        midgardmvc_core::get_instance()->head->set_title($this->data['title']);

        // FIXME: Query for top items instead
        $q = new midgard_query_select
        (
            new midgard_query_storage('com_meego_planet_item')
        );
        $q->add_order(new midgard_query_property('metadata.score'), SORT_DESC);

        $q->execute();

        $this->data['items'] = array_map
        (
            function($item)
            {
                // TODO: Get author and avatar
                return $item;
            },
            $q->list_objects()
        );
    }
}

<?php
class com_meego_planet_controllers_top
{
    public function __construct(midgardmvc_core_request $request)
    {
        $this->request = $request;
    }

    public function get_items(array $args)
    {
        $this->data['title'] = 'MeeGo Planet: Popular Posts';
        midgardmvc_core::get_instance()->head->set_title($this->data['title']);

        // FIXME: Query for top items instead
        $q = new midgard_query_select
        (
            new midgard_query_storage('com_meego_planet_item')
        );
        $q->add_order(new midgard_query_property('metadata.score'), SORT_DESC);

        $q->execute();

        $this->data['items'] = array_map
        (
            function($item)
            {
                // TODO: Get author and avatar
                return $item;
            },
            $q->list_objects()
        );
    }
}

Change title to 'Popular Posts'

Change title to 'Popular Posts'


<?php

namespace Algolia\SearchBundle\Searchable;

use Algolia\SearchBundle\Normalizer\SearchableArrayNormalizer;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Serializer\Serializer;

class SearchableEntity implements SearchableEntityInterface
{
    protected $indexName;
    protected $entity;
    protected $entityMetadata;
    protected $normalizers;

    public function __construct($indexName, $entity, $entityMetadata, array $normalizers = [])
    {
        $this->indexName = $indexName;
        $this->entity = $entity;
        $this->entityMetadata = $entityMetadata;
        $this->normalizers = $normalizer ?? [new SearchableArrayNormalizer()];
    }

    public function getIndexName()
    {
        return $this->indexName;
    }

    public function getSearchableArray()
    {
        $serializer = new Serializer($this->normalizers);

        return $serializer->normalize($this->entity, 'searchableArray', [
            'fieldsMapping' => $this->entityMetadata->fieldMappings,
        ]);
    }

    public function getId()
    {
        $ids = $this->entityMetadata->getIdentifierValues($this->entity);

        if (empty($ids)) {
            throw new Exception('Entity has no primary key');
        }

        if (1 == count($ids)) {
            return reset($ids);
        }

        $objectID = '';
        foreach ($ids as $key => $value) {
            $objectID .= $key . '-' . $value . '__';
        }

        return rtrim($objectID, '_');
    }
}

<?php

namespace Algolia\SearchBundle\Searchable;

use Algolia\SearchBundle\Normalizer\SearchableArrayNormalizer;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Serializer\Serializer;

class SearchableEntity implements SearchableEntityInterface
{
    private $id;
    protected $indexName;
    protected $entity;
    protected $entityMetadata;
    protected $normalizers;

    public function __construct($indexName, $entity, $entityMetadata, array $normalizers = [])
    {
        $this->indexName = $indexName;
        $this->entity = $entity;
        $this->entityMetadata = $entityMetadata;
        $this->normalizers = $normalizer ?? [new SearchableArrayNormalizer()];

        $this->setId();
    }

    public function getIndexName()
    {
        return $this->indexName;
    }

    public function getSearchableArray()
    {
        $serializer = new Serializer($this->normalizers);

        return $serializer->normalize($this->entity, 'searchableArray', [
            'fieldsMapping' => $this->entityMetadata->fieldMappings,
        ]);
    }

    private function setId()
    {
        $ids = $this->entityMetadata->getIdentifierValues($this->entity);

        if (empty($ids)) {
            throw new Exception('Entity has no primary key');
        }

        if (1 == count($ids)) {
            $this->id = reset($ids);
        }

        $objectID = '';
        foreach ($ids as $key => $value) {
            $objectID .= $key . '-' . $value . '__';
        }

        $this->id = rtrim($objectID, '_');
    }

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

Set searchableEntity Id in constructor In order to break earlier if there is no primary key


<?php
/*
 * Copyright 2017 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.md.
 */

namespace Chalk\Article\Backend\Controller;

use Chalk\Chalk;
use Chalk\Core\Backend\Controller\Content as ChalkCoreContent;
use Chalk\Core\Backend\Model;
use Chalk\Entity;
use Coast\Controller\Action;
use Coast\Request;
use Coast\Response;

class Article extends ChalkCoreContent
{
    protected $_entityClass = 'Chalk\Article\Article';

    protected function _create(Request $req, Response $res, Entity $entity)
    {
        $entity->author = $this->em->ref('core_user', $req->user->id);
    }
}

<?php
/*
 * Copyright 2017 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.md.
 */

namespace Chalk\Article\Backend\Controller;

use Chalk\Chalk;
use Chalk\Core\Backend\Controller\Content as ChalkCoreContent;
use Chalk\Core\Backend\Model;
use Chalk\Entity;
use Coast\Controller\Action;
use Coast\Request;
use Coast\Response;

class Article extends ChalkCoreContent
{
    protected $_entityClass = 'Chalk\Article\Article';

    protected function _create(Request $req, Response $res, Entity $entity)
    {
        $entity->author = $this->em->ref('core_user', $this->user->id);
    }
}

Fix author when creating new article

Fix author when creating new article


<?php

namespace TM\Provider;

use Silex\Application;
use Silex\ServiceProviderInterface;
use TM\Service\SitemapGenerator;

/**
 * @package TM\Provider
 */
class SitemapServiceProvider implements ServiceProviderInterface
{
    /**
     * Registers services on the given app.
     *
     * This method should only be used to configure services and parameters.
     * It should not get services.
     *
     * @param Application $app An Application instance
     */
    public function register(Application $app)
    {
        $options = [
            'xml_writer' => new \XMLWriter,
            'version' => '1.0',
            'charset' => 'utf-8',
            'scheme' => 'http://www.sitemaps.org/schemas/sitemap/0.9',
        ];

        if (isset($app['sitemap.options']) && is_array($app['sitemap.options'])) {
            $options = array_merge($options, $app['sitemap.options']);
        }

        $app['sitemap'] = $app->share(function () use ($options) {
            return new SitemapGenerator(
                $options['xml_writer'], $options['version'], $options['charset'], $options['scheme']
            );
        });
    }

    /**
     * Bootstraps the application.
     *
     * This method is called after all services are registered
     * and should be used for "dynamic" configuration (whenever
     * a service must be requested).
     *
     * @param Application $app An Application instance
     */
    public function boot(Application $app)
    {
    }
}

<?php

namespace TM\Provider;

use Pimple\Container;
use Pimple\ServiceProviderInterface;
use TM\Service\SitemapGenerator;

class SitemapServiceProvider implements ServiceProviderInterface
{
    /**
     * @param Container $app
     */
    public function register(Container $app)
    {
        $options = [
            'xml_writer' => new \XMLWriter,
            'version' => '1.0',
            'charset' => 'utf-8',
            'scheme' => 'http://www.sitemaps.org/schemas/sitemap/0.9',
        ];

        if (isset($app['sitemap.options']) && is_array($app['sitemap.options'])) {
            $options = array_merge($options, $app['sitemap.options']);
        }

        $app['sitemap'] = function () use ($options) {
            return new SitemapGenerator(
                $options['xml_writer'], $options['version'], $options['charset'], $options['scheme']
            );
        };
    }
}

Update provider for Silex 2.0

Update provider for Silex 2.0


<?php

namespace spec\GrumPHP\Runner;

use GrumPHP\Runner\TaskResult;
use GrumPHP\Task\Context\ContextInterface;
use GrumPHP\Task\TaskInterface;
use PhpSpec\ObjectBehavior;

class TaskResultSpec extends ObjectBehavior
{
    const FAILED_TASK_MESSAGE = 'failed task message';

    function it_creates_passed_task(TaskInterface $task, ContextInterface $context)
    {
        $this->beConstructedThrough('createPassed', [$task, $context]);

        $this->getTask()->shouldBe($task);
        $this->getResultCode()->shouldBe(TaskResult::PASSED);
        $this->isPassed()->shouldBe(true);
        $this->getMessage()->shouldBeNull();
    }

    function it_creates_failed_task(TaskInterface $task, ContextInterface $context)
    {
        $this->beConstructedThrough('createFailed', [$task, $context, self::FAILED_TASK_MESSAGE]);

        $this->getTask()->shouldBe($task);
        $this->getResultCode()->shouldBe(TaskResult::FAILED);
        $this->isPassed()->shouldBe(false);
        $this->getMessage()->shouldBe(self::FAILED_TASK_MESSAGE);
    }
}

<?php

namespace spec\GrumPHP\Runner;

use GrumPHP\Runner\TaskResult;
use GrumPHP\Task\Context\ContextInterface;
use GrumPHP\Task\TaskInterface;
use PhpSpec\ObjectBehavior;

class TaskResultSpec extends ObjectBehavior
{
    const FAILED_TASK_MESSAGE = 'failed task message';

    function it_creates_passed_task(TaskInterface $task, ContextInterface $context)
    {
        $this->beConstructedThrough('createPassed', array($task, $context));

        $this->getTask()->shouldBe($task);
        $this->getResultCode()->shouldBe(TaskResult::PASSED);
        $this->isPassed()->shouldBe(true);
        $this->getMessage()->shouldBeNull();
    }

    function it_creates_failed_task(TaskInterface $task, ContextInterface $context)
    {
        $this->beConstructedThrough('createFailed', array($task, $context, self::FAILED_TASK_MESSAGE));

        $this->getTask()->shouldBe($task);
        $this->getResultCode()->shouldBe(TaskResult::FAILED);
        $this->isPassed()->shouldBe(false);
        $this->getMessage()->shouldBe(self::FAILED_TASK_MESSAGE);
    }
}

Fix array syntax for PHP5.3

Fix array syntax for PHP5.3


@section('title')
Qualities - Cataclysm: Dark Days Ahead
@endsection

Qualities

@foreach($qualities as $quality)

id==$id) active @endif">id) }}">{{{$quality->name}}}

@endforeach

@if (!$id)
Please select an entry from the menu on the left.
@else

    Name
    Level
    Recipes

@foreach($items as $item)

  {{ $item->symbol }}
  id)}}">{{ $item->name }}
  {{{ $item->qualityLevel($id) }}}
  {{{ $item->count("toolFor") }}}

@endforeach

@endif

@section('title')
Qualities - Cataclysm: Dark Days Ahead
@endsection

Qualities

@foreach($qualities as $quality)

id==$id) active @endif">id) }}">{{{$quality->name}}}

@endforeach

@if (!$id)
Please select an entry from the menu on the left.
@else

    Name
    Level
    Recipes
    Construction

@foreach($items as $item)

  {{ $item->symbol }}
  id)}}">{{ $item->name }}
  {{{ $item->qualityLevel($id) }}}
  {{{ $item->count("toolFor") }}}
  {{{ $item->count("construction") }}}

@endforeach

@endif

Add construction counts to the qualities catalog.


<?php

Route::group(['middleware' => ['web'], 'namespace' => '\\Konsulting\\Butler\\Controllers'], function () {
    Route::get('/auth/provider/confirm/{token}', 'AuthController@confirm')->name('butler.confirm');
    Route::get('/auth/provider/{provider}', 'AuthController@redirect')->name('butler.redirect');
    Route::get('/auth/provider/{provider}/callback', 'AuthController@callback')->name('butler.callback');
});

<?php

Route::group(['middleware' => ['web'], 'namespace' => '\\Konsulting\\Butler\\Controllers'], function () {
    Route::get('/auth/provider/confirm/{token}', 'AuthController@confirm')->name('butler.confirm');
    Route::get('/auth/provider/{provider}', 'AuthController@redirect')->name('butler.redirect');
    Route::match(['get', 'post'], '/auth/provider/{provider}/callback', 'AuthController@callback')->name('butler.callback');
});

Allow get or post for callback

Allow get or post for callback


<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Auth::routes();

Route::get('/theme', 'HomeController@theme'); //Temporary route to theme.

Route::get('/', 'HomeController@index')->name('home');
Route::get('/home', 'HomeController@index');

Route::get('/workspaces/app/showRecord', 'WorkspaceController@appShowRecord')->name('workspaces.appShowRecord');
Route::get('/workspaces/ruggedyIndex', 'WorkspaceController@ruggedyIndex')->name('workspaces.ruggedyIndex');
Route::get('/workspaces/ruggedyCreate', 'WorkspaceController@ruggedyCreate')->name('workspaces.ruggedyCreate');
Route::get('/workspaces/ruggedyShow', 'WorkspaceController@ruggedyShow')->name('workspaces.ruggedyShow');

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Auth::routes();
Route::get('/home', 'HomeController@index');

Route::get('/workspaces/app/showRecord', 'WorkspaceController@appShowRecord')->name('workspaces.appShowRecord');
Route::get('/workspaces/ruggedyIndex', 'WorkspaceController@ruggedyIndex')->name('workspaces.ruggedyIndex');
Route::get('/workspaces/ruggedyCreate', 'WorkspaceController@ruggedyCreate')->name('workspaces.ruggedyCreate');
Route::get('/workspaces/ruggedyShow', 'WorkspaceController@ruggedyShow')->name('workspaces.ruggedyShow');

Remove redundant routes that are now implemented using annotations.


<?php

namespace App\Policies;

use App\User;
use App\DuesTransaction;
use Illuminate\Auth\Access\HandlesAuthorization;

class DuesTransactionPolicy
{
    use HandlesAuthorization;

    public function view(User $user, DuesTransaction $resource)
    {
        return $user->can('read-dues-transactions');
    }

    public function viewAny(User $user)
    {
        return $user->can('read-dues-transactions');
    }

    public function create(User $user)
    {
        return $user->can('create-dues-transactions');
    }

    public function update(User $user, DuesTransaction $resource)
    {
        return $user->can('update-dues-transactions');
    }

    public function delete(User $user, DuesTransaction $resource)
    {
        return $user->can('delete-dues-transactions');
    }

    public function restore(User $user, DuesTransaction $resource)
    {
        return $user->can('delete-dues-transactions');
    }

    public function forceDelete(User $user, DuesTransaction $resource)
    {
        return false;
    }
}

<?php

namespace App\Policies;

use App\User;
use App\DuesTransaction;
use Illuminate\Auth\Access\HandlesAuthorization;

class DuesTransactionPolicy
{
    use HandlesAuthorization;

    public function view(User $user, DuesTransaction $resource)
    {
        return $user->can('read-dues-transactions');
    }

    public function viewAny(User $user)
    {
        return $user->can('read-dues-transactions');
    }

    public function create(User $user)
    {
        return false;
    }

    public function update(User $user, DuesTransaction $resource)
    {
        return false;
    }

    public function delete(User $user, DuesTransaction $resource)
    {
        return false;
    }

    public function restore(User $user, DuesTransaction $resource)
    {
        return false;
    }

    public function forceDelete(User $user, DuesTransaction $resource)
    {
        return false;
    }
}

Disable most Nova functions for DuesTransactions


<?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\Translation\Dumper;

use Symfony\Component\Translation\MessageCatalogue;

/**
 * JsonFileDumper generates an json formatted string representation of a message catalogue.
 *
 * @author singles
 */
class JsonFileDumper extends FileDumper
{
    /**
     * {@inheritdoc}
     */
    public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = [])
    {
        if (isset($options['json_encoding'])) {
            $flags = $options['json_encoding'];
        } else {
            $flags = \defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0;
        }

        return json_encode($messages->all($domain), $flags);
    }

    /**
     * {@inheritdoc}
     */
    protected function getExtension()
    {
        return 'json';
    }
}

<?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\Translation\Dumper;

use Symfony\Component\Translation\MessageCatalogue;

/**
 * JsonFileDumper generates an json formatted string representation of a message catalogue.
 *
 * @author singles
 */
class JsonFileDumper extends FileDumper
{
    /**
     * {@inheritdoc}
     */
    public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = [])
    {
        if (isset($options['json_encoding'])) {
            $flags = $options['json_encoding'];
        } else {
            $flags = JSON_PRETTY_PRINT;
        }

        return json_encode($messages->all($domain), $flags);
    }

    /**
     * {@inheritdoc}
     */
    protected function getExtension()
    {
        return 'json';
    }
}

Use some PHP 5.4 constants unconditionally


<?php
namespace Concrete\Core\Console\Command;

use Concrete\Core\Console\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Core;

class ClearCacheCommand extends Command
{
    protected function configure()
    {
        $errExitCode = static::RETURN_CODE_ON_FAILURE;
        $this
            ->setName('c5:clear-cache')
            ->setDescription('Clear the concrete5 cache')
            ->addEnvOption()
            ->setHelp(<<<EOT
Returns codes:
  0 operation completed successfully
  $errExitCode errors occurred

More info at http://documentation.concrete5.org/developers/appendix/cli-commands#c5-clear-cache
EOT
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->write('Clearing the concrete5 cache... ');
        $cms = Core::make('app');
        $cms->clearCaches();
        $output->writeln('<info>done.</info>');
    }
}

<?php
namespace Concrete\Core\Console\Command;

use Concrete\Core\Config\Repository\Repository;
use Concrete\Core\Console\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Core;
use Exception;

class ClearCacheCommand extends Command
{
    protected function configure()
    {
        $errExitCode = static::RETURN_CODE_ON_FAILURE;
        $this
            ->setName('c5:clear-cache')
            ->setDescription('Clear the concrete5 cache')
            ->addOption('thumbnails', 't', InputOption::VALUE_REQUIRED, "Should the thumbnails be removed from the cache? [Y/N]")
            ->addEnvOption()
            ->setHelp(<<<EOT
If the --thumbnails options is not specified, we'll use the last value set in the dashboard.

Returns codes:
  0 operation completed successfully
  $errExitCode errors occurred

More info at http://documentation.concrete5.org/developers/appendix/cli-commands#c5-clear-cache
EOT
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $cms = Core::make('app');
        $thumbnails = $input->getOption('thumbnails');
        if ($thumbnails !== null) {
            switch (strtolower($thumbnails[0])) {
                case 'n':
                    $clearThumbnails = false;
                    break;
                case 'y':
                    $clearThumbnails = true;
                    break;
                default:
                    throw new Exception('Invalid value for the --thumbnails option: please specify Y[es] or N[o]');
            }
            $config = $cms->app->make(Repository::class);
            $config->set('concrete.cache.clear.thumbnails', $clearThumbnails);
        }
        $output->write('Clearing the concrete5 cache... ');
        $cms->clearCaches();
        $output->writeln('<info>done.</info>');
    }
}

Add an option to the c5:clear-cache CLI command to keep/delete thumbnails


<?php
namespace GusApi\Client;

/**
 * Class SoapActionMapper
 * @package GusApi\Client
 */
class SoapActionMapper
{
    public const PUBLIC_NAMESPACE = 'http://CIS/BIR/PUBL/2014/07/IUslugaBIRzewnPubl/';
    public const NAMESPACE = 'http://CIS/BIR/2014/07/IUslugaBIR/';

    public const ACTIONS = [
        'PobierzCaptcha' => self::NAMESPACE,
        'SprawdzCaptcha' => self::NAMESPACE,
        'GetValue' => self::NAMESPACE,
        'SetValue' => self::NAMESPACE,
        'Zaloguj' => self::PUBLIC_NAMESPACE,
        'Wyloguj' => self::PUBLIC_NAMESPACE,
        'DaneSzukaj' => self::PUBLIC_NAMESPACE,
        'DanePobierzPelnyRaport' => self::PUBLIC_NAMESPACE,
        'DaneKomunikat' => self::PUBLIC_NAMESPACE,
    ];

    /**
     * @param string $functionName
     * @return string
     */
    public static function getAction(string $functionName): string
    {
        if (!isset(self::ACTIONS[$functionName])) {
            //@todo throw invalid action name exception!
        }

        return self::ACTIONS[$functionName].$functionName;
    }
}

<?php
namespace GusApi\Client;
use GusApi\Exception\InvalidActionNameException;

/**
 * Class SoapActionMapper
 * @package GusApi\Client
 */
class SoapActionMapper
{
    public const PUBLIC_NAMESPACE = 'http://CIS/BIR/PUBL/2014/07/IUslugaBIRzewnPubl/';
    public const NAMESPACE = 'http://CIS/BIR/2014/07/IUslugaBIR/';

    public const ACTIONS = [
        'PobierzCaptcha' => self::NAMESPACE,
        'SprawdzCaptcha' => self::NAMESPACE,
        'GetValue' => self::NAMESPACE,
        'SetValue' => self::NAMESPACE,
        'Zaloguj' => self::PUBLIC_NAMESPACE,
        'Wyloguj' => self::PUBLIC_NAMESPACE,
        'DaneSzukaj' => self::PUBLIC_NAMESPACE,
        'DanePobierzPelnyRaport' => self::PUBLIC_NAMESPACE,
        'DaneKomunikat' => self::PUBLIC_NAMESPACE,
    ];

    /**
     * @param string $functionName
     * @return string
     * @throws InvalidActionNameException
     */
    public static function getAction(string $functionName): string
    {
        if (!isset(self::ACTIONS[$functionName])) {
            throw new InvalidActionNameException(sprintf('Invalid action %s', $functionName));
        }

        return self::ACTIONS[$functionName].$functionName;
    }
}

Add soap mapper exception if action was invalid name