<title>dcs-get package listing</title>

Package Listing

This is an up to date list of all packages available for dcs-get, along with their dependencies.

Packages

<?php

error_reporting(0);
//error_reporting(E_ALL);

define('BASE_URL', 'http://backus.uwcs.co.uk/dcs-get/');

$packages = json_decode(file_get_contents(BASE_URL.'packages.json'));

$sorted_packages = array();
foreach ($packages as $package => $data) {
	$sorted_packages[$package] = $data;
}
ksort($sorted_packages);

foreach($sorted_packages as $package => $data) {
	echo '
';
	echo '
';
	echo "$package - ";
	if (isset($data->description)) {
		echo "$data->description - ";
	}
	echo 'Version: '.implode(', ', $data->version).'
';
	if (isset($data->dependencies)) {
		echo '
';
		foreach ($data->dependencies as $dep => $stuff) {
			echo "
$stuff[0] - $stuff[1]
";
		}
		echo '
';
	}
	echo '
';
	echo '
';
}
?>

<?php

<title>dcs-get package listing</title>

Package Listing

This is an up to date list of all packages available for dcs-get, along with their dependencies.

Packages

<?php

//error_reporting(0);
error_reporting(E_ALL);

define('BASE_URL', 'http://backus.uwcs.co.uk/dcs-get/');

$packages = json_decode(file_get_contents(BASE_URL.'packages.json'), true);
ksort($packages);

foreach($packages as $package => $data) {
	echo '
';
	echo '
';
	echo htmlspecialchars($package).' - ';
	if (isset($data['description'])) {
		echo htmlspecialchars($data['description']).' - ';
	}
	echo 'Version: '.htmlspecialchars(implode(', ', $data['version'])).'
';
	if (isset($data['dependencies'])) {
		echo '
';
		foreach ($data['dependencies'] as $dep => $details) {
			echo '
'.htmlspecialchars($details[0]).' - '.htmlspecialchars($details[1]).'
';
		}
		echo '
';
	}
	echo '
';
	echo '
';
}
?>

Improve how variables are output. Remove useless php tag. Switch to associative arrays for decoded json.


<?php defined('SYSPATH') or die('No direct script access.');

return array(
	/**
	 * Gzip can dramatically reduce the size of the sitemap. We recommend you use
	 * this option with more than 1,000 entries. Gzipped entries are computed by
	 * appending the .gz extension to the url (sitemap.xml.gz)
	 */
	'gzip' => array
	(
		'enabled' => TRUE,
		/*
		 * From 1-9
		 */
		'level' => 9
	),
	/**
	 * Array of URLs to ping. This lets the provider know you have updated your
	 * sitemap. sprintf string.
	 */
	'ping' => array
	(
		'Google'	 => 'http://www.google.com/webmasters/tools/ping?sitemap=%s',
		'Yahoo'		 => 'http://search.yahooapis.com/SiteExplorerService/V1/ping?sitemap=%s',
		'Ask'			 => 'http://submissions.ask.com/ping?sitemap=%s',
		'Bing'		 => 'http://www.bing.com/webmaster/ping.aspx?siteMap=%s',
		'MoreOver' => 'http://api.moreover.com/ping?u=%s'
	)
);

<?php defined('SYSPATH') or die('No direct script access.');

return array(
	/**
	 * Gzip can dramatically reduce the size of the sitemap. We recommend you use
	 * this option with more than 1,000 entries. Gzipped entries are computed by
	 * appending the .gz extension to the url (sitemap.xml.gz)
	 */
	'gzip' => array
	(
		'enabled' => TRUE,
		/*
		 * From 1-9
		 */
		'level' => 9
	),
	/**
	 * Array of URLs to ping. This lets the provider know you have updated your
	 * sitemap. sprintf string.
	 */
	'ping' => array
	(
		'Google' => 'http://www.google.com/webmasters/tools/ping?sitemap=%s',
		'Yahoo'  => 'http://search.yahooapis.com/SiteExplorerService/V1/ping?sitemap=%s',
		'Ask'    => 'http://submissions.ask.com/ping?sitemap=%s',
		'Bing'   => 'http://www.bing.com/webmaster/ping.aspx?siteMap=%s'
	)
);

Remove moreover.com as the website no longer exists.


<?php

namespace App\Console\Commands\Import;

use App\Models\Collections\Image;

class ImportImages extends AbstractImportCommand
{

    protected $signature = 'import:images';

    protected $description = "Import all image data from data-service-images";

    public function handle()
    {

        $this->api = env('IMAGES_DATA_SERVICE_URL');

        $this->import( null, Image::class, 'images' );

    }

    // TODO: Optionally, use an inbound transformer here?
    protected function save( $datum, $model, $transformer )
    {

        $this->info("Importing #{$datum->id}: {$datum->title}");

        // TODO: When we make inbound transformers, provide a toggle between find() & findOrNew()
        $resource = $model::find( $datum->id );

        // For this one, we should ignore entities that don't exist here
        if( !$resource )
        {
            return;
        }

        // TODO: Move this to an inbound transformer
        $metadata = $image->metadata ?? (object) [];

        $metadata->lqip = $datum->lqip;
        $metadata->color = $datum->color;
        $metadata->width = $datum->width;
        $metadata->height = $datum->height;
        $metadata->colorfulness = round((float) $datum->colorfulness, 4);

        $resource->metadata = $metadata;

        $resource->save();

        return $resource;

    }

}

<?php

namespace App\Console\Commands\Import;

use App\Models\Collections\Image;

class ImportImages extends AbstractImportCommand
{

    protected $signature = 'import:images
                            {page? : Page to begin importing from}';

    protected $description = "Import all image data from data-service-images";

    public function handle()
    {

        $this->api = env('IMAGES_DATA_SERVICE_URL');

        $this->import( null, Image::class, 'images', $this->argument('page') ?: 1 );

    }

    // TODO: Optionally, use an inbound transformer here?
    protected function save( $datum, $model, $transformer )
    {

        $this->info("Importing #{$datum->id}: {$datum->title}");

        // TODO: When we make inbound transformers, provide a toggle between find() & findOrNew()
        $resource = $model::find( $datum->id );

        // For this one, we should ignore entities that don't exist here
        if( !$resource )
        {
            return;
        }

        // TODO: Move this to an inbound transformer
        $metadata = $image->metadata ?? (object) [];

        $metadata->lqip = $datum->lqip;
        $metadata->color = $datum->color;
        $metadata->width = $datum->width;
        $metadata->height = $datum->height;
        $metadata->colorfulness = round((float) $datum->colorfulness, 4);

        $resource->metadata = $metadata;

        $resource->save();

        return $resource;

    }

}

Add page argument to `import:images`

Add page argument to `import:images`


<?php

return [
    'adminEmail' => 'kipkoechmathew@gmail.com',
    'supportEmail' => 'kipkoechmathew@gmail.com',
    'user.passwordResetTokenExpire' => 3600
];

<?php

return [
    'adminEmail' => 'admin@intern.jkuat.dev',
    'supportEmail' => 'admin@intern.jkuat.dev',
    'user.passwordResetTokenExpire' => 3600
];

Change admin email to one matching the domain


<?php

    namespace papalapa\yiistart\modules\i18n\models;

    use papalapa\yiistart\modules\settings\models\Settings;
    use yii\base\InvalidParamException;

    /**
     * Class i18n
     * @package papalapa\yiistart\modules\i18n\models
     */
    class i18n
    {
        /**
         * @return array|mixed
         */
        public static function locales()
        {
            if (false === $locales = Settings::paramOf('i18n.locales.available', false)) {
                throw new InvalidParamException("Need to set available locales in 'params.php' file: ['ru','en'] or ['ru' => 'Ru', 'en' => 'En']");
            }

            if (array_values($locales) !== $locales) {
                $locales = array_keys($locales);
            }

            return $locales;
        }
    }

<?php

    namespace papalapa\yiistart\modules\i18n\models;

    use yii\base\InvalidConfigException;
    use yii\base\InvalidParamException;
    use yii\helpers\ArrayHelper;

    /**
     * Class i18n
     * @package papalapa\yiistart\modules\i18n\models
     */
    class i18n
    {
        /**
         * @return array|mixed
         * @throws InvalidConfigException|InvalidParamException
         */
        public static function locales()
        {
            if (false === $locales = ArrayHelper::getValue(\Yii::$app->params, 'i18n.locales.available', false)) {
                throw new InvalidParamException("Need to set available locales in 'params.php' file: ['ru','en'] or ['ru' => 'Ru', 'en' => 'En']");
            }

            if (array_values($locales) !== $locales) {
                $locales = array_keys($locales);
            }

            if (!in_array(\Yii::$app->language, $locales)) {
                throw new InvalidConfigException(sprintf("Only '%s' languages allowed in 'param.php' of your app, not '%s'.", implode(', ', $locales), \Yii::$app->language));
            }

            return $locales;
        }
    }

Check app language for exist in available locales


<?php

declare(strict_types = 1);

include('../src/common.php');

use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use unreal4u\MonologHandler;
use unreal4u\TelegramAPI\TgLog;
use unreal4u\TelegramBots\RequestHandler;

$logger = new Logger('TGBot');
$streamHandler = new RotatingFileHandler('telegramApiLogs/main.log', 365, Logger::DEBUG);
$monologTgLogger = new MonologHandler(new TgLog(MONOLOG_BOT), MONOLOG_CHATID, Logger::WARNING);
$logger->pushHandler($streamHandler);
$logger->pushHandler($monologTgLogger);

$trimmedRequestUri = trim($_SERVER['DOCUMENT_URI'], '/');

new RequestHandler($logger, $trimmedRequestUri);

<?php

declare(strict_types = 1);

include('../src/common.php');

use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use unreal4u\MonologHandler;
use unreal4u\TelegramAPI\TgLog;
use unreal4u\TelegramBots\RequestHandler;

$logger = new Logger('TGBot');
$streamHandler = new RotatingFileHandler('telegramApiLogs/main.log', 365, Logger::DEBUG);
$monologTgLogger = new MonologHandler(new TgLog(MONOLOG_BOT), MONOLOG_CHATID, Logger::ERROR);
$logger->pushHandler($streamHandler);
$logger->pushHandler($monologTgLogger);

$trimmedRequestUri = trim($_SERVER['DOCUMENT_URI'], '/');

new RequestHandler($logger, $trimmedRequestUri);

Set minimal notification to ERROR instead of WARNING


<?php
/**
 * Created by PhpStorm.
 * Date: 7/24/17
 */

namespace OK\Credentials\Environment;

class ProductionEnvironment extends Environment
{
    /**
     * Environment path part
     * @return string
     */
    function getBaseUrl() {
        return "secure.okit.com";
    }
}

<?php
/**
 * Created by PhpStorm.
 * Date: 7/24/17
 */

namespace OK\Credentials\Environment;

class ProductionEnvironment extends Environment
{
    /**
     * Environment path part
     * @return string
     */
    function getBaseUrl() {
        return "works-api.okit.com";
    }
}

Update production to new environment base url


<?php

namespace Yajra\DataTables\Facades;

use Illuminate\Support\Facades\Facade;

/**
 * @mixin \Yajra\DataTables\DataTables
 * @method eloquent($builder)
 * @method queryBuilder($builder)
 * @method collection($collection)
 */
class DataTables extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'datatables';
    }
}

<?php

namespace Yajra\DataTables\Facades;

use Illuminate\Support\Facades\Facade;
use Yajra\DataTables\CollectionDataTable;
use Yajra\DataTables\EloquentDatatable;
use Yajra\DataTables\QueryDataTable;

/**
 * @mixin \Yajra\DataTables\DataTables
 * @method EloquentDatatable eloquent($builder)
 * @method QueryDataTable queryBuilder($builder)
 * @method CollectionDataTable collection($collection)
 */
class DataTables extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'datatables';
    }
}

Add return type on doc methods.

Add return type on doc methods.


<?php

namespace Lily\Util;

class Response
{
    public static function response(
        $status,
        array $headers = array(),
        $body = '')
    {
        return compact('status', 'headers', 'body');
    }

    public static function redirect($uri, $status = 301)
    {
        return static::response($status, array('Location' => $uri));
    }

    public static function notFound()
    {
        return static::response(404);
    }
}

<?php

namespace Lily\Util;

class Response
{
    public static function response(
        $status,
        array $headers = array(),
        $body = '')
    {
        return compact('status', 'headers', 'body');
    }

    public static function redirect($uri, $status = 301)
    {
        return static::response($status, array('Location' => $uri));
    }

    public static function notFound(array $headers = array(), $body = NULL)
    {
        if ($body === NULL) {
            $body = 'Not found.';
        }

        return static::response(404, $headers, $body);
    }
}

Allow ::notFound() to take custom headers and body


<?php

/*
 * This file is part of the eluceo/iCal package.
 *
 * (c) Markus Poerschke <markus@eluceo.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Eluceo\iCal\Util;

class ComponentUtil
{
    /**
     * Folds a single line.
     *
     * According to RFC 5545, all lines longer than 75 characters should be folded
     *
     * @see https://tools.ietf.org/html/rfc5545#section-5
     * @see https://tools.ietf.org/html/rfc5545#section-3.1
     *
     * @param $string
     *
     * @return array
     */
    public static function fold($string)
    {
        $lines = [];
        while (strlen($string) > 0) {
            if (strlen($string) > 75) {
                $lines[] = mb_strcut($string, 0, 75, 'utf-8') . "\r\n";
                $str = ' ' . mb_strcut($string, 75, strlen($string), 'utf-8');
            } else {
                $lines[] = $string;
                $str = '';
                break;
            }
        }
        return $lines;
    }
}

<?php

/*
 * This file is part of the eluceo/iCal package.
 *
 * (c) Markus Poerschke <markus@eluceo.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Eluceo\iCal\Util;

class ComponentUtil
{
    /**
     * Folds a single line.
     *
     * According to RFC 5545, all lines longer than 75 characters should be folded
     *
     * @see https://tools.ietf.org/html/rfc5545#section-5
     * @see https://tools.ietf.org/html/rfc5545#section-3.1
     *
     * @param $string
     *
     * @return array
     */
    public static function fold($string)
    {
        $lines = [];
        while (strlen($string) > 0) {
            if (strlen($string) > 75) {
                $lines[] = mb_strcut($string, 0, 75, 'utf-8') . "\r\n";
                $string = ' ' . mb_strcut($string, 75, strlen($string), 'utf-8');
            } else {
                $lines[] = $string;
                $string = '';
                break;
            }
        }
        return $lines;
    }
}

Optimize Performance for long lines (use mb_strcut() instead of pred_split())


<?php defined('MONSTRA_ACCESS') or die('No direct script access.');

/**
 * Report All Errors
 *
 * By setting error reporting to -1, we essentially force PHP to report
 * every error, and this is guranteed to show every error on future
 * releases of PHP. This allows everything to be fixed early!
 */
error_reporting(-1);

/**
 *  Monstra requires PHP 5.2.3 or greater
 */
if (version_compare(PHP_VERSION, "5.2.3", "<")) {
    exit("Monstra requires PHP 5.2.3 or greater.");
}

/**
 *  Include Monstra Engine
 */
include ROOT . DS .'engine'. DS .'Monstra.php';

/**
 * Set Monstra Environment
 *
 * Monstra has four predefined environments:
 *   Monstra::DEVELOPMENT - The development environment.
 *   Monstra::TESTING     - The test environment.
 *   Monstra::STAGING     - The staging environment.
 *   Monstra::PRODUCTION  - The production environment.
 */
Monstra::$environment = Monstra::PRODUCTION;

/**
 * Initialize Monstra
 */
Monstra::init();

<?php defined('MONSTRA_ACCESS') or die('No direct script access.');

/**
 *  Monstra requires PHP 5.2.3 or greater
 */
if (version_compare(PHP_VERSION, "5.2.3", "<")) {
    exit("Monstra requires PHP 5.2.3 or greater.");
}

/**
 *  Include Monstra Engine
 */
include ROOT . DS .'engine'. DS .'Monstra.php';

/**
 * Set Monstra Environment
 *
 * Monstra has four predefined environments:
 *   Monstra::DEVELOPMENT - The development environment.
 *   Monstra::TESTING     - The test environment.
 *   Monstra::STAGING     - The staging environment.
 *   Monstra::PRODUCTION  - The production environment.
 */
Monstra::$environment = Monstra::PRODUCTION;

/**
 * Report Errors
 */
if (Monstra::$environment == Monstra::PRODUCTION) {
    error_reporting(0);
} else {
    error_reporting(-1);
}

/**
 * Initialize Monstra
 */
Monstra::init();

Remove turn off Error Handler for Production environment


<?php
declare(strict_types=1);

namespace Josegonzalez\Upload\File\Path;

use Cake\Datasource\EntityInterface;
use Cake\ORM\Table;
use Psr\Http\Message\UploadedFileInterface;

interface ProcessorInterface
{
    /**
     * Constructor
     *
     * @param \Cake\ORM\Table  $table the instance managing the entity
     * @param \Cake\Datasource\EntityInterface $entity the entity to construct a path for.
     * @param \Psr\Http\Message\UploadedFileInterface     $data the data being submitted for a save or filename stored in db
     * @param string           $field the field for which data will be saved
     * @param array            $settings the settings for the current field
     */
    public function __construct(Table $table, EntityInterface $entity, UploadedFileInterface $data, string $field, array $settings);

    /**
     * Returns the basepath for the current field/data combination
     *
     * @return string
     */
    public function basepath(): string;

    /**
     * Returns the filename for the current field/data combination
     *
     * @return string
     */
    public function filename(): string;
}

<?php
declare(strict_types=1);

namespace Josegonzalez\Upload\File\Path;

use Cake\Datasource\EntityInterface;
use Cake\ORM\Table;

interface ProcessorInterface
{
    /**
     * Constructor
     *
     * @param \Cake\ORM\Table  $table the instance managing the entity
     * @param \Cake\Datasource\EntityInterface $entity the entity to construct a path for.
     * @param \Psr\Http\Message\UploadedFileInterface|string     $data the data being submitted for a save or filename stored in db
     * @param string           $field the field for which data will be saved
     * @param array            $settings the settings for the current field
     */
    public function __construct(Table $table, EntityInterface $entity, $data, string $field, array $settings);

    /**
     * Returns the basepath for the current field/data combination
     *
     * @return string
     */
    public function basepath(): string;

    /**
     * Returns the filename for the current field/data combination
     *
     * @return string
     */
    public function filename(): string;
}

Fix one more type hint

Fix one more type hint


<?php

namespace App\Notifications;

use App\Mail\NewReplyEmail;
use App\Models\Reply;
use App\Models\Subscription;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;

final class NewReplyNotification extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * @var \App\Models\Reply
     */
    public $reply;

    /**
     * @var \App\Models\Subscription
     */
    public $subscription;

    public function __construct(Reply $reply, Subscription $subscription)
    {
        $this->reply = $reply;
        $this->subscription = $subscription;
    }

    public function via(User $user)
    {
        return ['mail'];
    }

    public function toMail(User $user)
    {
        return (new NewReplyEmail($this->reply, $this->subscription))
            ->to($user->emailAddress(), $user->name());
    }

    public function toArray(User $user)
    {
        return [
            //
        ];
    }
}

<?php

namespace App\Notifications;

use App\Mail\NewReplyEmail;
use App\Models\Reply;
use App\Models\Subscription;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;

final class NewReplyNotification extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * @var \App\Models\Reply
     */
    public $reply;

    /**
     * @var \App\Models\Subscription
     */
    public $subscription;

    public function __construct(Reply $reply, Subscription $subscription)
    {
        $this->reply = $reply;
        $this->subscription = $subscription;
    }

    public function via(User $user)
    {
        return ['mail', 'database'];
    }

    public function toMail(User $user)
    {
        return (new NewReplyEmail($this->reply, $this->subscription))
            ->to($user->emailAddress(), $user->name());
    }

    public function toArray(User $user)
    {
        return [
            'type' => 'reply',
            'author' => $this->reply->author(),
            'reply' => $this->reply,
            'thread' => $this->reply->replyAble(),
        ];
    }
}

Add database notification for new replies


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Controller extends CI_Controller {}

class Admin extends CI_Controller
{
    protected $roles = array('su', 'adm', 'edt', 'ctr', 'lnr');

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

        $this->check();
    }

    public function check()
    {
        if (!sentinel()->check()) {
            redirect('login', 'refresh');
        }

        if (!sentinel()->inRole($this->roles)) {
            set_message_error('Anda tidak mempunyai hak akses.');

            redirect('login', 'refresh');
        }
    }

    public function checkRole()
    {

    }
}

/* End of file MY_Controller.php */
/* Location: ./application/core/MY_Controller.php */

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Controller extends CI_Controller {}

class Admin extends CI_Controller
{
    protected $roles = array('su', 'adm', 'edt', 'ctr', 'lnr', 'pus');

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

        $this->check();
        $this->generateNavigator();
    }

    public function check()
    {
        if (!sentinel()->check()) {
            redirect('login', 'refresh');
        }

        if (!sentinel()->inRole($this->roles)) {
            set_message_error('Anda tidak mempunyai hak akses.');

            redirect('login', 'refresh');
        }
    }

    protected function generateNavigator()
    {
        $role       = sentinel()->getUser()->roles->pluck('slug')->toArray();
        $menus      = $this->getMenusByRole($role);
        $template   = $this->load->view('template/menus', compact('menus'), TRUE);

        $this->template->set('navigator', $template);

        return $template;
    }

    protected function getMenusByRole($role = 'su')
    {
        $menus      = $this->getMenuCollect();

        $filtered   = $menus->filter(function ($menu) use ($role) {
            if (array_key_exists('roles', $menu)) {
                if (in_array('all', $menu['roles']))
                    return true;

                return !array_diff($role, $menu['roles']);
            } else {
                return false;
            }
        });

        return $filtered;
    }

    protected function getMenuCollect()
    {
        $this->config->load('menus');

        $menus = $this->config->item('menus');

        return collect($menus);
    }
}

/* End of file MY_Controller.php */
/* Location: ./application/core/MY_Controller.php */

Add generate menus each role user

Add generate menus each role user


<?php

namespace App\Http\Controllers;

use App\Http\Requests\LoginRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $lockoutTime = 60 * 60 * 3;
    protected $maxLoginAttempts = 5;

    public function index()
    {
        // if the user is already logged in then redirect to index
        if (\Auth::check())
            return \Redirect::action('MangaController@index');

        return view('login');
    }

    public function login(LoginRequest $request)
    {
        if (\Auth::check())
            return \Redirect::action('MangaController@index');

        if ($this->hasTooManyLoginAttempts($request)) {

            $this->fireLockoutEvent($request);

            return \Redirect::action('LoginController@index')
                            ->withErrors(['lockout' => 'You have been locked out. Try again in 3 hours.']);
        }

        $username = \Input::get('username');
        $password = \Input::get('password');

        if (\Auth::attempt(['name' => $username, 'password' => $password]) == false) {

            $this->incrementLoginAttempts($request);

            return \Redirect::action('LoginController@index')
                            ->withErrors(['login' => 'You have given invalid credentials. Please try again.']);
        }

        $this->clearLoginAttempts($request);

        return \Redirect::intended();
    }

    public function logout() {
        \Auth::logout();

        return \Redirect::action('LoginController@login');
    }
}

<?php

namespace App\Http\Controllers;

use App\Http\Requests\LoginRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $lockoutTime = 60 * 60 * 3;
    protected $maxLoginAttempts = 5;

    public function index()
    {
        // if the user is already logged in then redirect to index
        if (\Auth::check())
            return \Redirect::action('HomeController@index');

        return view('login');
    }

    public function login(LoginRequest $request)
    {
        if (\Auth::check())
            return \Redirect::action('HomeController@index');

        if ($this->hasTooManyLoginAttempts($request)) {

            $this->fireLockoutEvent($request);

            return \Redirect::action('LoginController@index')
                            ->withErrors(['lockout' => 'You have been locked out. Try again in 3 hours.']);
        }

        $username = \Input::get('username');
        $password = \Input::get('password');

        if (\Auth::attempt(['name' => $username, 'password' => $password]) == false) {

            $this->incrementLoginAttempts($request);

            return \Redirect::action('LoginController@index')
                            ->withErrors(['login' => 'You have given invalid credentials. Please try again.']);
        }

        $this->clearLoginAttempts($request);

        return \Redirect::intended();
    }

    public function logout() {
        \Auth::logout();

        return \Redirect::action('LoginController@login');
    }
}

Fix reference to old controller name

Fix reference to old controller name


<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace Imbo\Image\OutputConverter;

/**
 * Basic output converter that supports gif/png/jpg.
 *
 * @author Mats Lindh <mats@lindh.no>
 * @package Image\OutputConverters
 */
class Basic implements OutputConverterInterface {
    public function getSupportedFormatsWithCallbacks() {
        return [
            [
                'mime' => 'image/png',
                'extension' => 'png',
                'callback' => [$this, 'convert'],
            ],
            [
                'mime' => 'image/jpeg',
                'extension' => ['jpeg', 'jpg'],
                'callback' => [$this, 'convert'],
            ],
            [
                'mime' => 'image/gif',
                'extension' => 'gif',
                'callback' => [$this, 'convert'],
            ],
        ];
    }

    public function convert($imagick, $image, $extension, $mime = null) {
        try {
            $imagick->setImageFormat($extension);
        } catch (ImagickException $e) {
            throw new OutputConversionException($e->getMessage(), 400, $e);
        }
    }
}

<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace Imbo\Image\OutputConverter;

/**
 * Basic output converter that supports gif/png/jpg.
 *
 * @author Mats Lindh <mats@lindh.no>
 * @package Image\OutputConverters
 */
class Basic implements OutputConverterInterface {
    public function getSupportedFormatsWithCallbacks() {
        return [
            [
                'mime' => 'image/png',
                'extension' => 'png',
                'callback' => [$this, 'convert'],
            ],
            [
                'mime' => 'image/jpeg',
                'extension' => ['jpg', 'jpeg'],
                'callback' => [$this, 'convert'],
            ],
            [
                'mime' => 'image/gif',
                'extension' => 'gif',
                'callback' => [$this, 'convert'],
            ],
        ];
    }

    public function convert($imagick, $image, $extension, $mime = null) {
        try {
            $imagick->setImageFormat($extension);
        } catch (ImagickException $e) {
            throw new OutputConversionException($e->getMessage(), 400, $e);
        }
    }
}

Change 'jpg' to be the default extension type for 'image/jpeg'


<?php

namespace JPGC;

class PluginsRepository extends \PWE\Modules\PWEModule implements \PWE\Modules\Outputable
{
    public function process()
    {
        if ($_POST['stats'] && $_POST['stats'] != 'null') {
            \PWE\Core\PWELogger::warn("Status: %s", $_POST['stats']);
        }
        $node = $this->PWE->getNode();
        $configsDir = $node['!a']['configs'];
        if (!$configsDir || !is_dir($configsDir)) {
            throw new \PWE\Exceptions\HTTP5xxException("Configs dir don't exist: " . realpath($configsDir));
        }

        $plugins = [];
        foreach (scandir($configsDir) as $fname) {
            if ($fname[0] == '.') {
                continue;
            }
            $set = json_decode(file_get_contents($configsDir . '/' . $fname), true);
            $plugins = array_merge($plugins, $set);
        }

        $this->PWE->sendHTTPHeader("Content-Type: application/json");
        throw new \PWE\Exceptions\HTTP2xxException(json_encode($plugins));
    }
}

<?php

namespace JPGC;

class PluginsRepository extends \PWE\Modules\PWEModule implements \PWE\Modules\Outputable
{
    public function process()
    {
        if ($_POST['stats'] && $_POST['stats'] != 'null') {
            \PWE\Core\PWELogger::warn("Status: %s", $_POST['stats']);
        }
        $node = $this->PWE->getNode();
        $configsDir = $node['!a']['configs'];
        if (!$configsDir || !is_dir($configsDir)) {
            throw new \PWE\Exceptions\HTTP5xxException("Configs dir don't exist: " . realpath($configsDir));
        }

        $plugins = [];
        foreach (scandir($configsDir) as $fname) {
            if ($fname[0] == '.') {
                continue;
            }
            $set = json_decode(file_get_contents($configsDir . '/' . $fname), true);
            $plugins = array_merge($plugins, $set);
        }

        if ($_REQUEST['id']) {
            foreach ($plugins as $plugin) {
                if ($plugin['id'] == $_REQUEST['id']) {
                    $plugins = array($plugin);
                    break;
                }
            }
        }

        $this->PWE->sendHTTPHeader("Content-Type: application/json");
        throw new \PWE\Exceptions\HTTP2xxException(json_encode($plugins));
    }
}

Allow getting plugin by ID

Allow getting plugin by ID


<?php

namespace NUSWhispers\Providers;

use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'NUSWhispers\Events\ConfessionWasCreated' => [
            'NUSWhispers\Listeners\SyncConfessionTags',
        ],
        'NUSWhispers\Events\ConfessionWasUpdated' => [
            'NUSWhispers\Listeners\SyncConfessionTags',
        ],
        'NUSWhispers\Events\ConfessionWasDeleted' => [
            'NUSWhispers\Listeners\DeleteConfessionFromFacebook',
        ],
        'NUSWhispers\Events\ConfessionStatusWasChanged' => [
            'NUSWhispers\Listeners\FlushConfessionQueue',
            'NUSWhispers\Listeners\LogConfessionStatusChange',
        ],
        'NUSWhispers\Events\ConfessionWasApproved' => [
            'NUSWhispers\Listeners\PostConfessionToFacebook',
        ],
        'NUSWhispers\Events\ConfessionWasFeatured' => [
            'NUSWhispers\Listeners\PostConfessionToFacebook',
        ],
        'NUSWhispers\Events\ConfessionWasRejected' => [
            'NUSWhispers\Listeners\DeleteConfessionFromFacebook',
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
    }
}

<?php

namespace NUSWhispers\Providers;

use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'NUSWhispers\Events\ConfessionWasCreated' => [
            'NUSWhispers\Listeners\SyncConfessionTags',
            'NUSWhispers\Listeners\FilterConfessionViaWordBlacklist',
        ],
        'NUSWhispers\Events\ConfessionWasUpdated' => [
            'NUSWhispers\Listeners\SyncConfessionTags',
        ],
        'NUSWhispers\Events\ConfessionWasDeleted' => [
            'NUSWhispers\Listeners\DeleteConfessionFromFacebook',
        ],
        'NUSWhispers\Events\ConfessionStatusWasChanged' => [
            'NUSWhispers\Listeners\FlushConfessionQueue',
            'NUSWhispers\Listeners\LogConfessionStatusChange',
        ],
        'NUSWhispers\Events\ConfessionWasApproved' => [
            'NUSWhispers\Listeners\PostConfessionToFacebook',
        ],
        'NUSWhispers\Events\ConfessionWasFeatured' => [
            'NUSWhispers\Listeners\PostConfessionToFacebook',
        ],
        'NUSWhispers\Events\ConfessionWasRejected' => [
            'NUSWhispers\Listeners\DeleteConfessionFromFacebook',
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
    }
}

Fix filter confession listener not triggering


<?php

use HarUtils\HttpPacket;
namespace HarUtils;

class HarHttpRequest extends HttpPacket
{
    public function getMethod()
    {
        return $this->packet['method'];
    }

    public function getQueryString()
    {
        return $this->packet['queryString'];
    }

    public function getUrl()
    {
        return $this->packet['url'];
    }

}

<?php

use HarUtils\HttpPacket;
namespace HarUtils;

class HarHttpRequest extends HttpPacket
{
    public function getMethod()
    {
        return $this->packet['method'];
    }

    public function getQueryString()
    {
        return $this->packet['queryString'];
    }

    public function getUrl()
    {
        return array_key_exists('url', $this->packet) ? $this->packet['url'] : null;
    }

}

Fix error when url field is null in entry


<?php
namespace Karen;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class Controller
{
    protected $request;
    protected $response;
    protected $queue = [];

    public function __construct(Request $request, Response $response)
    {
        $this->request = $request;
        $this->response = $response;
    }

    public function render(string $output)
    {
        $this->response->getBody()->write($output);

        return $this->response;
    }

    public static function sendResponse(Response $response)
    {
        header(sprintf(
            'HTTP/%s %s %s',
            $response->getProtocolVersion(),
            $response->getStatusCode(),
            $response->getReasonPhrase()
        ));
        foreach ($response->getHeaders() as $name => $values) {
            foreach ($values as $value) {
                header(sprintf('%s: %s', $name, $value), false);
            }
        }

        if (!in_array($response->getStatusCode(), [204, 205, 304])) {
            echo $response->getBody();
        }
    }

    public function addQueue(string $name, callable $queue)
    {
        $this->queue[$name] = $queue;
    }

    public function getQueue()
    {
        return $this->queue;
    }

    /**
     * get routing action queue of Middleware interface
     */
    public function actionQueue(callable $callable, array $args)
    {
        return function (Request $request, Response $response) use ($callable, $args){

            return call_user_func($callable, $args, $this);
        };
    }
}

<?php
namespace Karen;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class Controller
{
    public $request;
    public $response;
    protected $queue = [];

    public function __construct(Request $request, Response $response)
    {
        $this->request = $request;
        $this->response = $response;
    }

    public function render(string $output)
    {
        $this->response->getBody()->write($output);

        return $this->response;
    }

    public static function sendResponse(Response $response)
    {
        header(sprintf(
            'HTTP/%s %s %s',
            $response->getProtocolVersion(),
            $response->getStatusCode(),
            $response->getReasonPhrase()
        ));
        foreach ($response->getHeaders() as $name => $values) {
            foreach ($values as $value) {
                header(sprintf('%s: %s', $name, $value), false);
            }
        }

        if (!in_array($response->getStatusCode(), [204, 205, 304])) {
            echo $response->getBody();
        }
    }

    public function addQueue(string $name, callable $queue)
    {
        $this->queue[$name] = $queue;
    }

    public function getQueue()
    {
        return $this->queue;
    }

    /**
     * get routing action queue of Middleware interface
     */
    public function actionQueue(callable $callable, array $args)
    {
        return function (Request $request, Response $response) use ($callable, $args){

            return call_user_func($callable, $args, $this);
        };
    }
}

Fix outer script access to request, response property


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

namespace ZendTest\ModuleManager\Listener;

use Zend\ModuleManager\Listener\ModuleResolverListener;
use Zend\ModuleManager\ModuleEvent;

/**
 * @covers Zend\ModuleManager\Listener\AbstractListener
 * @covers Zend\ModuleManager\Listener\ModuleResolverListener
 */
class ModuleResolverListenerTest extends AbstractListenerTestCase
{
    public function testModuleResolverListenerCanResolveModuleClasses()
    {
        $moduleResolver = new ModuleResolverListener;
        $e = new ModuleEvent;

        $e->setModuleName('ListenerTestModule');
        $this->assertInstanceOf('ListenerTestModule\Module', $moduleResolver($e));
    }

    public function testModuleResolverListenerReturnFalseIfCannotResolveModuleClasses()
    {
        $moduleResolver = new ModuleResolverListener;
        $e = new ModuleEvent;

        $e->setModuleName('DoesNotExist');
        $this->assertFalse($moduleResolver($e));
    }
}

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

namespace ZendTest\ModuleManager\Listener;

use Zend\ModuleManager\Listener\ModuleResolverListener;
use Zend\ModuleManager\ModuleEvent;

/**
 * @covers Zend\ModuleManager\Listener\AbstractListener
 * @covers Zend\ModuleManager\Listener\ModuleResolverListener
 */
class ModuleResolverListenerTest extends AbstractListenerTestCase
{
    /**
     * @dataProvider validModuleNameProvider
     */
    public function testModuleResolverListenerCanResolveModuleClasses($moduleName, $expectedInstanceOf)
    {
        $moduleResolver = new ModuleResolverListener;
        $e = new ModuleEvent;

        $e->setModuleName($moduleName);
        $this->assertInstanceOf($expectedInstanceOf, $moduleResolver($e));
    }

    public function validModuleNameProvider()
    {
        return [
            // Description => [module name, expectedInstanceOf]
            'Append Module' => ['ListenerTestModule', ListenerTestModule\Module::class],
        ];
    }

    public function testModuleResolverListenerReturnFalseIfCannotResolveModuleClasses()
    {
        $moduleResolver = new ModuleResolverListener;
        $e = new ModuleEvent;

        $e->setModuleName('DoesNotExist');
        $this->assertFalse($moduleResolver($e));
    }
}

Refactor test as data provider

Refactor test as data provider


<?php

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

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

Route::post('/api/v1/authenticate', 'Auth\LoginController@authenticate');
Route::get('/api/v1/authenticate', 'Auth\LoginController@authenticate');

Route::get('/api/v1/teams', 'TeamController@index');
Route::post('/api/v1/team', 'TeamController@store');
Route::get('/api/v1/team/{team}/projects', 'ProjectController@teamProjects');

Route::post('api/v1/project', 'ProjectController@store');

Route::get('/api/v1/projects', 'ProjectController@index');
Route::get('/api/v1/project/{project}', 'ProjectController@show');
Route::get('/api/v1/project/{project}/typography', 'ProjectController@typography');
Route::get('/api/v1/project/{project}/fonts', 'ProjectController@fonts');
Route::get('/api/v1/project/{project}/logos', 'ProjectController@logos');
Route::get('/api/v1/project/{project}/colors', 'ProjectController@colors');
Route::get('/api/v1/currentUser', 'ProjectController@currentUser');

Auth::routes();

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

<?php

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

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

Route::post('/api/v1/authenticate', 'Auth\LoginController@authenticate');
Route::get('/api/v1/authenticate', 'Auth\LoginController@authenticate');

Route::group(['middleware' => 'auth'], function() {
		Route::get('/api/v1/teams', 'TeamController@index');
		Route::post('/api/v1/team', 'TeamController@store');
		Route::get('/api/v1/team/{team}/projects', 'ProjectController@teamProjects');

		Route::post('api/v1/project', 'ProjectController@store');

		Route::get('/api/v1/projects', 'ProjectController@index');
		Route::get('/api/v1/project/{project}', 'ProjectController@show');
		Route::get('/api/v1/project/{project}/typography', 'ProjectController@typography');
		Route::get('/api/v1/project/{project}/fonts', 'ProjectController@fonts');
		Route::get('/api/v1/project/{project}/logos', 'ProjectController@logos');
		Route::get('/api/v1/project/{project}/colors', 'ProjectController@colors');
		Route::get('/api/v1/currentUser', 'ProjectController@currentUser');
});

Auth::routes();

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

Add auth middleware to applicable routes


<?php
/**
 * @version     $Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Modules
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Modules Toolbar Class
 *
 * @author      Stian Didriksen <http://nooku.assembla.com/profile/stiandidriksen>
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Modules
 */
class ComModulesControllerToolbarModules extends ComDefaultControllerToolbarDefault
{
    public function __construct(KConfig $config)
    {
        parent::__construct($config);

        $this->addSeperator()
			 ->addEenable()
			 ->addDisable();
    }

    protected function _commandNew(KControllerToolbarCommand $command)
    {
        $command->append(array(
            'attribs' => array(
                'class' => array('modal'),
                'rel'   => '{handler: \'url\', ajaxOptions:{method:\'get\'}}',
                'href'	=> 'index.php?option=com_modules&view=modules&layout=list&installed=1&tmpl=component'
            )
        ));
    }
}

<?php
/**
 * @version     $Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Modules
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Modules Toolbar Class
 *
 * @author      Stian Didriksen <http://nooku.assembla.com/profile/stiandidriksen>
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Modules
 */
class ComModulesControllerToolbarModules extends ComDefaultControllerToolbarDefault
{
    public function getCommands()
    {
        $this->addSeperator()
			 ->addEenable()
			 ->addDisable();

        return parent::getCommands();
    }

    protected function _commandNew(KControllerToolbarCommand $command)
    {
        $command->append(array(
            'attribs' => array(
                'class' => array('modal'),
                'rel'   => '{handler: \'url\', ajaxOptions:{method:\'get\'}}',
                'href'	=> 'index.php?option=com_modules&view=modules&layout=list&installed=1&tmpl=component'
            )
        ));
    }
}

Insert custom commands through the getCommands() function.


<?php

// Shows the dashboard, if enabled
$app->get('/', [
    'middleware' => \Nord\ImageManipulationService\Http\Middleware\DashboardPageEnabledMiddleware::class,
    'uses'       => 'DashboardController@dashboard',
]);

// Shows the upload page, if enabled
$app->get('/upload', [
    'middleware' => \Nord\ImageManipulationService\Http\Middleware\UploadPageEnabledMiddleware::class,
    'uses'       => 'ImageController@index',
]);

// Serves an image
$app->get('/{path:.*}', [
    'as'         => 'serveImage',
    'middleware' => \Nord\ImageManipulationService\Http\Middleware\ServeImageAuthenticationMiddleware::class,
    'uses'       => 'ImageController@serveImage',
]);

// Health check
$app->get('/health', function() {
    return 'OK';
});

// Stores an uploaded image to the source filesystem, then returns the path to it
$app->post('/upload', [
    'middleware' => [
        \Nord\ImageManipulationService\Http\Middleware\UploadAuthenticationMiddleware::class,
        \Nord\ImageManipulationService\Http\Middleware\ImageUploadFromFileValidatorMiddleware::class,
    ],
    'uses'       => 'ImageController@uploadImageFromFile',
]);

$app->post('/uploadFromUrl', [
    'middleware' => [
        \Nord\ImageManipulationService\Http\Middleware\UploadAuthenticationMiddleware::class,
        \Nord\ImageManipulationService\Http\Middleware\ImageUploadFromUrlValidatorMiddleware::class,
    ],
    'uses'       => 'ImageController@uploadImageFromUrl',
]);

<?php

// Health check
$app->get('/health', function() {
    return 'OK';
});

// Shows the dashboard, if enabled
$app->get('/', [
    'middleware' => \Nord\ImageManipulationService\Http\Middleware\DashboardPageEnabledMiddleware::class,
    'uses'       => 'DashboardController@dashboard',
]);

// Shows the upload page, if enabled
$app->get('/upload', [
    'middleware' => \Nord\ImageManipulationService\Http\Middleware\UploadPageEnabledMiddleware::class,
    'uses'       => 'ImageController@index',
]);

// Serves an image
$app->get('/{path:.*}', [
    'as'         => 'serveImage',
    'middleware' => \Nord\ImageManipulationService\Http\Middleware\ServeImageAuthenticationMiddleware::class,
    'uses'       => 'ImageController@serveImage',
]);

// Stores an uploaded image to the source filesystem, then returns the path to it
$app->post('/upload', [
    'middleware' => [
        \Nord\ImageManipulationService\Http\Middleware\UploadAuthenticationMiddleware::class,
        \Nord\ImageManipulationService\Http\Middleware\ImageUploadFromFileValidatorMiddleware::class,
    ],
    'uses'       => 'ImageController@uploadImageFromFile',
]);

$app->post('/uploadFromUrl', [
    'middleware' => [
        \Nord\ImageManipulationService\Http\Middleware\UploadAuthenticationMiddleware::class,
        \Nord\ImageManipulationService\Http\Middleware\ImageUploadFromUrlValidatorMiddleware::class,
    ],
    'uses'       => 'ImageController@uploadImageFromUrl',
]);

Move health check route first, otherwise it gets shadowed


<?php
/**
 * Front End Accounts
 *
 * @category    WordPress
 * @package     FrontEndAcounts
 * @since       0.1
 * @author      Christopher Davis <http://christopherdavis.me>
 * @copyright   2013 Christopher Davis
 * @license     http://opensource.org/licenses/MIT MIT
 */

namespace Chrisguitarguy\FrontEndAccounts\Form\Field;

/**
 * Throw when a a validator fails to OK a value.
 *
 * @since   0.1
 */
class ValidationException extends \RuntimeException
{
    // empty
}

<?php
/**
 * Front End Accounts
 *
 * @category    WordPress
 * @package     FrontEndAcounts
 * @since       0.1
 * @author      Christopher Davis <http://christopherdavis.me>
 * @copyright   2013 Christopher Davis
 * @license     http://opensource.org/licenses/MIT MIT
 */

namespace Chrisguitarguy\FrontEndAccounts\Form\Validator;

/**
 * Throw when a a validator fails to OK a value.
 *
 * @since   0.1
 */
class ValidationException extends \RuntimeException
{
    // empty
}

Correct an incorrect namespace declaration


<?php namespace Leean\Endpoints\Inc;

/**
 * Class Template
 *
 * @package Leean\Endpoints\Inc
 */
class Template
{
	/**
	 * Returns the template used on a page:
	 *
	 * - Default for the default page template
	 * - Template Slug
	 * - Empty string if the post is not a page.
	 *
	 * @param Int|\WP_Post $post The post
	 * @return string
	 */
	public static function get( $post ) {
		$post = is_a( $post, 'WP_Post' ) ? $post : get_post( $post );
		$template = '';
		if ( 'page' === $post->post_type ) {
			$template_slug = get_page_template_slug( $post->ID );
			$template = empty( $template_slug )
				? 'default'
				: basename( $template_slug, '.php' );
		}
		return $template;
	}
}

<?php namespace Leean\Endpoints\Inc;

/**
 * Class Template
 *
 * @package Leean\Endpoints\Inc
 */
class Template
{
	/**
	 * Returns the type for the post, the term template applies to what type of
	 * post is or what type of template is using.
	 *
	 * @param Int|\WP_Post $post The post
	 * @return string
	 */
	public static function get( $post ) {
		$post = is_a( $post, 'WP_Post' ) ? $post : get_post( $post );
		$type = $post->post_type;
		if ( 'page' === $type ) {
			$template_slug = get_page_template_slug( $post->ID );
			$type = empty( $template_slug )
				? 'default'
				: basename( $template_slug, '.php' );
		}
		return $type;
	}
}

Update the type of the functio

Update the type of the functio


<?php
namespace CuriousCoder\TelegramBot;

/*
 * This file is part of the TelegramPHPBot package.
 *
 * (c) Vinay Kumar aka CuriousCoder
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

Class Helper{

	public function CheckFile($path,array $format){

		if(file_exists($path) && is_readable($path)){

			if(in_array(pathinfo($path,PATHINFO_EXTENSION),$format))
			{
				return true;
			}

		}
			return false;
	}

	public function checkUrl($url){
		if (filter_var($url, FILTER_VALIDATE_URL) === true || parse_url($url, PHP_URL_SCHEME) === 'https') {
			return true;
		}
		return false;
	}

}

<?php
namespace CuriousCoder\TelegramBot;

/*
 * This file is part of the TelegramPHPBot package.
 *
 * (c) Vinay Kumar aka CuriousCoder
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
use CuriousCoder\TelegramBot\Exception\FileFormatException;

Class Helper{

	public function CheckFile($path,array $format){

		if(file_exists($path) && is_readable($path)){

			if(in_array(pathinfo($path,PATHINFO_EXTENSION),$format))
			{
				return true;
			}

			throw new FileFormatException("Unsupported format. Allowed formats: ",null,$format);
		}

		throw new FileFormatException("Check file path: ".$path,null,[]);
	}

	public function checkUrl($url){
		if (filter_var($url, FILTER_VALIDATE_URL) === true || parse_url($url, PHP_URL_SCHEME) === 'https') {
			return true;
		}
		return false;
	}

}

Throw file path and invalid file format Exception


<?php

namespace ResponsiveImages;

use Functional as F;

class Source
{
  /**
   * @var Size[]
   */
  private $sizes;

  /**
   * Whether or not to render as an <img> instead of <source>. This is important
   * since the last element in a <picture> should be an <img>, but otherwise is
   * nearly the same as a <source>.
   *
   * @var bool
   */
  private $as_img;

  function __construct(array $sizes, $as_img=false)
  {
    $this->sizes  = $sizes;
    $this->as_img = $as_img;
  }

  public function renderFor($uri, SrcsetGeneratorInterface $srcset_gen)
  {
    $last = F\last($this->sizes);

    $srcset = F\map($this->sizes, function(Size $size) use ($uri, $srcset_gen){
      return $srcset_gen->listFor($uri, $size);
    });
    $srcset = F\unique(F\flatten($srcset));
    $srcset = implode(', ', $srcset);

    $sizes  = F\map($this->sizes, function(Size $size) use ($last){
      return $size === $last ? $size->renderWidthOnly() : (string)$size;
    });
    $sizes  = implode(', ', $sizes);

    $media = !$this->as_img ? ' media="'.$last->getMediaQuery().'""' : '';

    $attributes = "srcset=\"$srcset\" sizes=\"$sizes\"$media";
    return $this->as_img ? "<img $attributes>" : "<source $attributes>";
  }
}

<?php

namespace ResponsiveImages;

use Functional as F;

class Source
{
  /**
   * @var Size[]
   */
  private $sizes;

  /**
   * Whether or not to render as an <img> instead of <source>. This is important
   * since the last element in a <picture> should be an <img>, but otherwise is
   * nearly the same as a <source>.
   *
   * @var bool
   */
  private $as_img;

  function __construct(array $sizes, $as_img=false)
  {
    $this->sizes  = $sizes;
    $this->as_img = $as_img;
  }

  public function renderFor($uri, SrcsetGeneratorInterface $srcset_gen)
  {
    $last = F\last($this->sizes);

    $srcset = F\map($this->sizes, function(Size $size) use ($uri, $srcset_gen){
      return $srcset_gen->listFor($uri, $size);
    });
    $srcset = F\unique(F\flatten($srcset));
    $srcset = implode(', ', $srcset);

    $sizes  = F\map($this->sizes, function(Size $size) use ($last){
      return $size === $last ? $size->renderWidthOnly() : (string)$size;
    });
    $sizes  = implode(', ', $sizes);

    $media = !$this->as_img ? ' media="'.$last->getMediaQuery().'"' : '';

    $attributes = "srcset=\"$srcset\" sizes=\"$sizes\"$media";
    return $this->as_img ? "<img $attributes>" : "<source $attributes>";
  }
}

Remove extra " in generated <source> tags.


<?php
use TOL\PhotoHack\Youtube;

return function($app) {
    $twigView = new \Slim\Views\Twig();
    $twigView->parserOptions = ['autoescape' => false];

    $app->config('templates.path', __DIR__ . '/templates');
    $view = $app->view($twigView);
    $view->parserExtensions = [new \Slim\Views\TwigExtension()];

    $app->container->singleton('youtube', function() use($app) {
        return new Youtube($app->client);
    });

    $app->container->singleton('client', function() use($app) {
        $client = new Google_Client();
        $client->setClientId(getenv('YOUTUBE_CLIENT_ID'));
        $client->setClientSecret(getenv('YOUTUBE_CLIENT_SECRET'));
        $client->setScopes('https://www.googleapis.com/auth/youtube');
        $client->setRedirectUri('http://local.photohack.com/share');
        $token = $app->getCookie('token');
        if ($token) {
            $client->setAccessToken($token);
        }

        return $client;
    });
};

<?php
use TOL\PhotoHack\Youtube;

function hostName()
{
    $protocol = $_SERVER['HTTPS'] ? 'https://' : 'http://';
    $serverName = $_SERVER['SERVER_NAME'];
    return $protocol . $serverName;
}

return function($app) {
    $twigView = new \Slim\Views\Twig();
    $twigView->parserOptions = ['autoescape' => false];

    $app->config('templates.path', __DIR__ . '/templates');
    $view = $app->view($twigView);
    $view->parserExtensions = [new \Slim\Views\TwigExtension()];

    $app->container->singleton('youtube', function() use($app) {
        return new Youtube($app->client);
    });

    $app->container->singleton('client', function() use($app) {
        $client = new Google_Client();
        $client->setClientId(getenv('YOUTUBE_CLIENT_ID'));
        $client->setClientSecret(getenv('YOUTUBE_CLIENT_SECRET'));
        $client->setScopes('https://www.googleapis.com/auth/youtube');
        $serverName = hostName();
        $client->setRedirectUri("{$serverName}/share");
        $token = $app->getCookie('token');
        if ($token) {
            $client->setAccessToken($token);
        }

        return $client;
    });
};

Use current host name for redirect url

Use current host name for redirect url


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Bundle\UiBundle\Block;

use Sonata\BlockBundle\Event\BlockEvent;
use Sonata\BlockBundle\Model\Block;

final class BlockEventListener
{
    /** @var string */
    private $template;

    public function __construct(string $template)
    {
        @trigger_error(
            sprintf('Using "%s" to add blocks to the templates is deprecated since Sylius 1.7. Use "sylius_ui" configuration instead.', self::class),
            \E_USER_DEPRECATED
        );

        $this->template = $template;
    }

    public function onBlockEvent(BlockEvent $event): void
    {
        $block = new Block();
        $block->setId(uniqid('', true));
        $block->setSettings(array_replace($event->getSettings(), [
            'template' => $this->template,
        ]));
        $block->setType('sonata.block.service.template');

        $event->addBlock($block);
    }
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Bundle\UiBundle\Block;

use Sonata\BlockBundle\Event\BlockEvent;
use Sonata\BlockBundle\Model\Block;

final class BlockEventListener
{
    /** @var string */
    private $template;

    public function __construct(string $template)
    {
        @trigger_error(
            sprintf('Using "%s" to add blocks to the templates is deprecated since Sylius 1.7 and will be removed in Sylius 2.0. Use "sylius_ui" configuration instead.', self::class),
            \E_USER_DEPRECATED
        );

        $this->template = $template;
    }

    public function onBlockEvent(BlockEvent $event): void
    {
        $block = new Block();
        $block->setId(uniqid('', true));
        $block->setSettings(array_replace($event->getSettings(), [
            'template' => $this->template,
        ]));
        $block->setType('sonata.block.service.template');

        $event->addBlock($block);
    }
}

Improve deprecation notices for new template events system


        {err}

Check In

                <form method="get">

                        <input type="text" class="form-control" name="search" placeholder="หมายเลขประจำตัว, ชื่อ, นามสกุล, ชื่อเล่น">

                    <button type="submit" class="btn btn-default">Submit</button>
                </form>

                            ID
                            ชื่อ - นามสกุล
                            ชื่อเล่น
                            โรงเรียน
                            Action

                        {attendees}

        {err}

Check In

                <form method="get">

                        <input type="text" class="form-control" name="search" placeholder="หมายเลขประจำตัว, ชื่อ, นามสกุล, ชื่อเล่น" autofocus>

                    <button type="submit" class="btn btn-default">Submit</button>
                </form>

                            ID
                            ชื่อ - นามสกุล
                            ชื่อเล่น
                            โรงเรียน
                            Action

                        {attendees}

Add autofocus on field search

Add autofocus on field search


<?php
// Set this to true if you want to be able to load images from a url that doesn't
// end in an image file extension. E.g. through another proxy of kinds.
define('ALLOW_NO_EXT', false);

if (!$_GET['url']) {
  exit;
}

// Grab the URL
$url = trim(urldecode($_GET['url']));

$urlinfo = parse_url($url, PHP_URL_PATH);
$ext = array_reverse(explode(".", $urlinfo));

$ctype = null;
switch ($ext[0]) {
case 'gif': $ctype = 'image/gif'; break;
case 'png': $ctype = 'image/png'; break;
case 'jpeg':
case 'jpg': $ctype = 'image/jpg'; break;
default:
  if (ALLOW_NO_EXT) {
    $ctype = 'application/octet-stream';
  } else {
    exit;
  }
}

// Route the image through this script
header("Content-Type: $ctype");
readfile($url);

<?php
// Set this to true if you want to be able to load images from a url that doesn't
// end in an image file extension. E.g. through another proxy of kinds.
define('ALLOW_NO_EXT', false);

$proxyParam = 'camanProxyUrl';

if (!$_GET[$proxyParam]) {
  exit;
}

// Grab the URL
$url = trim(urldecode($_GET[$proxyParam]));

$urlinfo = parse_url($url, PHP_URL_PATH);
$ext = array_reverse(explode(".", $urlinfo));

$ctype = null;
switch ($ext[0]) {
case 'gif': $ctype = 'image/gif'; break;
case 'png': $ctype = 'image/png'; break;
case 'jpeg':
case 'jpg': $ctype = 'image/jpg'; break;
default:
  if (ALLOW_NO_EXT) {
    $ctype = 'application/octet-stream';
  } else {
    exit;
  }
}

// Route the image through this script
header("Content-Type: $ctype");
readfile($url);

Create a new variable in the php-proxy and set to the default proxyParam value


<?php

namespace Knp\RadBundle\Doctrine;

use Doctrine\ORM\EntityRepository as BaseEntityRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Common\Util\Inflector;

class EntityRepository extends BaseEntityRepository
{
    public function __call($method, $arguments)
    {
        if (0 === strpos($method, 'find')) {
            if (method_exists($this, $builder = 'build'.substr($method, 4))) {
                $qb = call_user_func_array(array($this, $builder), $arguments);

                return $qb->getQuery()->getResult();
            }
        }

        return parent::__call($method, $arguments);
    }

    protected function build()
    {
        return $this->createQueryBuilder($this->getAlias());
    }

    protected function buildOne($id)
    {
        return $this->build()->where($this->getAlias().'.id = '.intval($id));
    }

    protected function buildAll()
    {
        return $this->build();
    }

    protected function getAlias()
    {
        $name = basename(str_replace('\\', '/', $this->getClassName()));

        return Inflector::tableize($name);
    }
}

<?php

namespace Knp\RadBundle\Doctrine;

use Doctrine\ORM\EntityRepository as BaseEntityRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Common\Util\Inflector;

class EntityRepository extends BaseEntityRepository
{
    public function __call($method, $arguments)
    {
        if (0 === strpos($method, 'find')) {
            if (method_exists($this, $builder = 'build'.substr($method, 4))) {
                $qb = call_user_func_array(array($this, $builder), $arguments);

                if (0 === strpos(substr($method, 4), 'One')) {
                    return $qb->getQuery()->getOneOrNullResult();
                }

                return $qb->getQuery()->getResult();
            }
        }

        return parent::__call($method, $arguments);
    }

    protected function build()
    {
        return $this->createQueryBuilder($this->getAlias());
    }

    protected function buildOne($id)
    {
        return $this->build()->where($this->getAlias().'.id = '.intval($id));
    }

    protected function buildAll()
    {
        return $this->build();
    }

    protected function getAlias()
    {
        $name = basename(str_replace('\\', '/', $this->getClassName()));

        return Inflector::tableize($name);
    }
}

Return one or null result when calling repository method containing 'one'


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

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

function smarty_function_bootstrap_modal( $params, $smarty )
{
	$smarty->loadPlugin('smarty_function_service');
	$params['modal'] = 1;
	$href = smarty_function_service($params, $smarty);
	return "$href\" data-toggle=\"modal\" data-target=\".modal.fade:not(.in):first";
}

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

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

function smarty_function_bootstrap_modal( $params, $smarty )
{
	$smarty->loadPlugin('smarty_function_service');
	$params['modal'] = 1;
	$href = smarty_function_service($params, $smarty);
	return "$href\" data-toggle=\"modal\" data-backdrop=\"static\" data-target=\".modal.fade:not(.in):first";
}

[FIX] Edit popups should be modal (specifically Edit Tracker Item)

git-svn-id: 7564fe402ed407387e083b9f1c8ef2c2bd7bb5d7@54235 b456876b-0849-0410-b77d-98878d47e9d5


<?php
	namespace eNotasGW\Api;

	class eNotasGWHelper {
		public static function formatDate($date) {
			return $date->format('Y-m-d');
		}

		public static function formatDateTime($dateTime) {
			return $date->format('Y-m-d H:i:s');
		}
	}
?>

<?php
	namespace eNotasGW\Api;

	class eNotasGWHelper {
		public static function formatDate($date) {
			return $date->format('Y-m-d');
		}

		public static function formatDateTime($date) {
			return $date->format('Y-m-d H:i:s');
		}
	}
?>

Fix parameter in eNotasGWHelper function formatDateTime


Set token for a user-directed logout.

Set token for a user-directed logout.

git-svn-id: 245d8f85226f8eeeaacc1269b037bb4851d63c96@793 54a900ba-8191-11dd-a5c9-f1483cedc3eb


<?php

require_once 'SwatDB/SwatDBRecordsetWrapper.php';
require_once 'Building/dataobjects/BuildingBlock.php';

/**
 * Wrapper for BuildingBlock objects
 *
 * @package   Building
 * @copyright 2014-2016 silverorange
 * @license   http://www.opensource.org/licenses/mit-license.html MIT License
 * @see       BuildingBlock
 */
class BuildingBlockWrapper extends SwatDBRecordsetWrapper
{
	// {{{ protected function init()

	protected function init()
	{
		parent::init();
		$this->row_wrapper_class = 'BuildingBlock';
		$this->index_field = 'id';
	}

	// }}}
}

?>

<?php

require_once 'SwatDB/SwatDBRecordsetWrapper.php';
require_once 'Building/dataobjects/BuildingBlock.php';

/**
 * Wrapper for BuildingBlock objects
 *
 * @package   Building
 * @copyright 2014-2016 silverorange
 * @license   http://www.opensource.org/licenses/mit-license.html MIT License
 * @see       BuildingBlock
 */
class BuildingBlockWrapper extends SwatDBRecordsetWrapper
{
	// {{{ protected function init()

	protected function init()
	{
		parent::init();
		$this->row_wrapper_class = SwatDBClassMap::get('BuildingBlock');
		$this->index_field = 'id';
	}

	// }}}
}

?>

Use SwatDBClassMap to set the row class.


<?php
/* connector for Serpent
estimated execution time: 23 mins.
Connector screen scrapes the partner website.
*/
$timestart = microtime(1);

include_once(dirname(__FILE__) . "/../../config/environment.php");
require_library('connectors/SerpentAPI');
$GLOBALS['ENV_DEBUG'] = false;

$taxa = SerpentAPI::get_all_taxa();
$xml = SchemaDocument::get_taxon_xml($taxa);

$resource_path = CONTENT_RESOURCE_LOCAL_PATH . "170.xml";
$OUT = fopen($resource_path, "w+");
fwrite($OUT, $xml);
fclose($OUT);

$elapsed_time_sec = microtime(1)-$timestart;
echo "\n";
echo "elapsed time = $elapsed_time_sec sec              \n";
echo "elapsed time = " . $elapsed_time_sec/60 . " min   \n";
echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n";
exit("\n\n Done processing.");
?>

<?php
/* connector for SERPENT
estimated execution time: 23 mins.
Connector screen scrapes the partner website.
*/

include_once(dirname(__FILE__) . "/../../config/environment.php");
$timestart = time_elapsed();

require_library('connectors/SerpentAPI');
$GLOBALS['ENV_DEBUG'] = false;

$taxa = SerpentAPI::get_all_taxa();
$xml = SchemaDocument::get_taxon_xml($taxa);

$resource_id = 170;
$resource_path = CONTENT_RESOURCE_LOCAL_PATH . $resource_id . ".xml";
$OUT = fopen($resource_path, "w+");
fwrite($OUT, $xml);
fclose($OUT);

// set SERPENT to force harvest
if(filesize(CONTENT_RESOURCE_LOCAL_PATH . $resource_id . ".xml"))
{
    $GLOBALS['db_connection']->update("UPDATE resources SET resource_status_id=" . ResourceStatus::insert('Force Harvest') . " WHERE id=" . $resource_id);
}

$elapsed_time_sec = time_elapsed() - $timestart;
echo "\n";
echo "elapsed time = " . $elapsed_time_sec/60 . " minutes \n";
echo "elapsed time = " . $elapsed_time_sec/60/60 . " hours \n";
exit("\n\n Done processing.");
?>

Set Serpent connector to force_harvest when connector is done.

git-svn-id: d46fe582d22b46b457d3ac1c55a88da2fbe913a1@1727 baf6b65b-9124-4dc3-b1c0-01155b4af546


<?php

namespace RoyallTheFourth\QuickList\Common;

use Symfony\Component\Yaml\Yaml;

function iterableToArray(iterable $iter): array
{
    $out = [];
    foreach ($iter as $el) {
        $out[] = $el;
    }

    return $out;
}

function config(): array
{
    return Yaml::parse(file_get_contents(__DIR__ . '/../config/config.yml'));
}

function mailer(array $config): \PHPMailer
{
    $mailer = new \PHPMailer(true);
    $mailer->isSMTP();
    $mailer->Host = implode(';', $config['smtp']['hosts']);
    $mailer->Username = $config['smtp']['user'];
    $mailer->Password = $config['smtp']['pass'];
    $mailer->SMTPSecure = $config['smtp']['security'];
    $mailer->SMTPAuth = true;
    $mailer->SMTPKeepAlive = true;
    $mailer->Port = $config['smtp']['port'];
    $mailer->setFrom($config['from']);
    return $mailer;
}

/**
 * Converts database times to human-readable times
 *
 * @param string $dateTime The dateTime in UTC
 * @param \DateTimeZone $timezone
 * @return string
 */
function localDate(?string $dateTime, \DateTimeZone $timezone): string
{
    if ($dateTime === null) {
        return '';
    }
    return (new \DateTimeImmutable($dateTime, new \DateTimeZone('UTC')))
        ->setTimezone($timezone)
        ->format('Y-m-d H:i:s');
}

<?php

namespace RoyallTheFourth\QuickList\Common;

use Respect\Validation\Validator;
use Symfony\Component\Yaml\Yaml;

function iterableToArray(iterable $iter): array
{
    $out = [];
    foreach ($iter as $el) {
        $out[] = $el;
    }

    return $out;
}

function config(): array
{
    return Yaml::parse(file_get_contents(__DIR__ . '/../config/config.yml'));
}

function mailer(array $config): \PHPMailer
{
    $mailer = new \PHPMailer(true);
    $mailer->isSMTP();
    $mailer->Host = implode(';', $config['smtp']['hosts']);
    $mailer->Username = $config['smtp']['user'];
    $mailer->Password = $config['smtp']['pass'];
    $mailer->SMTPSecure = $config['smtp']['security'];
    $mailer->SMTPAuth = true;
    $mailer->SMTPKeepAlive = true;
    $mailer->Port = $config['smtp']['port'];
    $mailer->setFrom($config['from']);
    return $mailer;
}

/**
 * Converts database times to human-readable times
 *
 * @param string $dateTime The dateTime in UTC
 * @param \DateTimeZone $timezone
 * @return string
 */
function localDate(?string $dateTime, \DateTimeZone $timezone): string
{
    if ($dateTime === null) {
        return '';
    }
    return (new \DateTimeImmutable($dateTime, new \DateTimeZone('UTC')))
        ->setTimezone($timezone)
        ->format('Y-m-d H:i:s');
}

function readEmailsFromConsole(): iterable
{
    while ($email = readline()) {
        if (Validator::email()->validate($email)) {
            yield $email;
        }
    }
}

Add console email read function

Add console email read function


<?php

namespace Spec\PHPSpec2;

use PHPSpec2\SpecificationInterface;

class Stub implements SpecificationInterface
{
    public function described_with($stub)
    {
        $stub->is_an_instance_of('PHPSpec2\Stub');
    }

    public function registers_matcher_if_it_has_aliases($stub, $matcher)
    {
        $matcher->is_a_mock_of('PHPSpec2\Matcher\MatcherInterface');
        $matcher->getAliases()->should_return(array('should_be_equal'));

        $stub->__registerMatcher($matcher);
        $stub->__getMatchers()->should_contain(2);
    }

    public function does_not_registers_matcher_if_it_has_no_aliases($stub, $matcher)
    {
        $matcher->is_a_mock_of('PHPSpec2\Matcher\MatcherInterface');
        $matcher->getAliases()->should_return(array());

        $stub->__registerMatcher($matcher);
        $stub->__getMatchers()->should_contain(0);
    }
}

<?php

namespace Spec\PHPSpec2;

use PHPSpec2\SpecificationInterface;

class Stub implements SpecificationInterface
{
    public function described_with($stub)
    {
        $stub->is_an_instance_of('PHPSpec2\Stub');
    }

    public function registers_matcher_if_it_has_aliases($stub, $matcher)
    {
        $matcher->is_a_mock_of('PHPSpec2\Matcher\MatcherInterface');
        $matcher->getAliases()->should_return(array('should_be_equal'));

        $stub->__registerMatcher($matcher);
        $stub->__getMatchers()->should_contain(1);
    }

    public function does_not_registers_matcher_if_it_has_no_aliases($stub, $matcher)
    {
        $matcher->is_a_mock_of('PHPSpec2\Matcher\MatcherInterface');
        $matcher->getAliases()->should_return(array());

        $stub->__registerMatcher($matcher);
        $stub->__getMatchers()->should_contain(0);
    }
}

Fix spec broken previously to test exception


<?php

namespace Plummer\Calendarful\Event;

interface EventInterface
{
	public function getId();

	public function getStartDate();

	public function setStartDate(\DateTime $startDateFull);

	public function getEndDate();

	public function setEndDate(\DateTime $endDate);

	public function getDuration();

	public function getParentId();

	public function getOccurrenceDate();

    public function getRecurrenceType();

	public function setRecurrenceType($type = null);

    public function getRecurrenceUntil();

	public function getRecurrenceDayName();

	public function getRecurrenceDayOfMonth();

	public function getRecurrenceWeekNumber();
}

<?php

namespace Plummer\Calendarful\Event;

interface EventInterface
{
	public function getId();

	public function getStartDate();

	public function setStartDate(\DateTime $startDateFull);

	public function getEndDate();

	public function setEndDate(\DateTime $endDate);

	public function getDuration();

	public function getParentId();

	public function getOccurrenceDate();

    public function getRecurrenceType();

	public function setRecurrenceType($type = null);

    public function getRecurrenceUntil();

	public function getRecurrenceWeekDayNumber();

	public function getRecurrenceDayOfMonth();

	public function getRecurrenceWeekNumber();
}

Rename method to be more self explanatory.


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

namespace Darvin\ContentBundle\Meta\Tag\Provider;

/**
 * Meta tag provider
 */
interface MetaTagProviderInterface
{
    /**
     * @return string
     */
    public function getHeading(): string;

    /**
     * @return string
     */
    public function getMetaTitle(): string;

    /**
     * @return string
     */
    public function getMetaDescription(): string;
}

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

namespace Darvin\ContentBundle\Meta\Tag\Provider;

/**
 * Meta tag provider
 */
interface MetaTagProviderInterface
{
    /**
     * @param object        $object           Object
     * @param string|null   $heading          Original heading
     * @param string|null   $fallback         Fallback
     * @param callable|null $templateCallback Template callback
     *
     * @return string
     */
    public function getHeading(object $object, ?string $heading, ?string $fallback = null, ?callable $templateCallback = null): string;

    /**
     * @param object        $object           Object
     * @param string|null   $metaTitle        Original meta title
     * @param string|null   $fallback         Fallback
     * @param callable|null $templateCallback Template callback
     *
     * @return string
     */
    public function getMetaTitle(object $object, ?string $metaTitle, ?string $fallback = null, ?callable $templateCallback = null): string;

    /**
     * @param object        $object           Object
     * @param string|null   $metaDescription  Original meta description
     * @param string|null   $fallback         Fallback
     * @param callable|null $templateCallback Template callback
     *
     * @return string
     */
    public function getMetaDescription(object $object, ?string $metaDescription, ?string $fallback = null, ?callable $templateCallback = null): string;
}

Add meta tag provider interface.

Add meta tag provider interface.


<?php

namespace App\ServiceProvider;

/**
 * Standard service providers
 * @see https://github.com/container-interop/service-provider
 */
use Interop\Container\ServiceProvider;

/**
 * @see http://www.pomm-project.org/
 */
use PommProject\ModelManager\SessionBuilder;

/**
 * Class Pomm
 * @package App\ServiceProvider
 * @author Petr Pliska <petr.pliska@post.cz>
 */
class Pomm implements ServiceProvider
{
    /**
     * Returns a list of all container entries registered by this service provider.
     *
     * - the key is the entry name
     * - the value is a callable that will return the entry, aka the **factory**
     *
     * Factories have the following signature:
     *        function(ContainerInterface $container, callable $getPrevious = null)
     *
     * About factories parameters:
     *
     * - the container (instance of `Interop\Container\ContainerInterface`)
     * - a callable that returns the previous entry if overriding a previous entry, or `null` if not
     *
     * @return callable[]
     */
    public function getServices()
    {
        return [
            \PommProject\Foundation\Pomm::class => function () {
                return new Pomm(['db' => [
                    'dsn' => getenv('DATABASE_DSN'),
                    'class:session_builder' => SessionBuilder::class
                ]]);
            }
        ];
    }
}

<?php

namespace App\ServiceProvider;

/**
 * Standard service providers
 * @see https://github.com/container-interop/service-provider
 */
use Interop\Container\ServiceProvider;

/**
 * @see http://www.pomm-project.org/
 */
use PommProject\ModelManager\SessionBuilder;

/**
 * Class Pomm
 * @package App\ServiceProvider
 * @author Petr Pliska <petr.pliska@post.cz>
 */
class Pomm implements ServiceProvider
{
    /**
     * Returns a list of all container entries registered by this service provider.
     *
     * - the key is the entry name
     * - the value is a callable that will return the entry, aka the **factory**
     *
     * Factories have the following signature:
     *        function(ContainerInterface $container, callable $getPrevious = null)
     *
     * About factories parameters:
     *
     * - the container (instance of `Interop\Container\ContainerInterface`)
     * - a callable that returns the previous entry if overriding a previous entry, or `null` if not
     *
     * @return callable[]
     */
    public function getServices()
    {
        return [
            \PommProject\Foundation\Pomm::class => function () {
                return new \PommProject\Foundation\Pomm(['db' => [
                    'dsn' => getenv('DATABASE_DSN'),
                    'class:session_builder' => SessionBuilder::class
                ]]);
            }
        ];
    }
}

Fix error in pomm service provider

Fix error in pomm service provider


<?php
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;
use kartik\widgets\AlertBlock;

/* @var $this \yii\web\View */
/* @var $content string */

AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
    <meta charset="<?= Yii::$app->charset ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title><?= $this->title ? Html::encode(Yii::$app->name." | $this->title") : (Yii::$app->name.' | Home') ?></title>
    <?php $this->head() ?>
</head>
<body>

<?php
    echo AlertBlock::widget([
        'useSessionFlash' => true,
        'type' => AlertBlock::TYPE_GROWL,
        'delay' => false, // Don't automatically disappear.
    ]);
?>

<?php $this->beginBody() ?>
<?= $content ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

<?php
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;
use kartik\widgets\AlertBlock;

/* @var $this \yii\web\View */
/* @var $content string */

AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
    <meta name="Vanish" content="app-id=992815164, affiliate-data=myAffiliateData, app-argument=evote://">
    <meta charset="<?= Yii::$app->charset ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title><?= $this->title ? Html::encode(Yii::$app->name." | $this->title") : (Yii::$app->name.' | Home') ?></title>
    <?php $this->head() ?>
</head>
<body>

<?php
    echo AlertBlock::widget([
        'useSessionFlash' => true,
        'type' => AlertBlock::TYPE_GROWL,
        'delay' => false, // Don't automatically disappear.
    ]);
?>

<?php $this->beginBody() ?>
<?= $content ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

Add meta tag to display app banner

Add meta tag to display app banner


<?php

/**
 * Post upgrade, update filesizes for assets uploaded prior to FileSize capture
 *
 * @author marcus
 */
class UpdateFileSizeTask extends BuildTask
{
    public function run($request)
    {
        $number = $request->getVar('number');

        if (!$number) {
            $number = 50;
        }

        if (!$request->getVar('run')) {
            exit("Please supply the run= parameter, and a 'number' parameter (defaults to 50 if not set)");
        }

        $files = File::get()->filter(['FileSize' => 0, 'ClassName:not' => 'Folder', 'CDNFile:PartialMatch' => ':||'])->limit($number);

        echo "Processing " . $number . " files
\n"; flush();

        foreach ($files as $file) {
            echo "Downloading $file->ClassName #{$file->ID} " . $file->Title . " ... "; flush();
            $file->ensureLocalFile();
            if ($file->localFileExists()) {
                $file->FileSize = filesize($file->getFullPath());
                echo "filesize {$file->FileSize} ... "; flush();
                if ($file instanceof CdnImage) {
                    $dim = $file->getDimensions();
                    echo "dimensions $dim ... "; flush();
                }
                unlink($file->getFullPath());
            } else {
                echo " cannot download $file->Title - $file->CDNFile
\n";
            }
            echo "
\n";
        }
    }

}

<?php

/**
 * Post upgrade, update filesizes for assets uploaded prior to FileSize capture
 *
 * @author marcus
 */
class UpdateFileSizeTask extends BuildTask
{
    public function run($request)
    {
        $number = $request->getVar('number');

        if (!$number) {
            $number = 50;
        }

        if (!$request->getVar('run')) {
            exit("Please supply the run= parameter, and a 'number' parameter (defaults to 50 if not set)");
        }

        $files = File::get()->filter(['FileSize' => 0, 'ClassName:not' => 'Folder', 'CDNFile:PartialMatch' => ':||'])->limit($number);

        echo "Processing " . $number . " files
\n"; flush();

        foreach ($files as $file) {
            echo "Downloading $file->ClassName #{$file->ID} " . $file->Title . " ... "; flush();
            $file->ensureLocalFile();
            if ($file->localFileExists()) {
                $file->FileSize = filesize($file->getFullPath());
                echo "filesize {$file->FileSize} ... "; flush();
                if ($file instanceof CdnImage) {
                    $dim = $file->getDimensions();
                    echo "dimensions $dim ... "; flush();
                }
                $file->write();
                unlink($file->getFullPath());
            } else {
                echo " cannot download $file->Title - $file->CDNFile
\n";
            }
            echo "
\n";
        }
    }

}

FIX Ensure file is written after FileSize is set


<?php

namespace ATPCms\Model;

class Category extends \ATP\ActiveRecord
{
	protected function createDefinition()
	{
		$this->hasData('Name', 'Url', 'IsViewable', 'ShowPages', 'ShowInHeader', 'Text')
			->hasStaticBlocks()
			->hasPages()
			->isIdentifiedBy('Url')
			->tableNamespace("cms")
			->isOrderedBy("name ASC");
	}

	public function displayName()
	{
		return $this->name;
	}

	public static function headerCategories()
	{
		$where = "show_in_header=1";
		$cat = new self();
		return $cat->loadMultiple($where);
	}

	public function mostRecent($count)
	{
		$page = new Page();
		return $page->loadMultiple("category_id = ? AND is_active=1", array($this->id), array(), "post_date DESC");
	}
}
Category::init();

<?php

namespace ATPCms\Model;

class Category extends \ATP\ActiveRecord
{
	protected function createDefinition()
	{
		$this->hasData('Name', 'Url', 'IsViewable', 'ShowPages', 'ShowInHeader', 'Text')
			->hasStaticBlocks()
			->hasPages()
			->isIdentifiedBy('Url')
			->tableNamespace("cms")
			->isOrderedBy("name ASC");
	}

	public function displayName()
	{
		return $this->name;
	}

	public static function headerCategories()
	{
		$where = "show_in_header=1";
		$cat = new self();
		return $cat->loadMultiple($where);
	}

	public function mostRecent($count)
	{
		$page = new Page();
		return $page->loadMultiple("category_id = ? AND is_active=1", array($this->id), array(), "post_date DESC", $count);
	}
}
Category::init();

Add count param to mostRecent()

Add count param to mostRecent()


<?php

abstract class Userbin_TestCase extends \PHPUnit_Framework_TestCase
{
  public function assertRequest($method, $url, $headers=null)
  {
    $request = Userbin_RequestTransport::getLastRequest();
    $this->assertTrue($request['method'] == $method && $request['url'] == Userbin_Request::apiUrl($url));
    if (is_array($headers)) {
      foreach ($headers as $key => $value) {
        $this->assertTrue(array_key_exists($key, $request['headers']));
        $this->assertEquals($request['headers'][$key], $value);
      }
    }
  }
}

require(dirname(__FILE__) . '/../lib/Userbin/Userbin.php');
require(dirname(__FILE__) . '/../lib/Userbin/Errors.php');
require(dirname(__FILE__) . '/../lib/Userbin/SessionAdapter.php');
require(dirname(__FILE__) . '/../lib/Userbin/Models/Resource.php');
require(dirname(__FILE__) . '/../lib/Userbin/Models/Model.php');
require(dirname(__FILE__) . '/../lib/Userbin/Models/Challenge.php');
require(dirname(__FILE__) . '/../lib/Userbin/Models/Session.php');
require(dirname(__FILE__) . '/../lib/Userbin/Models/User.php');
require(dirname(__FILE__) . '/../lib/Userbin/JWT.php');
require(dirname(__FILE__) . '/TestTransport.php');
require(dirname(__FILE__) . '/../lib/Userbin/Request.php');

?>

<?php

abstract class Userbin_TestCase extends \PHPUnit_Framework_TestCase
{
  public function assertRequest($method, $url, $headers=null)
  {
    $request = Userbin_RequestTransport::getLastRequest();
    $this->assertTrue($request['method'] == $method && $request['url'] == Userbin_Request::apiUrl($url));
    if (is_array($headers)) {
      foreach ($headers as $key => $value) {
        $this->assertArrayHasKey($key, $request['headers']);
        $this->assertEquals($request['headers'][$key], $value);
      }
    }
  }
}

require(dirname(__FILE__) . '/../lib/Userbin/Userbin.php');
require(dirname(__FILE__) . '/../lib/Userbin/Errors.php');
require(dirname(__FILE__) . '/../lib/Userbin/SessionAdapter.php');
require(dirname(__FILE__) . '/../lib/Userbin/Models/Resource.php');
require(dirname(__FILE__) . '/../lib/Userbin/Models/Model.php');
require(dirname(__FILE__) . '/../lib/Userbin/Models/Challenge.php');
require(dirname(__FILE__) . '/../lib/Userbin/Models/Session.php');
require(dirname(__FILE__) . '/../lib/Userbin/Models/User.php');
require(dirname(__FILE__) . '/../lib/Userbin/JWT.php');
require(dirname(__FILE__) . '/TestTransport.php');
require(dirname(__FILE__) . '/../lib/Userbin/Request.php');

?>

Correct test helper in request test

Correct test helper in request test


<?php
/**
 * Slim Framework (http://slimframework.com)
 *
 * @link      https://github.com/codeguy/Slim
 * @copyright Copyright (c) 2011-2015 Josh Lockhart
 * @license   https://github.com/codeguy/Slim/blob/master/LICENSE (MIT License)
 */
namespace Slim\Handlers\Strategies;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Interfaces\InvocationStrategyInterface;

/**
 * Default route callback strategy with route parameters as an array of arguments.
 */
class RequestResponse implements InvocationStrategyInterface
{
    /**
     * Invoke a route callable with request, response, and all route parameters
     * as an array of arguments.
     *
     * @param array|callable         $callable
     * @param ServerRequestInterface $request
     * @param ResponseInterface      $response
     * @param array                  $routeArguments
     *
     * @return mixed
     */
    public function __invoke(
        callable $callable,
        ServerRequestInterface $request,
        ResponseInterface $response,
        array $routeArguments
    ) {
        foreach ($routeArguments as $k => $v) {
            $request = $request->withAttribute($k, $v);
        }

        return $callable($request, $response, $routeArguments);
    }
}

<?php
/**
 * Slim Framework (http://slimframework.com)
 *
 * @link      https://github.com/codeguy/Slim
 * @copyright Copyright (c) 2011-2015 Josh Lockhart
 * @license   https://github.com/codeguy/Slim/blob/master/LICENSE (MIT License)
 */
namespace Slim\Handlers\Strategies;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Interfaces\InvocationStrategyInterface;

/**
 * Default route callback strategy with route parameters as an array of arguments.
 */
class RequestResponse implements InvocationStrategyInterface
{
    /**
     * Invoke a route callable with request, response, and all route parameters
     * as an array of arguments.
     *
     * @param array|callable         $callable
     * @param ServerRequestInterface $request
     * @param ResponseInterface      $response
     * @param array                  $routeArguments
     *
     * @return mixed
     */
    public function __invoke(
        callable $callable,
        ServerRequestInterface $request,
        ResponseInterface $response,
        array $routeArguments
    ) {
        foreach ($routeArguments as $k => $v) {
            $request = $request->withAttribute($k, $v);
        }

        return call_user_func($callable, $request, $response, $routeArguments);
    }
}

Fix bug, a callable defined as 'class::method' is not possible


<?php

namespace filsh\yii2\oauth2server\controllers;

use Yii;
use yii\helpers\ArrayHelper;
use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter;

class DefaultController extends \yii\rest\Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'exceptionFilter' => [
                'class' => ErrorToExceptionFilter::className()
            ],
        ]);
    }

    public function actionToken()
    {
        $server = $this->module->getServer();
        $request = $this->module->getRequest();
        $response = $server->handleTokenRequest($request);

        return $response->getParameters();
    }
}

<?php

namespace filsh\yii2\oauth2server\controllers;

use Yii;
use yii\helpers\ArrayHelper;
use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter;

class DefaultController extends \yii\rest\Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
									  'exceptionFilter' => [
										  'class' => ErrorToExceptionFilter::className()
									  ],
        ]);
    }

    public function actionToken()
    {
        $server = $this->module->getServer();
        $request = $this->module->getRequest();
        $response = $server->handleTokenRequest($request);

		//Set cache control headers
		Yii::$app->response->headers['Cache-Control'] = 'no-cache';
		Yii::$app->response->headers['Pragma'] = 'no-cache';

		return $response->getParameters();
    }
}

Add no Cache-Control header to set it to 'no-cache'


<?php
namespace Oro\Bundle\FlexibleEntityBundle\Form\Type;

use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Form\FormBuilderInterface;

class EmailType extends CollectionItemAbstract
{
    const TYPE_CORPORATE = 1;
    const TYPE_PERSONAL  = 2;

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('id', 'hidden');
        $builder->add(
            'data',
            'email',
            array(
                'constraints' => array(
                    new Email()
                )
            )
        );
        $builder->add(
            'type',
            'choice',
            array(
                'empty_value'   => 'Choose email type...',
                'empty_data'    => null,
                'choice_list'   => new ChoiceList(
                    array_keys(self::getTypesArray()),
                    array_values(self::getTypesArray())
                ),
                'attr' => array ('class' => 'oro-multiselect')
            )
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getTypesArray()
    {
        return array(
            self::TYPE_CORPORATE => 'Сorporate email',
            self::TYPE_PERSONAL  => 'Personal email'
        );
    }

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

<?php
namespace Oro\Bundle\FlexibleEntityBundle\Form\Type;

use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Form\FormBuilderInterface;

class EmailType extends CollectionItemAbstract
{
    const TYPE_CORPORATE = 1;
    const TYPE_PERSONAL  = 2;

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('id', 'hidden');
        $builder->add(
            'data',
            'email'
        );
        $builder->add(
            'type',
            'choice',
            array(
                'empty_value'   => 'Choose email type...',
                'empty_data'    => null,
                'choice_list'   => new ChoiceList(
                    array_keys(self::getTypesArray()),
                    array_values(self::getTypesArray())
                ),
                'attr' => array ('class' => 'oro-multiselect')
            )
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getTypesArray()
    {
        return array(
            self::TYPE_CORPORATE => 'Сorporate email',
            self::TYPE_PERSONAL  => 'Personal email'
        );
    }

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

CRM-82: Apply forms JS validation
- remove constraint from email form type to fix tests