<?php
/**
 * Lazyload class
 */

class Lazyload {
    public static function LinkerMakeExternalImage(&$url, &$alt, &$img) {
        global $wgRequest;
        if (defined('MW_API') && $wgRequest->getVal('action') === 'parse') return true;
        $url = preg_replace('/^(http|https):/', '', $url);
        $img = ' ';
        return false;
    }

    public static function ThumbnailBeforeProduceHTML($thumb, &$attribs, &$linkAttribs) {
        global $wgRequest, $wgTitle;
        if (defined('MW_API') && $wgRequest->getVal('action') === 'parse') return true;
        if (isset($wgTitle) && $wgTitle->getNamespace() === NS_FILE) return true;
        $attribs['data-url'] = $attribs['src'];
        $attribs['src'] = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
        if (isset($attribs['srcset'])) {
            $attribs['data-srcset'] = $attribs['srcset'];
            unset($attribs['srcset']);
        }
        return true;
    }

    public static function BeforePageDisplay($out, $skin) {
        $out->addModules( 'ext.lazyload' );
        return true;
    }
}

<?php
/**
 * Lazyload class
 */

class Lazyload {
    public static function LinkerMakeExternalImage(&$url, &$alt, &$img) {
        global $wgRequest;
        if (defined('MW_API') && $wgRequest->getVal('action') === 'parse') return true;
        $url = preg_replace('/^(http|https):/', '', $url);
        $img = ' ';
        return false;
    }

    public static function ThumbnailBeforeProduceHTML($thumb, &$attribs, &$linkAttribs) {
        global $wgRequest, $wgTitle;
        if (defined('MW_API') && $wgRequest->getVal('action') === 'parse') return true;
        if (isset($wgTitle) && $wgTitle->getNamespace() === NS_FILE) return true;
        $attribs['data-url'] = $attribs['src'];
        $attribs['src'] = preg_replace('#/\d+px-#', '/10px-', $attribs['src']);
        if (isset($attribs['srcset'])) {
            $attribs['data-srcset'] = $attribs['srcset'];
            unset($attribs['srcset']);
        }
        return true;
    }

    public static function BeforePageDisplay($out, $skin) {
        $out->addModules( 'ext.lazyload' );
        return true;
    }
}

Replace Base64 with low quality placeholder

That should also fix MMV


<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Throwable  $e
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        return parent::render($request, $e);
    }
}

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        return parent::render($request, $e);
    }
}

Revert bad changes to the exception handler


<?php

namespace React\Promise\Internal;

/**
 * @internal
 */
final class CancellationQueue
{
    private $started = false;
    private $queue = [];

    public function __invoke(): void
    {
        if ($this->started) {
            return;
        }

        $this->started = true;
        $this->drain();
    }

    public function enqueue($cancellable): void
    {
        if (!\method_exists($cancellable, 'then') || !\method_exists($cancellable, 'cancel')) {
            return;
        }

        $length = \array_push($this->queue, $cancellable);

        if ($this->started && 1 === $length) {
            $this->drain();
        }
    }

    private function drain(): void
    {
        for ($i = \key($this->queue); isset($this->queue[$i]); $i++) {
            $cancellable = $this->queue[$i];

            $exception = null;

            try {
                $cancellable->cancel();
            } catch (\Throwable $exception) {
            }

            unset($this->queue[$i]);

            if ($exception) {
                throw $exception;
            }
        }

        $this->queue = [];
    }
}

<?php

namespace React\Promise\Internal;

/**
 * @internal
 */
final class CancellationQueue
{
    private $started = false;
    private $queue = [];

    public function __invoke(): void
    {
        if ($this->started) {
            return;
        }

        $this->started = true;
        $this->drain();
    }

    public function enqueue($cancellable): void
    {
        if (!\is_object($cancellable) || !\method_exists($cancellable, 'then') || !\method_exists($cancellable, 'cancel')) {
            return;
        }

        $length = \array_push($this->queue, $cancellable);

        if ($this->started && 1 === $length) {
            $this->drain();
        }
    }

    private function drain(): void
    {
        for ($i = \key($this->queue); isset($this->queue[$i]); $i++) {
            $cancellable = $this->queue[$i];

            $exception = null;

            try {
                $cancellable->cancel();
            } catch (\Throwable $exception) {
            }

            unset($this->queue[$i]);

            if ($exception) {
                throw $exception;
            }
        }

        $this->queue = [];
    }
}

Add check whether $cancellable is an object


<?php

    /**
     * PHPerian: PHP library for Experian's Web Services
     *
     * This is a convinience file for bootstrapping the library during testing.
     * Do not call this file if you are autoloading via Composer.
     *
     * @package     PHPerian
     * @category    Library
     * @author      Zander Baldwin <mynameiszanders@gmail.com>
     * @license     MIT/X11 <http://j.mp/mit-license>
     * @link        https://github.com/mynameiszanders/phperian/blob/develop/src/PHPerian.php
     */

    use PHPerian\TestLoader;

    require_once 'PHPerian/TestLoader.php';
    TestLoader::registerAutoloader();

<?php

    /**
     * PHPerian: PHP library for Experian's Web Services
     *
     * This is a convinience file for bootstrapping the library during testing.
     * Do not call this file if you are autoloading via Composer.
     *
     * @package     PHPerian
     * @category    Library
     * @author      Zander Baldwin <mynameiszanders@gmail.com>
     * @license     MIT/X11 <http://j.mp/mit-license>
     * @link        https://github.com/mynameiszanders/phperian/blob/develop/src/PHPerian.php
     */

    require_once 'PHPerian/TestLoader.php';
    \PHPerian\TestLoader::registerAutoloader();

Remove "use" statement. No point for it when the entire file just includes a file and executes one static method.


<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Foundation\Auth\VerifiesEmails;

class VerificationController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Email Verification Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling email verification for any
    | user that recently registered with the application. Emails may also
    | be resent if the user did not receive the original email message.
    |
    */

    use VerifiesEmails;

    /**
     * Where to redirect users after verification.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }
}

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Routing\Controller;
use Illuminate\Foundation\Auth\VerifiesEmails;

class VerificationController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Email Verification Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling email verification for any
    | user that recently registered with the application. Emails may also
    | be resent if the user did not receive the original email message.
    |
    */

    use VerifiesEmails;

    /**
     * Where to redirect users after verification.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }
}

Remove unnecessary use on verification controller


<?php

if (! function_exists('public_path')) {
    /**
     * Get the path to the public folder.
     *
     * @param  string  $path
     * @return string
     */
    function public_path($path = '')
    {
        return 'source'.($path ? DIRECTORY_SEPARATOR.$path : $path);
    }
}

if (! function_exists('elixir')) {
    /**
     * Get the path to a versioned Elixir file.
     *
     * @param  string  $file
     * @param  string  $buildDirectory
     * @return string
     *
     * @throws \InvalidArgumentException
     */
    function elixir($file, $buildDirectory = 'build')
    {
        static $manifest;
        static $manifestPath;

        if (is_null($manifest) || $manifestPath !== $buildDirectory) {
            $manifest = json_decode(file_get_contents(public_path($buildDirectory.'/rev-manifest.json')), true);

            $manifestPath = $buildDirectory;
        }

        if (isset($manifest[$file])) {
            return '/'.trim($buildDirectory.'/'.$manifest[$file], '/');
        }

        return $file;

        throw new InvalidArgumentException("File {$file} not defined in asset manifest.");
    }
}

<?php

if (! function_exists('public_path')) {
    /**
     * Get the path to the public folder.
     *
     * @param  string  $path
     * @return string
     */
    function public_path($path = '')
    {
        return 'source'.($path ? DIRECTORY_SEPARATOR.$path : $path);
    }
}

if (! function_exists('elixir')) {
    /**
     * Get the path to a versioned Elixir file.
     *
     * @param  string  $file
     * @param  string  $buildDirectory
     * @return string
     *
     * @throws \InvalidArgumentException
     */
    function elixir($file, $buildDirectory = 'build')
    {
        static $manifest;
        static $manifestPath;

        if (is_null($manifest) || $manifestPath !== $buildDirectory) {
            $manifest = json_decode(file_get_contents(public_path($buildDirectory.'/rev-manifest.json')), true);

            $manifestPath = $buildDirectory;
        }

        if (isset($manifest[$file])) {
            return '/'.trim($buildDirectory.'/'.$manifest[$file], '/');
        }

        throw new InvalidArgumentException("File {$file} not defined in asset manifest.");
    }
}

Allow exception to be thrown in `elixir` helper


<script type="text/javascript">
    // initializiation of counters for new elements
    var lastStudent = 0;

    // the subviews rendered with placeholders
    var trStudent = new String(<?php echo CJSON::encode($this->renderPartial('form/_studentRow', array('id' => 'idRep', 'model' => new Student, 'form' => $form, 'this' => $this), true, false)); ?>);

    function addStudent(button)
    {
        lastStudent++;
        button.parents('table').children('tbody').append(trStudent.replace(/idRep/g, 'newRow' + lastStudent));
    }

    function deleteStudent(button)
    {
        button.parents('tr').detach();
    }

</script>

<?php

Yii::app()->clientScript->registerScript('studentRow', "var lastStudent = 0;
    var trStudent = new String(" .
        CJSON::encode($this->renderPartial('form/_studentRow', array('id' => 'idRep', 'model' => new Student, 'form' => $form, 'this' => $this), true, false)) .
        ");
    function addStudent(button)
    {
        lastStudent++;
        button.parents('table').children('tbody').append(trStudent.replace(/idRep/g, 'newRow' + lastStudent));
    }

    function deleteStudent(button)
    {
        button.parents('tr').detach();
    }
");
?>

Use clientScript->registerScript to register the javascript otherwise it gives problems on pages where other javascript files are included.


<?php

namespace Backend\Modules\Blog\Tests\Action;

use Backend\Modules\Tags\DataFixtures\LoadTagsModulesTags;
use Backend\Modules\Tags\DataFixtures\LoadTagsTags;
use Common\WebTestCase;

class EditTest extends WebTestCase
{
    public function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Backend');
        }

        $client = self::createClient();
        $this->loadFixtures(
            $client,
            [
                LoadTagsTags::class,
                LoadTagsModulesTags::class,
            ]
        );
    }

    public function testAuthenticationIsNeeded(): void
    {
        $client = static::createClient();
        $this->logout($client);

        $client->setMaxRedirects(1);
        $client->request('GET', '/private/en/tags/edit?id=1');

        // we should get redirected to authentication with a reference to the wanted page
        $this->assertStringEndsWith(
            '/private/en/authentication?querystring=%2Fprivate%2Fen%2Ftags%2Fedit%3Fid%3D1',
            $client->getHistory()->current()->getUri()
        );
    }
}

<?php

namespace Backend\Modules\Blog\Tests\Action;

use Backend\Modules\Tags\DataFixtures\LoadTagsModulesTags;
use Backend\Modules\Tags\DataFixtures\LoadTagsTags;
use Common\WebTestCase;

class EditTest extends WebTestCase
{
    public function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Backend');
        }

        $client = self::createClient();
        $this->loadFixtures(
            $client,
            [
                LoadTagsTags::class,
                LoadTagsModulesTags::class,
            ]
        );
    }

    public function testAuthenticationIsNeeded(): void
    {
        $client = static::createClient();
        $this->logout($client);

        $client->setMaxRedirects(1);
        $client->request('GET', '/private/en/tags/edit?id=1');

        // we should get redirected to authentication with a reference to the wanted page
        $this->assertStringEndsWith(
            '/private/en/authentication?querystring=%2Fprivate%2Fen%2Ftags%2Fedit%3Fid%3D1',
            $client->getHistory()->current()->getUri()
        );
    }

    public function testWeCanGoToEditFromTheIndexPage(): void
    {
        $client = static::createClient();
        $this->login($client);

        $crawler = $client->request('GET', '/private/en/tags/index');
        $this->assertContains(
            'most used',
            $client->getResponse()->getContent()
        );

        $link = $crawler->selectLink('most used')->link();
        $client->click($link);

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertContains(
            '&id=2',
            $client->getHistory()->current()->getUri()
        );
    }
}

Test that we can go to the edit page of a tag from the index


My Regular Savings Accounts

<?php
if (isset($records)) : foreach ($records as $row) : ?>

Account Name

<?php echo $row->bank_name; ?>

Interest Rate

<?php echo $row->interest; ?>%

Monthly Deposits

£<?php echo $row->monthly_deposits; ?>

Age Of Account

    <?php
    $start_time = $row->start_date;
    $date1 = new DateTime('now');
    $date2 = new DateTime($start_time);
    echo $date1->diff($date2)->format
    ("%y years, %m months, %d days, %h hours, %i minuets and %s seconds");
    ?>

Total Balance To Date

    // p : principal
    // i : annual rate interest
    // c: compound
    // n : valid for
    // R : monthly deposit

    // calculate the terms that appear twice
    $x = $i / $c;
    $y = pow ( (1 + $x), ($n * $c) );

    $vf = $p * $y + ( ($R * $y - 1 ) / $x );

<?php endforeach; ?>

<?php else : ?>

No Accounts Added

Add Bank >

<?php endif; ?>

My Regular Savings Accounts

<?php
if (isset($records)) : foreach ($records as $row) : ?>

Account Name

<?php echo $row->bank_name; ?>

Interest Rate

<?php echo $row->interest; ?>%

Monthly Deposits

£<?php echo $row->monthly_deposits; ?>

Age Of Account

    <?php
    $start_time = $row->start_date;
    $date1 = new DateTime('now');
    $date2 = new DateTime($start_time);
   $age = ('echo $date1->diff($date2)->format');
    ("%y years, %m months, %d days, %h hours, %i minuets and %s seconds");
    ?>

Total Balance To Date

   <?php
    $p = 0;
    $i = $row->interest;
    $c = $row->compound_frequency;
    $n =
    ?>

    // i : annual rate interest
    // c: compound
    // n : valid for
    // R : monthly deposit

    // calculate the terms that appear twice
    $x = $i / $c;
    $y = pow ( (1 + $x), ($n * $c) );

    $vf = $p * $y + ( ($R * $y - 1 ) / $x );

<?php endforeach; ?>

<?php else : ?>

No Accounts Added

Add Bank >

<?php endif; ?>

UPDATE age of account now printing out

UPDATE age of account now printing out


<?php

/**
 * @group phriction
 */
final class PhrictionDocumentStatus extends PhrictionConstants {

  const STATUS_EXISTS     = 0;
  const STATUS_DELETED    = 1;
  const STATUS_STUB       = 3;

  public static function getConduitConstant($const) {
    static $map = array(
      self::STATUS_EXISTS   => 'exists',
      self::STATUS_DELETED   => 'deleted',
      self::STATUS_STUB      => 'stubbed',
    );

    return idx($map, $const, 'unknown');
  }

}

<?php

/**
 * @group phriction
 */
final class PhrictionDocumentStatus extends PhrictionConstants {

  const STATUS_EXISTS     = 0;
  const STATUS_DELETED    = 1;
  const STATUS_MOVED      = 2;
  const STATUS_STUB       = 3;

  public static function getConduitConstant($const) {
    static $map = array(
      self::STATUS_EXISTS   => 'exists',
      self::STATUS_DELETED   => 'deleted',
      self::STATUS_STUB      => 'stubbed',
    );

    return idx($map, $const, 'unknown');
  }

}

Define STATUS_MOVED constant ahead of its implementation

Summary: I landed some patches out of order and we haven't landed the one which actually implements this yet. Define the constant for now.

Test Plan: Deleted a page in Phriction without issue.

Reviewers: AnhNhan

Reviewed By: AnhNhan

CC: aran

Differential Revision: https://secure.phabricator.com/D5207


<?php namespace ProcessWire; ?>

        <a class="site__logo site__logo--reduced" href="<?=$homepage->httpUrl?>">
            <img srcset="<?=$homepage->image->get('name%=light')->size(92,92)->httpUrl?> 2x" src="<?=$homepage->image->get('name%=light')->size(180,180)->httpUrl?>" alt="" height="46" width="46">

            <? foreach ($homepage->children('template=page|overview') as $key => $child):?>

                <a class="<?= $child->id == $page->rootParent->id ? 'active' : ''?>" id="nav-<?=$child->name?>" href="<?=$child->url?>"><?=$child->title?>
            <? endforeach; ?>

        <form action="<?=$pages->get('/search/')->httpUrl?>" class="search" flex-end layout="row" layout-align="center center">
            <input type="text" name="for" size="20" placeholder="Search topics" value="<?=$input->get->for?>">
        </form>

<?php namespace ProcessWire; ?>

        <a class="site__logo site__logo--reduced" href="<?=$homepage->httpUrl?>">
            <img srcset="<?=$homepage->image->get('name%=light')->size(92,92)->httpUrl?> 2x" src="<?=$homepage->image->get('name%=light')->size(180,180)->httpUrl?>" alt="" height="46" width="46">

            <? foreach ($homepage->children('template=page|overview') as $key => $child):?>

                <a class="<?= $child->id == $page->rootParent->id ? 'active' : ''?>" id="nav-<?=$child->name?>" href="<?=$child->url?>"><?=$child->title?>
            <? endforeach; ?>

        <form action="<?=$pages->get('/search/')->httpUrl?>" class="search" flex-end layout="row" layout-align="center center">
            <input type="search" name="for" size="20" placeholder="Search topics" value="<?=$input->get->for?>">
        </form>

Make search a search input instead of text


<?php
/**
 * Arvici App Bootstrap.
 *
 * @author     Tom Valk <tomvalk@lt-box.info>
 * @copyright  2016 Tom Valk
 */

/**
 * Define the base directory containing the 'App' folder.
 */
defined('BASEPATH') || define('BASEPATH', __DIR__ . DS);

/**
 * Define all the paths in the base.
 */
defined('APPPATH') || define('APPPATH', BASEPATH . 'App' . DS);

/**
 * Load all configuration files.
 */
$configDir = APPPATH . '/Config/';
foreach (glob($configDir . '*.php') as $fileName) {
    require_once $fileName;
}

/**
 * Start the logger.
 */
\Logger::start();

/**
 * Start the router.
 */
\Arvici\Component\Router::getInstance()->run();

<?php
/**
 * Arvici App Bootstrap.
 *
 * @author     Tom Valk <tomvalk@lt-box.info>
 * @copyright  2016 Tom Valk
 */
use Arvici\Heart\Config\Configuration;

/**
 * Define the base directory containing the 'App' folder.
 */
defined('BASEPATH') || define('BASEPATH', __DIR__ . DS);

/**
 * Define all the paths in the base.
 */
defined('APPPATH') || define('APPPATH', BASEPATH . 'App' . DS);

/**
 * Load all configuration files.
 */
$configDir = APPPATH . '/Config/';
foreach (glob($configDir . '*.php') as $fileName) {
    require_once $fileName;
}

/**
 * Set default timezone
 */
date_default_timezone_set(Configuration::get('app.timezone', 'UTC'));

/**
 * Start the logger.
 */
\Logger::start();

/**
 * Start the router.
 */
\Arvici\Component\Router::getInstance()->run();

Set default timezone according to the configuration.


<?php namespace xp;

if (version_compare(PHP_VERSION, '5.4.0', '<')) {
  trigger_error('This version of the XP Framework requires PHP 5.4.0+, have PHP '.PHP_VERSION, E_USER_ERROR);
  exit(0x3d);
}

require __DIR__.DIRECTORY_SEPARATOR.'lang.base.php';

\lang\ClassLoader::registerPath(__DIR__);

<?php namespace xp;

if (version_compare(PHP_VERSION, '5.4.0', '<')) {
  trigger_error('This version of the XP Framework requires PHP 5.4.0+, have PHP '.PHP_VERSION, E_USER_ERROR);
  exit(0x3d);
}

$p= max(strrpos(__FILE__, DIRECTORY_SEPARATOR), strrpos(__FILE__, '?'));
require substr(__FILE__, 0, $p + 1).'lang.base.php';

\lang\ClassLoader::getDefault();

Fix loading from xar file

Fix loading from xar file


<?php

namespace UBC\Exam\MainBundle\EventListener;

use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use UBC\LtCommons\Service\StudentService;

class CourseInjectionListener {
    protected $session;
    protected $service;

    public function __construct(Session $session, StudentService $service)
    {
        $this->session = $session;
        $this->service = $service;
    }

    public function onLoginSuccess(InteractiveLoginEvent $event)
    {
        $courses = array();
        $user = $event->getAuthenticationToken()->getUser();
        // ignore the in_memory user
        if ($user instanceof \UBC\Exam\MainBundle\Entity\User) {
            $id = $user->getPuid();

            if (!empty($id)) {
                // TODO don't throw exceptions on 404
                $sections = $this->service->getStudentCurrentSections($id);

                foreach($sections as $s) {
                    $key = $s->getCourse()->getCode() . ' ' . $s->getCourse()->getNumber();
                    $courses[$key] = $s->getCourse();
                }
            }
        }

        $this->session->set('courses', $courses);
    }
}

<?php

namespace UBC\Exam\MainBundle\EventListener;

use GuzzleHttp\Exception\ClientException;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use UBC\LtCommons\Service\StudentService;

class CourseInjectionListener {
    protected $session;
    protected $service;

    public function __construct(Session $session, StudentService $service)
    {
        $this->session = $session;
        $this->service = $service;
    }

    public function onLoginSuccess(InteractiveLoginEvent $event)
    {
        $courses = array();
        $user = $event->getAuthenticationToken()->getUser();
        // ignore the in_memory user
        if ($user instanceof \UBC\Exam\MainBundle\Entity\User) {
            $id = $user->getPuid();

            if (!empty($id)) {
                try {
                    $sections = $this->service->getStudentCurrentSections($id);
                } catch (ClientException $e) {
                    // the user may not exists in SIS
                    if (404 == $e->getResponse()->getStatusCode()) {
                        $sections = array();
                    } else {
                        throw $e;
                    }
                }

                foreach($sections as $s) {
                    $key = $s->getCourse()->getCode() . ' ' . $s->getCourse()->getNumber();
                    $courses[$key] = $s->getCourse();
                }
            }
        }

        $this->session->set('courses', $courses);
    }
}

Handle 404 when user doesn't exist in SIS


<?php
namespace KDambekalns\Faker;

/*                                                                        *
 * This script belongs to the Flow package "Faker".                       *
 *                                                                        */

/**
 * Faker class for the Faker package
 *
 * The Faker package is based on http://faker.rubyforge.org/
 */
class Faker
{
    /**
     * Replace all # characters in $string with a random digit.
     *
     * @param string $string
     * @return string
     */
    public static function numerify($string)
    {
        return preg_replace('/#/e', 'rand(0,9)', $string);
    }

    /**
     * Replace all ? characters in $string with a random char (a-z).
     *
     * @param string $string
     * @return string
     */
    public static function letterify($string)
    {
        return preg_replace('/\?/e', 'chr(rand(97,122))', $string);
    }

    /**
     * Return the combined result of letterify() and numerify().
     *
     * @param string $string
     * @return string
     */
    public static function bothify($string)
    {
        return static::letterify(static::numerify($string));
    }
}

<?php
namespace KDambekalns\Faker;

/*                                                                        *
 * This script belongs to the Flow package "Faker".                       *
 *                                                                        */

/**
 * Faker class for the Faker package
 *
 * The Faker package is based on http://faker.rubyforge.org/
 */
class Faker
{
    /**
     * Replace all # characters in $string with a random digit.
     *
     * @param string $string
     * @return string
     */
    public static function numerify($string)
    {
        return preg_replace_callback('/#/', function() { return rand(0,9); }, $string);
    }

    /**
     * Replace all ? characters in $string with a random char (a-z).
     *
     * @param string $string
     * @return string
     */
    public static function letterify($string)
    {
        return preg_replace_callback('/\?/', function() { return chr(rand(97,122)); }, $string);
    }

    /**
     * Return the combined result of letterify() and numerify().
     *
     * @param string $string
     * @return string
     */
    public static function bothify($string)
    {
        return static::letterify(static::numerify($string));
    }
}

BUGFIX: Fix deprecated e modifier in preg_replace

With PHP 7, Faker issued the following warning:
preg_replace(): The /e modifier is no longer supported, use preg_replace_callback instead


<?php

class AddMailTest extends PHPUnit_Extensions_Selenium2TestCase
{
    protected function setUp()
    {
        $this->setHost('127.0.0.1');
        $this->setBrowser('firefox');
        $this->setBrowserUrl('http://mail-sender.dev');
    }

    public function setUpPage()
    {
        $this->url('/mail_sender.php?page=add_mail');

        $passwordField = $this->byId('pass');
        $passwordField->value('admin');

        $this->byId('OK')->click();
    }

    /**
     * @dataProvider emailProvider
     */
    public function testAddMail($mail, $expectedMessage)
    {
        $this->url('/mail_sender.php?page=add_mail');

        $emailField = $this->byName('n_mail');
        $emailField->value($mail);

        $button = $this->byName('add_mail');

        $button->click();

        $this->assertContains($expectedMessage, $this->source());
    }

    public function emailProvider()
    {
        return array(
            array('', 'Niepoprawne mail!'),
            array('some@', 'Niepoprawne mail!'),
            array('some@email', 'Niepoprawne mail!'),
            array('some@email.com', 'Maila dodano do bazy!'),
            array('some@email.com', 'Zapytanie ofertowe wysłano ponownie!'),
        );
    }
}

<?php

class AddMailTest extends PHPUnit_Extensions_Selenium2TestCase
{
    protected function setUp()
    {
        $this->setHost('127.0.0.1');
        $this->setBrowser('firefox');
        $this->setBrowserUrl('http://mail-sender.dev');
    }

    public function setUpPage()
    {
        $this->url('/mail_sender.php?page=add_mail');

        $passwordField = $this->byId('pass');
        $passwordField->value('admin');

        $this->byId('OK')->click();
    }

    /**
     * @dataProvider emailScenarios
     */
    public function testAddMail($mail, $expectedMessage)
    {
        $this->url('/mail_sender.php?page=add_mail');

        $emailField = $this->byName('n_mail');
        $emailField->value($mail);

        $button = $this->byName('add_mail');

        $button->click();

        $this->assertContains($expectedMessage, $this->source());
    }

    public function emailScenarios()
    {
        return array(
            array('', 'Niepoprawne mail!'),
            array('some@', 'Niepoprawne mail!'),
            array('some@email', 'Niepoprawne mail!'),
            array('some@email.com', 'Maila dodano do bazy!'),
            array('some@email.com', 'Zapytanie ofertowe wysłano ponownie!'),
        );
    }
}

Change data provider name for add email test


<?php
namespace wcf\util\exception;
use wcf\system\exception\IExtraInformationException;
use wcf\system\exception\SystemException;
use wcf\util\HTTPRequest;
use wcf\util\StringUtil;

/**
 * Denotes failure to perform a HTTP request.
 *
 * @author	Tim Duesterhus
 * @copyright	2001-2018 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Util\Exception
 * @since	3.0
 */
class HTTPException extends SystemException implements IExtraInformationException {
	/**
	 * The HTTP request that lead to this Exception.
	 *
	 * @param	HTTPRequest
	 */
	protected $http = null;

	/**
	 * @inheritDoc
	 */
	public function __construct(HTTPRequest $http, $message, $code = 0, $previous = null) {
		parent::__construct($message, $code, '', $previous);

		$this->http = $http;
	}

	/**
	 * @inheritDoc
	 */
	public function getExtraInformation() {
		$reply = $this->http->getReply();
		$body = StringUtil::truncate(preg_replace('/[\x00-\x1F\x80-\xFF]/', '.', $reply['body']), 512, StringUtil::HELLIP, true);

		return [
			['Body', $body],
			['Status Code', $reply['statusCode']]
		];
	}
}

<?php
namespace wcf\util\exception;
use wcf\system\exception\IExtraInformationException;
use wcf\system\exception\SystemException;
use wcf\util\HTTPRequest;
use wcf\util\StringUtil;

/**
 * Denotes failure to perform a HTTP request.
 *
 * @author	Tim Duesterhus
 * @copyright	2001-2018 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Util\Exception
 * @since	3.0
 */
class HTTPException extends SystemException implements IExtraInformationException {
	/**
	 * The HTTP request that lead to this Exception.
	 *
	 * @param	HTTPRequest
	 */
	protected $http = null;

	/**
	 * @inheritDoc
	 */
	public function __construct(HTTPRequest $http, $message, $code = 0, $previous = null) {
		parent::__construct($message, $code, '', $previous);

		$this->http = $http;
	}

	/**
	 * @inheritDoc
	 */
	public function getExtraInformation() {
		$reply = $this->http->getReply();
		$body = StringUtil::truncate(preg_replace('/[\x00-\x1F\x80-\xFF]/', '.', $reply['body']), 2048, StringUtil::HELLIP, true);

		return [
			['Body', $body],
			['Status Code', $reply['statusCode']]
		];
	}
}

Increase length of logged request responses in `HTTPException`


<?php
require_once(dirname(dirname(__FILE__)) . '/src/t1st3/JSONMin/JSONMin.php');
use t1st3\JSONMin\JSONMin as jsonMin;

class JSONMinTest extends PHPUnit_Framework_TestCase
{

  public function testMinifies () {
    $a = jsonMin::minify('{"a": "b"}');
    $this->assertEquals('{"a":"b"}', $a);
  }

}
?>

<?php
require_once(dirname(dirname(__FILE__)) . '/src/t1st3/JSONMin/JSONMin.php');
use t1st3\JSONMin\JSONMin as jsonMin;

class JSONMinTest extends PHPUnit_Framework_TestCase
{
  public function provideJson()
  {
      yield [
          '{"a": "b"}',
          '{"a":"b"}',
      ];
  }

  /**
   * @dataProvider provideJson
   */
  public function testMinifies ($json, $expectedResult) {
    $a = jsonMin::minify($json);
    $this->assertEquals($expectedResult, $a);
  }

}
?>

Refactor unit test to use data provider

Refactor unit test to use data provider


<?php

namespace NyroDev\UtilityBundle\Form\Type;

use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\CallbackTransformer;

class ConfigType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->addModelTransformer(new CallbackTransformer(
                function ($original) {
                    return $original && is_array($original) ? json_encode($original) : $original;
                },
                function ($submitted) {
                    $ret = null;
                    if ($submitted) {
                        $ret = json_decode($submitted, true);
                        if (!$ret) {
                            $ret = false;
                        }
                    }

                    return $ret;
                }
            ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);
        $resolver
            ->setDefault('constraints', array(
                new \NyroDev\UtilityBundle\Validator\Constraints\ValidConfig(),
            ));
    }

    public function getParent()
    {
        return TextareaType::class;
    }
}

<?php

namespace NyroDev\UtilityBundle\Form\Type;

use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\CallbackTransformer;

class ConfigType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->addModelTransformer(new CallbackTransformer(
                function ($original) {
                    return is_array($original) ? json_encode($original) : $original;
                },
                function ($submitted) {
                    $ret = null;
                    if ($submitted) {
                        $ret = json_decode($submitted, true);
                        if (!is_array($ret)) {
                            $ret = false;
                        }
                    }

                    return $ret;
                }
            ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);
        $resolver
            ->setDefault('constraints', array(
                new \NyroDev\UtilityBundle\Validator\Constraints\ValidConfig(),
            ));
    }

    public function getParent()
    {
        return TextareaType::class;
    }
}

Fix configType to check only for array

Fix configType to check only for array


<?php

/**
 * An example build task that publishes a bunch of pages - this demonstrates a realworld example of how the
 * queued jobs project can be used
 *
 *
 * @author Marcus Nyeholt <marcus@silverstripe.com.au>
 * @license BSD http://silverstripe.org/bsd-license/
 */
class PublishItemsTask extends BuildTask
{
    public function run($request) {
		$root = $request->getVar('parent');
		if (!$root) {
			throw new Exception("Sorry, you must provide a parent node to publish from");
		}

		$item = DataObject::get_by_id('Page', $root);

		if ($item) {
			$job = new PublishItemsJob($item);
			singleton('QueuedJobService')->queueJob($job);
		}
	}
}

<?php

/**
 * An example build task that publishes a bunch of pages - this demonstrates a realworld example of how the
 * queued jobs project can be used
 *
 *
 * @author Marcus Nyeholt <marcus@silverstripe.com.au>
 * @license BSD http://silverstripe.org/bsd-license/
 */
class PublishItemsTask extends BuildTask
{
    public function run($request) {
		$root = $request->getVar('parent');
		if (!$root) {
			throw new Exception("Sorry, you must provide a parent node to publish from");
		}

		$item = DataObject::get_by_id('Page', $root);

		if ($item && $item->exists()) {
			$job = new PublishItemsJob($root);
			singleton('QueuedJobService')->queueJob($job);
		}
	}
}

Update task to start queuedjob as per previous request...


        </div>
        <footer id="footer" class="panel-footer">
            <?php
                include 'footer/profiling.php';
            ?>
        </footer>
    </body>
</html>

        </div>
        <footer id="footer" class="panel-footer">
            <?php
                include 'views/footer/profiling.php';
            ?>
        </footer>
    </body>
</html>

Fix wrong path in footer include of profiling file


<?php

/**
 * Description of TelegramBotApi
 *
 * @author iman
 */

namespace Shaygan\TelegramBotApiBundle;

use Symfony\Component\DependencyInjection\Container;
use TelegramBot\Api\BotApi;

class TelegramBotApi extends BotApi
{

    public function __construct(Container $container)
    {
        $token = $container->getParameter('shaygan_telegram_bot_api.config');
//        var_dump($token);
        parent::__construct($token['token']);
    }

}

<?php

/**
 * Description of TelegramBotApi
 *
 * @author iman
 */

namespace Shaygan\TelegramBotApiBundle;

use Symfony\Component\DependencyInjection\Container;
use TelegramBot\Api\BotApi;

class TelegramBotApi extends BotApi
{

    public function __construct(Container $container)
    {
        $token = $container->getParameter('shaygan_telegram_bot_api.config');
//        var_dump($token);
        parent::__construct($token['token']);
    }

    /**
     * @param string $token
     */
    public function setToken($token)
    {
        $this->token = $token;
    }

}

Add setToken to the service

Add setToken to the service


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

class Jelly_Field_Boolean extends Jelly_Field
{
	/**
	 * @var mixed How TRUE is represented in the database
	 */
	public $true = 1;

	/**
	 * @var string How TRUE is represented to users (mainly in forms)
	 */
	public $pretty_true = "Yes";

	/**
	 * @var stringHow FALSE is represented in the database
	 */
	public $false = 0;

	/**
	 * @var string How FALSE is represented to users (mainly in forms)
	 */
	public $pretty_false = "No";

	/**
	 * Validates a boolean out of the value with filter_var
	 *
	 * @param mixed $value
	 * @return void
	 * @author Jonathan Geiger
	 */
	public function set($value)
	{
		$this->value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
	}

	/**
	 * Returns the value as it should be represented in the database
	 *
	 * @param string $loaded
	 * @return void
	 * @author Jonathan Geiger
	 */
	public function save($loaded)
	{
		return ($this->value) ? $this->true : $this->false;
	}
}

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

class Jelly_Field_Boolean extends Jelly_Field
{
	/**
	 * @var mixed How TRUE is represented in the database
	 */
	public $true = 1;

	/**
	 * @var string How TRUE is represented to users (mainly in forms)
	 */
	public $pretty_true = __("Yes");

	/**
	 * @var stringHow FALSE is represented in the database
	 */
	public $false = 0;

	/**
	 * @var string How FALSE is represented to users (mainly in forms)
	 */
	public $pretty_false = __("No");

	/**
	 * Validates a boolean out of the value with filter_var
	 *
	 * @param mixed $value
	 * @return void
	 * @author Jonathan Geiger
	 */
	public function set($value)
	{
		$this->value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
	}

	/**
	 * Returns the value as it should be represented in the database
	 *
	 * @param string $loaded
	 * @return void
	 * @author Jonathan Geiger
	 */
	public function save($loaded)
	{
		return ($this->value) ? $this->true : $this->false;
	}
}

Add i18n for Boolean Field

Add i18n for Boolean Field


<?php // 101_parallel_async_requests.php

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

(new Alert\ReactorFactory)->select()->run(function($reactor) {
    $client = new Artax\Client($reactor);
    $startTime = microtime(true);
    $promises = [];

    foreach (range('a', 'z') as $alpha) {
        $uri = 'http://www.bing.com/search?q=' . $alpha;
        $promise = $client->request($uri);
        $promise->onResolution(function($error, $result) use ($reactor, $uri) {
            if ($error) {
                echo $error->getMessage(), "\n";
            } else {
                printf(
                    "HTTP/%s %d %s | %s\n",
                    $result->getProtocol(),
                    $result->getStatus(),
                    $result->getReason(),
                    $uri
                );
            }
        });
        $promises[$alpha] = $promise;
    }

    After\some($promises)->onResolution(function() use ($reactor, $startTime) {
        printf("26 parallel HTTP requests completed in %s seconds\n", microtime(true) - $startTime);
        $reactor->stop();
    });
});

<?php // 101_parallel_async_requests.php

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

(new Alert\ReactorFactory)->select()->run(function($reactor) {
    $client = new Artax\Client($reactor);
    $startTime = microtime(true);
    $promises = [];

    foreach (range('a', 'z') as $alpha) {
        $uri = 'http://www.bing.com/search?q=' . $alpha;
        $promise = $client->request($uri);
        $promise->onResolve(function($error, $result) use ($reactor, $uri) {
            if ($error) {
                echo $error->getMessage(), "\n";
            } else {
                printf(
                    "HTTP/%s %d %s | %s\n",
                    $result->getProtocol(),
                    $result->getStatus(),
                    $result->getReason(),
                    $uri
                );
            }
        });
        $promises[$alpha] = $promise;
    }

    After\some($promises)->onResolve(function() use ($reactor, $startTime) {
        printf("26 parallel HTTP requests completed in %s seconds\n", microtime(true) - $startTime);
        $reactor->stop();
    });
});

Fix example code broken by After lib API changes


<?php

namespace Expressly\Event;

use Symfony\Component\EventDispatcher\Event;

class ResponseEvent extends Event
{
    private $response;

    public function getResponse()
    {
        return is_array($this->response) ? $this->response : json_decode($this->response, true);
    }

    public function setResponse($response)
    {
        $this->response = $response;

        return $this;
    }
}

<?php

namespace Expressly\Event;

use Symfony\Component\EventDispatcher\Event;

class ResponseEvent extends Event
{
    private $response;

    public function getResponse()
    {
        if (is_array($this->response)) {
            return $this->response;
        }

        return (json_last_error() == JSON_ERROR_NONE) ? json_decode($this->response, true) : $this->response;
    }

    public function setResponse($response)
    {
        $this->response = $response;

        return $this;
    }
}

Check for JSON errors when converting

Check for JSON errors when converting


<?php

namespace duncan3dc\Proxy;

use duncan3dc\Guzzle\Request;
use GuzzleHttp\Client;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class App
{
    private $client;

    public function __construct()
    {
        $this->client = new Client([
            "http_errors"   =>  false,
        ]);
    }

    public function run(): void
    {
        $request = $this->createRequest();

        $response = $this->client->send($request);

        $this->respond($response);
    }

    private function createRequest(): RequestInterface
    {
        $url = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];

        $request = Request::make($_SERVER["REQUEST_METHOD"], $url, [
            "headers"       =>  [
                "User-Agent"    =>  $_SERVER["HTTP_USER_AGENT"],
            ],
            "form_params"   =>  $_POST,
        ]);

        return $request;
    }

    private function respond(ResponseInterface $response): void
    {
        http_response_code($response->getStatusCode());
        header("Content-Type: " . $response->getHeader("content-type")[0]);
        echo $response->getBody();
    }
}

<?php

namespace duncan3dc\Proxy;

use duncan3dc\Guzzle\Request;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class App
{
    private $client;

    public function __construct()
    {
        $this->client = new Client([
            "http_errors"   =>  false,
        ]);
    }

    public function run(): void
    {
        $request = $this->createRequest();

        $response = $this->getResponse($request);

        $this->respond($response);
    }

    private function createRequest(): RequestInterface
    {
        $url = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];

        $request = Request::make($_SERVER["REQUEST_METHOD"], $url, [
            "headers"       =>  [
                "User-Agent"    =>  $_SERVER["HTTP_USER_AGENT"],
            ],
            "form_params"   =>  $_POST,
        ]);

        return $request;
    }

    private function getResponse(RequestInterface $request): ResponseInterface
    {
        try {
            $response = $this->client->send($request);
        } catch (\Throwable $e) {
            $response = $this->createErrorResponse($e);
        }

        return $response;
    }

    private function createErrorResponse(\Throwable $e): ResponseInterface
    {
        return new Response(500, ["Content-Type" => "text/plain"], $e->getMessage());
    }

    private function respond(ResponseInterface $response): void
    {
        http_response_code($response->getStatusCode());
        header("Content-Type: " . $response->getHeader("content-type")[0]);
        echo $response->getBody();
    }
}

Add a default error handler

Add a default error handler


<?php

use Illuminate\Routing\Router;

$router->group(['prefix' => '/setting'], function (Router $router) {
    $router->get('settings/{module}', ['as' => 'dashboard.module.settings', 'uses' => 'SettingController@getModuleSettings']);

    $router->resource('settings', 'SettingController', ['except' => ['show', 'edit', 'update', 'destroy', 'create'], 'names' => [
        'index' => 'admin.setting.settings.index',
        'store' => 'admin.setting.settings.store',
    ]]);
});

<?php

$router->group(['prefix' => '/setting'], function () {
    get('settings/{module}', ['as' => 'dashboard.module.settings', 'uses' => 'SettingController@getModuleSettings']);
    get('settings', ['as' => 'admin.setting.settings.index', 'uses' => 'SettingController@index']);
    post('settings', ['as' => 'admin.setting.settings.store', 'uses' => 'SettingController@store']);
});

Use manual route definition over the route resource shortcut


<?php namespace Laraplus\Form\Fields;

use Laraplus\Form\Fields\Base\Element;

class TextArea extends Element
{
    /**
     * @param string $cols
     * @return $this
     */
    public function cols($cols)
    {
        $this->attributes['cols'] = $cols;

        return $this;
    }

    /**
     * @param string $rows
     * @return $this
     */
    public function rows($rows)
    {
        $this->attributes['rows'] = $rows;

        return $this;
    }

    /**
     * @return string
     */
    public function render()
    {
        $attributes = $this->renderAttributes($this->attributes);

        return '<textarea' . $attributes . '>' . htmlspecialchars($this->getValue()) . '</textarea>';
    }
}

<?php namespace Laraplus\Form\Fields;

use Laraplus\Form\Fields\Base\Element;

class TextArea extends Element
{
    /**
     * @param string $cols
     * @return $this
     */
    public function cols($cols)
    {
        $this->attributes['cols'] = $cols;

        return $this;
    }

    /**
     * @param string $rows
     * @return $this
     */
    public function rows($rows)
    {
        $this->attributes['rows'] = $rows;

        return $this;
    }

    /**
     * @param string $placeholder
     * @return $this
     */
    public function placeholder($placeholder)
    {
        $this->attributes['placeholder'] = $placeholder;

        return $this;
    }

    /**
     * @return string
     */
    public function render()
    {
        $attributes = $this->renderAttributes($this->attributes);

        return '<textarea' . $attributes . '>' . htmlspecialchars($this->getValue()) . '</textarea>';
    }
}

Add placeholder attribute to textarea

Add placeholder attribute to textarea


<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    const VERSION = '0.8.6';
}

<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    public const VERSION = '0.8.7';
}

Set release version to 0.8.7

Set release version to 0.8.7


<?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use App\Trio;

class SolveTest extends DuskTestCase
{

    public function testCanSolveTrio()
    {
        $this->browse(function ($browser) {
            //Go to solve screen
            $browser->visit('/solve');
            $browser->pause(500);
            //Get current trio answer so we can answer correctly
            $trioId = $browser->text('#trio-id');
            sleep(1);
            $trio = Trio::findOrFail($trioId);
            $answer = $trio->answer;

            //Save first sentence so we can see if it changes later
            $sentence = $browser->value('#sentence1');
            //Input answer
            $browser->type('#answer', $answer);
            //Click check
            $browser->click('#check-button');
            //See if button changed
            $browser->assertSeeIn('#check-button', 'Correct, next trio');
            //Click again
            $browser->click('#check-button');
            //See if new trio is loaded
            $browser->assertDontSeeIn('#sentence1', $sentence);
            //See if buttons are reset
            //TODO
        });
    }
}

<?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use App\Trio;

class SolveTest extends DuskTestCase
{

    public function testCanSolveTrio()
    {
        $this->browse(function ($browser) {
            //Go to solve screen
            $browser->visit('/solve');
            $browser->pause(500);
            //Get current trio answer so we can answer correctly
            $trioId = $browser->text('#trio-id');
            sleep(1);
            $trio = Trio::findOrFail($trioId);
            $answer = $trio->answer;

            //Save first sentence so we can see if it changes later
            $sentence = $browser->value('#sentence1');
            //Input answer
            $browser->type('#answer', $answer);
            //Click check
            $browser->click('#check-button');
            sleep(1);
            //See if button changed
            $browser->assertSeeIn('#check-button', 'Correct, next trio');
            //Click again
            $browser->click('#check-button');
            //See if new trio is loaded
            $browser->assertDontSeeIn('#sentence1', $sentence);
            //See if buttons are reset
            //TODO
        });
    }
}

Fix tests (needed some delay)

Fix tests (needed some delay)


<?php

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';

// Use APC for autoloading to improve performance.
// Change 'sf2' to a unique prefix in order to prevent cache key conflicts
// with other applications also using APC.
/*
$loader = new ApcClassLoader('sf2', $loader);
$loader->register(true);
*/

require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', true);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';

// Use APC for autoloading to improve performance.
// Change 'sf2' to a unique prefix in order to prevent cache key conflicts
// with other applications also using APC.
/*
$loader = new ApcClassLoader('sf2', $loader);
$loader->register(true);
*/

require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Revert force debug on prod.

Revert force debug on prod.


<?php

namespace Alchemy\Zippy\Tests\Parser;

use Alchemy\Zippy\Parser\GNUTarOutputParser;
use Alchemy\Zippy\Tests\AbstractTestFramework;

class GNUTarOutputParserTest extends AbstractTestFramework
{
    public function testParse()
    {
        $parser = new GNUTarOutputParser();
        $this->assertEquals(array('hellow', 'world'), $parser->parseFileListing("\nhellow\nworld\n"));
        $this->assertEquals('2.8.3', $parser->parseVersion("bsdtar 2.8.3 - libarchive 2.8.3"));
    }
}

<?php

namespace Alchemy\Zippy\Tests\Parser;

use Alchemy\Zippy\Parser\GNUTarOutputParser;
use Alchemy\Zippy\Tests\AbstractTestFramework;
use Alchemy\Zippy\MemberInterface;

class GNUTarOutputParserTest extends AbstractTestFramework
{
    public function testNewParser()
    {
        return new GNUTarOutputParser();
    }

    /**
     * @depends testNewParser
     */
    public function testParseFileListing($parser)
    {
        $output = "drwxrwxrwx myself/user 0 May 31 21:49 1990 practice/
            -rw-rw-rw- myself/user 42 May 21 13:29 1990 practice/blues
            -rw-rw-rw- myself/user 62 May 23 10:55 1990 practice/folk
            -rw-rw-rw- myself/user 40 May 21 13:30 1990 practice/jazz
            -rw-rw-rw- myself/user 10240 May 31 21:48 1990 practice/records";

        $members = $parser->parseFileListing($output);

        $this->assertEquals(5, count($members));

        foreach ($members as $member) {
            $this->assertTrue($member instanceof MemberInterface);
        }

        $memberDirectory = array_shift($members);

        $this->assertTrue($memberDirectory->isDir());
        $this->assertEquals('practice/', $memberDirectory->getLocation());
        $this->assertEquals(0, $memberDirectory->getSize());
        $date = $memberDirectory->getLastModifiedDate();
        $this->assertTrue($date instanceof \DateTime);
        $this->assertEquals('644183340', $date->format("U"));

        $memberFile = array_pop($members);

        $this->assertFalse($memberFile->isDir());
        $this->assertEquals('practice/records', $memberFile->getLocation());
        $this->assertEquals(10240, $memberFile->getSize());
        $date = $memberFile->getLastModifiedDate();
        $this->assertTrue($date instanceof \DateTime);
        $this->assertEquals('644183280', $date->format("U"));
    }

    /**
     * @depends testNewParser
     */
    public function testParseVersion($parser)
    {
        $this->assertEquals('2.8.3', $parser->parseVersion("bsdtar 2.8.3 - libarchive 2.8.3"));
    }
}

Update Tar Parse adapter tests

Update Tar Parse adapter tests


<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

use App;

class LoginTest extends TestCase
{
    use DatabaseMigrations;

    public function testBasicTest()
    {
        $this->get('/')->assertRedirect('/login');
    }

    public function testLoggedIn()
    {
        $user = factory(App\User::class)->create();
        $this->actingAs($user)->get('/')->assertStatus(200);
    }

    public function testLogout()
    {
        $user = factory(App\User::class)->create();
        $this->actingAs($user)->post('/logout')->assertRedirect('/');
    }
}

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

use App;

class LoginTest extends TestCase
{
    use DatabaseMigrations;

    public function testBasicTest()
    {
        $this->get('/')->assertRedirect('/login');
        $this->get('/', [ 'X-Requested-With' => 'XMLHttpRequest' ])
            ->assertStatus(401);
    }

    public function testLoggedIn()
    {
        $user = [
            'email' => 'example@example.com',
            'name' => 'Example',
            'password' => 'testtest',
        ];

        factory(App\User::class)->create($user);
        $this->post('/login', $user)->assertRedirect('/');
    }

    public function testLogout()
    {
        $user = factory(App\User::class)->create();
        $this->actingAs($user)->post('/logout')->assertRedirect('/');
    }
}

Add assertions for login test

Add assertions for login test


<?php
return array(
    'router' => array(
        'routes' => array(
            'admin' => array(
                'type' => 'literal',
                'options' => array(
                    'route'    => '/admin',
                    'defaults' => array(
                        'controller' => 'SlmCmfAdmin\Controller\AdminController',
                        'action'     => 'index',
                    ),
                ),
                'may_terminate' => true,
                'child_routes' => array(
                    'page-open' => array(
                        'type' => 'SlmCmfAdmin\Router\Http\Segment',
                        'options' => array(
                            'route' => '/page/open/:id[/:params]',
                            'defaults' => array(
                                'controller' => 'SlmCmfAdmin\Controller\PageController',
                                'action' => 'open'
                            ),
                        ),
                    ),
                ),
            ),
        ),
    ),

    'view_manager' => array(
        'template_map' => array(
            'layout/admin' => __DIR__ . '/../view/layout/admin.phtml',
        ),
        'template_path_stack' => array(
            __DIR__ . '/../view'
        ),
        'helper_map' => array(
            'slug' => 'SlmCmfUtils\View\Helper\Slug',
            'url'  => 'SlmCmfUtils\View\Helper\Url',
        ),
    ),
);

<?php
return array(
    'router' => array(
        'routes' => array(
            'admin' => array(
                'type' => 'literal',
                'options' => array(
                    'route'    => '/admin',
                    'defaults' => array(
                        'controller' => 'SlmCmfAdmin\Controller\AdminController',
                        'action'     => 'index',
                    ),
                ),
                'may_terminate' => true,
                'child_routes' => array(
                    'page-open' => array(
                        'type' => 'SlmCmfAdmin\Router\Http\Segment',
                        'options' => array(
                            'route' => '/page/open/:id[/:params]',
                            'defaults' => array(
                                'controller' => 'SlmCmfAdmin\Controller\PageController',
                                'action' => 'open'
                            ),
                        ),
                    ),
                ),
            ),
        ),
    ),

    'view_manager' => array(
        'template_map' => array(
            'layout/admin' => __DIR__ . '/../view/layout/admin.phtml',
        ),
        'template_path_stack' => array(
            __DIR__ . '/../view'
        ),
        'helper_map' => array(
            'adminPageTree' => 'SlmCmfAdmin\View\Helper\PageTree',
        ),
    ),
);

Add admin page tree view helper to helper map


<?php

/**
 * @author Michael Slyshkin <m.slyshkin@gmail.com>
 */

namespace RsORMTest\Query\Engine\MySQL\Builder;

use RsORMTest;
use RsORM\Query\Engine\MySQL\Builder;
use RsORM\Query\Engine\MySQL\Flag;

class DeleteTest extends RsORMTest\Base {

    public function testShort() {
        $query = Builder::delete()
                ->table("table");
        $stmt = $query->build();
        $this->assertSame("DELETE FROM `table`", $stmt->prepare());
        $this->assertSame([], $stmt->values());
    }

    public function testFull() {
        $query = Builder::delete()
                ->table("table")
                ->flags([new Flag\HighPriority()]);
        $query->table("table");
        $stmt = $query->build();
        $this->assertSame("DELETE FROM `table`", $stmt->prepare());
        $this->assertSame([], $stmt->values());
    }

}

<?php

/**
 * @author Michael Slyshkin <m.slyshkin@gmail.com>
 */

namespace RsORMTest\Query\Engine\MySQL\Builder;

use RsORMTest;
use RsORM\Query\Engine\MySQL\Builder;
use RsORM\Query\Engine\MySQL\Flag;

class DeleteTest extends RsORMTest\Base {

    public function testShort() {
        $query = Builder::delete()
                ->table("table");
        $stmt = $query->build();
        $this->assertSame("DELETE FROM `table`", $stmt->prepare());
        $this->assertSame([], $stmt->values());
    }

    public function testFull() {
        $filter = Builder::filter()
                ->eq("type", 123);
        $query = Builder::delete()
                ->table("table")
                ->limit(10, 20)
                ->order(["flag"])
                ->where($filter)
                ->flags([new Flag\HighPriority()]);
        $query->table("table");
        $stmt = $query->build();
        $this->assertSame("DELETE HIGH_PRIORITY FROM `table` WHERE `type` = ? ORDER BY `flag` LIMIT ?, ?", $stmt->prepare());
        $this->assertSame([123, 10, 20], $stmt->values());
    }
}

Fix builder delete test 2

Fix builder delete test 2


<?php

/**
 * @file
 * Template overrides as well as (pre-)process and alter hooks for the
 * UCLALIB Omega theme.
 */

/**
 * Implements template_preprocess_panels_pane().
 *
 * Add bean type as a class to bean panes.
 */
function uclalib_omega_preprocess_panels_pane(&$vars) {
  if ($vars['pane']->type == 'block') {
    if (isset($vars['content']['bean']) && is_array($vars['content']['bean'])) {
      $bean_info = current($vars['content']['bean']);
      $bean_type = $bean_info['#bundle'];
      $vars['classes_array'][] = drupal_html_class('bean--' . $bean_type);
    }
  }
}

<?php

/**
 * @file
 * Template overrides as well as (pre-)process and alter hooks for the
 * UCLALIB Omega theme.
 */

/**
 * Implements template_preprocess_panels_pane().
 *
 * Add bean type as a class to bean panes.
 */
function uclalib_omega_preprocess_panels_pane(&$vars) {
  if ($vars['pane']->type == 'block') {
    if (isset($vars['content']['bean']) && is_array($vars['content']['bean'])) {
      $bean_info = current($vars['content']['bean']);
      $bean_type = $bean_info['#bundle'];
      $bean_class = drupal_html_class('pane-bean-' . $bean_type);

      // Replace class 'pane-block' with more useful 'pane-bean-$bean-type';
      foreach ($vars['classes_array'] as $index => $block_class) {
        if ($block_class == 'pane-block') {
          $vars['classes_array'][$index] = $bean_class;
          break;
        }
      }
    }
  }
}

UCLALIB-58: Replace pane-block class with pane-bean- class.


<?php

namespace Helper;

use APIJet\Config;
use \PDO;

class Db
{
    private static $instance = null;
    private static $options = [
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ];

    private function __construct() {}
    private function __clone() {}

    public static function getInstance()
    {
        if (self::$instance === null) {
            $config = Config::getByName('Db');

            self::$instance = new PDO('mysql:host='.$config['hostname'].';dbname='.$config['database'],
                $config['username'],
                $config['password'],
                self::$options
            );
        }

        return self::$instance;
    }

    public static function execQuery($query, array $parameters = [])
    {
        $statement = self::getInstance()->prepare($query);
        $statement->execute($parameters);
        return $statement;
    }

    public static function getLimitQuery($limit, $offset)
    {
        $limit = (int) $limit;
        $offset = (int) $offset;

        return " LIMIT $offset, $limit ";
    }

    public static function getLastInsertId()
    {
        return self::getInstance()->lastInsertId();
    }
}

<?php

namespace Helper;

use APIJet\Config;
use \PDO;

class Db
{
    private static $instance = null;
    private static $options = [
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ];

    private function __construct() {}
    private function __clone() {}

    public static function getInstance()
    {
        if (self::$instance === null) {
            $config = Config::getByName('Db');

            self::$instance = new PDO('mysql:host='.$config['hostname'].';dbname='.$config['database'],
                $config['username'],
                $config['password'],
                self::$options
            );
        }

        return self::$instance;
    }

    public static function execQuery($query, array $parameters = [])
    {
        $statement = self::getInstance()->prepare($query);
        $statement->execute($parameters);
        return $statement;
    }

    public static function getLimitQuery($limit, $offset)
    {
        $limit = (int) $limit;
        $offset = (int) $offset;

        return " LIMIT ".($offset * $limit).", $limit ";
    }

    public static function getLastInsertId()
    {
        return self::getInstance()->lastInsertId();
    }
}

Fix in getLimitQuery not valid result

Fix in getLimitQuery not valid result


<?php

namespace Bamboo\Feeds;

use Bamboo\Models\Broadcast;

class Broadcasts extends BaseParallel
{

    protected $_feedName = '/channels/{channel_id}/broadcasts';
    protected $_feeds = array();
    protected $_responses;

    public function __construct($params, $channels) {
        $this->_feeds = $this->_buildFeeds($channels);
        parent::__construct($params);
    }

    public function getBroadcasts() {
        $channels = array();
        foreach ($this->_responses as $resp) {
            $id = $resp->broadcasts->channel->id;
            $channels[$id] = $this->_buildModels($resp->broadcasts->elements);
        }

        return $channels;
    }

    private function _buildFeeds($channels) {
        $feedName = $this->_feedName;
        if (!is_array($channels)) {
            $channels = array($channels);
        }
        return array_map(
            function ($channel) use ($feedName) {
                return str_replace("{channel_id}", $channel, $feedName);
            },
            $channels
        );
    }
}

<?php

namespace Bamboo\Feeds;

use Bamboo\Models\Broadcast;

class Broadcasts extends BaseParallel
{
    const TIME_FORMAT = 'Y-m-d\TH:i';
    protected $_feedName = '/channels/{channel_id}/broadcasts';
    protected $_feeds = array();
    protected $_responses;

    public function __construct($params, $channels) {
        $this->_feeds = $this->_buildFeeds($channels);
        parent::__construct($params);
    }

    public function getBroadcasts() {
        $channels = array();
        foreach ($this->_responses as $resp) {
            $id = $resp->broadcasts->channel->id;
            $channels[$id] = $this->_buildModels($resp->broadcasts->elements);
        }

        return $channels;
    }

    private function _buildFeeds($channels) {
        $feedName = $this->_feedName;
        if (!is_array($channels)) {
            $channels = array($channels);
        }
        return array_map(
            function ($channel) use ($feedName) {
                return str_replace("{channel_id}", $channel, $feedName);
            },
            $channels
        );
    }
}

Add request time format to the broadcasts feed


<?php

namespace Memvents;

use Illuminate\Database\Eloquent\Model;

class Event extends Model
{

    protected $table = 'events';

    protected $fillable = [
        'name',
        'event_id',
        'time',
        'status',
        'event_url',
        'created'
    ];
}

<?php

namespace Memvents;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class Event extends Model
{

    protected $table = 'events';

    protected $fillable = [
        'name',
        'event_id',
        'time',
        'status',
        'event_url',
        'created'
    ];

    public function getSampleEvents()
    {
        return Storage::get('sample_events.json');
    }
}

Add method to grab sample data json file


<?php declare(strict_types=1);

namespace Symplify\CodingStandard\Sniffs\Architecture;

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use Symplify\TokenRunner\Analyzer\SnifferAnalyzer\Naming;
use function Safe\sprintf;

final class PreferredClassSniff implements Sniff
{
    /**
     * @var string[]
     */
    public $oldToPreferredClasses = [];

    /**
     * @var Naming
     */
    private $naming;

    public function __construct(Naming $naming)
    {
        $this->naming = $naming;
    }

    /**
     * @return int[]
     */
    public function register(): array
    {
        return [T_STRING];
    }

    /**
     * @param int $position
     */
    public function process(File $file, $position): void
    {
        if ($this->oldToPreferredClasses === []) {
            return;
        }

        $className = $this->naming->getClassName($file, $position);
        if (! isset($this->oldToPreferredClasses[$className])) {
            return;
        }

        $preferredClass = $this->oldToPreferredClasses[$className];
        $file->addError(
            sprintf('Instead of "%s" class, use "%s"', $className, $preferredClass),
            $position,
            self::class
        );
    }
}

<?php declare(strict_types=1);

namespace Symplify\CodingStandard\Sniffs\Architecture;

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use Symplify\TokenRunner\Analyzer\SnifferAnalyzer\Naming;
use function Safe\sprintf;

final class PreferredClassSniff implements Sniff
{
    /**
     * @var string[]
     */
    public $oldToPreferredClasses = [];

    /**
     * @var Naming
     */
    private $naming;

    public function __construct(Naming $naming)
    {
        $this->naming = $naming;
    }

    /**
     * @return int[]
     */
    public function register(): array
    {
        return [T_STRING];
    }

    /**
     * @param int $position
     */
    public function process(File $file, $position): void
    {
        if ($this->oldToPreferredClasses === []) {
            return;
        }

        $className = $this->naming->getClassName($file, $position);
        if (! isset($this->oldToPreferredClasses[$className])) {
            return;
        }

        $preferredClass = $this->oldToPreferredClasses[$className];
        $file->addError($this->createMessage($className, $preferredClass), $position, self::class);
    }

    private function createMessage(string $className, string $preferredCase): string
    {
        // class
        if (class_exists($preferredCase)) {
            return sprintf('Instead of "%s" class, use "%s"', $className, $preferredCase);
        }

        // advice
        return sprintf('You should not use "%s". Instead, %s', $className, lcfirst($preferredCase));
    }
}

Allow messgae in preffered class sniff

Allow messgae in preffered class sniff

Signed-off-by: Tomas Votruba <5445cc846624f8e1309aa4cd2a2306f4bc110566@gmail.com>


<?php

namespace Opifer\EavBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* DateTimeValue
*
* @ORM\Entity
*/
class DateTimeValue extends Value
{
    /**
    * Turn value into string for form field value purposes
    *
    * @return string
    */
    public function __toString()
    {
        return (string) $this->getTimestamp();
    }

    /**
     * Get value
     *
     * @return \DateTime
     */
    public function getValue()
    {
        $datetime = new \DateTime();

        return $datetime->setTimestamp($this->value);
    }

    /**
     * Set value
     *
     * @param \DateTime $value
     *
     * @return DateTimeValue
     */
    public function setValue($value)
    {
        $this->value = $value->getTimestamp();

        return $this;
    }

    /**
     * Get raw value
     *
     * @return string
     */
    public function getTimestamp()
    {
        return $this->value;
    }
}

<?php

namespace Opifer\EavBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* DateTimeValue
*
* @ORM\Entity
*/
class DateTimeValue extends Value
{
    /**
    * Turn value into string for form field value purposes
    *
    * @return string
    */
    public function __toString()
    {
        return date('d-m-Y H:i:s', $this->getTimestamp());
    }

    /**
     * Get value
     *
     * @return \DateTime
     */
    public function getValue()
    {
        $datetime = new \DateTime();

        return $datetime->setTimestamp($this->value);
    }

    /**
     * Set value
     *
     * @param \DateTime $value
     *
     * @return DateTimeValue
     */
    public function setValue($value)
    {
        $this->value = $value->getTimestamp();

        return $this;
    }

    /**
     * Get raw value
     *
     * @return string
     */
    public function getTimestamp()
    {
        return $this->value;
    }
}

Return readable date format in toString

Return readable date format in toString


<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        $schema->table('registration_tokens', function (Blueprint $table) {
            $table->string('provider');
            $table->string('identifier');
            $table->text('user_attributes')->nullable();

            $table->text('payload')->nullable()->change();
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('auth_tokens', function (Blueprint $table) {
            $table->dropColumn('provider', 'identifier', 'user_attributes');

            $table->string('payload', 150)->change();
        });
    }
];

<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        $schema->table('registration_tokens', function (Blueprint $table) {
            $table->string('provider');
            $table->string('identifier');
            $table->text('user_attributes')->nullable();

            $table->text('payload')->nullable()->change();
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('registration_tokens', function (Blueprint $table) {
            $table->dropColumn('provider', 'identifier', 'user_attributes');

            $table->string('payload', 150)->change();
        });
    }
];

Fix table name in migration

Fix table name in migration


<?php
// (c) Copyright 2002-2013 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$

class Search_Formatter_ValueFormatter_Snippet extends Search_Formatter_ValueFormatter_Abstract
{
	private $length = 240;
	private $suffix = '...';

	function __construct($arguments)
	{
		if (isset($arguments['length'])) {
			$this->length = (int) $arguments['length'];
		}

		if (isset($arguments['suffix'])) {
			$this->suffix = $arguments['suffix'];
		}
	}

	function render($name, $value, array $entry)
	{
		$snippet = TikiLib::lib('tiki')->get_snippet($value, 'n', '', $this->length + 1);

		if (function_exists('mb_strlen')) {
			if (mb_strlen($snippet) > $this->length) {
				$snippet = mb_substr($snippet, 0, -1) . $this->suffix;
			}
		} else {
			if (strlen($snippet) > $this->length) {
				$snippet = substr($snippet, 0, -1) . $this->suffix;
			}
		}

		return '~np~' . $snippet . '~/np~';
	}
}

<?php
// (c) Copyright 2002-2013 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$

class Search_Formatter_ValueFormatter_Snippet extends Search_Formatter_ValueFormatter_Abstract
{
	private $length = 240;
	private $suffix = '...';

	function __construct($arguments)
	{
		if (isset($arguments['length'])) {
			$this->length = (int) $arguments['length'];
		}

		if (isset($arguments['suffix'])) {
			$this->suffix = $arguments['suffix'];
		}
	}

	function render($name, $value, array $entry)
	{
		$snippet = TikiLib::lib('tiki')->get_snippet($value, 'n', '', $this->length + 1);

		if (function_exists('mb_strlen')) {
			if (mb_strlen($snippet) > $this->length) {
				$snippet = mb_substr($snippet, 0, -1) . $this->suffix;
			}
		} else {
			if (strlen($snippet) > $this->length) {
				$snippet = substr($snippet, 0, -1) . $this->suffix;
			}
		}

		return $snippet;
	}
}

[FIX] Revert r49045 which caused rogue ~np~ tags to appear in searchindex results. Still looking for a better fix for the original {list} plugin double-parsing issues... (thanks Nelson)

git-svn-id: fe65cb8b726aa1bab0c239f321eb4f822d15ce08@49435 b456876b-0849-0410-b77d-98878d47e9d5


<?php

namespace App\Http\Middleware;

use Closure;
use DB;
use Session;
use Route;
use Request;
use Redirect;
use EtuUTT;

class Dashboard
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!EtuUTT::isAuth())
        {
            return Redirect::route('index');
        }
        else if (!EtuUTT::student()->volunteer && Request::route()->getName() != 'dashboard.students.profil' && Request::route()->getName() != 'dashboard.students.profil.submit') {
            return Redirect::route('dashboard.students.profil')->withError('Veuillez remplir ce formulaire pour continuer :)');
        }

        return $next($request);
    }
}

<?php

namespace App\Http\Middleware;

use Closure;
use DB;
use Session;
use Route;
use Request;
use Redirect;
use EtuUTT;

class Dashboard
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!EtuUTT::isAuth())
        {
            return Redirect::route('index');
        }
        else if (!EtuUTT::student()->volunteer && Request::route()->getName() != 'dashboard.students.profil'
            && Request::route()->getName() != 'dashboard.students.profil.submit'
            && Request::route()->getName() != 'dashboard.ce.firsttime') {
            return Redirect::route('dashboard.students.profil')->withError('Veuillez remplir ce formulaire pour continuer :)');
        }

        return $next($request);
    }
}

Fix ce firsttime visit page

Fix ce firsttime visit page


<?php
/**
 * @copyright Copyright (c) 2016, ownCloud, Inc.
 *
 * @author Morris Jobke <hey@morrisjobke.de>
 * @author Robin Appelman <robin@icewind.nl>
 *
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program. If not, see <http://www.gnu.org/licenses/>
 *
 */
namespace OC\Files\Mount;

/**
 * Defines the mount point to be (re)moved by the user
 */
interface MoveableMount {
	/**
	 * Move the mount point to $target
	 *
	 * @param string $target the target mount point
	 * @return bool
	 */
	public function moveMount($target);

	/**
	 * Remove the mount points
	 *
	 * @return mixed
	 * @return bool
	 */
	public function removeMount();
}

<?php
/**
 * @copyright Copyright (c) 2016, ownCloud, Inc.
 *
 * @author Morris Jobke <hey@morrisjobke.de>
 * @author Robin Appelman <robin@icewind.nl>
 *
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program. If not, see <http://www.gnu.org/licenses/>
 *
 */
namespace OC\Files\Mount;

/**
 * Defines the mount point to be (re)moved by the user
 */
interface MoveableMount {
	/**
	 * Move the mount point to $target
	 *
	 * @param string $target the target mount point
	 * @return bool
	 */
	public function moveMount($target);

	/**
	 * Remove the mount points
	 *
	 * @return bool
	 */
	public function removeMount();
}

Fix docblock for return type

Fix docblock for return type

Signed-off-by: Daniel Kesselberg <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@danielkesselberg.de>


<?php

class Denkmal_FormField_TwitterUsername extends CM_FormField_Text {

    public function validate(CM_Frontend_Environment $environment, $userInput) {
        if ('@' === substr($userInput, 0, 1)) {
            $userInput = substr($userInput, 1);
        }

        if (preg_match('#[^\w]#', $userInput)) {
            throw new CM_Exception_FormFieldValidation('Contains invalid characters');
        }

        return parent::validate($environment, $userInput);
    }
}

<?php

class Denkmal_FormField_TwitterUsername extends CM_FormField_Text {

    public function validate(CM_Frontend_Environment $environment, $userInput) {
        $userInput = parent::validate($environment, $userInput);

        if ('@' === substr($userInput, 0, 1)) {
            $userInput = substr($userInput, 1);
        }

        if (preg_match('#[^\w]#', $userInput)) {
            throw new CM_Exception_FormFieldValidation('Contains invalid characters');
        }

        return $userInput;
    }
}

Fix twitterUsername formfield validation chaining


<?php
/** @var \WEEEOpen\Tarallo\User $user */
/** @var \WEEEOpen\Tarallo\Item $item */
/** @var string $url */
/** @var int|null $depth */
/** @var string|null $add */
/** @var string|null $edit */
$this->layout(
	'main',
	[
		'title' => $item->getCode(),
		'user' => $user,
		'moveDefaultFrom' => $item->getCode(),
	]
);
if(isset($depth)) {
	$this->insert('depthWarning', ['depth' => $depth, 'viewAllUrl' => $url]);
}
$this->insert(
	'item',
	[
		'item' => $item,
		'add' => $add,
		'edit' => $edit,
		'recursion' => false,
	]
);

<?php
/** @var \WEEEOpen\Tarallo\User $user */
/** @var \WEEEOpen\Tarallo\Item $item */
/** @var string $url */
/** @var int|null $depth */
/** @var string|null $add */
/** @var string|null $edit */
$this->layout(
	'main',
	[
		'title' => $item->getCode(),
		'user' => $user,
		'moveDefaultFrom' => $item->getCode(),
		'tooltips' => isset($edit) || isset($add),
	]
);
if(isset($depth)) {
	$this->insert('depthWarning', ['depth' => $depth, 'viewAllUrl' => $url]);
}
$this->insert(
	'item',
	[
		'item' => $item,
		'add' => $add,
		'edit' => $edit,
		'recursion' => false,
	]
);

Fix tooltips in item editor inside existing items


<?php

$phar = __DIR__ . '/../interfaceDistiller.phar';
if(file_exists($phar)) {
    unlink($phar);
}

$phar = new Phar($phar, 0 , 'interfaceDistiller.phar');
$phar->buildFromDirectory(__DIR__ . '/../src/');
$phar->setStub(<<<'STUB'
<?php
Phar::mapPhar('interfaceDistiller.phar');
require 'phar://interfaceDistiller.phar/autoload.php';
call_user_func(
    new com\github\gooh\InterfaceDistiller\Controller\CommandLine(
        new com\github\gooh\InterfaceDistiller\InterfaceDistiller
    ),
    $argv,
    new SplFileObject('php://stdout')
);
__HALT_COMPILER();
STUB
);

<?php

$phar = __DIR__ . '/../interfaceDistiller.phar';
if(file_exists($phar)) {
    unlink($phar);
}

$phar = new Phar($phar, 0 , 'interfaceDistiller.phar');
$phar->buildFromDirectory(__DIR__ . '/../src/');
$phar->setStub(<<<'STUB'
#!/usr/bin/env php
<?php
Phar::mapPhar('interfaceDistiller.phar');
require 'phar://interfaceDistiller.phar/autoload.php';
call_user_func(
    new com\github\gooh\InterfaceDistiller\Controller\CommandLine(
        new com\github\gooh\InterfaceDistiller\InterfaceDistiller
    ),
    $argv,
    new SplFileObject('php://stdout')
);
__HALT_COMPILER();
STUB
);

Allow for self executeable phar so it can be put into */bin

Doesn't break cross platform and makes life a little nicer.

See https://github.com/composer/composer/blob/master/src/Composer/Compiler.php#L170


<?php

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

namespace Symfony\Component\ExpressionLanguage\Tests\Fixtures;

use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
use Symfony\Component\ExpressionLanguage\ExpressionPhpFunction;

class TestProvider implements ExpressionFunctionProviderInterface
{
    public function getFunctions()
    {
        return [
            new ExpressionFunction('identity', function ($input) {
                return $input;
            }, function (array $values, $input) {
                return $input;
            }),

            ExpressionFunction::fromPhp('strtoupper'),

            ExpressionFunction::fromPhp('\strtolower'),

            ExpressionFunction::fromPhp('Symfony\Component\ExpressionLanguage\Tests\Fixtures\fn_namespaced', 'fn_namespaced'),
        ];
    }
}

function fn_namespaced()
{
    return true;
}

<?php

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

namespace Symfony\Component\ExpressionLanguage\Tests\Fixtures;

use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
use Symfony\Component\ExpressionLanguage\ExpressionPhpFunction;

class TestProvider implements ExpressionFunctionProviderInterface
{
    public function getFunctions(): array
    {
        return [
            new ExpressionFunction('identity', function ($input) {
                return $input;
            }, function (array $values, $input) {
                return $input;
            }),

            ExpressionFunction::fromPhp('strtoupper'),

            ExpressionFunction::fromPhp('\strtolower'),

            ExpressionFunction::fromPhp('Symfony\Component\ExpressionLanguage\Tests\Fixtures\fn_namespaced', 'fn_namespaced'),
        ];
    }
}

function fn_namespaced()
{
    return true;
}

Add return types to tests and final|internal|private methods


<?php

namespace Acd;

/**
* Request Class
* @author Acidvertigo MIT Licence
*/

class Request
{

    private $headers = [];

    /**
     * Check HTTP request headers
     * @return array list of response headers
     * @throws InvalidArgumentException if header is null
     */
    public function getRequestHeaders()
    {
      if (function_exists("getallheaders()"))
      {
          $this->headers = getallheaders();
      } else
      {
          $this->headers = $this->getServerHeaders();
      }
      if ($this->headers !== null)
      {
          return $this->headers;
      } else
      {
          throw new \InvalidArgumentException('Unable to get Request Headers');
      }
    }

   /**
    * Helper function if getallheaders() not available
    * @return array list of response headers
    */
  private function getServerHeaders() {
    foreach (array_keys($_SERVER) as $skey) {
      if (strpos($skey, 'HTTP_') !== FALSE)
      {
        $this->headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($skey, 5)))))] = $_SERVER[$skey];
      }
    }

    return $this->headers;
  }
}

<?php

namespace Acd;

/**
* Request Class
* @author Acidvertigo MIT Licence
*/

class Request
{

    private $headers = [];

    /**
     * Check HTTP request headers
     * @return array list of response headers
     * @throws InvalidArgumentException if header is null
     */
    public function getRequestHeaders()
    {
      if (function_exists('getallheaders()'))
      {
          $this->headers = getallheaders();
      } else
      {
          $this->headers = $this->getServerHeaders();
      }
      if ($this->headers !== null)
      {
          return $this->headers;
      } else
      {
          throw new \InvalidArgumentException('Unable to get Request Headers');
      }
    }

   /**
    * Helper function if getallheaders() not available
    * @return array list of response headers
    */
  private function getServerHeaders() {
    foreach (array_keys($_SERVER) as $skey) {
      if (strpos($skey, 'HTTP_') !== FALSE)
      {
        $this->headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($skey, 5)))))] = $_SERVER[$skey];
      }
    }

    return $this->headers;
  }
}

Replace double quotes with single

Replace double quotes with single


<?php

namespace ETNA\FeatureContext;

trait setUpScenarioDirectories
{
    /**
     * @BeforeScenario
     */
    public function setUpScenarioDirectories($event)
    {
        if ($event instanceof \Behat\Behat\Event\ScenarioEvent) {
            $this->results_path  = realpath(dirname($event->getScenario()->getFile())) . '/results/';
            $this->requests_path = realpath(dirname($event->getScenario()->getFile())) . '/requests/';
        } else {
            $this->results_path  = realpath(dirname($event->getOutline()->getFile())) . '/results/';
            $this->requests_path = realpath(dirname($event->getOutline()->getFile())) . '/requests/';
        }
    }
}

<?php

namespace ETNA\FeatureContext;

trait setUpScenarioDirectories
{
    /** @Var string */
    private $requests_path;
    /** @Var string */
    private $results_path;

    /**
     * @BeforeScenario
     */
    public function setUpScenarioDirectories($event)
    {
        if ($event instanceof \Behat\Behat\Event\ScenarioEvent) {
            $this->results_path  = realpath(dirname($event->getScenario()->getFile())) . '/results/';
            $this->requests_path = realpath(dirname($event->getScenario()->getFile())) . '/requests/';
        } else {
            $this->results_path  = realpath(dirname($event->getOutline()->getFile())) . '/results/';
            $this->requests_path = realpath(dirname($event->getOutline()->getFile())) . '/requests/';
        }
    }
}

Fix des alertes sur des attributs inexistants


SCROLL DOWN

<?php
$opacity = (isset($_GET['opacity']) ? $_GET['opacity'] : '0.5');
$url = (isset($_GET['url']) ? $_GET['url'] : 'http://rungo.idnes.cz/ankety.aspx?idanketa=A20160313_Pil_382&setver=full');
?>
<iframe
	style="opacity: <?php echo htmlspecialchars($opacity); ?>; width: 400px; height: 800px; left: 0px; position: absolute;"
	src="<?php echo htmlspecialchars($url); ?>">

Clickjacking

invisible frame <?php echo htmlspecialchars($url); ?>

half-visible frame <?php echo htmlspecialchars($url); ?>

SCROLL DOWN

<?php
$opacity = (isset($_GET['opacity']) ? $_GET['opacity'] : '0.5');
$url = (isset($_GET['url']) ? $_GET['url'] : 'https://rungo.idnes.cz/ankety.aspx?idanketa=A20160824_Pil_507&setver=full');
?>
<iframe
	style="opacity: <?php echo htmlspecialchars($opacity); ?>; width: 400px; height: 800px; left: 0px; position: absolute;"
	src="<?php echo htmlspecialchars($url); ?>">

Clickjacking

invisible frame <?php echo htmlspecialchars($url); ?>

half-visible frame <?php echo htmlspecialchars($url); ?>

Use HTTPS frame in clickjacking example

Use HTTPS frame in clickjacking example


<?php // [1] Regular responsivebackground image; default sized thumb (e.g. `responsiveimages.default`) ?>
<?php if($lazyload == false): ?>
	<div style="background-image:url(<?php echo $defaultthumburl; ?>);"<?php if($class): echo ' class="' . $class . '"'; endif; ?>>

<?php endif; ?>

<?php // [2] Lazyload responsive image; bgset and sizes ?>
<?php if($lazyload == true): ?>
	<div data-sizes="auto" data-bgset="<?php echo $srcset; ?>" class="<?php if($class): echo $class . ' '; endif; ?>lazyload">

		<div style="background-image:url(<?php echo $defaultthumburl; ?>);" <?php if($class): echo 'class="' . $class . '"'; endif; ?>>

<?php endif; ?>

<?php // [1] Regular responsivebackground image; default sized thumb (e.g. `responsiveimages.default`) ?>
<?php if($lazyload == false): ?>
	<div style="background-image:url(<?php echo $defaultthumburl; ?>);"<?php if($class): echo ' class="' . $class . '"'; endif; ?>>

<?php endif; ?>

<?php // [2] Lazyload responsive image; bgset and sizes ?>
<?php if($lazyload == true): ?>
	<div data-sizes="auto" data-bgset="<?php echo $srcset; ?>" data-default-bgset="<?php echo $defaultthumburl; ?>" class="<?php if($class): echo $class . ' '; endif; ?>lazyload">

		<div style="background-image:url(<?php echo $defaultthumburl; ?>);" <?php if($class): echo 'class="' . $class . '"'; endif; ?>>

<?php endif; ?>

Add bgset default size to template.

Add bgset default size to template.