<?php

namespace Orbt\ResourceMirror\Resource;
use Orbt\ResourceMirror\Exception\ReplicatorException;

/**
 * Basic replicator implementation using file operations to replicate.
 */
class FileReplicator implements Replicator
{
    /**
     * Base URL.
     * @var string
     */
    protected $baseUrl;

    /**
     * Target directory.
     * @var string
     */
    protected $directory;

    /**
     * Constructs a file replicator.
     */
    public function __construct($baseUrl, $directory)
    {
        $this->baseUrl = rtrim($baseUrl, '/').'/';
        $this->directory = rtrim($directory, '\\/').'/';
    }

    /**
     * {@inheritdoc}
     */
    public function replicate($resource)
    {
        $url = $this->baseUrl.$resource->getPath();
        if (!$source = @fopen($url, 'r')) {
            throw new ReplicatorException('Cannot open URL for reading.');
        }
        $file = $this->directory.$resource->getPath();
        if (!$target = @fopen($file, 'w')) {
            fclose($source);
            throw new ReplicatorException('Cannot open local file for writing.');
        }
        stream_copy_to_stream($source, $target);
        fclose($source);
        fclose($target);
    }
}

<?php

namespace Orbt\ResourceMirror\Resource;
use Orbt\ResourceMirror\Exception\ReplicatorException;

/**
 * Basic replicator implementation using file operations to replicate.
 */
class FileReplicator implements Replicator
{
    /**
     * Base URL.
     * @var string
     */
    protected $baseUrl;

    /**
     * Target directory.
     * @var string
     */
    protected $directory;

    /**
     * Constructs a file replicator.
     */
    public function __construct($baseUrl, $directory)
    {
        $this->baseUrl = rtrim($baseUrl, '/').'/';
        $this->directory = rtrim($directory, '\\/').'/';
    }

    /**
     * {@inheritdoc}
     */
    public function replicate($resource)
    {
        $url = $this->baseUrl.$resource->getPath();
        if (!$source = @fopen($url, 'r')) {
            throw new ReplicatorException('Cannot open URL for reading.');
        }
        $file = $this->directory.$resource->getPath();
        @mkdir(dirname($file), 0777, true);
        if (!$target = @fopen($file, 'w')) {
            fclose($source);
            throw new ReplicatorException('Cannot open local file for writing.');
        }
        stream_copy_to_stream($source, $target);
        fclose($source);
        fclose($target);
    }
}

Create directory to resource being replicated.


<?php

include '../scat.php';

$balance= (float)$_REQUEST['balance'];

$q= "INSERT INTO giftcard
        SET pin = SUBSTR(RAND(), 5, 4),
            active = 1";
$r= $db->query($q);
if (!$r) die(jsonp(array("error" => "Unable to create card.",
                         "detail" => $db->error)));

$q= "SELECT CONCAT(id, pin) card, id, pin FROM giftcard
      WHERE id = LAST_INSERT_ID()";
$r= $db->query($q);
if (!$r) die(jsonp(array("error" => "Unable to create card.",
                         "detail" => $db->error)));
$card= $r->fetch_assoc();

if ($balance) {
  $q= "INSERT INTO giftcard_txn
          SET card_id = $card[id],
              amount = $balance,
              entered = NOW()";

  $r= $db->query($q);
  if (!$r) die(jsonp(array("error" => "Unable to add balance to card.",
                                    "detail" => $db->error)));
}

echo jsonp(array("card" => $card['card'],
                 "balance" => sprintf("%.2f", $balance),
                 "success" =>sprintf("Card activated with \$%.2f balance.",
                                     $balance)));

<?php

include '../scat.php';

$balance= (float)$_REQUEST['balance'];
$expires= $_REQUEST['expires'];
if ($expires) {
  $expires= '"' . $db->escape($expires) . ' 23:59:59"';
} else {
  $expires= "NULL";
}

$q= "INSERT INTO giftcard
        SET pin = SUBSTR(RAND(), 5, 4),
            expires = $expires,
            active = 1";
$r= $db->query($q);
if (!$r) die(jsonp(array("error" => "Unable to create card.",
                         "detail" => $db->error)));

$q= "SELECT CONCAT(id, pin) card, id, pin FROM giftcard
      WHERE id = LAST_INSERT_ID()";
$r= $db->query($q);
if (!$r) die(jsonp(array("error" => "Unable to create card.",
                         "detail" => $db->error)));
$card= $r->fetch_assoc();

if ($balance) {
  $q= "INSERT INTO giftcard_txn
          SET card_id = $card[id],
              amount = $balance,
              entered = NOW()";

  $r= $db->query($q);
  if (!$r) die(jsonp(array("error" => "Unable to add balance to card.",
                                    "detail" => $db->error)));
}

echo jsonp(array("card" => $card['card'],
                 "balance" => sprintf("%.2f", $balance),
                 "success" =>sprintf("Card activated with \$%.2f balance.",
                                     $balance)));

Allow expiration of gift card to be set

Allow expiration of gift card to be set


<?php

namespace App\Realms;

use Illuminate\Database\Eloquent\Model;

/**
 * Invite model.
 *
 * @package App
 */
class Invite extends Model
{
    protected $guarded = [];

    protected function getDateFormat()
    {
        return 'U';
    }

}

<?php

namespace App\Realms;

use Illuminate\Database\Eloquent\Model;

/**
 * Invite model.
 *
 * @package App
 */
class Invite extends Model
{
    protected $guarded = [];

    protected function getDateFormat()
    {
        return 'U';
    }

    /**
     * Server relationship.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function server()
    {
        return $this->belongsTo('App\Realms\Server');
    }

    /**
     * Mutator for to attribute, encodes player objects into json.
     *
     * @param $value
     * @return string
     */
    public function setToAttribute($value)
    {
        $this->attributes['to'] = json_encode([
            'uuid' => $value->uuid,
            'username' => $value->username
        ]);
    }

    /**
     * Accessor for to attribute, decodes player objects from json.
     *
     * @param $value
     * @return Player
     */
    public function getToAttribute($value)
    {
        $playerJson = json_decode($value);
        return new Player(
            $playerJson->uuid,
            $playerJson->username
        );
    }
}

Add server relationship and to mutator/accessor.


<?php

global $db;

// Manage upgrade from DISA 1.0
// r2.0 Add Timeouts and add wait for confirmation
$sql = "SELECT digittimeout FROM disa";
$check = $db->getRow($sql, DB_FETCHMODE_ASSOC);
if(DB::IsError($check)) {
	// add new fields - Digit Timeout
	$sql = 'ALTER TABLE disa ADD COLUMN digittimeout INT DEFAULT "5"';
	$result = $db->query($sql);
	if(DB::IsError($result)) {
		die($result->getDebugInfo());
	}
	// Response Timeout
	$sql = 'ALTER TABLE disa ADD COLUMN resptimeout INT DEFAULT "10"';
	$result = $db->query($sql);
	if(DB::IsError($result)) {
		die($result->getDebugInfo());
	}
	$sql = 'ALTER TABLE disa ADD COLUMN needconf VARCHAR ( 10 )  DEFAULT ""';
	$result = $db->query($sql);
	if(DB::IsError($result)) {
		die($result->getDebugInfo());
	}
}

?>

<?php

global $db;

// Manage upgrade from DISA 1.0
// r2.0 Add Timeouts and add wait for confirmation
$sql = "SELECT digittimeout FROM disa";
$check = $db->getRow($sql, DB_FETCHMODE_ASSOC);
if(DB::IsError($check)) {
	// add new fields - Digit Timeout
	$sql = 'ALTER TABLE disa ADD COLUMN digittimeout INT DEFAULT "5"';
	$result = $db->query($sql);
	if(DB::IsError($result)) {
		die_freepbx($result->getDebugInfo());
	}
	// Response Timeout
	$sql = 'ALTER TABLE disa ADD COLUMN resptimeout INT DEFAULT "10"';
	$result = $db->query($sql);
	if(DB::IsError($result)) {
		die_freepbx($result->getDebugInfo());
	}
	$sql = 'ALTER TABLE disa ADD COLUMN needconf VARCHAR ( 10 )  DEFAULT ""';
	$result = $db->query($sql);
	if(DB::IsError($result)) {
		die_freepbx($result->getDebugInfo());
	}
}

?>

Change all freepbx die() calls to die_freepbx()


<?php

namespace Theapi\CctvBundle\Controller;

use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{

    public function indexAction()
    {
        return $this->videoAction();
    }

    public function videoAction($date = null)
    {
        $imageManager = $this->get('theapi_cctv.image_manager');
        try {
            $file = $imageManager->getVideoFile($date);
            $root = $this->get('service_container')->getParameter('theapi_cctv.web_root');
            $file = str_replace($root, '', $file);
            return $this->render('TheapiCctvBundle:Default:index.html.twig', array('file' => $file));
        } catch (\Exception $e) {
          throw $this->createNotFoundException($e->getMessage());
        }

    }

    /**
     * This doesn't work too well. Android chrome will hang on longer videos
     * @param string $date
     */
    public function vidAction($date)
    {
        $imageManager = $this->get('theapi_cctv.image_manager');
        try {
          $file = $imageManager->getVideoFile($date);
          return new BinaryFileResponse($file);
        } catch (\Exception $e) {
          throw $this->createNotFoundException($e->getMessage());
        }
    }

}

<?php

namespace Theapi\CctvBundle\Controller;

use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{

    public function indexAction()
    {
        return $this->videoAction();
    }

    public function videoAction($date = null)
    {
        $imageManager = $this->get('theapi_cctv.image_manager');
        try {
            $file = $imageManager->getVideoFile($date);
            $root = $this->get('service_container')->getParameter('theapi_cctv.web_root');
            $file = str_replace($root, '', $file);
            return $this->render('TheapiCctvBundle:Default:index.html.twig', array('file' => $file));
        } catch (\Exception $e) {
          throw $this->createNotFoundException($e->getMessage());
        }

    }

    /**
     * Serve the file using BinaryFileResponse.
     *
     * @param string $date
     */
    public function vidAction($date)
    {
        $imageManager = $this->get('theapi_cctv.image_manager');
        try {
            $filename = $imageManager->getVideoFile($date);
            $response = new BinaryFileResponse($filename);
            $response->trustXSendfileTypeHeader();
            $response->setContentDisposition(
                ResponseHeaderBag::DISPOSITION_INLINE,
                $filename,
                iconv('UTF-8', 'ASCII//TRANSLIT', $filename)
            );
        } catch (\Exception $e) {
            throw $this->createNotFoundException($e->getMessage());
        }

        return $response;
    }

}

Add content disposition to BinaryFileResponse


@extends('layouts.master')

@section('content')

        @include('layouts.alerts')

Reset Password

        <form method="POST" action="/password/email">
            {!! csrf_field() !!}
            <input type="hidden" name="token" value="{{ $token }}">

                <input id="email" name="email" type="email" value="{{ old('email') }}"/>
                Email

                <button class="btn waves-effect waves-light" type="submit" name="action">Send Password Reset Link
                </button>

        </form>

@endsection

@extends('layouts.master')

@section('content')

        @include('layouts.alerts')

Reset Password

        <form method="POST" action="/password/email">
            {!! csrf_field() !!}

                <input id="email" name="email" type="email" value="{{ old('email') }}"/>
                Email

                <button class="btn waves-effect waves-light" type="submit" name="action">Send Password Reset Link
                </button>

        </form>

@endsection

Fix broken password reset page

Fix broken password reset page


<?php

/*
 * This file is part of PHPExifTool.
 *
 * (c) 2012 Romain Neutron <imprec@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PHPExiftool\Driver;

use PHPExiftool\Exception;
use PHPExiftool\Tool\Command\ClassesBuilder;

/**
 * Metadata Object for mapping a Tag to a value
 *
 * @author      Romain Neutron - imprec@gmail.com
 * @license     http://opensource.org/licenses/MIT MIT
 */
class TagFactory
{

    /**
     * Build a Tag based on his Tagname
     *
     * @param string $tagname
     * @return \PHPExiftool\Driver\Tag
     * @throws \PHPExiftool\Exception\TagUnknown
     */
    public static function getFromRDFTagname($tagname)
    {
        $classname = self::classnameFromTagname($tagname);

        if ( ! class_exists($classname)) {
            throw new Exception\TagUnknown(sprintf('Unknown tag %s', $tagname));
        }

        return new $classname;
    }

    public static function hasFromRDFTagname($tagname)
    {
        return class_exists(self::classnameFromTagname($tagname));
    }

    protected static function classnameFromTagname($tagname)
    {
        $classname = '\PHPExiftool\Driver\Tag\\' . str_replace(':', '\\', $tagname);

        return ClassesBuilder::generateNamespace($classname);
    }
}

<?php

/*
 * This file is part of PHPExifTool.
 *
 * (c) 2012 Romain Neutron <imprec@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PHPExiftool\Driver;

use PHPExiftool\Exception;
use PHPExiftool\Tool\Command\ClassesBuilder;

/**
 * Metadata Object for mapping a Tag to a value
 *
 * @author      Romain Neutron - imprec@gmail.com
 * @license     http://opensource.org/licenses/MIT MIT
 */
class TagFactory
{

    /**
     * Build a Tag based on his Tagname
     *
     * @param string $tagname
     * @return \PHPExiftool\Driver\Tag
     * @throws \PHPExiftool\Exception\TagUnknown
     */
    public static function getFromRDFTagname($tagname)
    {
        $classname = self::classnameFromTagname($tagname);

        if ( ! class_exists($classname)) {
            throw new Exception\TagUnknown(sprintf('Unknown tag %s', $tagname));
        }

        return new $classname;
    }

    public static function hasFromRDFTagname($tagname)
    {
        return class_exists(self::classnameFromTagname($tagname));
    }

    protected static function classnameFromTagname($tagname)
    {
        $tagname = str_replace('/rdf:RDF/rdf:Description/', '', $tagname);

        $classname = '\PHPExiftool\Driver\Tag\\' . str_replace(':', '\\', $tagname);

        return ClassesBuilder::generateNamespace($classname);
    }
}

Tag Factory no understand full xpaths

Tag Factory no understand full xpaths


<?php
class CoreData
{
	private $containers = array();
	public  $current_container;

	public function __construct($content) {
		$this -> newContainer();
		$this -> parse_content($content);
	}

	// this function should be overridden to parse the content and create a set of collections with lines
	//   and possibly links
	public function parse_content($content) {
		// we want to import $content as JSON for CoreData - other interpretations for other types
		//$json = json_decode($content);
		// loop through pages
	}

	public function to_json() {
		// outputs a JSON representation of the containers and lines
	}

	public function newContainer($url = "") {
		$c = new CoreDataContainer($url);
		print var_dump($this -> current_container);
		$this -> containers[] = $c;
		$this -> current_container = $c;
	}
}

class CoreDataContainer {
	private $lines = array();
	public $image_url = "";

	public function __construct($url = "") {
		$this -> image_url = $url;
	}

	public function addLine($line) {
		print "Adding [$line]\n";
		$lines[] = $line;
	}
}

?>

<?php
class CoreData
{
	private $containers = array();
	public  $current_container;

	public function __construct($content) {
		$this -> newContainer();
		$this -> parse_content($content);
	}

	// this function should be overridden to parse the content and create a set of collections with lines
	//   and possibly links
	public function parse_content($content) {
		// we want to import $content as JSON for CoreData - other interpretations for other types
		//$json = json_decode($content);
		// loop through pages
	}

	public function to_json() {
		// outputs a JSON representation of the containers and lines
	}

	public function newContainer($url = "") {
		$c = new CoreDataContainer($url);
		print var_dump($this -> current_container);
		$this -> containers[] = $c;
		$this -> current_container = $c;
	}
}

class CoreDataContainer {
	private $lines = array();
	public $image_url = "";

	public function __construct($url = "") {
		$this -> image_url = $url;
	}

	public function addLine($line) {
		print "Adding [$line]\n";
		$this -> lines[] = $line;
	}
}

?>

Fix add line function in core data container


<?php

/**
 * Copyright 2016 Bitban Technologies, S.L.
 * Todos los derechos reservados.
 */

namespace Bitban\PhpCodeQualityTools;

class PhpCodeQualityTools
{
    const APP_NAME = 'Bitban Technologies PHP Code Quality Tools';
    const APP_VERSION = '0.9.4';
}

<?php

/**
 * Copyright 2016 Bitban Technologies, S.L.
 * Todos los derechos reservados.
 */

namespace Bitban\PhpCodeQualityTools;

class PhpCodeQualityTools
{
    const APP_NAME = 'Bitban Technologies PHP Code Quality Tools';
    const APP_VERSION = '0.9.5';
}

Update tool version to 0.9.5

Update tool version to 0.9.5


<?php
return function(MongoDB $db) {
    $collection = $db->budgets;

    $findOne = function($id) use($collection) {
        return $collection->findOne(['_id' => new MongoID($id)]);
    };

    return [
        'find' => function(array $conditions = array()) use($collection) {
            return array_map(function($budget) {
                $budget['total'] = array_sum(array_map(function($item) { return $item['amount']; }, $budget['items']));
                $budget['overrun'] = $budget['total'] > 0;

                return $budget;
            }, iterator_to_array($collection->find($conditions)->sort(['title' => 1])));
        },
        'findOne' => $findOne,
        'addItem' => function($id, array $item) use($collection) {
            if (empty($item['description']) || empty($item['amount'])) {
                throw new Exception('You must enter both a description and an amount.');
            }

            $collection->update(['_id' => new MongoID($id)], ['$push' => ['items' => $item]]);
        },
        'removeItem' => function($id, $index) use($collection, $findOne) {
            $budget = $findOne($id);
            unset($budget['items'][$index]);

            $collection->update(['_id' => new MongoID($id)], ['$set' => ['items' => array_values($budget['items'])]]);
        },
    ];
};

<?php
return function(MongoDB $db) {
    $collection = $db->budgets;

    $findOne = function($id) use($collection) {
        return $collection->findOne(['_id' => new MongoID($id)]);
    };

    return [
        'find' => function(array $conditions = array()) use($collection) {
            return array_map(function($budget) {
                $budget['total'] = array_sum(array_map(function($item) { return $item['amount']; }, $budget['items']));
                $budget['overrun'] = $budget['polarity'] * $budget['total'] > 0;

                return $budget;
            }, iterator_to_array($collection->find($conditions)->sort(['polarity' => 1, 'title' => 1])));
        },
        'findOne' => $findOne,
        'addItem' => function($id, array $item) use($collection) {
            if (empty($item['description']) || empty($item['amount'])) {
                throw new Exception('You must enter both a description and an amount.');
            }

            $collection->update(['_id' => new MongoID($id)], ['$push' => ['items' => $item]]);
        },
        'removeItem' => function($id, $index) use($collection, $findOne) {
            $budget = $findOne($id);
            unset($budget['items'][$index]);

            $collection->update(['_id' => new MongoID($id)], ['$set' => ['items' => array_values($budget['items'])]]);
        },
    ];
};

Add support for income accounts via a -1 polarity.


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

namespace Zend\Form;

/**
 * @category   Zend
 * @package    Zend\Form
 */
interface ElementPrepareAwareInterface
{
    /**
     * Prepare the form element (mostly used for rendering purposes)
     *
     * @param Form $form
     * @return mixed
     */
    public function prepareElement(Form $form);
}

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

namespace Zend\Form;

/**
 * @category   Zend
 * @package    Zend\Form
 */
interface ElementPrepareAwareInterface
{
    /**
     * Prepare the form element (mostly used for rendering purposes)
     *
     * @param FormInterface $form
     * @return mixed
     */
    public function prepareElement(FormInterface $form);
}

Use FormInterface instead of Form

Use FormInterface instead of Form


<?php

namespace mcordingley\Regression\Algorithm\GradientDescent;

use mcordingley\Regression\Observation;
use mcordingley\Regression\Observations;

final class Batch extends GradientDescent
{
    /**
     * @param Observations $observations
     * @param array $coefficients
     * @return array
     */
    protected function calculateGradient(Observations $observations, array $coefficients)
    {
        $gradient = array_fill(0, count($observations->getObservation(0)->getFeatures()), 0.0);

        /** @var Observation $observation */
        foreach ($observations as $observation) {
            $observationGradient = $this->gradient->gradient($coefficients, $observation->getFeatures(), $observation->getOutcome());

            foreach ($observationGradient as $i => $observationSlope) {
                $gradient[$i] += $observationSlope / count($observations);
            }
        }

        return $gradient;
    }
}

<?php

namespace mcordingley\Regression\Algorithm\GradientDescent;

use mcordingley\Regression\Observation;
use mcordingley\Regression\Observations;

final class Batch extends GradientDescent
{
    /**
     * @param Observations $observations
     * @param array $coefficients
     * @return array
     */
    protected function calculateGradient(Observations $observations, array $coefficients)
    {
        $gradient = array_fill(0, count($observations->getObservation(0)->getFeatures()), 0.0);
        $batchSize = count($observations);

        /** @var Observation $observation */
        foreach ($observations as $observation) {
            $observationGradient = $this->gradient->gradient($coefficients, $observation->getFeatures(), $observation->getOutcome());

            foreach ($observationGradient as $i => $observationSlope) {
                $gradient[$i] += $observationSlope / $batchSize;
            }
        }

        return $gradient;
    }
}

Normalize form of calculation to more closely align with other implementations.


<?php namespace Ccovey\LdapAuth;

use Exception;
use adLDAP\adLDAP;
use Illuminate\Auth\Guard;
use Illuminate\Auth\AuthManager;

/**
*
*/
class LdapAuthManager extends AuthManager
{
    /**
     *
     * @return \Config\Packages\Guard
     */
    protected function createLdapDriver()
    {
        $provider = $this->createLdapProvider();

        return new Guard($provider, $this->app['session']);
    }

    /**
     *
     * @return \Config\Packages\LdapUserProvider
     */
    protected function createLdapProvider()
    {
        $ad = new adLDAP($this->getLdapConfig());

        $model = null;

        if ($this->app['config']['auth.model']) {
            $model = $this->app['config']['auth.model'];
        }

        return new LdapAuthUserProvider($ad, $this->getAuthConfig(), $model);
    }

    protected function getAuthConfig()
    {
        if ( ! is_null($this->app['config']['auth']) ) {
            return $this->app['config']['auth'];
        }
        throw new MissingAuthConfigException;
    }

    protected function getLdapConfig()
    {
        if (is_array($this->app['config']['adldap'])) return $this->app['config']['adldap'];

        return array();
    }
}

/**
* MissingAuthConfigException
*/
class MissingAuthConfigException extends Exception
{

    function __construct()
    {
        $message = "Please Ensure a config file is present at app/config/auth.php";

        parent::__construct($message);
    }
}

<?php namespace Ccovey\LdapAuth;

use Exception;
use adLDAP\adLDAP;
use Illuminate\Auth\Guard;
use Illuminate\Auth\AuthManager;

/**
*
*/
class LdapAuthManager extends AuthManager
{
    /**
     *
     * @return \Config\Packages\Guard
     */
    protected function createLdapDriver()
    {
        $provider = $this->createLdapProvider();

        return new Guard($provider, $this->app['session.store']);
    }

    /**
     *
     * @return \Config\Packages\LdapUserProvider
     */
    protected function createLdapProvider()
    {
        $ad = new adLDAP($this->getLdapConfig());

        $model = null;

        if ($this->app['config']['auth.model']) {
            $model = $this->app['config']['auth.model'];
        }

        return new LdapAuthUserProvider($ad, $this->getAuthConfig(), $model);
    }

    protected function getAuthConfig()
    {
        if ( ! is_null($this->app['config']['auth']) ) {
            return $this->app['config']['auth'];
        }
        throw new MissingAuthConfigException;
    }

    protected function getLdapConfig()
    {
        if (is_array($this->app['config']['adldap'])) return $this->app['config']['adldap'];

        return array();
    }
}

/**
* MissingAuthConfigException
*/
class MissingAuthConfigException extends Exception
{

    function __construct()
    {
        $message = "Please Ensure a config file is present at app/config/auth.php";

        parent::__construct($message);
    }
}

Use session.store instead of session for Guard instance.

On September 30, commit 3816e425ae3fdaa69474763737d5e906e073c9a9 to
the Laravel framework changed the arguments of the Guard constructor,
so it now takes a Store object instead of a Session object. This one
line patch fixes the issue.


<?php
namespace Josegonzalez\Upload\File\Path\Basepath;

use Cake\Utility\Hash;
use LogicException;

trait DefaultTrait
{
    /**
     * Returns the basepath for the current field/data combination.
     * If a `path` is specified in settings, then that will be used as
     * the replacement pattern
     *
     * @return string
     * @throws LogicException if a replacement is not valid for the current dataset
     */
    public function basepath()
    {
        $defaultPath = 'webroot{DS}files{DS}{model}{DS}{field}{DS}';
        $path = Hash::get($this->settings, 'path', $defaultPath);
        if (strpos($path, '{primaryKey}') !== false) {
            if ($this->entity->isNew()) {
                throw new LogicException('{primaryKey} substitution not allowed for new entities');
            }
            if (is_array($this->table->primaryKey())) {
                throw new LogicException('{primaryKey} substitution not valid for composite primary keys');
            }
        }

        $replacements = [
            '{primaryKey}' => $this->entity->get($this->table->primaryKey()),
            '{model}' => $this->table->alias(),
            '{field}' => $this->field,
            '{time}' => time(),
            '{microtime}' => microtime(),
            '{DS}' => DIRECTORY_SEPARATOR,
        ];
        return str_replace(
            array_keys($replacements),
            array_values($replacements),
            $path
        );
    }
}

<?php
namespace Josegonzalez\Upload\File\Path\Basepath;

use Cake\Utility\Hash;
use LogicException;

trait DefaultTrait
{
    /**
     * Returns the basepath for the current field/data combination.
     * If a `path` is specified in settings, then that will be used as
     * the replacement pattern
     *
     * @return string
     * @throws LogicException if a replacement is not valid for the current dataset
     */
    public function basepath()
    {
        $defaultPath = 'webroot{DS}files{DS}{model}{DS}{field}{DS}';
        $path = Hash::get($this->settings, 'path', $defaultPath);
        if (strpos($path, '{primaryKey}') !== false) {
            if ($this->entity->isNew()) {
                throw new LogicException('{primaryKey} substitution not allowed for new entities');
            }
            if (is_array($this->table->primaryKey())) {
                throw new LogicException('{primaryKey} substitution not valid for composite primary keys');
            }
        }

        $replacements = [
            '{primaryKey}' => $this->entity->get($this->table->primaryKey()),
            '{model}' => $this->table->alias(),
            '{table}' => $this->table->table(),
            '{field}' => $this->field,
            '{time}' => time(),
            '{microtime}' => microtime(),
            '{DS}' => DIRECTORY_SEPARATOR,
        ];
        return str_replace(
            array_keys($replacements),
            array_values($replacements),
            $path
        );
    }
}

Add {table} placeholder for path.

Add {table} placeholder for path.


<?php

/**
 * Plugin Name: Papi
 * Description: Page Type API
 * Author: Fredrik Forsmo
 * Author URI: http://forsmo.me
 * Version: 2.3.0-dev
 * Plugin URI: https://wp-papi.github.io
 * Textdomain: papi
 */

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

// Load Composer autoload if it exists and
// the Container class isn't loaded.
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) &&
	! class_exists( '\\Frozzare\\Tank\\Container' ) ) {
	require_once __DIR__ . '/vendor/autoload.php';
}

// Load Papi loader.
require_once __DIR__ . '/src/papi-loader.php';

<?php

/**
 * Plugin Name: Papi
 * Description: Page Type API
 * Author: Fredrik Forsmo
 * Author URI: http://forsmo.me
 * Version: 2.3.0-dev
 * Plugin URI: https://wp-papi.github.io
 * Textdomain: papi
 */

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

// Load Composer autoload if it exists.
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
	require_once __DIR__ . '/vendor/autoload.php';
}

// Load Papi loader.
require_once __DIR__ . '/src/papi-loader.php';

Revert "Load composer only if container class dont exists"

This reverts commit 08c9a7daddc17c6ef19e7b0e7beff38ed75b222b.


@extends('layouts.app')

@section('content')

Students enrolled in {{ $course->name }}

        @if($enrollments->isEmpty())
            @include('students.shared.table.empty')
        @else
            @include('students.shared.table.index')
        @endif

                {{ $enrollments->links() }}

                Page {{ $enrollments->currentPage() }} of {{ $enrollments->lastPage() }}

@endsection

@extends('layouts.app')

@section('content')

Students enrolled in {{ $course->name }}

        @if($enrollments->isEmpty())
            @include('students.shared.table.empty')
        @else
            @include('students.shared.table.index')
        @endif

                {{ $enrollments->links() }}

                @if ($enrollments->lastPage() > 0)
                    Page {{ $enrollments->currentPage() }} of {{ $enrollments->lastPage() }}
                @endif

@endsection

Remove page status on empty results

Remove page status on empty results


<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new AppBundle\AppBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
            // $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
        }

        return $bundles;
    }

    public function getRootDir()
    {
        return __DIR__;
    }

    public function getCacheDir()
    {
        return dirname(__DIR__).'/var/cache/'.$this->environment;
    }

    public function getLogDir()
    {
        return dirname(__DIR__).'/var/logs';
    }

    protected function getEnvParameters()
    {
        return $_SERVER;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load($this->getRootDir().'/config/config.yml');
    }
}

<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new AppBundle\AppBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
        }

        return $bundles;
    }

    public function getRootDir()
    {
        return __DIR__;
    }

    public function getCacheDir()
    {
        return dirname(__DIR__).'/var/cache/'.$this->environment;
    }

    public function getLogDir()
    {
        return dirname(__DIR__).'/var/logs';
    }

    protected function getEnvParameters()
    {
        return $_SERVER;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load($this->getRootDir().'/config/config.yml');
    }
}

Remove distribution bundle from the loaded bundles.

We only need distribution bundle when updating dependencies.
No need to load it in the kernel.


<?php

declare(strict_types=1);

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

use PHPUnit\Framework\TestCase;
use Sonata\AdminBundle\DependencyInjection\SonataAdminExtension;
use Sonata\DoctrineORMAdminBundle\DependencyInjection\SonataDoctrineORMAdminExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class SonataDoctrineORMAdminExtensionTest extends TestCase
{
    /**
     * @var ContainerBuilder
     */
    protected $configuration;

    protected function tearDown(): void
    {
        unset($this->configuration);
    }

    public function testEntityManagerSetFactory(): void
    {
        $this->configuration = new ContainerBuilder();
        $this->configuration->setParameter('kernel.bundles', ['SimpleThingsEntityAuditBundle' => true]);
        $adminBundleExtension = new SonataAdminExtension();
        $adminBundleExtension->prepend($this->configuration);
        $loader = new SonataDoctrineORMAdminExtension();
        $loader->load([], $this->configuration);

        $definition = $this->configuration->getDefinition('sonata.admin.entity_manager');

        $this->assertNotNull($definition->getFactory());
        $this->assertNotFalse($this->configuration->getParameter('sonata_doctrine_orm_admin.audit.force'));
    }
}

<?php

declare(strict_types=1);

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

use PHPUnit\Framework\TestCase;
use Sonata\DoctrineORMAdminBundle\DependencyInjection\SonataDoctrineORMAdminExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class SonataDoctrineORMAdminExtensionTest extends TestCase
{
    /**
     * @var ContainerBuilder
     */
    protected $configuration;

    protected function tearDown(): void
    {
        unset($this->configuration);
    }

    public function testEntityManagerSetFactory(): void
    {
        $this->configuration = new ContainerBuilder();
        $this->configuration->setParameter('kernel.bundles', ['SimpleThingsEntityAuditBundle' => true]);
        $loader = new SonataDoctrineORMAdminExtension();
        $loader->load([], $this->configuration);

        $definition = $this->configuration->getDefinition('sonata.admin.entity_manager');

        $this->assertNotNull($definition->getFactory());
        $this->assertNotFalse($this->configuration->getParameter('sonata_doctrine_orm_admin.audit.force'));
    }
}

Revert "Fix missing prepending extension"

This reverts commit fa787a65bf64820654b6b403f1a75a8772e6c56a.


<?php

use App\User;
use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(User::class)->create([
            'name'     => 'Administrator',
            'username' => 'admin',
        ]);
    }
}

<?php

use App\User;
use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name'           => 'Administrator',
            'username'       => 'admin',
            'password'       => 'secret',
            'remember_token' => str_random(10),
        ]);
    }
}

Change user database seeder to User create

Factory helper uses Faker, which only dev dependency
If we use command "composer install --no-dev"
the database user seeder will throw error because
Faker not found.


<!DOCTYPE html>
<html lang="<?php echo $sf_user->getCulture() ?>" dir="<?php echo sfCultureInfo::getInstance($sf_user->getCulture())->direction ?>">
  <head>
    <?php include_http_metas() ?>
    <?php include_metas() ?>
    <?php include_title() ?>
    <link rel="shortcut icon" href="<?php echo public_path('favicon.ico') ?>"/>
    <?php include_stylesheets() ?>
    <?php include_component_slot('css') ?>
    <?php if ($sf_context->getConfiguration()->isDebug()): ?>
      <script type="text/javascript" charset="utf-8">
        less = { env: 'development', optimize: 0, relativeUrls: true };
      </script>
    <?php endif; ?>
    <?php include_javascripts() ?>
  </head>
  <body class="yui-skin-sam <?php echo $sf_context->getModuleName() ?> <?php echo $sf_context->getActionName() ?>">

    <?php echo get_partial('header') ?>

    <?php include_slot('pre') ?>

    <?php if (!include_slot('content')): ?>
      <div class="container-fluid">
        <?php echo $sf_content ?>
      </div>
    <?php endif; ?>

    <?php include_slot('post') ?>

    <?php echo get_partial('footer') ?>

  </body>
</html>

<!DOCTYPE html>
<html lang="<?php echo $sf_user->getCulture() ?>" dir="<?php echo sfCultureInfo::getInstance($sf_user->getCulture())->direction ?>">
  <head>
    <?php include_http_metas() ?>
    <?php include_metas() ?>
    <?php include_title() ?>
    <link rel="shortcut icon" href="<?php echo public_path('favicon.ico') ?>"/>
    <?php include_stylesheets() ?>
    <?php include_component_slot('css') ?>
    <?php if ($sf_context->getConfiguration()->isDebug()): ?>
      <script type="text/javascript" charset="utf-8">
        less = { env: 'development', optimize: 0, relativeUrls: true };
      </script>
    <?php endif; ?>
    <?php include_javascripts() ?>
  </head>
  <body class="yui-skin-sam <?php echo $sf_context->getModuleName() ?> <?php echo $sf_context->getActionName() ?>">

    <?php echo get_partial('header') ?>

    <?php include_slot('before-content') ?>

    <?php if (!include_slot('content')): ?>
      <div class="container-fluid">
        <?php echo $sf_content ?>
      </div>
    <?php endif; ?>

    <?php include_slot('after-content') ?>

    <?php echo get_partial('footer') ?>

  </body>
</html>

Change slot names for consistency

Change slot names for consistency


<?php
use Illuminate\Database\Migrations\Migration;

class ConfideSetupUsersTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Creates the users table
        Schema::create('users', function($table)
        {
            $table->increments('id');
            $table->string('username');
            $table->string('email');
            $table->string('password');
            $table->string('confirmation_code');
            $table->boolean('confirmed')->default(false);
            $table->timestamps();
        });

        // Creates password reminders table
        Schema::create('password_reminders', function($t)
        {
            $t->string('email');
            $t->string('token');
            $t->timestamp('created_at');
        });
    }

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

}

<?php
use Illuminate\Database\Migrations\Migration;

class ConfideSetupUsersTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Creates the users table
        Schema::create('users', function($table)
        {
            $table->increments('id');
            $table->string('username');
            $table->string('email');
            $table->string('password');
            $table->string('confirmation_code')->default(0);
            $table->boolean('confirmed')->default(false);
            $table->timestamps();
        });

        // Creates password reminders table
        Schema::create('password_reminders', function($t)
        {
            $t->string('email');
            $t->string('token');
            $t->timestamp('created_at');
        });
    }

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

}

Update default value of confirmation code


<?php

namespace AppBundle\WebService\SR;

use AppBundle\WebService\SR\Responses\AllProgramsResponse;
use Ci\RestClientBundle\Services\RestClient;
use JMS\Serializer\Serializer;

/**
 * Class SrWebServiceClient
 */
class SrWebServiceClient
{
    /** @var RestClient */
    protected $client;
    /** @var Serializer */
    protected $serializer;

    const API_BASE_URI = 'http://api.sr.se/api/v2/';

    /**
     * SrWebServiceClient constructor.
     *
     * @param RestClient $client
     */
    public function __construct(RestClient $client, Serializer $serializer)
    {
        $this->client = $client;
        $this->serializer = $serializer;
    }

    public function getAllPrograms()
    {
        $programs = $this->doGetAllPrograms();

        return $programs;
    }

    protected function doGetAllPrograms($programs = [], $nextPage = null)
    {
        $url = $nextPage ?: static::API_BASE_URI.'programs/index?format=json';

        $rawResponse = $this->client->get($url);
        $serializedResponse = $this->serializer->deserialize(
            $rawResponse->getContent(),
            AllProgramsResponse::class,
            'json'
        );

        $programs = array_merge($programs, $serializedResponse->getPrograms());

        if ($serializedResponse->getPagination()->getPage() < $serializedResponse->getPagination()->getTotalPages()) {
            return $this->doGetAllPrograms($programs, $serializedResponse->getPagination()->getNextPage());
        }

        return $programs;
    }
}

<?php

namespace AppBundle\WebService\SR;

use AppBundle\WebService\SR\Responses\AllProgramsResponse;
use Ci\RestClientBundle\Services\RestClient;
use JMS\Serializer\Serializer;

/**
 * Class SrWebServiceClient
 */
class SrWebServiceClient
{
    /** @var RestClient */
    protected $client;
    /** @var Serializer */
    protected $serializer;

    const API_BASE_URI = 'http://api.sr.se/api/v2/';

    /**
     * SrWebServiceClient constructor.
     *
     * @param RestClient $client
     */
    public function __construct(RestClient $client, Serializer $serializer)
    {
        $this->client = $client;
        $this->serializer = $serializer;
    }

    public function getAllPrograms()
    {
        $programs = $this->doGetAllPrograms();

        return $programs;
    }

    protected function doGetAllPrograms($programs = [], $nextPage = null)
    {
        $url = $nextPage ?: static::API_BASE_URI.'programs/index?format=json&size=100';

        $rawResponse = $this->client->get($url);
        $serializedResponse = $this->serializer->deserialize(
            $rawResponse->getContent(),
            AllProgramsResponse::class,
            'json'
        );

        $programs = array_merge($programs, $serializedResponse->getPrograms());

        if ($serializedResponse->getPagination()->getPage() < $serializedResponse->getPagination()->getTotalPages()) {
            return $this->doGetAllPrograms($programs, $serializedResponse->getPagination()->getNextPage());
        }

        return $programs;
    }
}

Increase page size to 100 on getAllPrograms to minimize number of requests required


<?php

namespace Backend\Modules\Faq\Actions;

/*
 * This file is part of Fork CMS.
 *
 * For the full copyright and license information, please view the license
 * file that was distributed with this source code.
 */

use Backend\Core\Engine\Base\ActionDelete as BackendBaseActionDelete;
use Backend\Core\Engine\Model as BackendModel;
use Backend\Modules\Faq\Engine\Model as BackendFaqModel;
use Backend\Modules\Faq\Form\FaqFeedbackDeleteType;

/**
 * This is the DeleteFeedback action, it will display a form to create a new item
 */
class DeleteFeedback extends BackendBaseActionDelete
{
    public function execute(): void
    {
        $deleteForm = $this->createForm(FaqFeedbackDeleteType::class);
        $deleteForm->handleRequest($this->getRequest());
        if (!$deleteForm->isSubmitted() || !$deleteForm->isValid()) {
            $this->redirect(BackendModel::createURLForAction('Index') . '&error=something-went-wrong');
        }
        $deleteFormData = $deleteForm->getData();

        $feedbackId = $deleteFormData['id'];
        $feedback = BackendFaqModel::getFeedback($feedbackId);

        // there is no feedback data, so redirect
        if (empty($feedback)) {
            $this->redirect(BackendModel::createURLForAction('Index') . '&error=non-existing');
        }

        BackendFaqModel::deleteFeedback($feedbackId);
        $this->redirect(
            BackendModel::createURLForAction('Edit') . '&id=' .
            $feedback['question_id'] . '&report=deleted#tabFeedback'
        );
    }
}

Fix redirect after deleting of faq feedback


<?php
/*
    Condorcet PHP - Election manager and results calculator.
    Designed for the Condorcet method. Integrating a large number of algorithms extending Condorcet. Expandable for all types of voting systems.

    By Julien Boudry and contributors - MIT LICENSE (Please read LICENSE.txt)
    https://github.com/julien-boudry/Condorcet
*/

// Self Autoload function coming after and as a fallback of composer or other framework PSR autoload implementation. Composer or framework autoload will alway be will be preferred to that custom function.
spl_autoload_register(function ($class) {

    // project-specific namespace prefix
    $prefix = 'CondorcetPHP\\Condorcet\\';

    // does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) :
        // no, move to the next registered autoloader
        return false;
    endif;

    // get the relative class name
    $relative_class = substr($class, $len);

    // replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    $file = __DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $relative_class) . '.php';

    // if the file exists, require it
    if (file_exists($file)) :
        require $file;
    else :
        return false;
    endif;
});

<?php
/*
    Condorcet PHP - Election manager and results calculator.
    Designed for the Condorcet method. Integrating a large number of algorithms extending Condorcet. Expandable for all types of voting systems.

    By Julien Boudry and contributors - MIT LICENSE (Please read LICENSE.txt)
    https://github.com/julien-boudry/Condorcet
*/
declare(strict_types=1);

// Self Autoload function coming after and as a fallback of composer or other framework PSR autoload implementation. Composer or framework autoload will alway be will be preferred to that custom function.
spl_autoload_register(function (string $class) : void {

    // project-specific namespace prefix
    $prefix = 'CondorcetPHP\\Condorcet\\';

    // does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) :
        // no, move to the next registered autoloader
        return;
    endif;

    // get the relative class name
    $relative_class = substr($class, $len);

    // replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    $file = __DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $relative_class) . '.php';

    // if the file exists, require it
    if (file_exists($file)) :
        require $file;
    endif;
});

Add type for Condorcet autoloader

Add type for Condorcet autoloader


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

        </button>
        Bang

                    Cartridges

                    Ranges

                    Stores

                    Firearms

                    Orders

                    Range Trips

Update menu to Bootstrap 4

Update menu to Bootstrap 4


<?php

/**
* Basis for ORM classes
*/
abstract class BaseModel{
	abstract static function displayName(): string;

	static function displayNamePlural(): string{
		return static::displayName().'s';
	}

	static function name(): string{
		return strtolower(static::displayName());
	}

	static function slug(): string{
		return preg_replace('/\\s+/', '-', strtolower(static::displayNamePlural()));
	}

	static function dbTableName(): string{
		return 'quotes_'.preg_replace('/\\s/', '', strtolower(static::displayName()));
	}

	static function indexQuery(int $offset=-1): string{
		$baseQuery = static::indexSelectQuery();
		$query = $baseQuery;
		if($offset >= 0){
			$columnOffset = $offset * self::indexPageOffset();
			$query = $baseQuery.' LIMIT '.self::indexPageOffset().' OFFSET '.$columnOffset;
		}

		return $query;
	}

	protected abstract static function indexSelectQuery(): string;

	static function selectOneQuery(): string{
		return '';
	}

	static function insertQuery(): string{
		return '';
	}

	static function updateQuery(): string{
		return '';
	}

	static function deleteQuery(): string{
		return 'DELETE FROM '.static::dbTableName().' WHERE id=?';
	}

	abstract static function toString(array $model): string;

	static function indexPageOffset(): int{
		return 100;
	}

}

<?php

/**
* Basis for ORM classes
*/
abstract class BaseModel{
	abstract static function displayName(): string;

	static function displayNamePlural(): string{
		return static::displayName().'s';
	}

	static function name(): string{
		return strtolower(static::displayName());
	}

	static function slug(): string{
		return preg_replace('/\\s+/', '-', strtolower(static::displayNamePlural()));
	}

	static function dbTableName(): string{
		return 'quotes_'.preg_replace('/\\s/', '', strtolower(static::displayName()));
	}

	static function countQuery(): string{
		return 'SELECT count(*) as count FROM '.static::dbTableName();
	}

	static function indexQuery(int $offset=-1): string{
		$baseQuery = static::indexSelectQuery();
		$query = $baseQuery;
		if($offset >= 0){
			$columnOffset = $offset * self::indexPageOffset();
			$query = $baseQuery.' LIMIT '.self::indexPageOffset().' OFFSET '.$columnOffset;
		}

		return $query;
	}

	protected abstract static function indexSelectQuery(): string;

	static function selectOneQuery(): string{
		return '';
	}

	static function insertQuery(): string{
		return '';
	}

	static function updateQuery(): string{
		return '';
	}

	static function deleteQuery(): string{
		return 'DELETE FROM '.static::dbTableName().' WHERE id=?';
	}

	abstract static function toString(array $model): string;

	static function indexPageOffset(): int{
		return 100;
	}

}

Add count query to base model

Add count query to base model


<?php namespace Illuminate\Http;

use Symfony\Component\HttpFoundation\Cookie;

trait ResponseTrait {

	/**
	 * Set a header on the Response.
	 *
	 * @param  string  $key
	 * @param  string  $value
	 * @param  bool    $replace
	 * @return $this
	 */
	public function header($key, $value, $replace = true)
	{
		$this->headers->set($key, $value, $replace);

		return $this;
	}

	/**
	 * Add a cookie to the response.
	 *
	 * @param  \Symfony\Component\HttpFoundation\Cookie  $cookie
	 * @return $this
	 */
	public function withCookie(Cookie $cookie)
	{
		$this->headers->setCookie($cookie);

		return $this;
	}

}

<?php namespace Illuminate\Http;

use Symfony\Component\HttpFoundation\Cookie;

trait ResponseTrait {

	/**
	 * Get the status code for the response.
	 *
	 * @return int
	 */
	public function status()
	{
		return $this->getStatusCode();
	}

	/**
	 * Get the content of the response.
	 *
	 * @return string
	 */
	public function content()
	{
		return $this->getContent();
	}

	/**
	 * Set a header on the Response.
	 *
	 * @param  string  $key
	 * @param  string  $value
	 * @param  bool    $replace
	 * @return $this
	 */
	public function header($key, $value, $replace = true)
	{
		$this->headers->set($key, $value, $replace);

		return $this;
	}

	/**
	 * Add a cookie to the response.
	 *
	 * @param  \Symfony\Component\HttpFoundation\Cookie  $cookie
	 * @return $this
	 */
	public function withCookie(Cookie $cookie)
	{
		$this->headers->setCookie($cookie);

		return $this;
	}

}

Add short-cuts for status and content.

Add short-cuts for status and content.


<?php namespace Flarum\Events;

use Flarum\Api\Request;
use Flarum\Http\RouteCollection;
use Psr\Http\Message\ServerRequestInterface;

class RegisterApiRoutes
{
    /**
     * @var RouteCollection
     */
    public $routes;

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

    public function get($url, $name, $action)
    {
        $this->route('get', $url, $name, $action);
    }

    public function patch($url, $name, $action)
    {
        $this->route('patch', $url, $name, $action);
    }

    protected function route($method, $url, $name, $action)
    {
        $this->routes->$method($url, $name, $this->action($action));
    }

    protected function action($class)
    {
        return function (ServerRequestInterface $httpRequest, $routeParams) use ($class) {
            $action = app($class);
            $actor = app('flarum.actor');

            $input = array_merge($httpRequest->getQueryParams(), $httpRequest->getAttributes(), $routeParams);
            $request = new Request($input, $actor, $httpRequest);

            return $action->handle($request);
        };
    }
}

<?php namespace Flarum\Events;

use Flarum\Api\Request;
use Flarum\Http\RouteCollection;
use Psr\Http\Message\ServerRequestInterface;

class RegisterApiRoutes
{
    /**
     * @var RouteCollection
     */
    public $routes;

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

    public function get($url, $name, $action)
    {
        $this->route('get', $url, $name, $action);
    }

    public function post($url, $name, $action)
    {
        $this->route('post', $url, $name, $action);
    }

    public function patch($url, $name, $action)
    {
        $this->route('patch', $url, $name, $action);
    }

    public function delete($url, $name, $action)
    {
        $this->route('delete', $url, $name, $action);
    }

    protected function route($method, $url, $name, $action)
    {
        $this->routes->$method($url, $name, $this->action($action));
    }

    protected function action($class)
    {
        return function (ServerRequestInterface $httpRequest, $routeParams) use ($class) {
            $action = app($class);
            $actor = app('flarum.actor');

            $input = array_merge($httpRequest->getQueryParams(), $httpRequest->getAttributes(), $routeParams);
            $request = new Request($input, $actor, $httpRequest);

            return $action->handle($request);
        };
    }
}

Add API methods to add POST/DELETE routes to the API


<?php
/**
 * This file is part of Rudolf.
 *
 * Site configuration.
 *
 * @author Mikołaj Pich <m.pich@outlook.com>
 * @package Rudolf\Config
 * @version 0.1
 */

return array (
	'front_theme' => 'beautifullibrary',
	'admin_theme' => 'reindeer',
	'debug' => true
);

<?php
/**
 * This file is part of Rudolf.
 *
 * Site configuration.
 *
 * @author Mikołaj Pich <m.pich@outlook.com>
 * @package Rudolf\Config
 * @version 0.1
 */

return array (
	'front_theme' => 'reindeer',
	'admin_theme' => 'reindeer',
	'debug' => true
);

Change config params to default

Change config params to default


<?php

declare(strict_types=1);

namespace Codeception\Lib\Actor\Shared;

use Codeception\Command\Console;
use Codeception\Lib\PauseShell;
use Codeception\Util\Debug;
use Psy\Shell;
use Psy\Configuration;

trait Pause
{
    public function pause(array $vars = []): void
    {
        if (!Debug::isEnabled()) {
            return;
        }

        $psy = (new PauseShell())
            ->addMessage(' $I-> to launch commands')
            ->addMessage(' $this-> to access current test')
            ->getShell();

        $vars['I'] = $this;
        $psy->setScopeVariables($vars);
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2);
        if (!$backtrace[1]['object'] instanceof Console) {
            // set the scope of test class
            $psy->setBoundObject($backtrace[1]['object']);
        }
        $psy->run();
    }
}

<?php

declare(strict_types=1);

namespace Codeception\Lib\Actor\Shared;

use Codeception\Command\Console;
use Codeception\Lib\PauseShell;
use Codeception\Util\Debug;
use Psy\Shell;
use Psy\Configuration;

trait Pause
{
    public function pause(array $vars = []): void
    {
        if (!Debug::isEnabled()) {
            return;
        }

        $psy = (new PauseShell())
            ->addMessage('$I-> to launch commands')
            ->addMessage('$this-> to access current test')
            ->addMessage('exit to exit')
            ->getShell();

        $vars['I'] = $this;
        $psy->setScopeVariables($vars);
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2);
        if (!$backtrace[1]['object'] instanceof Console) {
            // set the scope of test class
            $psy->setBoundObject($backtrace[1]['object']);
        }
        $psy->run();
    }
}

Add message how to exit Codeception console


<?php

namespace Oro\Bundle\CurrencyBundle\Form\Type;

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

class CurrencyType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'currency';
    }

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

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

    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);
        $resolver->setDefaults(['restrict' => false]);
    }
}

<?php

namespace Oro\Bundle\CurrencyBundle\Form\Type;

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

class CurrencyType extends AbstractType
{
    const CONFIG_FORM_NAME = 'oro_currency___default_currency';

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'currency';
    }

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

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

    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);
        $resolver->setDefaults(['restrict' => false]);
    }
}

OEE-1083: Edit form for currency rates
- Added configurator to hide controls 'Default currency' and 'Currency rates'


<?php

namespace Jwpage\Clickatell;

use Guzzle\Common\Collection;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;

class ClickatellClient extends Client
{
    public static function factory($config = array())
    {
        $default = array(
            'base_url' => 'http://api.clickatell.com/',
        );
        $required = array('api_id', 'username', 'password', 'base_url');
        $config = Collection::fromConfig($config, $default, $required);
        $description = ServiceDescription::factory(__DIR__.'/service.json');

        $client = new self($config->get('base_url'), $config);
        $client->setDescription($description);

        return $client;
    }
}

<?php

namespace Jwpage\Clickatell;

use Guzzle\Common\Collection;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;

class ClickatellClient extends Client
{
    public static function factory($config = array())
    {
        $default = array(
            'base_url' => 'http://api.clickatell.com/',
        );
        $required = array('api_id', 'user', 'password', 'base_url');
        $config = Collection::fromConfig($config, $default, $required);
        $description = ServiceDescription::factory(__DIR__.'/service.json');

        $client = new self($config->get('base_url'), $config);
        $client->setDescription($description);

        return $client;
    }

    public function createRequest($method = RequestInterface::GET, $uri = null, $headers = null, $body = null)
    {
        $request = parent::createRequest($method, $uri, $headers, $body);

        if (!$request->getPostField("session_id")) {
            $config = $this->getConfig();
            $request->addPostFields($config->getAll(array('api_id', 'user', 'password')));
        }

        return $request;
    }
}

Add auth details if session_id is not provided in the request


<?php
namespace Bolt\Tests\Mapping;

use Bolt\Mapping\MetadataDriver;
use Bolt\Tests\BoltUnitTest;

/**
 * Class to test src/Mapping/MetadataDriver.
 *
 * @author Ross Riley <riley.ross@gmail.com>
 */
class MetadataDriverTest extends BoltUnitTest
{
    public function testConstruct()
    {
        $app = $this->getApp();
        $map = new MetadataDriver($app['schema'], $app['config']->get('contenttypes'), $app['config']->get('taxonomy'), $app['storage.typemap']);
        $this->assertSame($app['schema'], \PHPUnit_Framework_Assert::readAttribute($map, 'schemaManager'));
    }

    public function testInitialize()
    {
        $app = $this->getApp();
        $map = new MetadataDriver($app['schema'], $app['config']->get('contenttypes'), $app['config']->get('taxonomy'), $app['storage.typemap']);
        $map->initialize();
        $metadata = $map->loadMetadataForClass('Bolt\Storage\Entity\Users');
        $this->assertNotNull($metadata);
        $this->assertEquals('bolt_users', $metadata->getTableName());
        $field = $metadata->getFieldMapping('id');
        $this->assertEquals('id', $field['fieldname']);
    }
}

<?php
namespace Bolt\Tests\Mapping;

use Bolt\Storage\Mapping\MetadataDriver;
use Bolt\Tests\BoltUnitTest;

/**
 * Class to test src/Mapping/MetadataDriver.
 *
 * @author Ross Riley <riley.ross@gmail.com>
 */
class MetadataDriverTest extends BoltUnitTest
{
    public function testConstruct()
    {
        $app = $this->getApp();
        $map = new MetadataDriver($app['schema'], $app['config']->get('contenttypes'), $app['config']->get('taxonomy'), $app['storage.typemap']);
        $this->assertSame($app['schema'], \PHPUnit_Framework_Assert::readAttribute($map, 'schemaManager'));
    }

    public function testInitialize()
    {
        $app = $this->getApp();
        $map = new MetadataDriver($app['schema'], $app['config']->get('contenttypes'), $app['config']->get('taxonomy'), $app['storage.typemap']);
        $map->initialize();
        $metadata = $map->loadMetadataForClass('Bolt\Storage\Entity\Users');
        $this->assertNotNull($metadata);
        $this->assertEquals('bolt_users', $metadata->getTableName());
        $field = $metadata->getFieldMapping('id');
        $this->assertEquals('id', $field['fieldname']);
    }
}

[Tests] Move Bolt\Mapping to Bolt\Storage\Mapping namespace


<?php

use Illuminate\Database\Seeder;
use REBELinBLUE\Deployer\Server;

class ServerTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('servers')->delete();

        Server::create([
            'name'        => 'Web VM',
            'ip_address'  => '192.168.33.50',
            'user'        => 'deploy',
            'path'        => '/var/www',
            'project_id'  => 1,
            'deploy_code' => true,
        ]);

        Server::create([
            'name'        => 'Cron VM',
            'ip_address'  => '192.168.33.60',
            'user'        => 'deploy',
            'path'        => '/var/www',
            'project_id'  => 1,
            'deploy_code' => true,
        ]);

        Server::create([
            'name'        => 'DB VM',
            'ip_address'  => '192.168.33.70',
            'user'        => 'deploy',
            'path'        => '/var/www',
            'project_id'  => 1,
            'deploy_code' => false,
        ]);
    }
}

<?php

use Illuminate\Database\Seeder;
use REBELinBLUE\Deployer\Server;

class ServerTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('servers')->delete();

        Server::create([
            'name'        => 'Web VM',
            'ip_address'  => '192.168.33.50',
            'user'        => 'deploy',
            'path'        => '/var/www',
            'project_id'  => 1,
            'deploy_code' => true,
        ]);

        Server::create([
            'name'        => 'Cron VM',
            'ip_address'  => '192.168.33.60',
            'user'        => 'deploy',
            'path'        => '/var/www',
            'project_id'  => 1,
            'deploy_code' => true,
        ]);

        Server::create([
            'name'        => 'Database VM',
            'ip_address'  => '192.168.33.70',
            'user'        => 'deploy',
            'path'        => '/home/deploy',
            'project_id'  => 1,
            'deploy_code' => false,
        ]);
    }
}

Change the DB VM seed

Change the DB VM seed


#!/usr/bin/env php
<?php
/*

// single file
php --file update_json.php -- -f eval-win81x64-enterprise.json

// *.json
ls -1 *.json | xargs -n1 -I% php --file update_json.php -- -f %
git diff --ignore-all-space --ignore-blank-lines >out
git co -- .
git apply out
rm out

*/

$shortopts = "";
$shortopts .= "f:";  // Required value

$options = getopt($shortopts);

$jfile = $options["f"];
$data = json_decode(file_get_contents($jfile), true);
for ($i = 0; $i < count($data['builders']); $i++) {
    if ($data['builders'][$i]['type'] == 'virtualbox-iso') {
        $data['builders'][$i]['post_shutdown_delay'] = "120s";
        $data['builders'][$i]['shutdown_timeout'] = "1h";

        // don't add new settings twice
        $nary = array('setextradata', '{{.Name}}', 'GUI/SuppressMessages', 'all');
        $found = false;
        foreach ($data['builders'][$i]['vboxmanage'] as $manage) {
            if (0 == count(array_diff($manage, $nary))) {
                $found = true;
                break;
            }
        }
        if (!$found) {
            array_push($data['builders'][$i]['vboxmanage'], $nary);
        }

    }
}
file_put_contents($jfile, json_encode($data));
file_put_contents($jfile, shell_exec("jq . $jfile"));

#!/usr/bin/env php
<?php
/*

// single file
php --file update_json.php -- -f eval-win81x64-enterprise.json

// *.json
ls -1 *.json | xargs -n1 -I% php --file update_json.php -- -f %
git diff --ignore-all-space --ignore-blank-lines >out
git co -- .
git apply out
rm out

*/

$shortopts = "";
$shortopts .= "f:";  // Required value

$options = getopt($shortopts);

$jfile = $options["f"];
$data = json_decode(file_get_contents($jfile), true);
for ($i = 0; $i < count($data['builders']); $i++) {
    if ($data['builders'][$i]['type'] == 'virtualbox-iso') {
        $data['builders'][$i]['post_shutdown_delay'] = "120s";
        $data['builders'][$i]['shutdown_timeout'] = "1h";
    }
}
file_put_contents($jfile, json_encode($data));
file_put_contents($jfile, shell_exec("jq . $jfile"));

Use global settings to suppress all GUI alerts

Do this instead:
vboxmanage setextradata global GUI/SuppressMessages "all"

to update ~/.virtualbox.d/virtualbox.xml


<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Doug
 * Date: 28/07/13
 * Time: 12:58
 * To change this template use File | Settings | File Templates.
 */

  namespace DVDoug\BoxPacker;

  class ItemListTest extends \PHPUnit_Framework_TestCase {

    function testCompare() {

      $box1 = new TestItem('Small', 20, 20, 2, 100);
      $box2 = new TestItem('Large', 200, 200, 20, 1000);
      $box3 = new TestItem('Medium', 100, 100, 10, 500);

      $list = new ItemList;
      $list->insert($box1);
      $list->insert($box2);
      $list->insert($box3);

      $sorted = [];
      while (!$list->isEmpty()) {
        $sorted[] = $list->extract();
      }
      self::assertEquals(array($box2,$box3,$box1), $sorted);
    }
  }

<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Doug
 * Date: 28/07/13
 * Time: 12:58
 * To change this template use File | Settings | File Templates.
 */

  namespace DVDoug\BoxPacker;

  class ItemListTest extends \PHPUnit_Framework_TestCase {

    function testCompare() {

      $box1 = new TestItem('Small', 20, 20, 2, 100);
      $box2 = new TestItem('Large', 200, 200, 20, 1000);
      $box3 = new TestItem('Medium', 100, 100, 10, 500);

      $list = new ItemList;
      $list->insert($box1);
      $list->insert($box2);
      $list->insert($box3);

      $sorted = array();
      while (!$list->isEmpty()) {
        $sorted[] = $list->extract();
      }
      self::assertEquals(array($box2,$box3,$box1), $sorted);
    }
  }

Use PHP5.3 compat array syntax

Use PHP5.3 compat array syntax


<?php
namespace phpgt\fetch;

use React\Promise\Deferred;

/**
 * Contains multiple requests and their promises.
 */
class RequestResolver implements \Iterator {

private $requestArray = [];
private $deferredArray = [];
private $index;

public function __construct() {

}

// Iterator methods ////////////////////////////////////////////////////////////

public function add(Request $request, Deferred $deferred) {
	$this->requestArray []= $request;
	$this->deferredArray []= $deferred;
}

public function current() {
	return $this->deferredArray[$this->index];
}

public function key() {
	return $this->requestArray[$this->index];
}

public function next() {
	++ $this->index;
}

public function rewind() {
	$this->index = 0;
}

public function valid() {
	return isset($this->requestArray[$this->index]);
}

}#

<?php
namespace phpgt\fetch;

use React\Promise\Deferred;

/**
 * Contains multiple requests and their promises.
 */
class RequestResolver implements \Iterator {

private $requestArray = [];
private $deferredArray = [];
private $index;

public function __construct() {

}

public function add(Request $request, Deferred $deferred) {
	$this->requestArray []= $request;
	$this->deferredArray []= $deferred;
}

// Iterator methods ////////////////////////////////////////////////////////////

public function current() {
	return $this->deferredArray[$this->index];
}

public function key() {
	return $this->requestArray[$this->index];
}

public function next() {
	++ $this->index;
}

public function rewind() {
	$this->index = 0;
}

public function valid() {
	return isset($this->requestArray[$this->index]);
}

}#

Move add out of Iterator methods section.


<?php

namespace App;

class CSRFProtection {
	protected static $_cookieKey = 'CSRF_TOKEN';
	public static $isForged;

	/**
	 * Checks POSTed data for CSRF token validity
	 */
	public static function detect(){
		if (self::$isForged !== null || $_SERVER['REQUEST_METHOD'] === 'GET')
			return;

		self::$isForged = !isset($_REQUEST[self::$_cookieKey]) || !Cookie::exists(self::$_cookieKey) || $_REQUEST[self::$_cookieKey] !== Cookie::get(self::$_cookieKey);
		if (self::$isForged)
			Cookie::set(self::$_cookieKey,bin2hex(random_bytes(16)), Cookie::SESSION);
	}

	/**
	 * Blocks CSRF requests
	 */
	public static function protect(){
		self::detect();

		if (self::$isForged === true)
			HTTP::statusCode(401, AND_DIE);
	}

	/**
	 * Removes the CSRF query parameter (if any) from any URL
	 *
	 * @param string $url
	 *
	 * @return string
	 */
	public static function removeParamFromURL($url){
		return rtrim(preg_replace(new RegExp(preg_quote(self::$_cookieKey, '~').'=[^&]+(&|$)'),'',$url),'?&');
	}
}

<?php

namespace App;

class CSRFProtection {
	protected static $_cookieKey = 'CSRF_TOKEN';
	public static $isForged;

	/**
	 * Checks POSTed data for CSRF token validity
	 */
	public static function detect(){
		$cookieMissing = !Cookie::exists(self::$_cookieKey);
		if (self::$isForged !== null || ($_SERVER['REQUEST_METHOD'] === 'GET' && !$cookieMissing))
			return;

		self::$isForged = !isset($_REQUEST[self::$_cookieKey]) || $cookieMissing || $_REQUEST[self::$_cookieKey] !== Cookie::get(self::$_cookieKey);
		if (self::$isForged)
			Cookie::set(self::$_cookieKey, bin2hex(random_bytes(16)), Cookie::SESSION);
	}

	/**
	 * Blocks CSRF requests
	 */
	public static function protect(){
		self::detect();

		if (self::$isForged === true)
			HTTP::statusCode(401, AND_DIE);
	}

	/**
	 * Removes the CSRF query parameter (if any) from any URL
	 *
	 * @param string $url
	 *
	 * @return string
	 */
	public static function removeParamFromURL($url){
		return rtrim(preg_replace(new RegExp(preg_quote(self::$_cookieKey, '~').'=[^&]+(&|$)'),'',$url),'?&');
	}
}

Fix CSRF tokens not existing after only get requests


<?php

final class PhutilAuthAdapterRemoteUser extends PhutilAuthAdapter {

  public function getProviderName() {
    return pht('RemoteUser');
  }

  public function getDescriptionForCreate() {
    return pht(
      'Configure a connection to use web server authentication '.
      'credentials to log in to Phabricator.');
  }

  public function getAdapterDomain() {
    return 'self';
  }

  public function getAdapterType() {
    return 'RemoteUser';
  }

  public function getAccountID() {
    return $_SERVER['REMOTE_USER'];
  }

  public function getAccountName() {
    return $this->getAccountID();
  }

}

<?php

final class PhutilAuthAdapterRemoteUser extends PhutilAuthAdapter {

  public function getProviderName() {
    return pht('RemoteUser');
  }

  public function getDescriptionForCreate() {
    return pht(
      'Configure a connection to use web server authentication '.
      'credentials to log in to Phabricator.');
  }

  public function getAdapterDomain() {
    return 'self';
  }

  public function getAdapterType() {
    return 'RemoteUser';
  }

  public function getAccountID() {
    return $_SERVER['REMOTE_USER'];
  }

  public function getAccountName() {
    return $this->getAccountID();
  }

  // if LDAP authorization is configured in addition to kerberos
  // authentication, Apache allows putting other attributes from LDAP
  // into the environment prefixed by AUTHORIZE_, so use them if present.
  public function getAccountRealName() {
    // cn is a standard LDAP attibute
    if (!empty($_SERVER['AUTHORIZE_CN']))
      return $_SERVER['AUTHORIZE_CN'];
    // Some installations may prefer to use displayName
    else if (!empty($_SERVER['AUTHORIZE_DISPLAYNAME']))
      return $_SERVER['AUTHORIZE_DISPLAYNAME'];
    // Some installations may populate the name field with the user's real
    // name. This seems to be erroneous, based on Microsoft documenting
    // this attribute as an RDN, so only use it as a last resort.
    else if (!empty($_SERVER['AUTHORIZE_NAME']))
      return $_SERVER['AUTHORIZE_NAME'];
    else
      return parent::getAccountRealName();
  }

  public function getAccountEmail() {
    if (!empty($_SERVER['AUTHORIZE_MAIL']))
      return $_SERVER['AUTHORIZE_MAIL'];
    else
      return parent::getAccountEmail();
  }

  public function getAccountURI() {
    if (!empty($_SERVER['AUTHORIZE_URL']))
      return $_SERVER['AUTHORIZE_URL'];
    else
      return parent::getAccountURI();
  }
}

Add additional methods to get info from mod_authnz_ldap environment.


<?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$

require_once('lib/wizard/wizard.php');

/**
 * Show the initial profiles choices
 */
class AdminWizardProfiles extends Wizard
{
    function pageTitle ()
    {
        return tra('Initialize Tiki');
    }
	function isEditable ()
	{
		return false;
	}

	function onSetupPage ($homepageUrl)
	{
		global	$smarty, $prefs;

		// Run the parent first
		parent::onSetupPage($homepageUrl);

		// Assign the page temaplte
		$wizardTemplate = 'wizard/admin_profiles.tpl';
		$smarty->assign('wizardBody', $wizardTemplate);

		return true;
	}

	function onContinue ($homepageUrl)
	{
		// Run the parent first
		parent::onContinue($homepageUrl);
	}
}

<?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$

require_once('lib/wizard/wizard.php');

/**
 * Show the initial profiles choices
 */
class AdminWizardProfiles extends Wizard
{
    function pageTitle ()
    {
        return tra('Featured Profiles');
    }
	function isEditable ()
	{
		return false;
	}

	function onSetupPage ($homepageUrl)
	{
		global	$smarty, $prefs;

		// Run the parent first
		parent::onSetupPage($homepageUrl);

		// Assign the page temaplte
		$wizardTemplate = 'wizard/admin_profiles.tpl';
		$smarty->assign('wizardBody', $wizardTemplate);

		return true;
	}

	function onContinue ($homepageUrl)
	{
		// Run the parent first
		parent::onContinue($homepageUrl);
	}
}

[ENH] Rename wizard page "Initialize Tiki" to "Featured Profiles". It describes better what it is and "invites" more profile pages

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


<?php
/**
 * Sage includes
 *
 * The $sage_includes array determines the code library included in your theme.
 * Add or remove files to the array as needed. Supports child theme overrides.
 *
 * Please note that missing files will produce a fatal error.
 *
 * @link https://github.com/roots/sage/pull/1042
 */
$sage_includes = [
  'lib/assets.php',  // Scripts and stylesheets
  'lib/extras.php',  // Custom functions
  'lib/setup.php',   // Theme setup
  'lib/titles.php',  // Page titles
  'lib/wrapper.php',
  'lib/upload.php'  // Theme wrapper class
];

foreach ($sage_includes as $file) {
  if (!$filepath = locate_template($file)) {
    trigger_error(sprintf(__('Error locating %s for inclusion', 'sage'), $file), E_USER_ERROR);
  }

  require_once $filepath;
}
unset($file, $filepath);

function myprefix_unregister_tags() {
    unregister_taxonomy_for_object_type('post_tag', 'post');
}
add_action('init', 'myprefix_unregister_tags');

/**
 * @var $roleObject WP_Role
 */
$roleObject = get_role( 'editor' );
if (!$roleObject->has_cap( 'edit_theme_options' ) ) {
    $roleObject->add_cap( 'edit_theme_options' );
}
function hide_menu() {
    global $submenu;
    unset($submenu['themes.php'][6]); // remove customize link
    remove_submenu_page( 'themes.php', 'themes.php' ); // hide the theme selection submenu
    remove_submenu_page( 'themes.php', 'widgets.php' ); // hide the widgets submenu

}

add_action('admin_menu', 'hide_menu');

Add menu cap to editor

Add menu cap to editor


<?php

if (! function_exists('locale')) {
    /**
     * Get the active locale.
     *
     * @return string
     */
    function locale()
    {
        return config('app.locale', config('app.fallback_locale'));
    }
}

if (! function_exists('carbonize')) {
    /**
     * Create a Carbon object from a string.
     *
     * @param string $timeString
     *
     * @return \Carbon\Carbon
     */
    function carbonize($timeString = null)
    {
        return new \Carbon\Carbon($timeString);
    }
}

if (! function_exists('isActiveRoute')) {
    /**
     * @param string $routeName
     * @param string $output
     *
     * @return bool
     */
    function isActiveRoute($routeName, $output = 'active')
    {
        /** @var \Laravelista\Ekko\Ekko $ekko */
        $ekko = app('Laravelista\Ekko\Ekko');

        return $ekko->isActiveRoute($routeName, $output);
    }
}

if (! function_exists('take')) {
    /**
     * Create a new piped item from a given value.
     *
     * @param mixed $value
     *
     * @return \SebastiaanLuca\Helpers\Pipe\Item
     */
    function take($value)
    {
        return new \SebastiaanLuca\Helpers\Pipe\Item($value);
    }
}

<?php

if (! function_exists('locale')) {
    /**
     * Get the active locale.
     *
     * @return string
     */
    function locale()
    {
        return config('app.locale', config('app.fallback_locale'));
    }
}

if (! function_exists('carbonize')) {
    /**
     * Create a Carbon object from a string.
     *
     * @param string $timeString
     *
     * @return \Carbon\Carbon
     */
    function carbonize($timeString = null)
    {
        return new \Carbon\Carbon($timeString);
    }
}

if (! function_exists('isActiveRoute')) {
    /**
     * Check if the given route is currently active.
     *
     * @param string $routeName
     * @param string $output
     *
     * @return bool
     */
    function isActiveRoute($routeName, $output = 'active')
    {
        /** @var \Laravelista\Ekko\Ekko $ekko */
        $ekko = app('Laravelista\Ekko\Ekko');

        return $ekko->isActiveRoute($routeName, $output);
    }
}

if (! function_exists('take')) {
    /**
     * Create a new piped item from a given value.
     *
     * @param mixed $value
     *
     * @return \SebastiaanLuca\Helpers\Pipe\Item
     */
    function take($value)
    {
        return new \SebastiaanLuca\Helpers\Pipe\Item($value);
    }
}

Add helper method phpdoc info

Add helper method phpdoc info


<?php

namespace Bolt\Extension\Bolt\Members;

use Bolt\Extension\Bolt\ClientLogin\ClientRecords;
use Bolt\Extension\Bolt\ClientLogin\Session;

/**
 * Members Profiles
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class MembersProfiles
{
    public function __construct(\Bolt\Application $app)
    {
        $this->app = $app;
    }

    public function getMembersProfiles($userid)
    {
        $records = new MembersRecords($this->app);

        $member = $records->getMember('id', $userid);

        if ($member) {
            $member['avatar']   = $records->getMemberMeta($userid, 'avatar');
            $member['location'] = $records->getMemberMeta($userid, 'location');

            return $member;
        }

        return $this->getDeletedUser();
    }

    private function getDeletedUser()
    {
        return array(
            'id' => -1,
            'username' => 'deleted',
            'email' => '',
            'displayname' => 'Deleted User',
            'lastseen' => '0000-00-00 00:00:00',
            'lastip' => '',
            'enabled' => 0,
            'roles' => '',
            'avatar' => 'http://placehold.it/350x150&text=Deleted+User',
            'location' => 'Unknown'
        );
    }
}

<?php

namespace Bolt\Extension\Bolt\Members;

use Bolt\Extension\Bolt\ClientLogin\ClientRecords;
use Bolt\Extension\Bolt\ClientLogin\Session;

/**
 * Members Profiles
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class MembersProfiles
{
    public function __construct(\Bolt\Application $app)
    {
        $this->app = $app;
    }

    public function getMembersProfiles($userid)
    {
        $records = new MembersRecords($this->app);

        $member = $records->getMember('id', $userid);

        if ($member) {
            $member['avatar']   = $records->getMemberMetaValue($userid, 'avatar');
            $member['location'] = $records->getMemberMetaValue($userid, 'location');

            return $member;
        }

        return $this->getDeletedUser();
    }

    private function getDeletedUser()
    {
        return array(
            'id' => -1,
            'username' => 'deleted',
            'email' => '',
            'displayname' => 'Deleted User',
            'lastseen' => '0000-00-00 00:00:00',
            'lastip' => '',
            'enabled' => 0,
            'roles' => '',
            'avatar' => 'http://placehold.it/350x150&text=Deleted+User',
            'location' => 'Unknown'
        );
    }
}

Add only the value to a members extra info

Signed-off-by: Gawain Lynch <f745ec5336bcd096400627fc09f6ec7139408726@gmail.com>


<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use \Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseRegistrationFormType;

class RegistrationFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName')
            ->add('lastName');
    }

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

<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use \Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseRegistrationFormType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RegistrationFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName')
            ->add('lastName');
    }

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

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('csrf_protection', false);
    }
}

Update namespace and add one more function in order to override csrf_token field


打卡紀錄

    @forelse($records as $record)

{{ $record->club->name }}
                    {!! $record->club->clubType->tag ?? '' !!}
                    @if(!$record->club->is_counted)
                        不列入集點
                    @endif

                    {{ $record->created_at }}
                    （{{ (new \Carbon\Carbon($record->created_at))->diffForHumans() }}）

    @empty

                尚無打卡紀錄，快去打卡吧

    @endforelse

打卡紀錄

    @forelse($records as $record)

{{ link_to_route('clubs.show', $record->club->name, $record->club) }}
                    {!! $record->club->clubType->tag ?? '' !!}
                    @if(!$record->club->is_counted)
                        不列入集點
                    @endif

                    {{ $record->created_at }}
                    （{{ (new \Carbon\Carbon($record->created_at))->diffForHumans() }}）

    @empty

                尚無打卡紀錄，快去打卡吧

    @endforelse

Add link to club name

Add link to club name


<?php

use Assembly\Container\Container;
use GlideModule\GlideDefinitionProvider;

class GlideDefinitionProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testGlide()
    {
        $container = new Container([], [new GlideDefinitionProvider()]);

        $glide = $container->get('glide');

        $this->assertInstanceOf('League\Glide\Server', $glide);
    }
}

<?php

use Assembly\Container\Container;
use GlideModule\GlideDefinitionProvider;

class GlideDefinitionProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testGlide()
    {
        $container = new Container([], [new GlideDefinitionProvider(), new GlideOptionDefinitionProvider]);

        $glide = $container->get('glide');

        $this->assertInstanceOf('League\Glide\Server', $glide);
    }
}

class GlideOptionDefinitionProvider extends \Assembly\ArrayDefinitionProvider
{
    public function getArrayDefinitions()
    {
        return [
            // Options are required for glide factory
            'glide.options' => ['source' => sys_get_temp_dir(), 'cache' => sys_get_temp_dir()],
        ];
    }
}

Fix require glide configuration for tests

Add 'source' and 'cache' for glide.options


<?php namespace Modules\Blog\Repositories\Cache;

use Modules\Blog\Repositories\TagRepository;
use Modules\Core\Repositories\Cache\BaseCacheDecorator;

class CacheTagDecorator extends BaseCacheDecorator implements TagRepository
{
    /**
     * @var TagRepository
     */
    protected $repository;

    public function __construct(TagRepository $tag)
    {
        parent::__construct();
        $this->entityName = 'tags';
        $this->repository = $tag;
    }

    /**
     * @param $name
     * @return mixed
     */
    public function findByName($name)
    {
        return $this->cache
            ->tags($this->entityName, 'global')
            ->remember("{$this->locale}.{$this->entityName}.findByName.{$name}", $this->cacheTime,
                function () use ($name) {
                    return $this->repository->findByName($name);
                }
            );
    }

    /**
     * Create the tag for the specified language
     *
     * @param string $lang
     * @param array $name
     * @return mixed
     */
    public function createForLanguage($lang, $name)
    {
        $this->cache->tags($this->entityName)->flush();

        return $this->repository->createForLanguage($lang, $name);
    }
}

Add empty line at EOF

Add empty line at EOF


<?php

declare(strict_types=1);

namespace Doctrine\Bundle\MongoDBBundle\Repository;

use Doctrine\ODM\MongoDB\Repository\DocumentRepository;

/**
 * Optional DocumentRepository base class with a simplified constructor (for autowiring).
 *
 * To use in your class, inject the "registry" service and call
 * the parent constructor. For example:
 *
 * class YourDocumentRepository extends ServiceDocumentRepository
 * {
 *     public function __construct(RegistryInterface $registry)
 *     {
 *         parent::__construct($registry, YourDocument::class);
 *     }
 * }
 */
class ServiceDocumentRepository extends DocumentRepository implements ServiceDocumentRepositoryInterface
{
    use ServiceRepositoryTrait;
}

<?php

declare(strict_types=1);

namespace Doctrine\Bundle\MongoDBBundle\Repository;

use Doctrine\ODM\MongoDB\Repository\DocumentRepository;

/**
 * Optional DocumentRepository base class with a simplified constructor (for autowiring).
 *
 * To use in your class, inject the "registry" service and call
 * the parent constructor. For example:
 *
 * namespace AppBundle\Repository;
 *
 * use AppBundle\Document\YourDocument;
 * use Doctrine\Bundle\MongoDBBundle\ManagerRegistry;
 * use Doctrine\Bundle\MongoDBBundle\Repository\ServiceDocumentRepository;
 *
 * class YourDocumentRepository extends ServiceDocumentRepository
 * {
 *     public function __construct(ManagerRegistry $registry)
 *     {
 *         parent::__construct($registry, YourDocument::class);
 *     }
 * }
 */
class ServiceDocumentRepository extends DocumentRepository implements ServiceDocumentRepositoryInterface
{
    use ServiceRepositoryTrait;
}

Update example for repository autowired

Update example for repository autowired

The example was a fast copy/paste from the ORM version.
The ODM one is a little different


<?php
/**
 * This file is part of HookMeUp.
 *
 * (c) Sebastian Feldmann <sf@sebastian.feldmann.info>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace HookMeUp\Hook\Message\Validator\Rule;

use HookMeUp\Git\CommitMessage;
use HookMeUp\Hook\Message\Validator\Rule;

/**
 * Class Base
 *
 * @package HookMeUp
 * @author  Sebastian Feldmann <sf@sebastian-feldmann.info>
 * @link    https://github.com/sebastianfeldmann/hookmeup
 * @since   Class available since Release 0.9.0
 */
abstract class Base implements Rule
{
    /**
     * Rule hint.
     *
     * @var string
     */
    protected $hint;

    /**
     * @return string
     */
    public function getHint()
    {
        return $this->hint;
    }

    /**
     * @param  \HookMeUp\Git\CommitMessage $msg
     * @return bool
     */
    public abstract function pass(CommitMessage $msg);
}

<?php
/**
 * This file is part of HookMeUp.
 *
 * (c) Sebastian Feldmann <sf@sebastian.feldmann.info>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace HookMeUp\Hook\Message\Validator\Rule;

use HookMeUp\Git\CommitMessage;
use HookMeUp\Hook\Message\Validator\Rule;

/**
 * Class Base
 *
 * @package HookMeUp
 * @author  Sebastian Feldmann <sf@sebastian-feldmann.info>
 * @link    https://github.com/sebastianfeldmann/hookmeup
 * @since   Class available since Release 0.9.0
 */
abstract class Base implements Rule
{
    /**
     * Rule hint.
     *
     * @var string
     */
    protected $hint;

    /**
     * @return string
     */
    public function getHint()
    {
        return $this->hint;
    }

    /**
     * @param  \HookMeUp\Git\CommitMessage $msg
     * @return bool
     */
    abstract public function pass(CommitMessage $msg);
}

Move abstract declaration in front to precede visibility


    <input name="<?php  echo $nameform ?>" type="text" class="timepicker" value="<?php echo $value ?>">

<?php if(!empty($value)): ?>

<?php endif; ?>

    <input name="<?php  echo $nameform ?>" type="text" class="timepicker" readonly="readonly" value="<?php echo $value ?>">

<?php if(!empty($value)): ?>

<?php endif; ?>

Read only to force the use of the time picker


<?php

use Sami\Sami;
use Sami\Version\GitVersionCollection;
use Symfony\Component\Finder\Finder;

$dir = __DIR__ . '/src';
$iterator = Finder::create()
    ->files()
    ->name('*.php')
    ->in($dir)
;

$versions = GitVersionCollection::create($dir)
    ->addFromTags(function ($version) { return preg_match('/^v?\d+\.\d+\.\d+$/', $version); })
    ->add('master', 'production')
    ->add('develop', 'development')
;

$options = array(
    'title'                => 'jk/restserver API',
    'versions'             => $versions,
    'build_dir'            => __DIR__.'/build/sami/%version%',
    'cache_dir'            => __DIR__.'/build/sami_cache/%version%',
    'default_opened_level' => 2,
);

return new Sami($iterator, $options);

<?php

use Sami\Sami;
use Sami\Version\GitVersionCollection;
use Symfony\Component\Finder\Finder;

$dir = __DIR__ . '/src';
$iterator = Finder::create()
    ->files()
    ->name('*.php')
    ->in($dir);

$versions = GitVersionCollection::create($dir)
    ->addFromTags(function ($version) {
        return preg_match('/^v?\d+\.\d+\.\d+$/', $version);
    })
    ->add('master', 'production')
    ->add('develop', 'development');

$options = array(
    'title' => 'jk/restserver API',
    'versions' => $versions,
    'build_dir' => __DIR__ . '/build/sami/%version%',
    'cache_dir' => __DIR__ . '/build/sami_cache/%version%',
    'default_opened_level' => 2,
);

return new Sami($iterator, $options);

Make sami/sami config PSR1/2 compliant

Make sami/sami config PSR1/2 compliant


<?php

Director::addRules(60, array(
	'extadmin' => 'ExternalContentAdmin',
	'extcon' => 'ExternalContentPage_Controller',
));

// enable this for older versions  of 2.4 and disable the extension
// Object::useCustomClass('HtmlEditorField_Toolbar', 'ExternalHtmlEditorField_Toolbar');

Object::add_extension('HtmlEditorField_Toolbar', 'ExternalContentHtmlEditorExtension');

set_include_path(dirname(__FILE__).'/thirdparty'.PATH_SEPARATOR.get_include_path());

<?php

Director::addRules(60, array(
	'extadmin' => 'ExternalContentAdmin',
	'extcon' => 'ExternalContentPage_Controller',
));

// enable this for older versions  of 2.4 and disable the extension
// Object::useCustomClass('HtmlEditorField_Toolbar', 'ExternalHtmlEditorField_Toolbar');

// Disabled as it still has a problem:
// - loading javascript from the updateLinkForm call yields a blank form
//Object::add_extension('HtmlEditorField_Toolbar', 'ExternalContentHtmlEditorExtension');

set_include_path(dirname(__FILE__).'/thirdparty'.PATH_SEPARATOR.get_include_path());

Disable the linking form - javascript loading problem.

Prevents the linking form from being visible at all.