<?php namespace Neonbug\News\Repositories;

class NewsRepository {

	const CONFIG_PREFIX = 'neonbug.news';

	protected $latest_items_limit = 20;
	protected $model;

	public function __construct()
	{
		$this->model = config(static::CONFIG_PREFIX . '.model');
	}

	public function getLatest()
	{
		$model = $this->model;
		return $model::where('published', true)
			->where('published_from_date', '<=', date('Y-m-d'))
			->orderBy('published_from_date', 'DESC')
			->limit($this->latest_items_limit)
			->get();
	}

	public function getForAdminList()
	{
		$model = $this->model;
		return $model::all();
	}

}

<?php namespace Neonbug\News\Repositories;

class NewsRepository {

	const CONFIG_PREFIX = 'neonbug.news';

	protected $latest_items_limit = 20;
	protected $model;

	public function __construct()
	{
		$this->model = config(static::CONFIG_PREFIX . '.model');
	}

	public function getLatest()
	{
		$model = $this->model;
		return $model::where('published', true)
			->where('published_from_date', '<=', date('Y-m-d'))
			->orderBy('published_from_date', 'DESC')
			->orderBy('updated_at', 'DESC')
			->limit($this->latest_items_limit)
			->get();
	}

	public function getForAdminList()
	{
		$model = $this->model;
		return $model::all();
	}

}

Fix order of news items, published on the same day


<?php
/**
 * Definition of class DICTest
 *
 * @copyright  2015-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 * @package    justso\justapi\test
 */

namespace justso\justapi\test;

use justso\justapi\Bootstrap;
use justso\justapi\DependencyContainer;
use justso\justapi\testutil\FileSystemSandbox;

require (dirname(__DIR__) . '/testutil/MockClass.php');
require (dirname(__DIR__) . '/testutil/MockClass2.php');

/**
 * Class DICTest
 *
 * @package justso\justapi\test
 */
class DICTest extends \PHPUnit_Framework_TestCase
{
    public function testInstantiation()
    {
        $config = array('environments' => array('test' => array('approot' => '/test')));
        Bootstrap::getInstance()->setTestConfiguration('/test', $config);
        $fs = new FileSystemSandbox();
        $fs->copyFromRealFS(dirname(__DIR__) . '/testutil/TestDICConfig.php', '/test/conf/dependencies.php');
        $env = new DependencyContainer($fs);
        $object = $env->newInstanceOf('TestInterface');
        $this->assertInstanceOf('MockClass', $object);
    }
}

<?php
/**
 * Definition of class DICTest
 *
 * @copyright  2015-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 * @package    justso\justapi\test
 */

namespace justso\justapi\test;

use justso\justapi\Bootstrap;
use justso\justapi\DependencyContainer;
use justso\justapi\testutil\FileSystemSandbox;

require_once(dirname(__DIR__) . '/testutil/MockClass.php');
require_once(dirname(__DIR__) . '/testutil/MockClass2.php');

/**
 * Class DICTest
 *
 * @package justso\justapi\test
 */
class DICTest extends \PHPUnit_Framework_TestCase
{
    public function testInstantiation()
    {
        $config = array('environments' => array('test' => array('approot' => '/test')));
        Bootstrap::getInstance()->setTestConfiguration('/test', $config);
        $fs = new FileSystemSandbox();
        $fs->copyFromRealFS(dirname(__DIR__) . '/testutil/TestDICConfig.php', '/test/conf/dependencies.php');
        $env = new DependencyContainer($fs);
        $object = $env->newInstanceOf('TestInterface');
        $this->assertInstanceOf('MockClass', $object);
    }
}

Make sure that Mock classes are included only once.


<?php

// Set the title for the main template
$parent->context->page_title = 'Support - ' . $frontend->title;

?>

Support

There's a Pyrus section in PEAR manual.

There are some PEAR-related mailing lists, check PEAR website for more info.

You can also ask for help on the #pear
                <acronym title="Internet Relay Chat">IRC</acronym> channel at the
                 Eris Free Net.

If you'd like to report a problem or request a feature for the pear2.php.net website, you can submit an issue on the project page.

Add info on where to report a bug for the pear2 website.


<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\CartBundle\Repository;

use Doctrine\ORM\Query\Expr;
use WellCommerce\Bundle\DoctrineBundle\Repository\AbstractEntityRepository;

/**
 * Class CartProductRepository
 *
 * @author Adam Piotrowski <adam@wellcommerce.org>
 */
class CartProductRepository extends AbstractEntityRepository implements CartProductRepositoryInterface
{
    public function getDataSetQueryBuilder()
    {
        $queryBuilder = $this->getQueryBuilder();
        $queryBuilder->groupBy('cart_product.id');
        $queryBuilder->leftJoin('cart_product.product', 'product');
        $queryBuilder->leftJoin('cart_product.variant', 'product_variant');
        $queryBuilder->leftJoin('product.translations', 'product_translation');
        $queryBuilder->leftJoin('product.sellPriceTax', 'sell_tax');
        $queryBuilder->leftJoin('product.productPhotos', 'gallery', Expr\Join::WITH, 'gallery.mainPhoto = :mainPhoto');
        $queryBuilder->leftJoin('gallery.photo', 'photos');
        $queryBuilder->setParameter('mainPhoto', 1);

        return $queryBuilder;
    }
}

<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\CartBundle\Repository;

use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\QueryBuilder;
use WellCommerce\Bundle\DoctrineBundle\Repository\AbstractEntityRepository;

/**
 * Class CartProductRepository
 *
 * @author Adam Piotrowski <adam@wellcommerce.org>
 */
class CartProductRepository extends AbstractEntityRepository implements CartProductRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function getDataSetQueryBuilder() : QueryBuilder
    {
        $queryBuilder = $this->getQueryBuilder();
        $queryBuilder->groupBy('cart_product.id');
        $queryBuilder->leftJoin('cart_product.product', 'product');
        $queryBuilder->leftJoin('cart_product.variant', 'product_variant');
        $queryBuilder->leftJoin('product.translations', 'product_translation');
        $queryBuilder->leftJoin('product.sellPriceTax', 'sell_tax');
        $queryBuilder->leftJoin('product.productPhotos', 'gallery', Expr\Join::WITH, 'gallery.mainPhoto = :mainPhoto');
        $queryBuilder->leftJoin('gallery.photo', 'photos');
        $queryBuilder->setParameter('mainPhoto', 1);

        return $queryBuilder;
    }
}

Return types in repositories & dataset

Return types in repositories & dataset


<?php

require_once('../config.php');
require_once('authenticate.php');

if (! is_numeric($_POST[KEY_SYS]) OR ! is_numeric($_POST[KEY_DIA]) OR ! is_numeric($_POST[KEY_PULSE])) {
    header('HTTP/1.1 400 Bad Request');
    exit;
}

$log_entry = implode(',', [$_POST[KEY_DATETIME], $_POST[KEY_SYS], $_POST[KEY_DIA], $_POST[KEY_PULSE]]);

file_put_contents(STORAGE_FILEPATH, "$log_entry\n", FILE_APPEND | LOCK_EX);

<?php

require_once('../config.php');
require_once('authenticate.php');

if (! is_numeric($_POST[KEY_SYS]) || ! is_numeric($_POST[KEY_DIA]) || ! is_numeric($_POST[KEY_PULSE])) {
    header('HTTP/1.1 400 Bad Request');
    exit;
}

$log_entry = implode(',', [$_POST[KEY_DATETIME], $_POST[KEY_SYS], $_POST[KEY_DIA], $_POST[KEY_PULSE]]);

file_put_contents(STORAGE_FILEPATH, "$log_entry\n", FILE_APPEND | LOCK_EX);

Use pipes || instead of OR in PHP code

Use pipes || instead of OR in PHP code


<?php

use Jenssegers\Mongodb\Model as Eloquent;

class Token extends ELoquent {

  protected $collection = 'tokens';

  protected $guarded = array('key');

  public static function randomKey($size) {
    do {
      $key = openssl_random_pseudo_bytes ( $size , $strongEnough );
    }
    while( !$strongEnough );

    $key = str_replace( '+', '', base64_encode($key) );
    $key = str_replace( '/', '', $key );

    return base64_encode($key);
  }

  public static function getInstance() {
    $token = new Token();
    $token->key = Token::randomKey(32);
    return $token;
  }

  public static function userFor($token) {
    $token = Token::where('key', '=', $token)->first();
    if ( empty($token) ) return null;

    return User::find($token->user_id);
  }

  public static function isUserToken( $user_id, $token ) {
    return Token::where('user_id', '=', $user_id)
                ->where('key', '=', $token)
                ->exists();
  }

}

<?php

use Jenssegers\Mongodb\Model as Eloquent;

class Token extends Eloquent {

  protected $collection = 'tokens';

  protected $guarded = array('key');

  public static function randomKey($size) {
    do {
      $key = openssl_random_pseudo_bytes ( $size , $strongEnough );
    }
    while( !$strongEnough );

    $key = str_replace( '+', '', base64_encode($key) );
    $key = str_replace( '/', '', $key );

    return base64_encode($key);
  }

  public static function getInstance() {
    $token = new Token();
    $token->key = Token::randomKey(32);
    return $token;
  }

  public static function userFor($token) {
    $token = Token::where('key', '=', $token)->first();
    if ( empty($token) ) return null;

    return User::find($token->user_id);
  }

  public static function isUserToken( $user_id, $token ) {
    return Token::where('user_id', '=', $user_id)
                ->where('key', '=', $token)
                ->exists();
  }

}

Fix capitalization in class name.

Fix capitalization in class name.


<?php
/*
 * This file is part of the wp-magnify/magnify-elasticsearch package.
 *
 * (c) Christopher Davis <http://christopherdavis.me>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Magnify\Elasticsearch as ES;
/**
 * Hooked into the `magnify_loaded` to initialize the driver.
 *
 * @param $magnify the magnify application class.
 * @return void
 */
function magnify_elasticsearch_load(Magnify $magnify)
{
    foreach (magnify_elasticsearch_drivers() as $d) {
        $magnify["elasticsearch.{$d}.factory"] = function ($magnify) use ($d) {
            return new ES\OptionsClientFactory($magnify['logger'], sprintf(
                'magnify_elasticsearch_%s',
                $d
            ));
        };

        $magnify["elasticsearch.{$d}"] = function ($magnify) use ($d) {
            return new ES\ElasticsearchDriver(
                $magnify["elasticsearch.{$d}.factory"],
                $d
            );
        };

        $magnify->registerDriver($magnify["elasticsearch.{$d}"]);
    }
}

function magnify_elasticsearch_drivers()
{
    return magnify_filter('elasticsearch_drivers', ['default']);
}

<?php
/*
 * This file is part of the wp-magnify/magnify-elasticsearch package.
 *
 * (c) Christopher Davis <http://christopherdavis.me>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Magnify\Elasticsearch as ES;

/**
 * Hooked into the `magnify_loaded` to initialize the driver.
 *
 * @param $magnify the magnify application class.
 * @return void
 */
function magnify_elasticsearch_load(Magnify $magnify)
{
    foreach (magnify_elasticsearch_drivers() as $d) {
        $magnify["elasticsearch.{$d}.factory"] = function ($magnify) use ($d) {
            return new ES\OptionsClientFactory($magnify['logger'], $d);
        };

        $magnify["elasticsearch.{$d}"] = function ($magnify) use ($d) {
            return new ES\ElasticsearchDriver(
                $magnify["elasticsearch.{$d}.factory"],
                $d
            );
        };

        $magnify->registerDriver($magnify["elasticsearch.{$d}"]);
    }
}

function magnify_elasticsearch_drivers()
{
    return magnify_filter('elasticsearch_drivers', ['default']);
}

Create the OptionsClientFactory without the Name


<?php

namespace AmpProject\CompatibilityFix;

use AmpProject\CompatibilityFix;

/**
 * Backwards compatibility fix for classes that were moved.
 *
 * @package ampproject/amp-toolbox
 */
final class MovedClasses implements CompatibilityFix
{

    /**
     * Mapping of aliases to be registered.
     *
     * @var array<string, string> Associative array of class alias mappings.
     */
    const ALIASES = [
        // v0.9.0 - moving HTML-based utility into a separate `Html` subnamespace.
        'AmpProject\AtRule'             => 'AmpProject\Html\AtRule',
        'AmpProject\Attribute'          => 'AmpProject\Html\Attribute',
        'AmpProject\LengthUnit'         => 'AmpProject\Html\LengthUnit',
        'AmpProject\RequestDestination' => 'AmpProject\Html\RequestDestination',
        'AmpProject\Role'               => 'AmpProject\Html\Role',
        'AmpProject\Tag'                => 'AmpProject\Html\Tag',

        // v0.9.0 - Extracting `Encoding` out of `Dom\Document`, as it is turned into AMP value object.
        'AmpProject\Dom\Document\Encoding' => 'AmpProject\Encoding',

    ];

    /**
     * Register the compatibility fix.
     *
     * @return void
     */
    public static function register()
    {
        foreach (self::ALIASES as $old => $new) {
            if (class_exists($old)) {
                continue;
            }

            class_alias($new, $old, true);
        }
    }
}

<?php

namespace AmpProject\CompatibilityFix;

use AmpProject\CompatibilityFix;

/**
 * Backwards compatibility fix for classes that were moved.
 *
 * @package ampproject/amp-toolbox
 */
final class MovedClasses implements CompatibilityFix
{

    /**
     * Mapping of aliases to be registered.
     *
     * @var array<string, string> Associative array of class alias mappings.
     */
    const ALIASES = [
        // v0.9.0 - moving HTML-based utility into a separate `Html` subnamespace.
        'AmpProject\AtRule'             => 'AmpProject\Html\AtRule',
        'AmpProject\Attribute'          => 'AmpProject\Html\Attribute',
        'AmpProject\LengthUnit'         => 'AmpProject\Html\LengthUnit',
        'AmpProject\RequestDestination' => 'AmpProject\Html\RequestDestination',
        'AmpProject\Role'               => 'AmpProject\Html\Role',
        'AmpProject\Tag'                => 'AmpProject\Html\Tag',

        // v0.9.0 - Extracting `Encoding` out of `Dom\Document`, as it is turned into AMP value object.
        'AmpProject\Dom\Document\Encoding' => 'AmpProject\Encoding',

    ];

    /**
     * Register the compatibility fix.
     *
     * @return void
     */
    public static function register()
    {
        spl_autoload_register(
            static function ($oldClassName) {
                if (! array_key_exists($oldClassName, self::ALIASES)) {
                    return false;
                }

                class_alias(self::ALIASES[$oldClassName], $oldClassName, true);

                return true;
            }
        );
    }
}

Use indirect class alias registration to fix PHP 5.6 behavior


<?php
namespace DlcCategory\Form;

use DlcCategory\Form\BaseForm;
use DlcCategory\Service\Category as CategoryService;
use Zend\Form\FormInterface;

class EditCategory extends BaseForm
{
    public function init()
    {
        parent::init();

        $this->setLabel('Edit category');
    }

    public function bind($category, $flags = FormInterface::VALUES_NORMALIZED)
    {
        parent::bind($category, $flags);

        $node = $this->getServiceLocator()
                     ->get('dlccategory_category_service')
                     ->getNestedSetManager()
                     ->wrapNode($category);

        if ($node->isRoot()) {
            $insertionAs = CategoryService::ROOT_NODE;
            $insertionOf = '';
        } elseif ($node->hasNextSibling()) {
            $insertionAs = CategoryService::PREV_SIBILING_OF;
            $insertionOf = $node->getNextSibiling()->getNode()->getId();
        } elseif ($node->hasPrevSibling()) {
            $insertionAs = CategoryService::NEXT_SIBILING_OF;
            $insertionOf = $node->getPrivSibiling()->getNode()->getId();
        } elseif ($node->hasParent()) {
            $insertionAs = CategoryService::FIRST_CHILD_OF;
            $insertionOf = $node->getParent()->getNode()->getId();
        } else {
            $insertionAs = '';
            $insertionOf = '';
        }

        $this->byName['category']->get('insertion-method')->setValue($insertionAs);
        $this->byName['category']->get('insertion-point')->setValue($insertionOf);
    }
}

<?php
namespace DlcCategory\Form;

use DlcCategory\Form\BaseForm;
use DlcCategory\Service\Category as CategoryService;
use Zend\Form\FormInterface;

class EditCategory extends BaseForm
{
    public function init()
    {
        parent::init();

        $this->setLabel('Edit category');
    }

    public function bind($category, $flags = FormInterface::VALUES_NORMALIZED)
    {
        parent::bind($category, $flags);

        $node = $this->getServiceLocator()
                     ->get('dlccategory_category_service')
                     ->getNestedSetManager()
                     ->wrapNode($category);

        if ($node->isRoot()) {
            $insertionAs = CategoryService::ROOT_NODE;
            $insertionOf = '';
        } elseif ($node->hasNextSibling()) {
            $insertionAs = CategoryService::PREV_SIBILING_OF;
            $insertionOf = $node->getNextSibling()->getNode()->getId();
        } elseif ($node->hasPrevSibling()) {
            $insertionAs = CategoryService::NEXT_SIBILING_OF;
            $insertionOf = $node->getPrivSibiling()->getNode()->getId();
        } elseif ($node->hasParent()) {
            $insertionAs = CategoryService::FIRST_CHILD_OF;
            $insertionOf = $node->getParent()->getNode()->getId();
        } else {
            $insertionAs = '';
            $insertionOf = '';
        }

        $this->byName['category']->get('insertion-method')->setValue($insertionAs);
        $this->byName['category']->get('insertion-point')->setValue($insertionOf);
    }
}

Fix typo in edit form

Fix typo in edit form


<?php

namespace OpenDominion\Http\Middleware;

use Analytics;
use Closure;
use Illuminate\Support\Facades\Auth;

class Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $auth = Auth::guard($guard);

        if ($auth->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest(route('auth.login'));
            }
        }

        $user = $auth->user();

        if (!$user->activated) {
            $auth->logout();
            // todo: add "click here to have a new activation email being sent to you"
            $request->session()->flash('alert-danger', 'Your account has not been activated yet. Check your spam folder for the activation email.');
            return redirect()->guest(route('auth.login'));
        }

        // Analytics
        Analytics::setUserId(md5(env('APP_KEY') . $user->id));

        return $next($request);
    }
}

<?php

namespace OpenDominion\Http\Middleware;

use Analytics;
use Closure;
use Illuminate\Support\Facades\Auth;

class Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $auth = Auth::guard($guard);

        if ($auth->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest(route('auth.login'));
            }
        }

        $user = $auth->user();

        if (!$user->activated) {
            $auth->logout();
            // todo: add "click here to have a new activation email being sent to you"
            $request->session()->flash('alert-danger', 'Your account has not been activated yet. Check your spam folder for the activation email.');
            return redirect()->guest(route('auth.login'));
        }

        // Analytics
        Analytics::setUserId(md5($user->email));

        return $next($request);
    }
}

Make GA user id persistent across database resets and app_key resets


<?php

namespace LaraComponents\Seo\Contracts;

interface Title
{
}

<?php

namespace LaraComponents\Seo\Contracts;

interface Title
{
    /**
     * Set title separator.
     *
     * @param string $separator
     * @return \LaraComponents\Seo\Contracts\Title
     */
    public function setSeparator($separator);

    /**
     * Get title separator.
     *
     * @return string
     */
    public function getSeparator();

    /**
     * Set site name.
     *
     * @param string $siteName
     * @return \LaraComponents\Seo\Contracts\Title
     */
    public function setSiteName($siteName);

    /**
     * Get site name.
     *
     * @return string
     */
    public function getSiteName();

    /**
     * Set segment max length.
     *
     * @param int $max
     * @return \LaraComponents\Seo\Contracts\Title
     */
    public function setMaxSegemnt($max);

    /**
     * Get segment max length.
     *
     * @return int
     */
    public function getMaxSegment();

    /**
     * Set title max length.
     *
     * @param int $max
     * @return \LaraComponents\Seo\Contracts\Title
     */
    public function setMaxTitle($max);

    /**
     * Get title max length.
     *
     * @return int
     */
    public function getMaxTitle();

    /**
     * Set reverse title position.
     *
     * @param bool $reverse
     * @return \LaraComponents\Seo\Contracts\Title
     */
    public function setReverse($reverse);

    /**
     * Check reverse title position.
     *
     * @return bool
     */
    public function isReverse();

    /**
     * Set the site name visibility.
     *
     * @param bool $visible
     */
    public function setSiteNameVisibility($visible);

    /**
     * Check if site name exists and visible.
     *
     * @return bool
     */
    public function isSiteNameVisible();

    /**
     * Appent title to segments.
     *
     * @return \LaraComponents\Seo\Contracts\Title
     */
    public function append();

    /**
     * Set title segments.
     *
     * @return \LaraComponents\Seo\Contracts\Title
     */
    public function set();

    /**
     * Get title segments.
     *
     * @return array
     */
    public function get();

    /**
     * Make the title string.
     *
     * @return string
     */
    public function make();
}

Add public methods into interface

Add public methods into interface


<?php

namespace App\Http\Middleware;

use Cache;
use Closure;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies = [];

    /**
     * The headers that should be used to detect proxies.
     *
     * @var string
     */
    protected $headers = Request::HEADER_X_FORWARDED_AWS_ELB;

    /**
     * Add remote address to trusted proxy list
     */
    public function handle(Request $request, Closure $next)
    {
        $ips = Cache::remember('list-cloudfront-ips', 60*60, function () {
            return file_get_contents('http://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips');
        });

        $ips = json_decode($ips);

        $this->proxies = array_merge(
            $this->proxies,
            $ips->{"CLOUDFRONT_GLOBAL_IP_LIST"},
            $ips->{"CLOUDFRONT_REGIONAL_EDGE_IP_LIST"}
        );

        array_push($this->proxies, $request->server->get('REMOTE_ADDR'));
        parent::handle($request, $next);
        return $next($request);
    }
}

<?php

namespace App\Http\Middleware;

use Cache;
use Closure;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies = [];

    /**
     * The headers that should be used to detect proxies.
     *
     * @var string
     */
    protected $headers = Request::HEADER_X_FORWARDED_AWS_ELB;

    /**
     * Add remote address to trusted proxy list
     */
    public function handle(Request $request, Closure $next)
    {
        $ips = Cache::remember('list-cloudfront-ips', 60*60, function () {
            return file_get_contents('http://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips');
        });

        $ips = json_decode($ips);

        $this->proxies = array_merge(
            $this->proxies,
            $ips->{"CLOUDFRONT_GLOBAL_IP_LIST"},
            $ips->{"CLOUDFRONT_REGIONAL_EDGE_IP_LIST"}
        );

        array_push($this->proxies, $request->server->get('REMOTE_ADDR'));
        return parent::handle($request, $next);
    }
}

Remove redundant handle call in TrustedProxies middleware


<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            'Illuminate\Contracts\Auth\Registrar',
            'App\Services\Registrar'
        );

        if ($this->app->environment() == 'local') {
            $this->app->register('Laracasts\Generators\GeneratorsServiceProvider');
            $this->app->register('Barryvdh\Debugbar\ServiceProvider');
            $this->app->register('Potsky\LaravelLocalizationHelpers\LaravelLocalizationHelpersServiceProvider');
        }

        if ($this->app->environment() != 'testing') {
            $this->app->register(Jenssegers\Rollbar\RollbarServiceProvider::class);
        }
    }
}

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Jenssegers\Rollbar\RollbarServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            'Illuminate\Contracts\Auth\Registrar',
            'App\Services\Registrar'
        );

        if ($this->app->environment() == 'local') {
            $this->app->register('Laracasts\Generators\GeneratorsServiceProvider');
            $this->app->register('Barryvdh\Debugbar\ServiceProvider');
            $this->app->register('Potsky\LaravelLocalizationHelpers\LaravelLocalizationHelpersServiceProvider');
        }

        if ($this->app->environment() != 'testing') {
            $this->app->register(RollbarServiceProvider::class);
        }
    }
}

Fix service provider import path

Fix service provider import path


<?php namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
use Illuminate\Routing\Stack\Builder as Stack;

class AppServiceProvider extends ServiceProvider {

	/**
	 * All of the application's route middleware keys.
	 *
	 * @var array
	 */
	protected $middleware = [
		'auth' => 'App\Http\Middleware\AuthMiddleware',
		'auth.basic' => 'App\Http\Middleware\BasicAuthMiddleware',
		'csrf' => 'App\Http\Middleware\CsrfMiddleware',
		'guest' => 'App\Http\Middleware\GusetMiddleware',
	];

	/**
	 * The application's middleware stack.
	 *
	 * @var array
	 */
	protected $stack = [
		'App\Http\Middleware\MaintenanceMiddleware',
		'Illuminate\Cookie\Guard',
		'Illuminate\Cookie\Queue',
		'Illuminate\Session\Middleware\Reader',
		'Illuminate\Session\Middleware\Writer',
	];

	/**
	 * Bootstrap any necessary services.
	 *
	 * @return void
	 */
	public function boot()
	{
		// This service provider is a convenient place to register your services
		// in the IoC container. If you wish, you may make additional methods
		// or service providers to keep the code more focused and granular.

		$this->app->stack(function(Stack $stack, Router $router)
		{
			return $stack
				->middleware($this->stack)
				->then(function($request) use ($router)
				{
					return $router->dispatch($request);
				});
			});
	}

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

}

<?php namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Routing\Stack\Builder as Stack;
use Illuminate\Foundation\Support\Providers\AppServiceProvider as ServiceProvider;

class AppServiceProvider extends ServiceProvider {

	/**
	 * All of the application's route middleware keys.
	 *
	 * @var array
	 */
	protected $middleware = [
		'auth' => 'App\Http\Middleware\AuthMiddleware',
		'auth.basic' => 'App\Http\Middleware\BasicAuthMiddleware',
		'csrf' => 'App\Http\Middleware\CsrfMiddleware',
		'guest' => 'App\Http\Middleware\GusetMiddleware',
	];

	/**
	 * The application's middleware stack.
	 *
	 * @var array
	 */
	protected $stack = [
		'App\Http\Middleware\MaintenanceMiddleware',
		'Illuminate\Cookie\Guard',
		'Illuminate\Cookie\Queue',
		'Illuminate\Session\Middleware\Reader',
		'Illuminate\Session\Middleware\Writer',
	];

}

Write a base app service provider.

Write a base app service provider.


<?php
/**
 * Silktide Nibbler. Copyright 2013-2014 Silktide Ltd. All Rights Reserved.
 */
namespace Silktide\LazyBoy\Provider;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Enables application to handles CORS requests
 *
 * TODO: Review security implications
 */
class CorsServiceProvider implements ServiceProviderInterface
{

    public function register(Container $app) {
        if ($app instanceof Application) {
            //handling CORS preflight request
            $app->before(function (Request $request) {
                if ($request->getMethod() === "OPTIONS") {
                    $response = new Response();
                    $response->headers->set("Access-Control-Allow-Origin","*");
                    $response->headers->set("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
                    $response->headers->set("Access-Control-Allow-Headers","Content-Type");
                    $response->setStatusCode(200);
                    $response->send();
                    exit();
                }
            }, Application::EARLY_EVENT);

            //handling CORS response with right headers
            $app->after(function (Request $request, Response $response) {
                $response->headers->set("Access-Control-Allow-Origin","*");
                $response->headers->set("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
            });
        }
    }

}

<?php

namespace Silktide\LazyBoy\Provider;

use Pimple\Container;
use Pimple\ServiceProviderInterface;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Enables application to handles CORS requests
 *
 * TODO: Review security implications
 */
class CorsServiceProvider implements ServiceProviderInterface
{

    public function register(Container $app) {
        if ($app instanceof Application) {
            //handling CORS preflight request
            $app->before(function (Request $request) {
                if ($request->getMethod() === "OPTIONS") {
                    $response = new Response();
                    $response->headers->set("Access-Control-Allow-Origin","*");
                    $response->headers->set("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
                    $response->headers->set("Access-Control-Allow-Headers","Content-Type,Authorization");
                    $response->setStatusCode(200);
                    $response->send();
                    exit();
                }
            }, Application::EARLY_EVENT);

            //handling CORS response with right headers
            $app->after(function (Request $request, Response $response) {
                $response->headers->set("Access-Control-Allow-Origin","*");
                $response->headers->set("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
            });
        }
    }

}

Allow "Authorization" header to be used, in the CORS preflight request


<?php

namespace App\Controller;

class Templates extends \App\Controller\App
{

    public function action_index()
    {
        $this->view->title = 'SMS Templates';

        if ($this->request->method == 'POST') {
            foreach ($this->request->post('templatesId') as $templateId) {
                $template = $this->pixie->orm->get('templates', $templateId);
                if ($template->loaded()) {

                    // remove templates messages
                    if ($this->request->post('delete')) {
                        $template->delete();
                        $this->add_message_success('Templates removed!');
                    }

                    // send message from template
                    if ($this->request->post('send')) {
                        $this->pixie->send_message($template->to, $template->text)
                            ? $this->add_message_success('Message sent to the queue for sending!')
                            : $this->add_message_error('Error while sending message!');
                    }
                }
            }
        }

        $templates = $this->pixie->orm->get('templates');
        $this->add_view_data('templates', $templates->find_all());
        $this->add_view_data('total_templates', (int)$templates->count_all());
    }

}

<?php

namespace App\Controller;

class Templates extends \App\Controller\App
{

    public function action_index()
    {
        $this->view->title = 'SMS Templates';

        if ($this->request->method == 'POST') {
            foreach ($this->request->post('templatesId') as $templateId) {
                $template = $this->pixie->orm->get('templates', $templateId);
                if ($template->loaded()) {
                    $postData = $this->request->post();

                    // remove templates messages
                    if (isset($postData['delete'])) {
                        $template->delete();
                        $this->add_message_success('Templates removed!');
                    }

                    // send message from template
                    if (isset($postData['send'])) {
                        $this->pixie->send_message($template->to, $template->text)
                            ? $this->add_message_success('Message sent to the queue for sending!')
                            : $this->add_message_error('Error while sending message!');
                    }
                }
            }
        }

        $templates = $this->pixie->orm->get('templates');
        $this->add_view_data('templates', $templates->find_all());
        $this->add_view_data('total_templates', (int)$templates->count_all());
    }

}

Fix isset POST key for remove and send template


<form class="" action="sinal_confirmaCad.php" method="post">
  Titulo:<input type="text" name="titulo">

  Categoria:<select name="categoria">
  <option value="OB" selected>Obras</option>
  <option value="IT">Interditado</option>
  <option value="AC">Acidentado</option>
  <option value="OT">Outros</option>
  </select>

  Descrição:<textarea name="descricao">
  </textarea>

  Longitude<input type="number" name="longitude">

  Latitude:<input type="number" name="latitude">

  <input type="submit" value="Cadastrar sinal">

</form>

<form class="" action="sinal_confirmaCad.php" method="post">
  Titulo:<input type="text" name="titulo">

  Categoria:<select name="categoria">
  <option value="OB" selected>Obras</option>
  <option value="IT">Interditado</option>
  <option value="AC">Acidentado</option>
  <option value="OT">Outros</option>
  </select>

  Descrição:<textarea name="descricao">
  </textarea>

  Longitude<input type="number" name="longitude">

  Latitude:<input type="number" name="latitude">

  Data de publicação:<input type="date" name="data_public">
  <input type="submit" value="Cadastrar sinal">

</form>

ADD campo data_public no formulario

ADD campo data_public no formulario


<?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('root', [
    'uses'          => 'RootController@index',
    'middleware'    => ['auth', 'acl'],
    'is'            => 'root']);

Route::resource('businesses', 'BusinessesController');

Route::get('lang/{lang}', ['as'=>'lang.switch', 'uses'=>'LanguageController@switchLang']);

Route::get('/', 'WelcomeController@index');

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

Route::controllers([
	'auth' => 'Auth\AuthController',
	'password' => 'Auth\PasswordController',
]);

<?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('root', [
    'uses'          => 'RootController@index',
    'middleware'    => ['auth', 'acl'],
    'is'            => 'root']);

Route::resource('businesses', 'BusinessesController');

Route::get('lang/{lang}', ['as'=>'lang.switch', 'uses'=>'LanguageController@switchLang']);

Route::get('/', 'WelcomeController@index');

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

Route::get('select/{business_slug}', function ($business_slug) {

    try {

    	$business_id = App\Business::where('slug', $business_slug)->first()->id;

    } catch (Exception $e) {

    	return 'error';

    }

    Session::set('selected.business_id', $business_id);

	return $business_id;
});

Route::get('selected', function () {

	$business_id = Session::get('selected.business_id');

	return $business_id;
});

Route::controllers([
	'auth' => 'Auth\AuthController',
	'password' => 'Auth\PasswordController',
]);

Add select business basic functions

Add select business basic functions


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserProfile extends Model{

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'users_profile';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'provider', 'provider_id', 'oauth_token', 'oauth_token_secret'
    ];

    public function user(){
        return $this->belongsTo('App\User', 'user_id');
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserProfile extends Model{

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'users_profile';

    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'user_id';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'provider', 'provider_id', 'oauth_token', 'oauth_token_secret'
    ];

    public function user(){
        return $this->belongsTo('App\User', 'user_id');
    }
}

Set Primary key in userprofile model

Set Primary key in userprofile model


<?php

namespace GraphStory\Cache;

interface CacheAdapter
{
    /**
     * Gets a cache entry
     * returning null if not in cache.
     *
     * @return null|mixed
     */
    public function get($key);

    /**
     * Sets a cache entry.
     *
     * @param mixed $key
     * @param mixed $value
     */
    public function set($key, $value);

    /**
     * Deletes a cache entry.
     *
     * @param mixed $key
     */
    public function delete($key);
}

<?php

namespace GraphStory\Cache;

interface CacheAdapter
{
    /**
     * Gets a cache entry
     * returning null if not in cache.
     *
     * @return null|mixed
     */
    public function get($key);

    /**
     * Sets a cache entry.
     *
     * @param mixed $key
     * @param mixed $value
     * @param int   $ttl   Time to live
     */
    public function set($key, $value, $ttl);

    /**
     * Deletes a cache entry.
     *
     * @param mixed $key
     */
    public function delete($key);
}

Update interface to allow for ttl on set()


<?php
declare(strict_types=1);

namespace MeetupOrganizing\Command;

use MeetupOrganizing\ServiceContainer;
use PHPUnit_Framework_TestCase;
use Webmozart\Console\Args\StringArgs;
use Webmozart\Console\ConsoleApplication;
use Webmozart\Console\IO\OutputStream\BufferedOutputStream;

final class ScheduleMeetupConsoleHandlerTest extends PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function it_schedules_a_meetup(): void
    {
        $container = new ServiceContainer(getenv('PROJECT_ROOT_DIR'));

        $config = new MeetupApplicationConfig($container);
        $config->setTerminateAfterRun(false);
        $cli = new ConsoleApplication($config);

        $output = new BufferedOutputStream();
        $args = new StringArgs('schedule 1 Akeneo Meetup "2018-04-20 20:00"');
        $cli->run($args, null, $output);

        $this->assertContains(
            'Scheduled the meetup successfully',
            $output->fetch()
        );
    }
}

<?php
declare(strict_types=1);

namespace MeetupOrganizing\Command;

use MeetupOrganizing\SchemaManager;
use MeetupOrganizing\ServiceContainer;
use PHPUnit_Framework_TestCase;
use Webmozart\Console\Args\StringArgs;
use Webmozart\Console\ConsoleApplication;
use Webmozart\Console\IO\OutputStream\BufferedOutputStream;

final class ScheduleMeetupConsoleHandlerTest extends PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function it_schedules_a_meetup(): void
    {
        $container = new ServiceContainer(getenv('PROJECT_ROOT_DIR'));
        /** @var SchemaManager $schemaManager */
        $schemaManager = $container[SchemaManager::class];
        $schemaManager->updateSchema();

        $config = new MeetupApplicationConfig($container);
        $config->setTerminateAfterRun(false);
        $cli = new ConsoleApplication($config);

        $output = new BufferedOutputStream();
        $args = new StringArgs('schedule 1 Akeneo Meetup "2018-04-20 20:00"');
        $cli->run($args, null, $output);

        $this->assertContains(
            'Scheduled the meetup successfully',
            $output->fetch()
        );
    }
}

Prepare the schema in the ConsoleHandlerTest


<?php

namespace CalendarReminder;

use PHPUnit\Framework\TestCase;

class ReminderFileRepositoryTest extends TestCase
{
    const REMINDERS_ROOT_PATH = 'tests/reminders';

    /** @var ReminderFileRepository */
    public $reminderRepository;

    protected function setUp()
    {
        $this->reminderRepository = new ReminderFileRepository(self::REMINDERS_ROOT_PATH);
    }

    protected function tearDown()
    {
        $this->deleteRecursive(self::REMINDERS_ROOT_PATH);
    }

    /**
     * @test
     */
    public function itShouldHaveRepositoryRootPath()
    {
        $this->assertEquals(self::REMINDERS_ROOT_PATH, $this->reminderRepository->remindersPath());
    }

    /**
     * @test
     */
    public function itShouldCreateReminderAndSave()
    {
        $date = date('d.m.Y');
        $content = 'some content';
        $this->reminderRepository->createReminder($date, $content);
        $reminderFileName = sprintf('%s/%s/%s'
            , self::REMINDERS_ROOT_PATH
            , $date
            , $content
        );
        $foundReminder = unserialize(file_get_contents($reminderFileName));
        $this->assertEquals($foundReminder->date(), $date);
        $this->assertEquals($foundReminder->content(), $content);
    }

    }
}

<?php

namespace CalendarReminder;

use PHPUnit\Framework\TestCase;

class ReminderFileRepositoryTest extends TestCase
{
    const REMINDERS_ROOT_PATH = 'tests/reminders';

    /** @var ReminderFileRepository */
    public $reminderRepository;

    protected function setUp()
    {
        $this->reminderRepository = new ReminderFileRepository(self::REMINDERS_ROOT_PATH);
    }

    protected function tearDown()
    {
        $this->deleteRecursive(self::REMINDERS_ROOT_PATH);
    }

    /**
     * @test
     */
    public function itShouldHaveRepositoryRootPath()
    {
        $this->assertEquals(self::REMINDERS_ROOT_PATH, $this->reminderRepository->remindersPath());
    }

    /**
     * @test
     */
    public function itShouldCreateReminderAndSave()
    {
        $date = date('d.m.Y');
        $content = 'some content';
        $this->reminderRepository->createReminder($date, $content);
        $reminderFileName = sprintf('%s/%s/%s'
            , self::REMINDERS_ROOT_PATH
            , $date
            , $content
        );
        $foundReminder = unserialize(file_get_contents($reminderFileName));
        $this->assertEquals($foundReminder->date(), $date);
        $this->assertEquals($foundReminder->content(), $content);
    }

    private function deleteRecursive($input)
    {
        if (is_file($input)) {
            unlink($input);
            return;
        }
        if (is_dir($input)) {
            foreach (scandir($input) as $file) {
                if ($file === '.' || $file === '..') {
                    continue;
                }
                $file = join('/', [$input, $file]);
                if (is_file($file)) {
                    unlink($file);
                    continue;
                }
                $this->deleteRecursive($file);
                rmdir($file);
            }
        }
    }
}

Delete recursive root path input

Delete recursive root path input


@extends ('index')
@section ('title', $observatory)
@section ('route', 'observatory')
@section ('observatory', $observatory)

@section ('sidebar')
<sidebar class="col-lg-3 col-xl-4 p-3">

                発表機関一覧（最終更新順）

            @foreach ($observatories as $obs)
             $obs->observatory_name]) }}">{{ $obs->observatory_name }} ({{ $obs->count }})
            @endforeach

</sidebar>
@endsection

@extends ('index')
@section ('title', $observatory)
@section ('route', 'observatory')
@section ('observatory', $observatory)

@section ('sidebar')
<sidebar class="col-lg-3 col-xl-4 p-3">

                発表機関一覧（最終更新順）

            @foreach ($observatories as $obs)
                @if ($observatory !== $obs->observatory_name)
                     $obs->observatory_name]) }}">{{ $obs->observatory_name }} ({{ $obs->count }})
                @else
                     $obs->observatory_name]) }}">{{ $obs->observatory_name }} ({{ $obs->count }})
                @endif
            @endforeach

</sidebar>
@endsection

Change viewing observatory to active

Change viewing observatory to active


<?php

namespace Northstar\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Northstar\Http\Middleware\ParseOAuthHeader::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Northstar\Http\Middleware\Authenticate::class,
        'guest' => \Northstar\Http\Middleware\RedirectIfAuthenticated::class,
        'scope' => \Northstar\Http\Middleware\RequireScope::class,

        // @TODO: Remove this old alias for the scope middleware.
        'key' => \Northstar\Http\Middleware\RequireScope::class,
    ];
}

<?php

namespace Northstar\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

        // @TODO: Enable this once we've updated PHP version.
        //  \Northstar\Http\Middleware\ParseOAuthHeader::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Northstar\Http\Middleware\Authenticate::class,
        'guest' => \Northstar\Http\Middleware\RedirectIfAuthenticated::class,
        'scope' => \Northstar\Http\Middleware\RequireScope::class,

        // @TODO: Remove this old alias for the scope middleware.
        'key' => \Northstar\Http\Middleware\RequireScope::class,
    ];
}

Disable OAuth header parsing for now.

Disable OAuth header parsing for now.


<?php

namespace Asmaster\EquipTwig\Configuration;

use Asmaster\EquipTwig\TwigFormatter;
use Auryn\Injector;
use Equip\Configuration\ConfigurationInterface;
use Equip\Configuration\EnvTrait;
use Equip\Responder\FormattedResponder;
use Twig_Environment as TwigEnvironment;
use Twig_Loader_Filesystem as TwigLoaderFilesystem;

final class TwigResponderConfiguration implements ConfigurationInterface
{
    use EnvTrait;

    /**
     * @param Injector $injector
     */
    public function apply(Injector $injector)
    {
        $injector->prepare(FormattedResponder::class, function(FormattedResponder $responder) {
            return $responder->withValue(TwigFormatter::class, 1.0);
        });

        $injector->define(TwigLoaderFilesystem::class, [
            ':paths' => $this->env->getValue('TWIG_TEMPLATES')
        ]);

        $injector->define(TwigEnvironment::class, [
            ':loader'  => TwigLoaderFilesystem::class,
            ':options' => $this->getEnvOptions()
        ]);
    }

    /**
     * @return array Configuration options from environment variables
     */
    public function getEnvOptions()
    {
        $env = $this->env;

        $options = [
            'debug'            => $env->getValue('TWIG_DEBUG', false),
            'auto_reload'      => $env->getValue('TWIG_AUTO_RELOAD', true),
            'strict_variables' => $env->getValue('TWIG_STRICT_VARIABLES', false),
            'cache'            => $env->getValue('TWIG_CACHE', false)
        ];

        return $options;
    }
}

<?php

namespace Asmaster\EquipTwig\Configuration;

use Asmaster\EquipTwig\TwigFormatter;
use Auryn\Injector;
use Equip\Configuration\ConfigurationInterface;
use Equip\Configuration\EnvTrait;
use Equip\Responder\FormattedResponder;
use Twig_Environment as TwigEnvironment;
use Twig_Loader_Filesystem as TwigLoaderFilesystem;

final class TwigResponderConfiguration implements ConfigurationInterface
{
    use EnvTrait;

    /**
     * @param Injector $injector
     */
    public function apply(Injector $injector)
    {
        $injector->prepare(FormattedResponder::class, function(FormattedResponder $responder) {
            return $responder->withValue(TwigFormatter::class, 1.0);
        });

        $injector->define(TwigLoaderFilesystem::class, [
            ':paths' => $this->env->getValue('TWIG_TEMPLATES')
        ]);

        $injector->define(TwigEnvironment::class, [
            'loader'   => TwigLoaderFilesystem::class,
            ':options' => $this->getEnvOptions()
        ]);
    }

    /**
     * @return array Configuration options from environment variables
     */
    public function getEnvOptions()
    {
        $env = $this->env;

        $options = [
            'debug'            => $env->getValue('TWIG_DEBUG', false),
            'auto_reload'      => $env->getValue('TWIG_AUTO_RELOAD', true),
            'strict_variables' => $env->getValue('TWIG_STRICT_VARIABLES', false),
            'cache'            => $env->getValue('TWIG_CACHE', false)
        ];

        return $options;
    }
}

Fix an injection definition for the Twig_Environment


<?
session_start();
if($_REQUEST['logout']){unset($_SESSION['admin']);}

if($_SESSION['admin'] == ""){
	die();
}

include("../lib/CloudMngr/cloudmngr.core.class.php");

$CloudMngr = new CloudMngr($_GET['id']);

$module = $_GET['module'];//{TODO input filertering
$action = $_GET['action'];

if($module != "" && file_exists($CloudMngr->class_path . DIRECTORY_SEPARATOR . "modules" . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . $module.'.php')){
	$file = $CloudMngr->class_path . DIRECTORY_SEPARATOR . "modules" . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . "cmd" . DIRECTORY_SEPARATOR . $action .'.php';
	if(file_exists($action_file)){
		include($action_file);
	}
}

?>

<?
session_start();
if($_REQUEST['logout']){unset($_SESSION['admin']);}

if($_SESSION['admin'] == ""){
	die();
}

include("../lib/CloudMngr/cloudmngr.core.class.php");

$CloudMngr = new CloudMngr($_GET['id']);

$module = $_POST['module'];//{TODO input filertering
$action = $_POST['action'];

if($module != "" && file_exists($CloudMngr->class_path . DIRECTORY_SEPARATOR . "modules" . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . $module.'.php')){
	$file = $CloudMngr->class_path . DIRECTORY_SEPARATOR . "modules" . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . "cmd" . DIRECTORY_SEPARATOR . $action .'.php';
	if(file_exists($action_file)){
		include($action_file);
	}
}

?>

Change cmg get to post

Change cmg get to post


<?php

use App\Models\Setting;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        $this->call(CompanySeeder::class);
        $this->call(CategorySeeder::class);
        $this->call(UserSeeder::class);
        $this->call(DepreciationSeeder::class);
        $this->call(DepartmentSeeder::class);
        $this->call(ManufacturerSeeder::class);
        $this->call(LocationSeeder::class);
        $this->call(SupplierSeeder::class);
        $this->call(AssetModelSeeder::class);
        $this->call(DepreciationSeeder::class);
        $this->call(StatuslabelSeeder::class);
        $this->call(AccessorySeeder::class);
        $this->call(AssetSeeder::class);
        $this->call(LicenseSeeder::class);
        $this->call(ComponentSeeder::class);
        $this->call(ConsumableSeeder::class);
        $this->call(ActionlogSeeder::class);
        $this->call(CustomFieldSeeder::class);

        // Only create default settings if they do not exist in the db.
        if(!Setting::first()) {
            factory(Setting::class)->create();
        }
        Artisan::call('snipeit:sync-asset-locations', ['--output' => 'all']);
        $output = Artisan::output();
        \Log::info($output);

        Model::reguard();
    }
}

<?php

use App\Models\Setting;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        $this->call(CompanySeeder::class);
        $this->call(CategorySeeder::class);
        $this->call(UserSeeder::class);
        $this->call(DepreciationSeeder::class);
        $this->call(DepartmentSeeder::class);
        $this->call(ManufacturerSeeder::class);
        $this->call(LocationSeeder::class);
        $this->call(SupplierSeeder::class);
        $this->call(AssetModelSeeder::class);
        $this->call(DepreciationSeeder::class);
        $this->call(StatuslabelSeeder::class);
        $this->call(AccessorySeeder::class);
        $this->call(AssetSeeder::class);
        $this->call(LicenseSeeder::class);
        $this->call(ComponentSeeder::class);
        $this->call(ConsumableSeeder::class);
        $this->call(ActionlogSeeder::class);
        $this->call(CustomFieldSeeder::class);

        // Only create default settings if they do not exist in the db.
        if(!Setting::first()) {
            factory(Setting::class)->create();
        }
        Artisan::call('snipeit:sync-asset-locations', ['--output' => 'all']);
        $output = Artisan::output();
        \Log::info($output);

        Model::reguard();

        DB::table('imports')->truncate();

    }
}

Truncate imports table on seed

Truncate imports table on seed


<?php

/**
 * League.Csv (https://csv.thephpleague.com)
 *
 * (c) Ignace Nyamagana Butera <nyamsprod@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace League\Csv;

use IteratorIterator;
use Traversable;

/**
 * Map value from an iterator before yielding.
 *
 * @internal used internally to modify CSV content
 */
final class MapIterator extends IteratorIterator
{
    /**
     * The callback to apply on all InnerIterator current value.
     *
     * @var callable
     */
    private $callable;

    /**
     * New instance.
     */
    public function __construct(Traversable $iterator, callable $callable)
    {
        parent::__construct($iterator);
        $this->callable = $callable;
    }

    /**
     * @return mixed The value of the current element.
     */
    public function current()
    {
        return ($this->callable)(parent::current(), parent::key());
    }
}

<?php

/**
 * League.Csv (https://csv.thephpleague.com)
 *
 * (c) Ignace Nyamagana Butera <nyamsprod@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace League\Csv;

use IteratorIterator;
use Traversable;

/**
 * Map value from an iterator before yielding.
 *
 * @internal used internally to modify CSV content
 */
final class MapIterator extends IteratorIterator
{
    /**
     * The callback to apply on all InnerIterator current value.
     *
     * @var callable
     */
    private $callable;

    /**
     * New instance.
     */
    public function __construct(Traversable $iterator, callable $callable)
    {
        parent::__construct($iterator);
        $this->callable = $callable;
    }

    /**
     * @return mixed The value of the current element.
     */
    #[\ReturnTypeWillChange]
    public function current()
    {
        return ($this->callable)(parent::current(), parent::key());
    }
}

Fix PHP 8.1 deprecation errors

Fix PHP 8.1 deprecation errors


<?php

  get_header();

  global $query_string;
  $query_modifications = is_category() ? "" : "&cat=-308"; // Exclude hidden posts unless on a category page
  $query_modifications .= parent_category_is("trips") ? "&order=ASC" : "";
  query_posts($query_string.$query_modifications);

  is_front_page() && !is_paged() ? require("nav.php") : null;

  if (have_posts()) {

    while (have_posts()) {

      the_post();
      require(in_category("words") ? "text.php" : "image.php");

    }

  } else {

    require("404.php");

  }

  get_footer();

?>

<?php

  get_header();

  global $query_string;
  $query_modifications = is_category() ? "" : "&cat=-7"; // Exclude hidden posts unless on a category page
  $query_modifications .= parent_category_is("trips") ? "&order=ASC" : "";
  query_posts($query_string.$query_modifications);

  is_front_page() && !is_paged() ? require("nav.php") : null;

  if (have_posts()) {

    while (have_posts()) {

      the_post();
      require(in_category("words") ? "text.php" : "image.php");

    }

  } else {

    require("404.php");

  }

  get_footer();

?>

Fix reference to hidden category (seems to have changed to a taxomonmy at some point)


<?php
namespace Grav\Plugin;

use \Grav\Common\Grav;

class AdminTwigExtension extends \Twig_Extension
{
    protected $grav;

    public function __construct()
    {
        $this->grav = Grav::instance();
    }

    /**
     * Returns extension name.
     *
     * @return string
     */
    public function getName()
    {
        return 'AdminTwigExtension';
    }

    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('tu', [$this, 'tuFilter']),

        ];
    }

    public function tuFilter()
    {
        return $this->grav['language']->translate(func_get_args());
    }

}

<?php
namespace Grav\Plugin;

use \Grav\Common\Grav;

class AdminTwigExtension extends \Twig_Extension
{
    protected $grav;

    public function __construct()
    {
        $this->grav = Grav::instance();
        $this->lang = $this->grav['user']->language;
    }

    /**
     * Returns extension name.
     *
     * @return string
     */
    public function getName()
    {
        return 'AdminTwigExtension';
    }

    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('tu', [$this, 'tuFilter']),

        ];
    }

    public function tuFilter()
    {
        return $this->grav['language']->translate(func_get_args(), [$this->grav['user']->authenticated ? $this->lang : 'en']);
    }
}

Use the user-set language in twig filter


<?php
/**
 * Bright Nucleus View Component.
 *
 * @package   BrightNucleus\View
 * @author    Alain Schlesser <alain.schlesser@gmail.com>
 * @license   MIT
 * @link      http://www.brightnucleus.com/
 * @copyright 2016 Alain Schlesser, Bright Nucleus
 */

namespace BrightNucleus\View;

$engineFinder = [
    'ClassName'  => 'BrightNucleus\View\Engine\BaseEngineFinder',
    'Engines'    => [
        'PHPEngine' => 'BrightNucleus\View\Engine\PHPEngine',
    ],
    'NullObject' => 'BrightNucleus\View\Engine\NullEngine',
];

$viewFinder = [
    'ClassName'  => 'BrightNucleus\View\View\BaseViewFinder',
    'Views'      => [
        'BaseView' => 'BrightNucleus\View\View\BaseView',
    ],
    'NullObject' => 'BrightNucleus\View\View\NullView',
];

return [
    'BrightNucleus' => [
        'View' => [
            'EngineFinder' => $engineFinder,
            'ViewFinder'   => $viewFinder,
        ],
    ],
];

<?php
/**
 * Bright Nucleus View Component.
 *
 * @package   BrightNucleus\View
 * @author    Alain Schlesser <alain.schlesser@gmail.com>
 * @license   MIT
 * @link      http://www.brightnucleus.com/
 * @copyright 2016 Alain Schlesser, Bright Nucleus
 */

namespace BrightNucleus\View;

$engineFinder = [
    'ClassName'  => Engine\BaseEngineFinder::class,
    'Engines'    => [
        'PHPEngine' => Engine\PHPEngine::class,
    ],
    'NullObject' => Engine\NullEngine::class,
];

$viewFinder = [
    'ClassName'  => View\BaseViewFinder::class,
    'Views'      => [
        'BaseView' => View\BaseView::class,
    ],
    'NullObject' => View\NullView::class,
];

return [
    'BrightNucleus' => [
        'View' => [
            'EngineFinder' => $engineFinder,
            'ViewFinder'   => $viewFinder,
        ],
    ],
];

Use class name constants in config file.


<?php

return [
    'endpoints' => [
        'products' => [
            'host' => env('SOLR_HOST', '127.0.0.1'),
            'port' => env('SOLR_PORT', '8983'),
            'path' => env('SOLR_PATH', '/solr/'),
            'core' => env('SOLR_CORE', 'collection1')
        ]
    ]
];

<?php

return [
    'endpoints' => [
        'default' => [
            'host' => env('SOLR_HOST', '127.0.0.1'),
            'port' => env('SOLR_PORT', '8983'),
            'path' => env('SOLR_PATH', '/solr/'),
            'core' => env('SOLR_CORE', 'collection1')
        ]
    ]
];

Rename Solarium endpoint to clarify purpose

We will be configuring Solarium through our `.env` file, not through
the provider config. Additionally, our current SolrScoutEngine follows
the Algolia example in that it uses `searchableAs`, which assumes that
each model will have it's own index (i.e. core?). I'm uncertain whether
that's how Solr is meant to work, but we intend to store all models
under a common schema anyway, so this is the first step to moving
in that direction.

https://solarium.readthedocs.io/en/stable/getting-started/#basic-usage


<?php

namespace ByteUnits;

class PowerScale
{
    private $base;
    private $scale;
    private $precision;

    public function __construct($base, $scale, $precision)
    {
        $this->base = $base;
        $this->scale = $scale;
        $this->precision = $precision;
    }

    public function scaleToUnit($quantity, $unit)
    {
        return bcdiv(
            $quantity,
            bcpow($this->base, $this->scale[$unit], $this->precision),
            $this->precision
        );
    }

    public function scaleFromUnit($quantity, $unit)
    {
        return $quantity * bcpow(
            $this->base,
            $this->scale[$unit],
            $this->precision
        );
    }

    public function isKnownUnit($unitAsString)
    {
        return preg_match(
            '/^(?:' . implode('|', array_keys($this->scale)) . ')$/i',
            trim($unitAsString)
        );
    }

    public function normalizeNameOfUnit($unitAsString)
    {
        foreach ($this->scale as $unit => $_) {
            if (strtolower($unit) === strtolower($unitAsString)) {
                return $unit;
            }
        }
    }

    public function normalUnitFor($quantity)
    {
        foreach ($this->scale as $unit => $_) {
            $scaled = $this->scaleToUnit($quantity, $unit);
            if (bccomp($scaled, 1) >= 0) {
                return $unit;
            }
        }
    }

    public function isBaseUnit($unit)
    {
        return $this->scale[$unit] === 0;
    }
}

<?php

namespace ByteUnits;

class PowerScale
{
    private $base;
    private $scale;
    private $precision;

    public function __construct($base, $scale, $precision)
    {
        $this->base = $base;
        $this->scale = $scale;
        $this->precision = $precision;
    }

    public function scaleToUnit($quantity, $unit)
    {
        if ($quantity === "0") return "0";
        return bcdiv(
            $quantity,
            bcpow($this->base, $this->scale[$unit], $this->precision),
            $this->precision
        );
    }

    public function scaleFromUnit($quantity, $unit)
    {
        return $quantity * bcpow(
            $this->base,
            $this->scale[$unit],
            $this->precision
        );
    }

    public function isKnownUnit($unitAsString)
    {
        return preg_match(
            '/^(?:' . implode('|', array_keys($this->scale)) . ')$/i',
            trim($unitAsString)
        );
    }

    public function normalizeNameOfUnit($unitAsString)
    {
        foreach ($this->scale as $unit => $_) {
            if (strtolower($unit) === strtolower($unitAsString)) {
                return $unit;
            }
        }
    }

    public function normalUnitFor($quantity)
    {
        foreach ($this->scale as $unit => $_) {
            $scaled = $this->scaleToUnit($quantity, $unit);
            if (bccomp($scaled, 1) >= 0) {
                return $unit;
            }
        }
    }

    public function isBaseUnit($unit)
    {
        return (!isset($this->scale[$unit]) || $this->scale[$unit] === 0);
    }
}

Make it so library doesn't spit out error, when trying to display 0


<?php

class Soflomo_Form extends Zend_Form
{
    /**
     * Constructor
     *
     * @return Soflomo_Form
     */
    public function __construct ($options = null)
    {
        $this->addPrefixPath('Soflomo_Form_', 'Soflomo/Form/');
        parent::__construct($options);
    }

    /**
     * Clear all values from elements
     *
     * @return void
     */
    public function clearValues ()
    {
        foreach ($this->getElements() as $element) {
            $element->setValue(null);
        }
    }
}

<?php

/**
 * This is free and unencumbered software released into the public domain.
 *
 * Anyone is free to copy, modify, publish, use, compile, sell, or
 * distribute this software, either in source code form or as a compiled
 * binary, for any purpose, commercial or non-commercial, and by any
 * means.
 *
 * In jurisdictions that recognize copyright laws, the author or authors
 * of this software dedicate any and all copyright interest in the
 * software to the public domain. We make this dedication for the benefit
 * of the public at large and to the detriment of our heirs and
 * successors. We intend this dedication to be an overt act of
 * relinquishment in perpetuity of all present and future rights to this
 * software under copyright law.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * For more information, please refer to <http://unlicense.org/>
 *
 * @category   Soflomo
 * @package    Soflomo_Form
 * @copyright  Copyright (c) 2009-2011 Soflomo (http://www.soflomo.com)
 * @license    http://unlicense.org Unlicense
 */

/**
 * Soflomo_Form
 *
 * @category   Soflomo
 * @package    Soflomo_Form
 * @author     Jurian Sluiman <jurian@soflomo.com>
 * @copyright  Copyright (c) 2009-2011 Soflomo (http://www.soflomo.com)
 * @license    http://unlicense.org Unlicense
 */
class Soflomo_Form extends Zend_Form
{
    /**
     * Constructor
     *
     * @return Soflomo_Form
     */
    public function __construct ($options = null)
    {
        $this->addPrefixPath('Soflomo_Form_', 'Soflomo/Form/');
        parent::__construct($options);
    }

    /**
     * Clear all values from elements
     *
     * @return void
     */
    public function clearValues ()
    {
        foreach ($this->getElements() as $element) {
            $element->setValue(null);
        }
    }
}

Add phpdoc and license to file

Add phpdoc and license to file


<?php

namespace EHEncryptionBundle\Annotation;

use Doctrine\Common\Annotations\Annotation;

/**
 * @Annotation
 * @Target("CLASS")
 */
final class EncryptedFile
{
    public $enabled = true;

    public $mode;
}

<?php

namespace EHEncryptionBundle\Annotation;

use Doctrine\Common\Annotations\Annotation;
use EHEncryptionBundle\Service\EncryptionService;

/**
 * @Annotation
 * @Target("CLASS")
 */
final class EncryptedFile
{
    public $enabled = true;

    public $mode = EncryptionService::MODE_PER_USER_SHAREABLE;
}

Document and file encryption changes

Document and file encryption changes


Sign In

            <?php echo inputText('username', 'Username'); ?>

            <?php echo inputPassword('password', 'Password'); ?>

            <?php echo inputCheckbox('keep', 'Remember Me'); ?>

            <?php echo inputSubmit('Sign In'); ?>

            Don't have an account yet? <a href="<?php echo baseUrl(); ?>user/signup">Sign Up

Sign In

            <?php echo inputText('username', 'Username'); ?>

            <?php echo inputPassword('password', 'Password'); ?>

            <?php echo inputCheckbox('keep', 'Remember Me'); ?>

            <?php echo inputSubmit('Sign In'); ?>

            Don't have an account yet? <a href="<?php echo baseUrl(); ?>user/signup">Create an Account

Rename 'Sign Up' display to 'Create an Account'


<?
class QuickSearch extends Filter {
    /*
     * Quicksearch represents one-field filter which goes perfectly with a grid
     */

    var $region=null;
    var $region_url=null;

    function defaultTemplate(){
        return array('compact_form','form');
    }
    function init(){
        parent::init();
        $this->useDQ($this->owner->dq);
        $this->addField('Search','q','Find');
        $this->addButton('Go')->submitForm($this);

        $this->onSubmit()->submitForm($this);
    }
    function useFields($fields){
        $this->fields=$fields;
        return $this;
    }
    function applyDQ($dq){
        if(!($v=$this->get('q')))return;

        $v=addslashes($v);  // quote it

        $q=array();
        foreach($this->fields as $field){
            $q[]="$field like '%".$v."%'";
        }
        if($q){
            $dq->where(join(' or ',$q));
        }
    }
    function submitted(){
        if(parent::submitted()){
            $a=$this->add('Ajax');
            if(!$this->region){
                $a->redirect();
            }else{
                if($this->region_url){
                    $a->loadRegionURL($this->region,$this->region_url);
                }else{
                    $a->reloadRegion($this->region);
                }
            }
            $a->execute();
        }
    }
}

<?
class QuickSearch extends Filter {
    /*
     * Quicksearch represents one-field filter which goes perfectly with a grid
     */

    var $region=null;
    var $region_url=null;

    function defaultTemplate(){
        return array('compact_form','form');
    }
    function init(){
        parent::init();
        $this->useDQ($this->owner->dq);
        $this->addField('Search','q','Find');
        $this->addButton('Go')->submitForm($this);

        $this->onSubmit()->submitForm($this);
    }
    function useFields($fields){
        $this->fields=$fields;
        return $this;
    }
    function applyDQ($dq){
        if(!($v=$this->get('q')))return;

        $v=addslashes($v);  // quote it

        $q=array();
        foreach($this->fields as $field){
            $q[]="$field like '%".$v."%'";
        }
        if($q){
            $dq->having(join(' or ',$q));
        }
    }
    function submitted(){
        if(parent::submitted()){
            $a=$this->add('Ajax');
            if(!$this->region){
                $a->redirect();
            }else{
                if($this->region_url){
                    $a->loadRegionURL($this->region,$this->region_url);
                }else{
                    $a->reloadRegion($this->region);
                }
            }
            $a->execute();
        }
    }
}

Use "having" instead of "where". We don't want to break the query and want to filter by all possible fields.


<?php

ini_set('xdebug.max_nesting_level', 300);
ini_set('display_errors', 1);

require dirname(__DIR__) . '/apps/Demo.Helloworld/bin/clear.php';
require dirname(__DIR__) . '/apps/Demo.Sandbox/bin/clear.php';

// loader
error_reporting(E_ALL ^ E_NOTICE);
$loader = require dirname(__DIR__) . '/vendor/autoload.php';
/** @var $loader \Composer\Autoload\ClassLoader */
$loader->addPsr4('BEAR\Package\\', __DIR__);
$loader->addPsr4('Vendor\MockApp\\', __DIR__ . '/Mock');
error_reporting(E_ALL);

$_ENV['TEST_DIR'] = __DIR__;
$_ENV['TMP_DIR'] = __DIR__ . '/tmp';
$_ENV['PACKAGE_DIR'] = dirname(__DIR__);

<?php

ini_set('xdebug.max_nesting_level', 300);
ini_set('display_errors', 1);

require dirname(__DIR__) . '/apps/Demo.Helloworld/bin/clear.php';
require dirname(__DIR__) . '/apps/Demo.Sandbox/bin/clear.php';

// loader
error_reporting(E_ALL ^ E_NOTICE);
$loader = require dirname(__DIR__) . '/vendor/autoload.php';
/** @var $loader \Composer\Autoload\ClassLoader */
$loader->addPsr4('BEAR\Package\\', __DIR__);
error_reporting(E_ALL);

// load for p($var); e();
(new \BEAR\Package\Dev\Dev)->loadDevFunctions();

$_ENV['TEST_DIR'] = __DIR__;
$_ENV['TMP_DIR'] = __DIR__ . '/tmp';
$_ENV['PACKAGE_DIR'] = dirname(__DIR__);

Revert "remove deprecated loadDevFunctions function"

This reverts commit 509c65250fc1fa46da2f2d395fad5b9e7901eb4c.


<?php

/**
 * @file
 * template.php
 */

/**
 * theme_preprocess_page
 */
function tedxlausanne_preprocess_page(&$variables) {

}

/**
 * Preprocess variables for node.tpl.php
 *
 * @see node.tpl.php
 */
function tedxlausanne_preprocess_node(&$variables) {

  // That will let you use a template file like: node--[type|nodeid]--teaser.tpl.php
  if($variables['view_mode'] == 'teaser') {
    $variables['theme_hook_suggestions'][] = 'node__' . $variables['node']->type . '__teaser';
  }

  if($variables['view_mode'] == 'full_teaser') {
    $variables['theme_hook_suggestions'][] = 'node__' . $variables['node']->type . '__full_teaser';
  }
  // if (module_exists('devel')) {
  //   dpm($variables);
  // }
}

<?php

/**
 * @file
 * template.php
 */

/**
 * theme_preprocess_page
 */
function tedxlausanne_preprocess_page(&$variables) {

  // Display speaker name in the talk title
  if(isset($variables['node']) && isset($variables['node']->field_talk_speaker['und'][0]['entity']->title) && $variables['node']->type == 'talk'){
    $speaker = $variables['node']->field_talk_speaker['und'][0]['entity']->title;
    $variables['title'] = ''.$speaker.'
 '.$variables['node']->title;
  }

}

/**
 * Preprocess variables for node.tpl.php
 *
 * @see node.tpl.php
 */
function tedxlausanne_preprocess_node(&$variables) {

  // That will let you use a template file like: node--[type|nodeid]--teaser.tpl.php
  if($variables['view_mode'] == 'teaser') {
    $variables['theme_hook_suggestions'][] = 'node__' . $variables['node']->type . '__teaser';
  }

  if($variables['view_mode'] == 'full_teaser') {
    $variables['theme_hook_suggestions'][] = 'node__' . $variables['node']->type . '__full_teaser';
  }

}

Add speaker name in talk page

Add speaker name in talk page


<?php
namespace DMS\Bundle\TwigExtensionBundle\Twig\Date;

/**
 * Adds support for Padding a String in Twig
 */
class PadStringExtension extends \Twig_Extension
{
    /**
     * Name of Extension
     *
     * @return string
     */
    public function getName()
    {
        return 'PadStringExtension';
    }

    /**
     * Available filters
     *
     * @return array
     */
    public function getFilters()
    {
        return array(
            'padString' => new \Twig_Filter_Method($this, 'padStringFilter'),
        );
    }

    /**
     * Pads string on right or left with given padCharacter until string
     * reaches maxLength
     *
     * @param string  $value
     * @param string  $padCharacter
     * @param int     $maxLength
     * @param bool    $padLeft
     * @return string
     * @throws \InvalidArgumentException
     */
    public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true)
    {
        if ( ! is_int($maxLength) ) {
            throw new \InvalidArgumentException('Pad String Filter expects its second argument to be an integer');
        }

        if (function_exists('mb_strlen')) {
            $padLength = $maxLength - mb_strlen($value);
        } else {
            $padLength = $maxLength - strlen($value);
        }

        if ($padLength <= 0) {
            return $value;
        }

        $padString = str_repeat($padCharacter, $padLength);

        if ($padLeft) {
            return $padString . $value;
        }

        return $value . $padString;
    }
}

<?php
namespace DMS\Bundle\TwigExtensionBundle\Twig\Text;

/**
 * Adds support for Padding a String in Twig
 */
class PadStringExtension extends \Twig_Extension
{
    /**
     * Name of Extension
     *
     * @return string
     */
    public function getName()
    {
        return 'PadStringExtension';
    }

    /**
     * Available filters
     *
     * @return array
     */
    public function getFilters()
    {
        return array(
            'padString' => new \Twig_Filter_Method($this, 'padStringFilter'),
        );
    }

    /**
     * Pads string on right or left with given padCharacter until string
     * reaches maxLength
     *
     * @param string  $value
     * @param string  $padCharacter
     * @param int     $maxLength
     * @param bool    $padLeft
     * @return string
     * @throws \InvalidArgumentException
     */
    public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true)
    {
        if ( ! is_int($maxLength) ) {
            throw new \InvalidArgumentException('Pad String Filter expects its second argument to be an integer');
        }

        if (function_exists('mb_strlen')) {
            $padLength = $maxLength - mb_strlen($value);
        } else {
            $padLength = $maxLength - strlen($value);
        }

        if ($padLength <= 0) {
            return $value;
        }

        $padString = str_repeat($padCharacter, $padLength);

        if ($padLeft) {
            return $padString . $value;
        }

        return $value . $padString;
    }
}

Correct error in namespace declaration

Correct error in namespace declaration


<?php
/**
 * Template Name: Full Width
 *
 * The template for displaying all pages.
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site may use a
 * different template.
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package Bemmy
 */

get_header(); ?>

  <div id="primary" class="page">
    <main id="main" class="page__main page__main--full-width" role="main">

      <?php
      while ( have_posts() ) : the_post();

        get_template_part( 'template-parts/content', 'page' );

        // If comments are open or we have at least one comment, load up the comment template.
        if ( comments_open() || get_comments_number() ) :
          comments_template();
        endif;

      endwhile; // End of the loop.
      ?>

    </main><!-- #main -->
  </div><!-- #primary -->

<?php
get_sidebar();
get_footer();

<?php
/**
 * Template Name: Full Width
 *
 * The template for displaying all pages.
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site may use a
 * different template.
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package Bemmy
 */

// Full Width template removes wpautop!
remove_filter('the_content', 'wpautop');

get_header(); ?>

  <div id="primary" class="page">
    <main id="main" class="page__main page__main--full-width" role="main">

      <?php
      while ( have_posts() ) : the_post();

        get_template_part( 'template-parts/content', 'page' );

        // If comments are open or we have at least one comment, load up the comment template.
        if ( comments_open() || get_comments_number() ) :
          comments_template();
        endif;

      endwhile; // End of the loop.
      ?>

    </main><!-- #main -->
  </div><!-- #primary -->

<?php
get_sidebar();
get_footer();

Remove wpautop for full width template

Remove wpautop for full width template


<?php
/**
 * A queued job that publishes a target after a delay.
 *
 * @package advancedworkflow
 */
class WorkflowPublishTargetJob extends AbstractQueuedJob {

	public function __construct($obj = null, $type = null) {
		if ($obj) {
			$this->setObject($obj);
			$this->publishType = $type ? strtolower($type) : 'publish';
			$this->totalSteps = 1;
		}
	}

	public function getTitle() {
		return "Scheduled $this->publishType of " . $this->getObject()->Title;
	}

	public function process() {
		if ($target = $this->getObject()) {
			if ($this->publishType == 'publish') {
				$target->doPublish();
			} else if ($this->publishType == 'unpublish') {
				$target->doUnpublish();
			}
		}
		$this->currentStep = 1;
		$this->isComplete = true;
	}

}

<?php
/**
 * A queued job that publishes a target after a delay.
 *
 * @package advancedworkflow
 */
class WorkflowPublishTargetJob extends AbstractQueuedJob {

	public function __construct($obj = null, $type = null) {
		if ($obj) {
			$this->setObject($obj);
			$this->publishType = $type ? strtolower($type) : 'publish';
			$this->totalSteps = 1;
		}
	}

	public function getTitle() {
		return "Scheduled $this->publishType of " . $this->getObject()->Title;
	}

	public function process() {
		if ($target = $this->getObject()) {
			if ($this->publishType == 'publish') {
				$target->PublishOnDate = '';
				$target->writeWithoutVersion();
				$target->doPublish();
			} else if ($this->publishType == 'unpublish') {
				$target->UnPublishOnDate = '';
				$target->writeWithoutVersion();
				$target->doUnpublish();
			}
		}
		$this->currentStep = 1;
		$this->isComplete = true;
	}

}

API: Clear embargo fields once embargo processed


<?php

namespace wcf\system\worker;

use wcf\data\object\type\ObjectType;
use wcf\system\WCF;

/**
 * Represents a worker that is registered with the RebuildWorkerCollecting event.
 *
 * @author Tim Duesterhus
 * @copyright 2001-2022 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Worker
 * @since 6.0
 */
final class RegisteredWorker
{
    public function __construct(
        public readonly string $classname,
        private readonly ?ObjectType $legacyObjectType = null,
    ) {
    }

    public function getName(): string
    {
        if ($this->legacyObjectType !== null) {
            return WCF::getLanguage()->get(\sprintf(
                'wcf.acp.rebuildData.%s',
                $this->legacyObjectType->objectType
            ));
        }

        return WCF::getLanguage()->get(\sprintf(
            'wcf.acp.rebuildData.%s',
            \str_replace('\\', '_', $this->classname)
        ));
    }

    public function getDescription(): string
    {
        if ($this->legacyObjectType !== null) {
            return WCF::getLanguage()->get(\sprintf(
                'wcf.acp.rebuildData.%s.description',
                $this->legacyObjectType->objectType
            ));
        }

        return WCF::getLanguage()->get(\sprintf(
            'wcf.acp.rebuildData.%s.description',
            \str_replace('\\', '_', $this->classname)
        ));
    }
}

<?php

namespace wcf\system\worker;

use wcf\data\object\type\ObjectType;
use wcf\system\WCF;

/**
 * Represents a worker that is registered with the RebuildWorkerCollecting event.
 *
 * @author Tim Duesterhus
 * @copyright 2001-2022 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Worker
 * @since 6.0
 */
final class RegisteredWorker
{
    public function __construct(
        public readonly string $classname,
        private readonly ?ObjectType $legacyObjectType = null,
    ) {
    }

    public function getName(): string
    {
        return WCF::getLanguage()->get(\sprintf(
            'wcf.acp.rebuildData.%s',
            $this->getIdentifier(),
        ));
    }

    public function getDescription(): string
    {
        return WCF::getLanguage()->get(\sprintf(
            'wcf.acp.rebuildData.%s.description',
            $this->getIdentifier(),
        ));
    }

    private function getIdentifier(): string
    {
        if ($this->legacyObjectType !== null) {
             return $this->legacyObjectType->objectType;
        }

        return \str_replace('\\', '_', $this->classname);
    }
}

Reduce logic duplication in RegisteredWorker


<?php

if (Site::getConfig('handle') == 'skeleton-v1') {
    Git::$repositories['emergence-skeleton-v1'] = [
        'remote' => 'https://github.com/JarvusInnovations/emergence-skeleton.git',
        'originBranch' => 'master',
        'workingBranch' => 'master',
        'trees' => [
            'dwoo-plugins',
            'event-handlers',
            'ext-library',
            'html-templates',
            'js-library',
            'php-classes',
            'php-config',
            'php-migrations',
            'phpunit-tests',
            'sencha-build',
            'sencha-workspace',
            'site-root',
            'site-tasks'
        ]
    ];
}

<?php

if (Site::getConfig('handle') == 'skeleton-v1') {
    Git::$repositories['emergence-skeleton-v1'] = [
        'remote' => 'https://github.com/JarvusInnovations/emergence-skeleton.git',
        'originBranch' => 'master',
        'workingBranch' => 'master',
        'trees' => [
            'dwoo-plugins',
            'event-handlers',
            'ext-library',
            'html-templates',
            'js-library',
            'php-classes',
            'php-config',
            'php-migrations',
            'phpunit-tests',
            'sencha-build',
            'sencha-workspace',
            'site-root',
            'site-tasks'
        ]
    ];

    Git::$repositories['symfony-yaml'] = [
        'remote' => 'https://github.com/symfony/Yaml.git'
        ,'originBranch' => 'master'
        ,'workingBranch' => 'master'
        ,'trees' => [
            'php-classes/Symfony/Component/Yaml' => [
                'path' => '.'
                ,'exclude' => [
                    '#\\.gitignore$#'
                    ,'#^/Tests#'
                    ,'#\\.md$#'
                    ,'#composer\\.json#'
                    ,'#phpunit\\.xml\\.dist#'
                ]
            ]
        ]
    ];
}

Add git config for symfony-yaml

Add git config for symfony-yaml


Switch workbench option to package

Switch workbench option to package


<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Application Debug Mode
    |--------------------------------------------------------------------------
    |
    | When your application is in debug mode, detailed error messages with
    | stack traces will be shown on every error that occurs within your
    | application. If disabled, a simple generic error page is shown.
    |
    */

    'debug' => true,

    /*
    |--------------------------------------------------------------------------
    | Application URL
    |--------------------------------------------------------------------------
    |
    | This URL is used by the console to properly generate URLs when using
    | the Artisan command line tool. You should set this to the root of
    | your application so that it is used when running Artisan tasks.
    |
    */

    'url' => 'http://staging.yourserver.com',

    /*
    |--------------------------------------------------------------------------
    | Encryption Key
    |--------------------------------------------------------------------------
    |
    | This key is used by the Illuminate encrypter service and should be set
    | to a random, 32 character string, otherwise these encrypted strings
    | will not be safe. Please do this before deploying an application!
    |
    | Run a php artisan key:generate --env=staging to create a random one
    */

    'key' => 'Change_this_key_or_snipe_will_get_ya',

);

<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Application Debug Mode
    |--------------------------------------------------------------------------
    |
    | When your application is in debug mode, detailed error messages with
    | stack traces will be shown on every error that occurs within your
    | application. If disabled, a simple generic error page is shown.
    |
    */

    'debug' => false,

    /*
    |--------------------------------------------------------------------------
    | Application URL
    |--------------------------------------------------------------------------
    |
    | This URL is used by the console to properly generate URLs when using
    | the Artisan command line tool. You should set this to the root of
    | your application so that it is used when running Artisan tasks.
    |
    */

    'url' => 'http://production.yourserver.com',

    /*
    |--------------------------------------------------------------------------
    | Encryption Key
    |--------------------------------------------------------------------------
    |
    | This key is used by the Illuminate encrypter service and should be set
    | to a random, 32 character string, otherwise these encrypted strings
    | will not be safe. Please do this before deploying an application!
    |
    | Run a php artisan key:generate --env=staging to create a random one
    */

    'key' => 'Change_this_key_or_snipe_will_get_ya',

);

Set default debug to false for production config


<?php

class Theme extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'themes';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('user_id');

}

<?php

class Theme extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'themes';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('user_id');

    /**
     * The validation rules for store
     *
     * @var array
     */
    protected $rules = array(
        ['title' => 'required|min:1'],
        ['template' => 'required'],
        ['parent_theme_key' => 'min:40'],
    );

}

Add validation rules for themes

Add validation rules for themes


<?php

namespace TFox\MpdfPortBundle\Service;

use Mpdf\Mpdf;
use Mpdf\Output\Destination;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PDFService {

    /**
     * @var string
     */
    private $cacheDir;

    /**
     * MpdfService constructor.
     * @param string $cacheDir
     */
    public function __construct(string $cacheDir)
    {
        $this->cacheDir = $cacheDir;
    }

    /**
     * @param string $html
     * @param array $options
     * @return string
     * @throws \Mpdf\MpdfException
     */
    public function generatePdf($html, $options = array())
    {
        $resolver = new OptionsResolver();
        $resolver->setDefaults(array(
            'mode' => 'utf-8',
            'format' => 'A4',
            'tempDir' => $this->cacheDir
        ));
        $options = $resolver->resolve($options);
        $mpdf = new Mpdf($options);
        $mpdf->WriteHTML($html);

        return $mpdf->Output(null, Destination::STRING_RETURN);
    }
}

<?php

namespace TFox\MpdfPortBundle\Service;

use Mpdf\Mpdf;
use Mpdf\Output\Destination;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PDFService {

    /**
     * @var string
     */
    private $cacheDir;

    /**
     * MpdfService constructor.
     * @param string $cacheDir
     */
    public function __construct(string $cacheDir)
    {
        $this->cacheDir = $cacheDir;
    }

    /**
     * @param string $html
     * @param array $options
     * @return string
     * @throws \Mpdf\MpdfException
     */
    public function generatePdf($html, $options = array())
    {
        $resolver = new OptionsResolver();
        $resolver
            ->setDefined(array_keys($options))
            ->setDefaults(array(
                'mode' => 'utf-8',
                'format' => 'A4',
                'tempDir' => $this->cacheDir
            ));
        $options = $resolver->resolve($options);
        $mpdf = new Mpdf($options);
        $mpdf->WriteHTML($html);

        return $mpdf->Output(null, Destination::STRING_RETURN);
    }
}

Allow extra options for mpdf

Allow extra options for mpdf


<?php
/**
 * A single 'item' in the Spelling Dictionary Admin Links page
 */
class SDItem {
	public $link;

	static function showPage( $page_title, $desc = null, $query = [] ) {
		$item = new SDItem();
		$item->link = Linker::link( $page_title, $desc );
		return $item;
	}

	static function customSpecialPage( $page_title ) {
		$item = new SDItem();
		$page = SpecialPageFactory::getPage( $page_title );
		$item->link = Linker::link( $page->getPageTitle(), $page->getDescription() );
		return $item;
	}

}

<?php

use MediaWiki\MediaWikiServices;

/**
 * A single 'item' in the Spelling Dictionary Admin Links page
 */
class SDItem {
	public $link;

	static function showPage( $page_title, $desc = null, $query = [] ) {
		$item = new SDItem();
		$item->link = Linker::link( $page_title, $desc );
		return $item;
	}

	static function customSpecialPage( $page_title ) {
		$item = new SDItem();

		if ( class_exists( 'MediaWiki\Special\SpecialPageFactory' ) ) {
			// MW 1.32+
			$page = MediaWikiServices::getInstance()
				->getSpecialPageFactory()
				->getPage( $page_title );
		} else {
			$page = SpecialPageFactory::getPage( $page_title );
		}

		$item->link = Linker::link( $page->getPageTitle(), $page->getDescription() );
		return $item;
	}

}

Replace uses of old deprecated SpecialPageFactory in MW 1.32+

Bug: T246142
Change-Id: Iefe22e0143b9651ad3f3d0999a1ba3b8a1564de3


<?php

namespace Jhg\DoctrinePagination\ORM;

trait PaginatedRepositoryFindByTrait
{
    /**
     * {@inheritdoc}
     *
     * @deprecated this method will be removed in this repository
     */
    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        if ($offset !== null && $limit !== null && $limit > 0) {
            $page = ceil($offset/$limit) + 1;
        } else {
            $page = 1;
        }

        return $this->findPageBy($page, $limit !== null && $limit > 0 ? $limit : -1, $criteria, $orderBy);
    }
}

<?php

namespace Jhg\DoctrinePagination\ORM;

trait PaginatedRepositoryFindByTrait
{
    /**
     * {@inheritdoc}
     */
    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        if ($offset !== null && $limit !== null && $limit > 0) {
            $page = ceil($offset/$limit) + 1;
        } else {
            $page = 1;
        }

        return $this->findPageBy($page, $limit !== null && $limit > 0 ? $limit : -1, $criteria, $orderBy);
    }
}

Remove findBy deprecation in trait

Remove findBy deprecation in trait


<?php
$code = file_get_contents($file);
$obj = null;

$tempns = uniqid('phoxy\fork_');

$header = <<<END
  namespace $tempns;

  use \phoxy as phoxy;
END;

$code = str_replace('<?php', $header, $code);
$code = preg_replace('/ api\s*\n/', '\\api', $code);

eval($code);

$classname = "\\".$tempns."\\$module";

<?php
$code = file_get_contents($file);
$obj = null;

if ($classname != 'phoxy')
{
  $tempns = uniqid('phoxy\fork_');

  $header = <<<END
  namespace $tempns;

  use \phoxy as phoxy;
END;

  $code = str_replace('<?php', $header, $code);
  $code = preg_replace('/ api\s*\n/', ' \\api', $code);

  eval($code);

  $classname = "\\".$tempns."\\$module";
}

Fix crossinclude conflict for phoxy class