<?php

final class PhabricatorHomeProfileMenuItem
  extends PhabricatorProfileMenuItem {

  const MENUITEMKEY = 'home.dashboard';

  public function getMenuItemTypeName() {
    return pht('Home');
  }

  private function getDefaultName() {
    return pht('Home');
  }

  public function canHideMenuItem(
    PhabricatorProfileMenuItemConfiguration $config) {
    return false;
  }

  public function canMakeDefault(
    PhabricatorProfileMenuItemConfiguration $config) {
    return true;
  }

  public function getDisplayName(
    PhabricatorProfileMenuItemConfiguration $config) {
    $name = $config->getMenuItemProperty('name');

    if (strlen($name)) {
      return $name;
    }

    return $this->getDefaultName();
  }

  public function newPageContent() {
    $viewer = $this->getViewer();

    return id(new PHUIHomeView())
      ->setViewer($viewer);
  }

  public function buildEditEngineFields(
    PhabricatorProfileMenuItemConfiguration $config) {
    return array(
      id(new PhabricatorTextEditField())
        ->setKey('name')
        ->setLabel(pht('Name'))
        ->setPlaceholder($this->getDefaultName())
        ->setValue($config->getMenuItemProperty('name')),
    );
  }

  protected function newNavigationMenuItems(
    PhabricatorProfileMenuItemConfiguration $config) {
    $viewer = $this->getViewer();

    $name = $this->getDisplayName($config);
    $icon = 'fa-home';
    $href = $this->getItemViewURI($config);

    $item = $this->newItem()
      ->setHref($href)
      ->setName($name)
      ->setIcon($icon);

    return array(
      $item,
    );
  }

}

<?php

final class PhabricatorHomeProfileMenuItem
  extends PhabricatorProfileMenuItem {

  const MENUITEMKEY = 'home.dashboard';

  public function getMenuItemTypeName() {
    return pht('Home');
  }

  private function getDefaultName() {
    return pht('Home');
  }

  public function canMakeDefault(
    PhabricatorProfileMenuItemConfiguration $config) {
    return true;
  }

  public function getDisplayName(
    PhabricatorProfileMenuItemConfiguration $config) {
    $name = $config->getMenuItemProperty('name');

    if (strlen($name)) {
      return $name;
    }

    return $this->getDefaultName();
  }

  public function newPageContent() {
    $viewer = $this->getViewer();

    return id(new PHUIHomeView())
      ->setViewer($viewer);
  }

  public function buildEditEngineFields(
    PhabricatorProfileMenuItemConfiguration $config) {
    return array(
      id(new PhabricatorTextEditField())
        ->setKey('name')
        ->setLabel(pht('Name'))
        ->setPlaceholder($this->getDefaultName())
        ->setValue($config->getMenuItemProperty('name')),
    );
  }

  protected function newNavigationMenuItems(
    PhabricatorProfileMenuItemConfiguration $config) {
    $viewer = $this->getViewer();

    $name = $this->getDisplayName($config);
    $icon = 'fa-home';
    $href = $this->getItemViewURI($config);

    $item = $this->newItem()
      ->setHref($href)
      ->setName($name)
      ->setIcon($icon);

    return array(
      $item,
    );
  }

}

Allow "Magic Home" to be hidden

Allow "Magic Home" to be hidden

Summary: Ref T12174. Fallback behavior on this already appears to be sensible.

Test Plan:
  - Hid "Magic Home".
  - Viewed homepage with no dashboards on the menu.
  - Saw "Magic Home" content, with no item in the menu selected, which seems reasonable.

{F2557022}

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T12174

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


<?php

namespace Stevenmaguire\OAuth2\Client\Provider;

use League\OAuth2\Client\Provider\ResourceOwnerInterface;

class DropboxResourceOwner implements ResourceOwnerInterface
{
    /**
     * Raw response
     *
     * @var array
     */
    protected $response;

    /**
     * Creates new resource owner.
     *
     * @param array  $response
     */
    public function __construct(array $response = array())
    {
        $this->response = $response;
    }

    /**
     * Get resource owner id
     *
     * @return string
     */
    public function getId()
    {
        return $this->response['uid'] ?: null;
    }

    /**
     * Get resource owner name
     *
     * @return string
     */
    public function getName()
    {
        return $this->response['display_name'] ?: null;
    }

    /**
     * Return all of the owner details available as an array.
     *
     * @return array
     */
    public function toArray()
    {
        return $this->response;
    }
}

<?php

namespace Stevenmaguire\OAuth2\Client\Provider;

use League\OAuth2\Client\Provider\ResourceOwnerInterface;

class DropboxResourceOwner implements ResourceOwnerInterface
{
    /**
     * Raw response
     *
     * @var array
     */
    protected $response;

    /**
     * Creates new resource owner.
     *
     * @param array  $response
     */
    public function __construct(array $response = array())
    {
        $this->response = $response;
    }

    /**
     * Get resource owner id
     *
     * @return string
     */
    public function getId()
    {
        return $this->response['account_id'] ?: null;
    }

    /**
     * Get resource owner name
     *
     * @return string
     */
    public function getName()
    {
        return $this->response['name']['display_name'] ?: null;
    }

    /**
     * Return all of the owner details available as an array.
     *
     * @return array
     */
    public function toArray()
    {
        return $this->response;
    }
}

Migrate to Dropbox API v2

Migrate to Dropbox API v2


<?php
echo "
";
echo "
Sorry, your request could not be completed.
";
echo "
It seems that the page you were trying to reach is unavailable, or maybe it has just been moved. The best thing to do is to start again from the href("home.html")}\">home page.
";
echo "
If the problem persists or if you definitely cannot find what you are looking for, please feel free to href("contact.html")}\">report the issue.
";
echo "
";
?>

Add background color to container

Add background color to container


<form name="loginform" action="<?php bloginfo("wpurl");?>/wp-login.php" method="post">
	<input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" />
	<input type="hidden" name="user-cookie" value="1" />

	<input type="text" name="log" placeholder="E-postadress eller nick"
		<?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?>
		 />

	<input type="password" name="pwd" placeholder="Lösenord" />

		<input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" />
		Håll mig inloggad

		<input type="submit" name="submit" class="small" value="Logga in" />

</form>

<form name="loginform" action="<?php echo wp_login_url(home_url());?>" method="post">
	<input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" />
	<input type="hidden" name="user-cookie" value="1" />

	<input type="text" name="log" placeholder="E-postadress eller nick"
		<?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?>
		 />

	<input type="password" name="pwd" placeholder="Lösenord" />

		<input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" />
		Håll mig inloggad

		<input type="submit" name="submit" class="small" value="Logga in" />

</form>

Fix incorrect login url for sign in form on frontpage


<?php

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

Route::get('/',  array('as' => 'project.index', 'uses' => 'ProjectController@index'));

Route::get('oauth2/{provider}', 'OauthController@index');

Route::get('login', array('as' => 'login', function () {
    return Redirect::to('oauth2/google');
}))->before('guest');

Route::get('logout', array('as' => 'logout', function () {
    Auth::logout();
    return Redirect::to('/');
}))->before('auth');

<?php

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

Route::get('/',  array('as' => 'project.index', 'uses' => 'ProjectController@index'));

Route::get('oauth2/{provider}', 'OauthController@index');

Route::get('login', array('as' => 'login', function () {
    return Redirect::to('oauth2/google');
}));

Route::get('logout', array('as' => 'logout', function () {
    Auth::logout();
    return Redirect::to('/');
}))->before('auth');

Fix for the login route not working

Fix for the login route not working


<?php

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

namespace Symfony\Component\HttpKernel\Tests\Fixtures;

use Symfony\Component\HttpKernel\Client;

class TestClient extends Client
{
    protected function getScript($request)
    {
        $script = parent::getScript($request);

        $script = preg_replace('/(\->register\(\);)/', "$0\nrequire_once '".__DIR__."/../../vendor/autoload.php';", $script);

        return $script;
    }
}

<?php

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

namespace Symfony\Component\HttpKernel\Tests\Fixtures;

use Symfony\Component\HttpKernel\Client;

class TestClient extends Client
{
    protected function getScript($request)
    {
        $script = parent::getScript($request);

        $autoload = file_exists(__DIR__.'/../../vendor/autoload.php')
            ? __DIR__.'/../../vendor/autoload.php'
            : __DIR__.'/../../../../../../../../autoload.php'
        ;

        $script = preg_replace('/(\->register\(\);)/', "$0\nrequire_once '$autoload';\n", $script);

        return $script;
    }
}

Fix Symfony2 full framework tests

[HttpKernel] Fix Symfony2 full framework tests


<?php

use Symfony\Component\HttpFoundation\Request;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

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

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

<?php

use Symfony\Component\HttpFoundation\Request;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if ($_SERVER['HTTP_HOST'] !== 'beta.forexcashback.com' || $_SERVER['REMOTE_ADDR'] === '127.0.0.1') {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

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

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

Allow access from beta site

Allow access from beta site


<?php

namespace Fenrizbes\UploadableBundle\File;

use Symfony\Component\HttpFoundation\File\File;

class UploadableFile extends File
{
    /**
     * Path to the project's root directory
     *
     * @var string
     */
    protected $root_path;

    /**
     * Web path to the file
     *
     * @var string
     */
    protected $web_path;

    public function __construct($root_path, $web_path)
    {
        $this->root_path = $root_path;
        $this->web_path  = $web_path;

        return parent::__construct($root_path . $web_path);
    }

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

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

<?php

namespace Fenrizbes\UploadableBundle\File;

use Symfony\Component\HttpFoundation\File\File;

class UploadableFile extends File
{
    /**
     * Path to the project's root directory
     *
     * @var string
     */
    protected $root_path;

    /**
     * Web path to the file
     *
     * @var string
     */
    protected $web_path;

    public function __construct($root_path, $web_path)
    {
        $this->root_path = $root_path;
        $this->web_path  = $web_path;

        parent::__construct($root_path . $web_path);
    }

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

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

Fix an issue 'Constructor returns value'


<?php

namespace Showpad;

use Buzz\Browser;

final class BuzzAdapter implements Adapter
{
    /**
     * @var Browser
     */
    private $browser;

    /**
     * Constructor
     *
     * @param Browser $browser A Buzz browser instance
     */
    public function __construct(Browser $browser)
    {
        $this->browser = $browser;
    }

    /**
     * Send an http request
     *
     * @param string $method     The HTTP method
     * @param string $url        The url to send the request to
     * @param array  $parameters The parameters for the request (assoc array)
     * @param array  $headers    The headers for the request (assoc array)
     *
     * return mixed
     */
    public function request($method, $url, array $parameters = null, array $headers = null)
    {
        $response = $this->browser->submit($url, $parameters, $method, $headers);

        return json_decode($response->getContent(), true);
    }
}

<?php

namespace Showpad;

use Buzz\Browser;

final class BuzzAdapter implements Adapter
{
    /**
     * @var Browser
     */
    private $browser;

    /**
     * Constructor
     *
     * @param Browser $browser A Buzz browser instance
     */
    public function __construct(Browser $browser)
    {
        $this->browser = $browser;
    }

    /**
     * Send an http request
     *
     * @param string $method     The HTTP method
     * @param string $url        The url to send the request to
     * @param array  $parameters The parameters for the request (assoc array)
     * @param array  $headers    The headers for the request (assoc array)
     *
     * return mixed
     */
    public function request($method, $url, array $parameters = null, array $headers = null)
    {
        // add query parameters to the url if needed
        if (isset($parameters['query']) && is_array($parameters['query'])) {
            $query = parse_url($url, PHP_URL_QUERY);

            $url .= ($query === null ? '?' : '&') . http_build_query($parameters['query']);
        }

        $response = $this->browser->submit($url, $parameters, $method, $headers);

        return json_decode($response->getContent(), true);
    }
}

Add the get parameters to the url.

Add the get parameters to the url.


<?php
require_once __DIR__ . '/base.php';
require_once __DIR__ . '/../../lib/utils.php';

class NavigatorSection extends RawDataContainer implements Component {
  public function render(): Component {
    $subpagetmpls = $this->get('subpages');

    $subpageitems = array_map(
      function ($tmpl) {
        return HtmlElement::emmetDepth(
          "li#to-{$tmpl['page']}>a",
          [
            [
              'dataset' => $tmpl,
            ],
            [
              'href' => $tmpl['href'],
              $tmpl['title'],
            ],
          ]
        );
      },

      $subpagetmpls
    );

    return HtmlElement::emmetBottom('nav>ul', [
      HtmlElement::emmetTop('li#subpage-navigator-title.subpage.title', []),
      HtmlElement::emmetTop('ul#subpage-navigator.subpage', $subpageitems),
    ]);
  }
}
?>

<?php
require_once __DIR__ . '/base.php';
require_once __DIR__ . '/../../lib/utils.php';

class NavigatorSection extends RawDataContainer implements Component {
  public function render(): Component {
    $currentpage = $this->get('page');
    $subpagetmpls = $this->get('subpages');

    $subpageitems = array_map(
      function ($tmpl) use($currentpage) {
        $page = $tmpl['page'];

        return HtmlElement::emmetDepth(
          "li#to-$page>a",
          [
            [
              'dataset' => $tmpl,
              'classes' => $currentpage === $page ? ['current-page'] : [],
            ],
            [
              'href' => $tmpl['href'],
              $tmpl['title'],
            ],
          ]
        );
      },

      $subpagetmpls
    );

    return HtmlElement::emmetBottom('nav>ul', [
      HtmlElement::emmetTop('li#subpage-navigator-title.subpage.title', []),
      HtmlElement::emmetTop('ul#subpage-navigator.subpage', $subpageitems),
    ]);
  }
}
?>

Mark link to points to displaying page

Mark link to points to displaying page

As .current-page


<?php

declare(strict_types=1);

namespace Rinvex\Support\Traits;

use DateTimeZone;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;

trait HasTimezones
{
    /**
     * Return a timestamp as DateTime object.
     *
     * @param mixed $value
     *
     * @return \Illuminate\Support\Carbon
     */
    protected function asDateTime($value)
    {
        $datetime = parent::asDateTime($value);
        $timezone = optional(request()->user())->timezone;

        if (! $timezone || $timezone === config('app.timezone')) {
            return $datetime;
        }

        $thisIsUpdateRequest = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 30), function ($trace) {
            return $trace['function'] === 'setAttribute';
        });

        if ($thisIsUpdateRequest) {
            // When updating attributes, we need to reset user timezone to system timezone before saving!
            return Date::parse($datetime->toDateTimeString(), $timezone)->setTimezone(config('app.timezone'));
        }

        return $datetime->setTimezone(new DateTimeZone($timezone));
    }
}

<?php

declare(strict_types=1);

namespace Rinvex\Support\Traits;

use DateTimeZone;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;

trait HasTimezones
{
    /**
     * Return a timestamp as DateTime object.
     *
     * @param mixed $value
     *
     * @return \Illuminate\Support\Carbon
     */
    protected function asDateTime($value)
    {
        $datetime = parent::asDateTime($value);
        $timezone = optional(request()->user())->timezone;

        if (! $timezone || $timezone === config('app.timezone')) {
            return $datetime;
        }

        $thisIsUpdateRequest = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 30), function ($trace) {
            return $trace['function'] === 'setAttribute';
        });

        if ($thisIsUpdateRequest) {
            // When updating attributes, we need to reset user timezone to system timezone before saving!
            return Date::parse($datetime->toDateTimeString(), $timezone)->setTimezone(config('app.timezone'));
        }

        return $datetime->setTimezone(new DateTimeZone($timezone));
    }

    /**
     * Get a fresh timestamp for the model.
     *
     * @return \Illuminate\Support\Carbon
     */
    public function freshTimestamp()
    {
        $now = Date::now();

        $timezone = optional(request()->user())->timezone;

        return (! $timezone || $timezone === config('app.timezone')) ? $now : $now->setTimezone($timezone);
    }
}

Fix timezone issue with created_at, updated_at, and automatically generated timestamp fields


<?php

namespace Faker\Test\Provider\en_US;

use Faker\Provider\en_US\Company;
use Faker\Generator;

class CompanyTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var Generator
     */
    private $faker;

    public function setUp()
    {
        $faker = new Generator();
        $faker->addProvider(new Company($faker));
        $this->faker = $faker;
    }

    public function testEin()
    {
        $number = $this->faker->ein;

        // should be in the format ##-#######, with a valid prefix
        $this->assertRegExp('/^(0[1-6]||1[0-6]|2[0-7]|[35]\d|[468][0-8]|7[1-7]|9[0-58-9])-\d{7}$/', $number);
    }
}

<?php

namespace Faker\Test\Provider\en_US;

use Faker\Provider\en_US\Company;
use Faker\Generator;

class CompanyTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var Generator
     */
    private $faker;

    public function setUp()
    {
        $faker = new Generator();
        $faker->addProvider(new Company($faker));
        $this->faker = $faker;
    }

    /**
     * @link https://stackoverflow.com/questions/4242433/regex-for-ein-number-and-ssn-number-format-in-jquery/35471665#35471665
     */
    public function testEin()
    {
        $number = $this->faker->ein;

        // should be in the format ##-#######, with a valid prefix
        $this->assertRegExp('/^(0[1-6]||1[0-6]|2[0-7]|[35]\d|[468][0-8]|7[1-7]|9[0-58-9])-\d{7}$/', $number);
    }
}

Add source link to EIN validation regex

Add source link to EIN validation regex


<?php

namespace FOQ\ElasticaBundle\Transformer;

use RuntimeException;
use Traversable;
use ArrayAccess;

/**
 * AutomaticObjectToArrayTransformer
 * Tries to convert objects by generating getters
 * based on the required keys
 */
class ObjectToArrayAutomaticTransformer implements ObjectToArrayTransformerInterface
{
    /**
     * Transforms an object into an array having the required keys
     *
     * @param object $object the object to convert
     * @param array $requiredKeys the keys we want to have in the returned array
     * @return array
     **/
    public function transform($object, array $requiredKeys)
    {
        $class = get_class($object);
        $array = array();
        foreach ($requiredKeys as $key) {
            $getter = 'get'.ucfirst($key);
            if (!method_exists($class, $getter)) {
                throw new RuntimeException(sprintf('The getter %s::%s does not exist', $class, $getter));
            }
            $array[$key] = $this->normalizeValue($object->$getter());
        }

        return array_filter($array);
    }

    public function normalizeValue($value)
    {
        if (is_array($value) || $value instanceof Traversable || $value instanceof ArrayAccess) {
            $values = array();
            foreach ($value as $v) {
                $values[] = (string) $v;
            }
            $value = implode(', ', $values);
        }

        return (string) $value;
    }
}

<?php

namespace FOQ\ElasticaBundle\Transformer;

use RuntimeException;
use Traversable;
use ArrayAccess;

/**
 * AutomaticObjectToArrayTransformer
 * Tries to convert objects by generating getters
 * based on the required keys
 */
class ObjectToArrayAutomaticTransformer implements ObjectToArrayTransformerInterface
{
    /**
     * Transforms an object into an array having the required keys
     *
     * @param object $object the object to convert
     * @param array $requiredKeys the keys we want to have in the returned array
     * @return array
     **/
    public function transform($object, array $requiredKeys)
    {
        $class = get_class($object);
        $array = array();
        foreach ($requiredKeys as $key) {
            $getter = 'get'.ucfirst($key);
            if (!method_exists($class, $getter)) {
                throw new RuntimeException(sprintf('The getter %s::%s does not exist', $class, $getter));
            }
            $array[$key] = $this->normalizeValue($object->$getter());
        }

        return array_filter($array);
    }

    public function normalizeValue($value)
    {
        if (is_array($value) || $value instanceof Traversable || $value instanceof ArrayAccess) {
            $value = array_map(function($v) {
                return (string) $v;
            }, is_array($value) ? $value : iterator_to_array($value));
        } else {
            $value = (string) $value;
        }

        return $value;
    }
}

Make the automatic object to array transformer generate deep arrays


<?php

class CataloguePageProductExtension extends DataExtension
{

    public function updateRelativeLink($base, $action)
    {
        $page = CataloguePage::get()->first();

        $link = Controller::join_links(
            $page->RelativeLink("product"),
            $this->owner->URLSegment,
            $action
        );

        return $link;
    }

    public function updateAncestors($ancestors, $include_parent)
    {

        // Check if there is a catalogue page with this product
        $page = CataloguePage::get()
            ->filter("Products.ID", $this->owner->ID)
            ->first();

        if(!$page) {
            // Else check we have a product in a category that matches
            $categories = $this->owner->Categories();
            $page = null;

            // Find the first category page we have mapped
            foreach($categories as $category) {
                if(!$page && $category->CataloguePages()->exists()) {
                    $page = $category->CataloguePages()->first();
                }
            }
        }

        if($page) {
            // Clear all ancestors
            foreach($ancestors as $ancestor) {
                $ancestors->remove($ancestor);
            }

            if($include_parent) {
                $ancestors->push($page);
            }

            while($page = $page->getParent()) {
                $ancestors->push($page);
            }
        }
    }

}

<?php

class CataloguePageProductExtension extends DataExtension
{

    public function updateRelativeLink($base, $action)
    {
        $page = null;

        // Try to find the current product's page
        if ($this->owner->CataloguePages()->exists()) {
            $page = $this->owner->CataloguePages()->first();
        } elseif ($category = $this->owner->Categories()->first()) {
            if($category->CataloguePages()->exists()) {
                $page = $category->CataloguePages()->first();
            }
        }

        // If no page has been found, revert to a default
        if (!$page) {
            $page = CataloguePage::get()->first();
        }

        $link = Controller::join_links(
            $page->RelativeLink("product"),
            $this->owner->URLSegment,
            $action
        );

        return $link;
    }

    public function updateAncestors($ancestors, $include_parent)
    {

        // Check if there is a catalogue page with this product
        $page = CataloguePage::get()
            ->filter("Products.ID", $this->owner->ID)
            ->first();

        if(!$page) {
            // Else check we have a product in a category that matches
            $categories = $this->owner->Categories();
            $page = null;

            // Find the first category page we have mapped
            foreach($categories as $category) {
                if(!$page && $category->CataloguePages()->exists()) {
                    $page = $category->CataloguePages()->first();
                }
            }
        }

        if($page) {
            // Clear all ancestors
            foreach($ancestors as $ancestor) {
                $ancestors->remove($ancestor);
            }

            if($include_parent) {
                $ancestors->push($page);
            }

            while($page = $page->getParent()) {
                $ancestors->push($page);
            }
        }
    }

}

Update product relative link to link to the correct parent page


<?php

/**
 * This file is part of Herbie.
 *
 * (c) Thomas Breuss <www.tebe.ch>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace herbie\plugin\disqus;

use Herbie;
use Twig_SimpleFunction;

class DisqusPlugin extends Herbie\Plugin
{

    /**
     * @var Twig_Environment
     */
    private $twig;

    public function onTwigInitialized(Herbie\Event $event)
    {
        $this->twig = $event['twig'];
        $this->twig->addFunction(
            new Twig_SimpleFunction('disqus', [$this, 'disqus'], ['is_safe' => ['html']])
        );
    }

    /**
     * @param string $shortname
     * @return string
     */
    public function disqus($shortname)
    {
        $template = $this->app['config']->get(
            'plugins.config.disqus.template',
            '@plugin/disqus/templates/disqus.twig'
        );
        return $this->twig->render($template, [
           'shortname' => $shortname
        ]);
    }
}

<?php

/**
 * This file is part of Herbie.
 *
 * (c) Thomas Breuss <www.tebe.ch>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace herbie\plugin\disqus;

use Herbie;
use Twig_SimpleFunction;

class DisqusPlugin extends Herbie\Plugin
{

    /**
     * @var Twig_Environment
     */
    private $twig;

    public function onTwigInitialized(Herbie\Event $event)
    {
        $this->twig = $event['twig'];
        $this->twig->addFunction(
            new Twig_SimpleFunction('disqus', [$this, 'disqus'], ['is_safe' => ['html']])
        );
    }

    /**
     * @param string $shortname
     * @return string
     */
    public function disqus($shortname)
    {
        $template = $this->config->get(
            'plugins.config.disqus.template',
            '@plugin/disqus/templates/disqus.twig'
        );
        return $this->twig->render($template, [
           'shortname' => $shortname
        ]);
    }
}

Use config method from plugin class

Use config method from plugin class


<?php namespace Illuminate\Foundation;

use Illuminate\Support\Collection;

class Inspiring {

	/**
	 * Get an inspiring quote.
	 *
	 * Taylor & Dayle made this commit from Jungfraujoch. (11,333 ft.)
	 *
	 * @return string
	 */
	public static function quote()
	{
		return Collection::make([

			'When there is no desire, all things are at peace. - Laozi',

		])->random();
	}

}

<?php namespace Illuminate\Foundation;

use Illuminate\Support\Collection;

class Inspiring {

	/**
	 * Get an inspiring quote.
	 *
	 * Taylor & Dayle made this commit from Jungfraujoch. (11,333 ft.)
	 *
	 * @return string
	 */
	public static function quote()
	{
		return Collection::make([

			'When there is no desire, all things are at peace. - Laozi',
			'Simplicity is the ultimate sophistication. - Leonardo da Vinci',
			'Simplicity is the essence of happiness. - Cedric Bledsoe',
			'Smile, breathe, and go slowly. - Thich Nhat Hanh',
			'Simplicity is an aquired taste. - Katharine Gerould',

		])->random();
	}

}

Add a few more quotes.

Add a few more quotes.


        <?php echo formOpen('user/signup'); ?>

Sign Up

            <?php echo inputText('username', 'Username, 4-16 characters.'); ?>

            <?php echo inputPassword('password', 'Password, 6-32 characters.'); ?>

            <?php echo inputPassword('rpassword', 'Retype your password.'); ?>

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

            Already have account? <a href="<?php echo baseUrl(); ?>user/signup">Sign In

        <?php echo formClose(); ?>

        <?php echo formOpen('user/signup'); ?>

Sign Up

            <?php echo inputText('username', 'Username, 5-16 characters.'); ?>

            <?php echo inputPassword('password', 'Password, 6-32 characters.'); ?>

            <?php echo inputPassword('rpassword', 'Retype your password.'); ?>

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

            Already have account? <a href="<?php echo baseUrl(); ?>user/signup">Sign In

        <?php echo formClose(); ?>

Rename username to use 5 character minimum


<?php
/**
 * @package plugins.captionSearch
 * @subpackage api.objects
 */
class KalturaCaptionAssetItem extends KalturaObject
{
	/**
	 * The Caption Asset object
	 *
	 * @var KalturaCaptionAsset
	 */
	public $asset;

	/**
	 * The entry object
	 *
	 * @var KalturaBaseEntry
	 */
	public $entry;

	/**
	 * @var int
	 */
	public $startTime;

	/**
	 * @var int
	 */
	public $endTime;

	/**
	 * @var string
	 */
	public $content;

	private static $map_between_objects = array
	(
		"startTime",
		"endTime",
		"content",
	);

	public function getMapBetweenObjects ( )
	{
		return array_merge ( parent::getMapBetweenObjects() , self::$map_between_objects );
	}

	public function fromObject($source_object)
	{
		/* @var $source_object CaptionAssetItem */

		$ret = parent::fromObject($source_object);

		$this->asset = new KalturaCaptionAsset();
		$this->asset->fromObject($source_object->getAsset());

		$entry = $source_object->getEntry();
		$this->entry = KalturaEntryFactory::getInstanceByType($entry->getType());
		$this->entry->fromObject($entry);

		return $ret;
	}
}

<?php
/**
 * @package plugins.captionSearch
 * @subpackage api.objects
 */
class KalturaCaptionAssetItem extends KalturaObject
{
	/**
	 * The Caption Asset object
	 *
	 * @var KalturaCaptionAsset
	 */
	public $asset;

	/**
	 * The entry object
	 *
	 * @var KalturaBaseEntry
	 */
	public $entry;

	/**
	 * @var int
	 */
	public $startTime;

	/**
	 * @var int
	 */
	public $endTime;

	/**
	 * @var string
	 */
	public $content;

	private static $map_between_objects = array
	(
		"startTime",
		"endTime",
		"content",
	);

	public function getMapBetweenObjects ( )
	{
		return array_merge ( parent::getMapBetweenObjects() , self::$map_between_objects );
	}

	public function fromObject($source_object)
	{
		/* @var $source_object CaptionAssetItem */

		$ret = parent::fromObject($source_object);

		$this->asset = new KalturaCaptionAsset();
		$this->asset->fromObject($source_object->getAsset());

		$entry = $source_object->getEntry();

		if ($entry)
		{
			$this->entry = KalturaEntryFactory::getInstanceByType($entry->getType());
			$this->entry->fromObject($entry);
		}

		return $ret;
	}
}

Fix null object ref error

Fix null object ref error


@extends('layouts.app')

@section('css')
@parent
<link rel="stylesheet" href="{{ asset('css/datetime.css') }}">
@endsection

@section('content')

@endsection

@section('footer_scripts')
@parent

@endsection

Remove allDaySlot from calendar view

Remove allDaySlot from calendar view


<?php

namespace AppBundle\Services\Approvals\Providers;

use AppBundle\Entity\BadgeHolder;
use AppBundle\Services\Approvals\ApprovalQueueItem;
use AppBundle\Services\Approvals\ApprovalQueueProviderInterface;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class BadgeApprovalProvider implements ApprovalQueueProviderInterface
{
    /**
     * @param Registry $doctrine
     * @param UrlGeneratorInterface $url
     *
     * @return ApprovalQueueItem[]
     */
    function getItems(Registry $doctrine, UrlGeneratorInterface $url)
    {
        $repository = $doctrine->getRepository('AppBundle:BadgeHolder');
        $badges = $repository->findByIncomplete()->getQuery()->getResult();

        return array_map(function (BadgeHolder $badge) use ($url) {
            return new ApprovalQueueItem('badge', (string)$badge, $url->generate('badge_detail', ['id' => $badge->getBadge()->getId()]), $badge);
        }, $badges);
    }
}

<?php

namespace AppBundle\Services\Approvals\Providers;

use AppBundle\Entity\BadgeHolder;
use AppBundle\Services\Approvals\ApprovalQueueItem;
use AppBundle\Services\Approvals\ApprovalQueueProviderInterface;
use AppBundle\Services\Enum\BadgeState;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class BadgeApprovalProvider implements ApprovalQueueProviderInterface
{
    /**
     * @param Registry $doctrine
     * @param UrlGeneratorInterface $url
     *
     * @return ApprovalQueueItem[]
     */
    function getItems(Registry $doctrine, UrlGeneratorInterface $url)
    {
        $repository = $doctrine->getRepository('AppBundle:BadgeHolder');
        $badges = $repository->findByIncomplete()->getQuery()->getResult();

        return array_map(function (BadgeHolder $badge) use ($url) {
            $name = (string)$badge . ' - ' . BadgeState::$choices[$badge->getState()];

            return new ApprovalQueueItem('badge', $name, $url->generate('badge_detail', ['id' => $badge->getBadge()->getId()]), $badge);
        }, $badges);
    }
}

Add badge state to approval list

Add badge state to approval list


<?php

/*
 * This file is part of the PlemiBoomgoBundle.
 *
 * (c) Plemi <dev@plemi.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Plemi\Bundle\BoomgoBundle\Tests\Units;

use mageekguy\atoum;

/**
 * Define namespace for unit test
 *
 * @author David Guyon <dguyon@gmail.com>
 */
abstract class Test extends atoum\test
{
    /**
     * {@inheritdoc}
     */
    public function __construct(score $score = null, locale $locale = null, adapter $adapter = null)
    {
        $this->setTestNamespace('\\Tests\\Units');
        parent::__construct($score, $locale, $adapter);
    }
}

<?php

/*
 * This file is part of the PlemiBoomgoBundle.
 *
 * (c) Plemi <dev@plemi.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Plemi\Bundle\BoomgoBundle\Tests\Units;

use mageekguy\atoum,
    mageekguy\atoum\factory;

/**
 * Define namespace for unit test
 *
 * @author David Guyon <dguyon@gmail.com>
 */
abstract class Test extends atoum\test
{
    /**
     * {@inheritdoc}
     */
    public function __construct(factory $factory = null)
    {
        $this->setTestNamespace('\\Tests\\Units');
        parent::__construct($factory);
    }
}

Update default unit test class with atoum refactoring


<?php

namespace Maghead\Sharding;

use Maghead\Sharding\Shard;
use Maghead\Schema\BaseSchema;

class ShardStatsCollector
{
    protected $shards;

    public function __construct(ShardCollection $shards)
    {
        $this->shards = $shards;
    }

    public function collect(BaseSchema $schema)
    {
        $stats = [];
        $repoClass = $schema->getRepoClass();
        foreach ($this->shards as $shard) {
            $repo = $shard->repo($repoClass);
            $startTime = microtime(true);
            $stats[$shard->id]['rows'] = count($repo);
            $stats[$shard->id]['queryTime'] = microtime(true) - $startTime;
        }
        return $stats;
    }
}

<?php

namespace Maghead\Sharding;

use Maghead\Sharding\Shard;
use Maghead\Schema\BaseSchema;

class ShardStatsCollector
{
    protected $shards;

    public function __construct(ShardCollection $shards)
    {
        $this->shards = $shards;
    }

    public function collect(BaseSchema $schema)
    {
        $stats = [];
        $repoClass = $schema->getRepoClass();
        foreach ($this->shards as $shard) {
            $repo = $shard->repo($repoClass);
            $startTime = microtime(true);
            $stats[$shard->id]['rows'] = count($repo);
            $stats[$shard->id]['queryTime'] = microtime(true) - $startTime;
            // TODO: query table/index stats
        }
        return $stats;
    }
}

Add todo item for shard stats collector

Add todo item for shard stats collector


<?php

namespace Bugcache\Storage\Mysql;

use Amp\Mysql\Pool;
use Amp\Mysql\ResultSet;
use Amp\Promise;
use Bugcache\Storage;
use Generator;
use function Amp\resolve;

class UserRepository implements Storage\UserRepository {
    private $mysql;

    public function __construct(Pool $mysql) {
        $this->mysql = $mysql;
    }

    public function findByName(string $username): Promise {
        $sql = "SELECT id, name FROM users WHERE name = ?";

        return resolve($this->fetchUser($sql, [$username]));
    }

    private function fetchUser(string $sql, array $params = []): Generator {
        /** @var ResultSet $result */
        $result = yield $this->mysql->prepare($sql, $params);

        if (yield $result->rowCount()) {
            $record = yield $result->fetchObject();
            return $record;
        } else {
            return (object) [
                "id" => 0,
                "name" => "anonymous",
            ];
        }

        throw new Storage\NoRecordException;
    }
}

<?php

namespace Bugcache\Storage\Mysql;

use Amp\Mysql\Pool;
use Amp\Mysql\ResultSet;
use Amp\Promise;
use Bugcache\Storage;
use Generator;
use function Amp\resolve;

class UserRepository implements Storage\UserRepository {
    private $mysql;

    public function __construct(Pool $mysql) {
        $this->mysql = $mysql;
    }

    public function findByName(string $username): Promise {
        $sql = "SELECT id, name FROM users WHERE name = ?";

        return resolve($this->fetchUser($sql, [$username]));
    }

    private function fetchUser(string $sql, array $params = []): Generator {
        /** @var ResultSet $result */
        $result = yield $this->mysql->prepare($sql, $params);

        if (yield $result->rowCount()) {
            $record = yield $result->fetchObject();
            return $record;
        } else {
            return (object) [
                "id" => 0,
                "name" => "anonymous",
            ];
        }
    }
}

Remove superfluous / outdated throw NoRecordException


<?php
namespace Codeception\Module;

// here you can define custom actions
// all public methods declared in helper class will be available in $I

class UnitHelper extends \Codeception\Module
{

}

Add newline to fix code lint errors

[dev] Add newline to fix code lint errors


<?php

namespace Fuzz\ApiServer\Validation;

use Fuzz\ApiServer\Exception\BadRequestException;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\Validator;
use Illuminate\Http\Exception\HttpResponseException;

trait ValidatesRequests
{
	/**
	 * Validate the given request with the given rules.
	 *
	 * @param  \Illuminate\Http\Request $request
	 * @param  array                    $rules
	 * @param  array                    $messages
	 * @return void
	 */
	public function validate(Request $request, array $rules, array $messages = [])
	{
		$validator = $this->getValidationFactory()->make($request->all(), $rules, $messages);

		if ($validator->fails()) {
			$this->throwValidationException($request, $validator);
		}
	}

	/**
	 * Throw the failed validation exception.
	 *
	 * @param  \Illuminate\Http\Request                   $request
	 * @param  \Illuminate\Contracts\Validation\Validator $validator
	 * @return void
	 */
	protected function throwValidationException(Request $request, Validator $validator)
	{
		throw new BadRequestException('Request validation failed.', $validator->errors()->getMessages());
	}

	/**
	 * Get a validation factory instance.
	 *
	 * @return \Illuminate\Contracts\Validation\Factory
	 */
	protected function getValidationFactory()
	{
		return app('Illuminate\Contracts\Validation\Factory');
	}
}

<?php

namespace Fuzz\ApiServer\Validation;

use Illuminate\Validation\Validator;
use Fuzz\ApiServer\Exception\BadRequestException;

trait ValidatesRequests
{
	/**
	 * Validate the given request with the given rules.
	 *
	 * @param  array $request
	 * @param  array $rules
	 * @param  array $messages
	 * @return void
	 */
	public function validate(array $input, array $rules, array $messages = [])
	{
		$validator = $this->getValidationFactory()->make($input, $rules, $messages);

		if ($validator->fails()) {
			$this->throwValidationException($validator);
		}
	}

	/**
	 * Throw the failed validation exception.
	 *
	 * @param  \Illuminate\Contracts\Validation\Validator $validator
	 * @return void
	 */
	protected function throwValidationException(Validator $validator)
	{
		throw new BadRequestException('Request validation failed.', $validator->errors()->getMessages());
	}

	/**
	 * Get a validation factory instance.
	 *
	 * @return \Illuminate\Contracts\Validation\Factory
	 */
	protected function getValidationFactory()
	{
		return app('Illuminate\Contracts\Validation\Factory');
	}
}

Change validation handler to use array input instead of assuming a request


<?php

date_default_timezone_set('Africa/Cairo');

require('src/PingLogger.php');

require('config.default.php');

@include('config.php');
$config = (object) array_merge($configDefault, $config);

require('auth.php');

<?php

date_default_timezone_set('Africa/Cairo');

require('src/PingLogger.php');

require('config.default.php');

$config = array();
@include('config.php');
$config = (object) array_merge($configDefault, @$config);

require('auth.php');

Fix notices when user config is not present.


<?php

namespace Milax\Mconsole\Providers;

use Illuminate\Support\ServiceProvider;

class ViewComposersServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        view()->composer('mconsole::app', 'Milax\Mconsole\Composers\SectionComposer');
        view()->composer('mconsole::partials.menu', 'Milax\Mconsole\Composers\MenuComposer');
        view()->composer('mconsole::app', 'Milax\Mconsole\Composers\OptionsComposer');
        view()->composer('mconsole::forms.upload', 'Milax\Mconsole\Composers\UploadFormComposer');
        view()->composer('mconsole::forms.tags', 'Milax\Mconsole\Composers\TagsInputComposer');
        view()->composer('mconsole::helpers.blade', 'Milax\Mconsole\Composers\BladeHelperViewComposer');
        view()->composer('mconsole::forms.links', 'Milax\Mconsole\Composers\LinksSetsComposer');
        view()->composer('mconsole::menu.form', 'Milax\Mconsole\Composers\LanguagesComposer');
    }
}

<?php

namespace Milax\Mconsole\Providers;

use Illuminate\Support\ServiceProvider;

class ViewComposersServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        view()->composer('mconsole::app', 'Milax\Mconsole\Composers\SectionComposer');
        view()->composer('mconsole::partials.menu', 'Milax\Mconsole\Composers\MenuComposer');
        view()->composer('mconsole::app', 'Milax\Mconsole\Composers\OptionsComposer');
        view()->composer(['mconsole::forms.upload', 'mconsole::uploads.form'], 'Milax\Mconsole\Composers\UploadFormComposer');
        view()->composer('mconsole::forms.tags', 'Milax\Mconsole\Composers\TagsInputComposer');
        view()->composer('mconsole::helpers.blade', 'Milax\Mconsole\Composers\BladeHelperViewComposer');
        view()->composer('mconsole::forms.links', 'Milax\Mconsole\Composers\LinksSetsComposer');
        view()->composer('mconsole::menu.form', 'Milax\Mconsole\Composers\LanguagesComposer');
    }
}

Add uploads form laguage composer

Add uploads form laguage composer


      <?php
        $p = get_boundary_post( true, '', true, 'category' );
        post_to_anchor_or_hash( $p, "nav-first-text", "first" );
      ?>

      <?php
        $p = get_previous_post(true);
        post_to_anchor_or_hash( $p, "nav-prev-text", "prev" );
      ?>

      <a class="nav-random-text" href="<?php echo get_bloginfo('wpurl'); ?>/random/" rel="random">random

      <?php
        $p = get_next_post(true);
        post_to_anchor_or_hash( $p, "nav-next-text", "next" );
      ?>

      <?php
        $p = get_boundary_post( true, '', false, 'category' );
        post_to_anchor_or_hash( $p, "nav-last-text", "last" );
      ?>

      <?php
        $p = get_boundary_post( true, '', true, 'category' );
        post_to_anchor_or_hash( $p, "nav-first-text", "first" );
      ?>

      <?php
        $p = get_previous_post(true);
        post_to_anchor_or_hash( $p, "nav-prev-text", "prev" );
      ?>

      <a class="nav-random-text" href="<?php echo get_bloginfo('url'); ?>/random/" rel="random">random

      <?php
        $p = get_next_post(true);
        post_to_anchor_or_hash( $p, "nav-next-text", "next" );
      ?>

      <?php
        $p = get_boundary_post( true, '', false, 'category' );
        post_to_anchor_or_hash( $p, "nav-last-text", "last" );
      ?>

Fix 'random' link by using 'url' instead of 'wpurl'


<?php
/**
 * Created by IntelliJ IDEA.
 * User: sebastian
 * Date: 27.05.15
 * Time: 13:15
 */

namespace Sandstorm\Newsletter\Domain\Model;

use Doctrine\Common\Collections\ArrayCollection;
use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\Persistence\PersistenceManagerInterface;
use Doctrine\ORM\Mapping as ORM;

/**
 * Class CsvReceiverSource
 * @package Sandstorm\Newsletter\Domain\Model
 * @Flow\Entity
 */
class JsonReceiverSource extends ReceiverSource {

	/**
	 * @var string
	 * @Flow\Validate(type="Sandstorm\Newsletter\Validator\ExistingFileValidator")
	 * @Flow\Validate(type="NotEmpty")
	 */
	protected $sourceFileName;

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

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

	public function getConfigurationAsString() {
		return $this->sourceFileName;
	}

	public function getType() {
		return 'json';
	}
}

<?php
/**
 * Created by IntelliJ IDEA.
 * User: sebastian
 * Date: 27.05.15
 * Time: 13:15
 */

namespace Sandstorm\Newsletter\Domain\Model;

use Doctrine\Common\Collections\ArrayCollection;
use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\Persistence\PersistenceManagerInterface;
use Doctrine\ORM\Mapping as ORM;

/**
 * Class CsvReceiverSource
 * @package Sandstorm\Newsletter\Domain\Model
 * @Flow\Entity
 */
class JsonReceiverSource extends ReceiverSource {

	/**
	 * @var string
	 * @Flow\Validate(type="Sandstorm\Newsletter\Validator\ExistingFileValidator")
	 * @Flow\Validate(type="NotEmpty")
	 */
	protected $sourceFileName;

	/**
	 * @return string
	 */
	public function getSourceFileName() {
	    $sourceFileName = trim($this->sourceFileName);
	    if ($sourceFileName !== '' && $sourceFileName[0] === '/') {
            return $this->sourceFileName;
        } else {
	        return \FLOW_PATH_ROOT . $sourceFileName;
        }
	}

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

	public function getConfigurationAsString() {
		return $this->sourceFileName;
	}

	public function getType() {
		return 'json';
	}
}

TASK: Add support for relative source file in ReceiverSource


<?php

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

namespace Symfony\Component\HttpFoundation\Session\Storage;

/**
 * NativeSqliteSessionStorage.
 *
 * Session based on native PHP sqlite database handler.
 *
 * @author Drak <drak@zikula.org>
 */
class NativeSqliteSessionStorage extends AbstractSessionStorage
{
    /**
     * @var string
     */
    private $dbPath;

    /**
     * Constructor.
     *
     * @param string                $dbPath     Path to SQLite database file.
     * @param array                 $options    Session configuration options.
     *
     * @see AbstractSessionStorage::__construct()
     */
    public function __construct($dbPath, array $options = array())
    {
        if (!extension_loaded('sqlite')) {
            throw new \RuntimeException('PHP does not have "sqlite" session module registered');
        }

        $this->dbPath = $dbPath;
        parent::__construct($options);
    }

    /**
     * {@inheritdoc}
     */
    protected function registerSaveHandlers()
    {
        ini_set('session.save_handler', 'sqlite');
        ini_set('session.save_path', $this->dbPath);
    }
}

<?php

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

namespace Symfony\Component\HttpFoundation\Session\Storage;

/**
 * NativeSqliteSessionStorage.
 *
 * Session based on native PHP sqlite database handler.
 *
 * @author Drak <drak@zikula.org>
 */
class NativeSqliteSessionStorage extends AbstractSessionStorage
{
    /**
     * @var string
     */
    private $dbPath;

    /**
     * Constructor.
     *
     * @param string $dbPath  Path to SQLite database file.
     * @param array  $options Session configuration options.
     *
     * @see AbstractSessionStorage::__construct()
     */
    public function __construct($dbPath, array $options = array())
    {
        if (!extension_loaded('sqlite')) {
            throw new \RuntimeException('PHP does not have "sqlite" session module registered');
        }

        $this->dbPath = $dbPath;
        parent::__construct($options);
    }

    /**
     * {@inheritdoc}
     */
    protected function registerSaveHandlers()
    {
        ini_set('session.save_handler', 'sqlite');
        ini_set('session.save_path', $this->dbPath);
    }

    /**
     * {@inheritdoc}
     *
     * Sets any values sqlite ini values.
     *
     * @see http://php.net/sqlite.configuration
     */
    protected function setOptions(array $options)
    {
        foreach ($options as $key => $value) {
            if (in_array($key, array('sqlite.assoc_case'))) {
                ini_set($key, $value);
            }
        }

        parent::setOptions($options);
    }
}

[HttpFoudation] Add ability to configure sqlite session storage.


<?php

namespace Avalanche\Bundle\ImagineBundle\DependencyInjection\Compiler;

use RuntimeException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class CreateCacheDirectoriesCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $webRoot     = $container->getParameter('imagine.web_root');
        $cachePrefix = $container->getParameter('imagine.cache_prefix');
        $filters     = $container->getParameter('imagine.filters');

        foreach ($filters as $filter => $options) {
            if (isset($options['path'])) {
                $dir = $webRoot . '/' . $options['path'];
            } else {
                $dir = $webRoot . '/' . $cachePrefix . '/' . $filter;
            }

            if (!is_dir($dir) && !mkdir($dir, 0777, true)) {
                $message = sprintf('Could not create directory for caching processed images in "%s"', $dir);
                throw new RuntimeException($message);
            }
        }
    }
}

<?php

namespace Avalanche\Bundle\ImagineBundle\DependencyInjection\Compiler;

use RuntimeException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;

class CreateCacheDirectoriesCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $webRoot     = $container->getParameter('imagine.web_root');
        $cachePrefix = $container->getParameter('imagine.cache_prefix');
        $filters     = $container->getParameter('imagine.filters');
        $filesystem  = new Filesystem();

        foreach ($filters as $filter => $options) {
            if (isset($options['path'])) {
                $dir = $webRoot . '/' . $options['path'];
            } else {
                $dir = $webRoot . '/' . $cachePrefix . '/' . $filter;
            }

            try {
                $filesystem->mkdir($dir);
            } catch (IOException $e) {
                $message = sprintf('Could not create directory for caching processed images in "%s"', $dir);
                throw new RuntimeException($message, 0, $e);
            }
        }
    }
}

Switch to Filesystem::mkdir() method (from native)


<?php

/* @var Illuminate\Routing\Router $router */
$router->get('/', ['uses' => 'RootController@index', 'as' => 'api.index']);

$router->group([
    'as'         => 'api.v1.',
    'domain'     => 'dev.'.config('app.url'),
    'prefix'     => 'api/v1/',
    'middleware' => ['track', 'bindings'],
], function () use ($router) {
    $apiOnlyIndexAndShow = ['only' => ['index', 'show']];

    $router->resource('system', 'SystemController', $apiOnlyIndexAndShow);
    $router->resource('body', 'BodyController', $apiOnlyIndexAndShow);
    $router->resource('legislativeterm', 'LegislativeTermController', $apiOnlyIndexAndShow);
    $router->resource('agendaitem', 'AgendaItemController', $apiOnlyIndexAndShow);
    $router->resource('person', 'PersonController', $apiOnlyIndexAndShow);
    $router->resource('meeting', 'MeetingController', $apiOnlyIndexAndShow);
    $router->resource('organization', 'OrganizationController', $apiOnlyIndexAndShow);
    $router->resource('membership', 'MembershipController', $apiOnlyIndexAndShow);
    $router->resource('paper', 'PaperController', $apiOnlyIndexAndShow);
    $router->resource('consultation', 'ConsultationController', $apiOnlyIndexAndShow);
    $router->resource('location', 'LocationController', $apiOnlyIndexAndShow);
    $router->resource('file', 'FileController', $apiOnlyIndexAndShow);
});

<?php

/* @var Illuminate\Routing\Router $router */
$router->get('/', ['uses' => 'RootController@index', 'as' => 'api.index']);

$router->group([
    'as'         => 'api.v1.',
    'domain'     => 'dev.'.config('app.url'),
    'prefix'     => 'api/oparl/v1/',
    'middleware' => ['track', 'bindings'],
], function () use ($router) {
    $apiOnlyIndexAndShow = ['only' => ['index', 'show']];

    $router->resource('system', 'SystemController', $apiOnlyIndexAndShow);
    $router->resource('body', 'BodyController', $apiOnlyIndexAndShow);
    $router->resource('legislativeterm', 'LegislativeTermController', $apiOnlyIndexAndShow);
    $router->resource('agendaitem', 'AgendaItemController', $apiOnlyIndexAndShow);
    $router->resource('person', 'PersonController', $apiOnlyIndexAndShow);
    $router->resource('meeting', 'MeetingController', $apiOnlyIndexAndShow);
    $router->resource('organization', 'OrganizationController', $apiOnlyIndexAndShow);
    $router->resource('membership', 'MembershipController', $apiOnlyIndexAndShow);
    $router->resource('paper', 'PaperController', $apiOnlyIndexAndShow);
    $router->resource('consultation', 'ConsultationController', $apiOnlyIndexAndShow);
    $router->resource('location', 'LocationController', $apiOnlyIndexAndShow);
    $router->resource('file', 'FileController', $apiOnlyIndexAndShow);
});

Move oparl api from /api/v1/ to /api/oparl/v1


<?php
    $grammar = isset($_GET['grammar']) ? "grammar=" . $_GET['grammar'] : '';
    $code = isset($_GET['code']) ? "code=fun_code/" . $_GET['code'] : '';
    $verbose = isset($_GET['verbose']) ? "verbose=true" : "verbose=false";

    $output = array();
    $exec = "/usr/local/bin/node parse_and_run.js $grammar $code $verbose";
    exec($exec, $output);
    echo implode($output, "\n");
?>

<?php
    $grammar = isset($_GET['grammar']) ? "grammar=" . $_GET['grammar'] : '';
    $code = isset($_GET['code']) ? "code=fun_code/" . $_GET['code'] : '';
    $verbose = isset($_GET['verbose']) ? "verbose=" . $_GET['verbose'] : '';

    $output = array();
    $exec = "/usr/local/bin/node parse_and_run.js $grammar $code $verbose";
    exec($exec, $output);
    echo implode($output, "\n");
?>

Make the output verbose by default

Make the output verbose by default


<?php
class PrerequisitesTest extends PHPUnit_Framework_TestCase
{
    /**
     * The minimum version of PHP required for this project
     * @var string
     */
    const PHP_VERSION_REQUIRED = '5.3.0';
    public function testPhpVersion()
    {
        $isRightVersion = version_compare(PHP_VERSION, self::PHP_VERSION_REQUIRED) >= 0;
        $this->assertTrue($isRightVersion, 'PHP 5.3+ is required');
    }
    public function testApc()
    {
        $this->assertTrue(function_exists('apc_fetch'), 'APC extension is not installed (not required, but good for performance)');
    }
    public function testUtf8()
    {
        $this->assertTrue(function_exists('mb_internal_encoding'), 'MB extension is not installed');
        $this->assertTrue('UTF-8' === mb_internal_encoding(), 'MB must be in UTF-8 mode');
    }
    public function testSha256()
    {
        $this->assertContains('sha256', hash_algos(), 'sha256 hash algorithm is not supported');
    }
    public function testUtc()
    {
        $this->assertEquals('UTC', date_default_timezone_get(), 'Timezone must be UTC');
    }
    public function testCurl()
    {
        $this->assertTrue(function_exists('curl_version'), 'cURL is not enabled. Enable it or be sure to use the Stream request adapter instead');
    }
    public function testStream()
    {
        $this->assertContains('http', stream_get_wrappers(), 'The HTTP stream wrapper is not available. Enable it or be sure to use the cURL request adapter instead');
    }
}

<?php
class PrerequisitesTest extends PHPUnit_Framework_TestCase
{
    /**
     * The minimum version of PHP required for this project
     * @var string
     */
    const PHP_VERSION_REQUIRED = '5.3.0';
    public function testPhpVersion()
    {
        $isRightVersion = version_compare(PHP_VERSION, self::PHP_VERSION_REQUIRED) >= 0;
        $this->assertTrue($isRightVersion, 'PHP 5.3+ is required');
    }
    public function testApc()
    {
        $this->assertTrue(function_exists('apc_fetch'), 'APC extension is not installed (not required, but good for performance)');
    }
    public function testSha256()
    {
        $this->assertContains('sha256', hash_algos(), 'sha256 hash algorithm is not supported');
    }
    public function testUtc()
    {
        $this->assertEquals('UTC', date_default_timezone_get(), 'Timezone must be UTC');
    }
    public function testCurl()
    {
        $this->assertTrue(function_exists('curl_version'), 'cURL is not enabled. Enable it or be sure to use the Stream request adapter instead');
    }
    public function testStream()
    {
        $this->assertContains('http', stream_get_wrappers(), 'The HTTP stream wrapper is not available. Enable it or be sure to use the cURL request adapter instead');
    }
}

Remove mb test (not required)

Remove mb test (not required)


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Third Party Services
    |--------------------------------------------------------------------------
    |
    | This file is for storing the credentials for third party services such
    | as Stripe, Mailgun, SparkPost and others. This file provides a sane
    | default location for this type of information, allowing packages
    | to have a conventional place to find your various credentials.
    |
    */

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
    ],

    'ses' => [
        'key' => env('SES_KEY'),
        'secret' => env('SES_SECRET'),
        'region' => 'us-east-1',
    ],

    'sparkpost' => [
        'secret' => env('SPARKPOST_SECRET'),
    ],

    'stripe' => [
        'model' => App\User::class,
        'key' => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
    ],

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Third Party Services
    |--------------------------------------------------------------------------
    |
    | This file is for storing the credentials for third party services such
    | as Stripe, Mailgun, SparkPost and others. This file provides a sane
    | default location for this type of information, allowing packages
    | to have a conventional place to find your various credentials.
    |
    */

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
    ],

    'ses' => [
        'key' => env('SES_KEY'),
        'secret' => env('SES_SECRET'),
        'region' => env('SES_REGION','us-east-1'),
    ],

    'sparkpost' => [
        'secret' => env('SPARKPOST_SECRET'),
    ],

    'stripe' => [
        'model' => App\User::class,
        'key' => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
    ],

];

Add SES_REGION to local environment file

The region used by SES was hardcoded into the config file, when all other values were set as environment variables. Tweaked to keep the region consistent with other config options


<?php
// ~/Sites/presentation/mvc-basics/resources/views/event/tickets/create.blade.php
// Using your text editor, create the `create.blade.php` file and paste the
// following code.

    <title>Create Event Ticket</title>

    <form method="post" action="{{ route('event.tickets.store') }}">
    {{ csrf_field() }}

                Ticketholder Name

                <input type="text" class="form-control" name="ticketholder_name" />

                Ticket Price

                $ <input type="text" class="form-control" name="ticket_price" style="width: 150px;" />

                <button type="submit" class="btn btn-primary">Save Ticket</button>
                Cancel

    </form>

<?php
// ~/Sites/presentation/mvc-basics/resources/views/event/tickets/create.blade.php
// Using your text editor, create the `create.blade.php` file and paste the
// following code.

    <title>Create Event Ticket</title>

    <form class="form-horizontal" method="post" action="{{ route('event.tickets.store') }}">
    {{ csrf_field() }}

            Ticketholder Name

                <input type="text" class="form-control" name="ticketholder_name" />

            Ticket Price

                $ <input type="text" class="form-control" name="ticket_price" style="width: 150px; display: inline;" />

                <button type="submit" class="btn btn-primary">Save Ticket</button>
                Cancel

    </form>

Update laravel/mvc-basics/step-by-step/23 with theme formatting


<?php

/**
 * This file contains an abstract WebController class,
 * containing methods specifically targeted for the
 * Web Usage.
 *
 * PHP Version 5.3
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */

/**
 * Web Controller class
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */
abstract class WebController extends Controller
{

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Destructor
     */
    public function __destruct()
    {
        parent::__destruct();
    }

    /**
     * Handle unimplemented calls
     *
     * @param String $name      Method name
     * @param array  $arguments Arguments passed to the method
     *
     * @return String JSON encoded error String
     */
    public function __call($name, $arguments)
    {
        return "
Not implemented
";
    }

    /**
     * Default method as defined in conf.application.inc.php
     *
     * @return void
     */
    abstract public function index();

}

?>

<?php

/**
 * This file contains an abstract WebController class,
 * containing methods specifically targeted for the
 * Web Usage.
 *
 * PHP Version 5.3
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */

/**
 * Web Controller class
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */
abstract class WebController extends Controller
{

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Destructor
     */
    public function __destruct()
    {
        parent::__destruct();
    }

    /**
     * Handle unimplemented calls
     *
     * @param String $name      Method name
     * @param array  $arguments Arguments passed to the method
     *
     * @return String JSON encoded error String
     */
    public function __call($name, $arguments)
    {
        return "
Not implemented
";
    }

}

?>

system: Fix wrongly redefining an already abstract method
  in the WebController


<?php

class InvalidClassException extends Exception {}
class NotFoundException extends RuntimeException {}
class DataAccessException extends RuntimeException {}
class CacheException extends DataAccessException {}

// User Safe Exceptions are exceptions where the message is safe to display to the user
class UserSafeException extends RuntimeException {}
class UnauthorizedException extends UserSafeException {}
class MissingAssetException extends UserSafeException {}

<?php

class InvalidClassException extends Exception {}
class NotFoundException extends RuntimeException {}
class DataAccessException extends RuntimeException {}
class CacheException extends DataAccessException {}

// User Safe Exceptions are exceptions where the message is safe to display to the user
class UserSafeException extends RuntimeException {}
class UnauthorizedException extends UserSafeException {}
class UnauthorisedException extends UnauthorizedException {}
class MissingAssetException extends UserSafeException {}

Add UK spelling for UnauthorisedException


<?php

namespace VHX;

class Collections extends ApiResource {
  public static function all($params = array(), $headers = null) {
    return self::_list($params, $headers);
  }
  public static function retrieve($id = null, $headers = null) {
    return self::_retrieve($id, null, $headers);
  }
  public static function create($params = array(), $headers = null) {
    return self::_create($params, $headers);
  }
  public static function update($id = null, $params = array(), $headers = null) {
    return self::_update($id, $params, null, $headers);
  }
  public static function items($id = null, $params = array(), $headers = null) {
    if (is_array($id) && isset($id['collection'])) {
      $params = $id;
      $id = $id['collection'];
    }
    return self::_items($id, $params, $headers);
  }

  // deprecated (same as items)
  public static function allItems($id = null, $params = array(), $headers = null) {
    return self::_items($id, $params, $headers);
  }
}

<?php

namespace VHX;

class Collections extends ApiResource {
  public static function all($params = array(), $headers = null) {
    return self::_list($params, $headers);
  }
  public static function retrieve($id = null, $headers = null) {
    return self::_retrieve($id, null, $headers);
  }
  public static function create($params = array(), $headers = null) {
    return self::_create($params, $headers);
  }
  public static function update($id = null, $params = array(), $headers = null) {
    return self::_update($id, $params, null, $headers);
  }
  public static function items($id = null, $params = array(), $headers = null) {
    if (is_array($id) && isset($id['collection'])) {
      $params = $id;
      $id = $id['collection'];
    }
    return self::_items($id, $params, null, $headers);
  }

  // deprecated (same as items)
  public static function allItems($id = null, $params = array(), $headers = null) {
    return self::_items($id, $params, $headers);
  }
}

Fix fatal error in collection episodes listing

Add null as scope parameter to _items call


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

<?php echo esc_html(get_permalink()) ?>

<?php the_title() ?>

    <?php the_content() ?>

<?php endwhile ?>

Remove visible unprefixed print class name


<?php

/*
 * This file is part of Laravel Database.
 *
 * (c) Brian Faust <hello@brianfaust.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

/*
 * This file is part of Laravel Database.
 *
 * (c) Brian Faust <hello@brianfaust.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace BrianFaust\Database\Migrations;

use BrianFaust\Database\Schema\Blueprint;

abstract class Migration
{
    protected $connection;

    protected $schema;

    public function __construct(): void
    {
        $this->schema = \DB::getSchemaBuilder();

        $this->schema->blueprintResolver(function ($table, $callback) {
            return new Blueprint($table, $callback);
        });
    }

    public function getConnection()
    {
        return $this->connection;
    }
}

<?php

/*
 * This file is part of Laravel Database.
 *
 * (c) Brian Faust <hello@brianfaust.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

/*
 * This file is part of Laravel Database.
 *
 * (c) Brian Faust <hello@brianfaust.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace BrianFaust\Database\Migrations;

use BrianFaust\Database\Schema\Blueprint;

abstract class Migration
{
    protected $connection;

    protected $schema;

    public function __construct()
    {
        $this->schema = \DB::getSchemaBuilder();

        $this->schema->blueprintResolver(function ($table, $callback) {
            return new Blueprint($table, $callback);
        });
    }

    public function getConnection()
    {
        return $this->connection;
    }
}

:ambulance: Fix '__construct() cannot declare a return type'


<?php
class Kwf_Util_Hash
{
    public static function hash($str)
    {
        $salt = Kwf_Cache_SimpleStatic::fetch('hashpp-');
        if (!$salt) {
            if ($salt = Kwf_Config::getValue('hashPrivatePart')) {
                //defined in config, required if multiple webservers should share the same salt
            } else {
                $hashFile = 'cache/hashprivatepart';
                if (!file_exists($hashFile)) {
                    file_put_contents($hashFile, time().rand(100000, 1000000));
                }
                $salt = file_get_contents($hashFile);
                Kwf_Cache_SimpleStatic::add('hashpp-', $salt);
            }
        }
        return md5($salt.$str);
    }
}

<?php
class Kwf_Util_Hash
{
    public static function getPrivatePart()
    {
        $salt = Kwf_Cache_SimpleStatic::fetch('hashpp-');
        if (!$salt) {
            if ($salt = Kwf_Config::getValue('hashPrivatePart')) {
                //defined in config, required if multiple webservers should share the same salt
            } else {
                $hashFile = 'cache/hashprivatepart';
                if (!file_exists($hashFile)) {
                    file_put_contents($hashFile, time().rand(100000, 1000000));
                }
                $salt = file_get_contents($hashFile);
                Kwf_Cache_SimpleStatic::add('hashpp-', $salt);
            }
        }
        return $salt;
    }

    public static function hash($str)
    {
        return md5(self::getPrivatePart().$str);
    }
}

Add public method for getting private hash part


<?php

namespace App\Controllers;

use Philo\Blade\Blade;

class Controller
{
	/**
	 * The blade instance
	 * @var Philo\Blade\Blade
	 */
	protected $blade;

	/**
	 * Blade view engine class is injected into the base controller
	 * @param Philo\Blade\Blade $blade
	 */
	public function __construct(Blade $blade)
	{
		$this->blade = $blade;
	}
}

<?php

namespace App\Controllers;

use Philo\Blade\Blade;

abstract class Controller
{
	/**
	 * The blade instance
	 * @var Philo\Blade\Blade
	 */
	protected $blade;

	/**
	 * Blade view engine class is injected into the base controller
	 * @param Philo\Blade\Blade $blade
	 */
	public function __construct(Blade $blade)
	{
		$this->blade = $blade;
	}
}

Make the controller class abstract

Make the controller class abstract


<?php

namespace TFox\MpdfPortBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('t_fox_mpdf_port');

        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}

<?php

namespace TFox\MpdfPortBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('t_fox_mpdf_port');
        $rootNode = method_exists(TreeBuilder::class, 'getRootNode')
            ? $treeBuilder->getRootNode()
            : $treeBuilder->root('t_fox_mpdf_port');

        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}

Fix Symfony 4.2 deprecation warning

Fix Symfony 4.2 deprecation warning


<?php

final class ConduitQueryConduitAPIMethod extends ConduitAPIMethod {

  public function getAPIMethodName() {
    return 'conduit.query';
  }

  public function getMethodDescription() {
    return 'Returns the parameters of the Conduit methods.';
  }

  public function defineParamTypes() {
    return array();
  }

  public function defineReturnType() {
    return 'dict<dict>';
  }

  public function defineErrorTypes() {
    return array();
  }

  protected function execute(ConduitAPIRequest $request) {
    $classes = id(new PhutilSymbolLoader())
      ->setAncestorClass('ConduitAPIMethod')
      ->setType('class')
      ->loadObjects();

    $names_to_params = array();
    foreach ($classes as $class) {
      $names_to_params[$class->getAPIMethodName()] = array(
        'params' => $class->defineParamTypes(),
        'return' => $class->defineReturnType(),
      );
    }

    return $names_to_params;
  }

}

<?php

final class ConduitQueryConduitAPIMethod extends ConduitAPIMethod {

  public function getAPIMethodName() {
    return 'conduit.query';
  }

  public function getMethodDescription() {
    return 'Returns the parameters of the Conduit methods.';
  }

  public function defineParamTypes() {
    return array();
  }

  public function defineReturnType() {
    return 'dict<dict>';
  }

  public function defineErrorTypes() {
    return array();
  }

  protected function execute(ConduitAPIRequest $request) {
    $classes = id(new PhutilSymbolLoader())
      ->setAncestorClass('ConduitAPIMethod')
      ->setType('class')
      ->loadObjects();

    $names_to_params = array();
    foreach ($classes as $class) {
      $names_to_params[$class->getAPIMethodName()] = array(
        'description' => $class->getMethodDescription(),
        'params' => $class->defineParamTypes(),
        'return' => $class->defineReturnType(),
      );
    }

    return $names_to_params;
  }

}

Add method description to `conduit.query`

Summary: As suggested in T6950, add the method description to the response from `conduit.query`.

Test Plan: Called `echo '{}' | arc call-conduit conduit.query` and verified that the response contained the method description.

Reviewers: epriestley, #blessed_reviewers

Reviewed By: epriestley, #blessed_reviewers

Subscribers: Korvin, epriestley

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


<?php

/*
 * This file is a part of the ChZ-PHP package.
 *
 * (c) François LASSERRE <choiz@me.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Engine;

class Controller
{
    function __construct()
    {
    }

    public function loadView($file)
    {
        require_once VIEWS_DIR.'/'.$file.'.php';
        return true;
    }
}

<?php

/*
 * This file is a part of the ChZ-PHP package.
 *
 * (c) François LASSERRE <choiz@me.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Engine;

class Controller
{
    function __construct()
    {
    }

    protected function loadView($file)
    {
        require_once VIEWS_DIR.'/'.$file.'.php';
        return true;
    }

    protected function loadAjax($params = array())
    {
        header('Content-Type: application/json');
        echo json_encode($params, true);
        return true;
    }
}

Add loadAjax method and update methods visibility


<?php

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

class AddDailyBonusesColumns extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('dominions', function (Blueprint $table) {
            $table->boolean('daily_platinum')->default(false);
            $table->boolean('daily_land')->default(false);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('dominions', function (Blueprint $table) {
            $table->dropColumn(['daily_platinum', 'daily_land']);
        });
    }
}

<?php

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

class AddDailyBonusesColumns extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('dominions', function (Blueprint $table) {
            $table->boolean('daily_platinum')->default(false)->after('wizard_strength');
            $table->boolean('daily_land')->default(false)->after('daily_platinum');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('dominions', function (Blueprint $table) {
            $table->dropColumn(['daily_platinum', 'daily_land']);
        });
    }
}

Move daily_* fields after wizard_strength


@extends('layout.master')

@section('main_content')

 Edit User

@if ($aurora_user)
  Admin: {{ $aurora_user->hasRole('admin') ? '✓' : 'x' }}
  @if (!$aurora_user->hasRole('admin'))
    {{ Form::open(['route' => array('admin.create', $aurora_user->id)]) }}
    {{ Form::submit('make admin') }}
    {{ Form::close() }}
  @endif
@endif

 @foreach($user as $key => $field)
  @if (!in_array($key, ['created_at', 'updated_at', 'campaigns']))
    @if (!empty($field))

{{ $key }}

 {{ $field }}

     @endif
   @endif

  @if ($key == 'campaigns')
    @foreach($field as $campaigns)
      {{var_dump($campaigns)}}
    @endforeach
  @endif
 @endforeach

@stop

@extends('layout.master')

@section('main_content')

 {{ $user['first_name'] }}

 Edit User
@if ($aurora_user)
  Admin: {{ $aurora_user->hasRole('admin') ? '✓' : 'x' }}
  @if (!$aurora_user->hasRole('admin'))
    {{ Form::open(['route' => array('admin.create', $aurora_user->id)]) }}
    {{ Form::submit('make admin') }}
    {{ Form::close() }}
  @endif
@endif

   @foreach($user as $key => $field)
    @if (!in_array($key, ['created_at', 'updated_at', 'campaigns']))
      @if (!empty($field))

{{ $key }}

 {{ $field }}

       @endif
     @endif

    @if ($key == 'campaigns')
      @foreach($field as $campaigns)
        {{var_dump($campaigns)}}
      @endforeach
    @endif
   @endforeach

@stop

Fix up some styling on user show page.

Fix up some styling on user show page.


<?php

namespace Oro\Bundle\EmailBundle\Placeholder;

use Oro\Bundle\EmailBundle\Entity\Email;
use Doctrine\Common\Util\ClassUtils;

class SendEmailPlaceholderFilter
{
    /** @var Email */
    protected $email;

    public function __construct() {
        $this->email  = new Email();
    }

    /**
     * Check if send email action is applicable to entity as activity
     *
     * @param object|null $entity
     * @return bool
     */
    public function isApplicable($entity = null)
    {
        return is_object($entity) && $this->email->supportActivityTarget(ClassUtils::getClass($entity));
    }
}

CRM-4296: Call customers from OroCRM via Google Voice/Hangouts

- code style fixes


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

namespace Chrisguitarguy\FrontEndAccounts\Form\Field;

class Select extends FieldBase implements FieldInterface
{
    /**
     * {@inheritdoc}
     * @see     Chrisguitarguy\FrontEndAccounts\Form\Field\FieldInterface::render();
     */
    public function render()
    {
        printf(
            '<select id="%1$s" name="%1$s" %2$s>',
            $this->escAttr($this->getName()),
            $this->arrayToAttr($this->getAdditionalAttributes())
        );

        if ($emp = $this->getArg('empty_first')) {
            printf('<option value="">%s</option>', $this->escAttr($emp));
        }

        foreach ($this->getArg('choices', array()) as $val => $label) {
            printf(
                '<option value="%2$s">%2$s</option>',
                $this->escAttr($val),
                $this->escHtml($label)
            );
        }

        echo '</select>';
    }

    /**
     * {@inheritdoc}
     */
    protected function getAdditionalAttributes()
    {
        $atts = parent::getAdditionalAttributes();

        if (!empty($this->args['multi'])) {
            $atts['multiple'] = 'multiple';
        }

        return $atts;
    }
}

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

namespace Chrisguitarguy\FrontEndAccounts\Form\Field;

class Select extends FieldBase implements FieldInterface
{
    /**
     * {@inheritdoc}
     * @see     Chrisguitarguy\FrontEndAccounts\Form\Field\FieldInterface::render();
     */
    public function render()
    {
        printf(
            '<select id="%1$s" name="%1$s" %2$s>',
            $this->escAttr($this->getName()),
            $this->arrayToAttr($this->getAdditionalAttributes())
        );

        if ($emp = $this->getArg('empty_first')) {
            printf('<option value="">%s</option>', $this->escAttr($emp));
        }

        foreach ($this->getArg('choices', array()) as $val => $label) {
            printf(
                '<option value="%1$s" %2$s>%3$s</option>',
                $this->escAttr($val),
                selected($this->getValue(), $val, false), // XXX WordPress specific
                $this->escHtml($label)
            );
        }

        echo '</select>';
    }

    /**
     * {@inheritdoc}
     */
    protected function getAdditionalAttributes()
    {
        $atts = parent::getAdditionalAttributes();

        if (!empty($this->args['multi'])) {
            $atts['multiple'] = 'multiple';
        }

        return $atts;
    }
}

Make the select field type work like it's supposed to


<?php
/**
 * Changes made by Pierre-Henry Soria.
 */

// JavaScript file is located in the directory ~static/js/str.js which is included in the file ~templates/themes/base/tpl/layout.tpl
namespace PFBC\Element;

class Textarea extends \PFBC\Element
{
    protected $attributes = array('class' => 'pfbc-textarea', 'rows' => '5');

    public function jQueryDocumentReady()
    {
        echo 'jQuery("#', $this->attributes['id'], '").outerWidth(jQuery("#', $this->attributes['id'], '").width());';
    }

    public function render()
    {
        $iLength = (!empty($this->attributes['value'])) ? (new \PH7\Framework\Str\Str)->length($this->attributes['value']) : '0';

        echo '<textarea onkeyup="textCounter(\'', $this->attributes['id'], '\',\'', $this->attributes['id'], '_rem_len\')"', $this->getAttributes('value'), $this->getHtmlRequiredIfApplicable(), '>';

        if (!empty($this->attributes['value'])) {
            echo $this->filter($this->attributes['value']);
        }

        echo '</textarea>
attributes['id'], '_rem_len">' . $iLength . ' ', t('character(s).'), '
';
    }
}

<?php
/**
 * Changes made by Pierre-Henry Soria.
 */

// JavaScript file is located in the directory ~static/js/str.js which is included in the file ~templates/themes/base/tpl/layout.tpl
namespace PFBC\Element;

class Textarea extends \PFBC\Element
{
    /** @var array */
    protected $attributes = array('class' => 'pfbc-textarea');

    public function jQueryDocumentReady()
    {
        echo 'jQuery("#', $this->attributes['id'], '").outerWidth(jQuery("#', $this->attributes['id'], '").width());';
    }

    public function render()
    {
        $iLength = (!empty($this->attributes['value'])) ? (new \PH7\Framework\Str\Str)->length($this->attributes['value']) : '0';

        echo '<textarea onkeyup="textCounter(\'', $this->attributes['id'], '\',\'', $this->attributes['id'], '_rem_len\')"', $this->getAttributes('value'), $this->getHtmlRequiredIfApplicable(), '>';

        if (!empty($this->attributes['value'])) {
            echo $this->filter($this->attributes['value']);
        }

        echo '</textarea>
attributes['id'], '_rem_len">' . $iLength . ' ', t('character(s).'), '
';
    }
}

Remove rows attribute. Just use CSS now

Remove rows attribute. Just use CSS now


@extends ('base')

@section ('subheader')

@stop

@section ('content')

                @lang('app.contact.info')

                    GitHub

                        @lang('app.contact.github')

                    @OParl-Tech

                        @lang('app.contact.mailinglist')

                    @lang('app.contact.form_info')

                        @lang('app.contact.form')

@stop

@section ('scripts')

@stop

@extends ('base')

@section ('subheader')

@stop

@section ('content')

                @lang('app.contact.info')

                    GitHub

                        @lang('app.contact.github')

                    @OParl-Tech

                        @lang('app.contact.mailinglist')

                {{--
--}}
                    {{----}}
                    {{--@lang('app.contact.form_info')--}}
                    {{--
--}}
                        {{--@lang('app.contact.form')--}}
                    {{--
--}}
                {{--
--}}

@stop

@section ('scripts')

@stop

Hide currently bogus contact text

Hide currently bogus contact text


<!DOCTYPE html>

        Course ID
        Course
        Student ID
        Student Name
        Student E-mail
        Enrollment Date
        Shift

    @foreach($enrollments as $enrollment)

        {{ $enrollment->course->code }}
        {{ $enrollment->course->name }}
        {{ $enrollment->student->student_number }}
        {{ $enrollment->student->user->name }}
        {{ $enrollment->student->user->email }}
        {{ $enrollment->student->created_at }}
        {{-- Shift field --}}

    @endforeach

<!DOCTYPE html>

        Course ID
        Course
        Student ID
        Student Name
        Student E-mail
        Enrollment Date
        Shift

    @foreach($enrollments as $enrollment)

        {{ $enrollment->course->code }}
        {{ $enrollment->course->name }}
        {{ $enrollment->student->student_number }}
        {{ $enrollment->student->user->name }}
        {{ $enrollment->student->user->email }}
        {{ $enrollment->student->created_at }}
        {{ $enrollment->present()->getShiftTag('') }}

    @endforeach

Add shift tag to exported enrollments

Add shift tag to exported enrollments


<?php

namespace Customizer;

class Section {

	public function add_control( Control $control ) {

	}

	public function remove_control( Control $control ) {

	}

}

<?php

namespace Customizer;

class Section {

	public $id;

	protected $controls = array();

	/**
	 * Add a control to the section
	 *
	 * @param Control $control
	 */
	public function add_control( Control $control ) {

	}

	/**
	 * Get a control object by ID
	 *
	 * @param string $control_id
	 *
	 * @return Control
	 */
	public function get_control( $control_id ) {

	}

	/**
	 * Remove a control by ID
	 *
	 * @param string $control_id
	 */
	public function remove_control( $control_id ) {

	}

}

Add a get_control and doc blocks for methods


<?php

/**
 * This file is part of the Miny framework.
 * (c) Dániel Buga <daniel@bugadani.hu>
 *
 * For licensing information see the LICENSE file.
 */

namespace Modules\Templating\Compiler\Operators\TestOperators;

use Modules\Templating\Compiler\Compiler;
use Modules\Templating\Compiler\Nodes\OperatorNode;

class NotDivisibleByOperator extends DivisibleByOperator
{

    public function operators()
    {
        return 'is not divisible by';
    }

    public function compile(Compiler $compiler, OperatorNode $node)
    {
        $compiler->add('!');
        parent::compile($compiler, $node);
    }
}

<?php

/**
 * This file is part of the Miny framework.
 * (c) Dániel Buga <daniel@bugadani.hu>
 *
 * For licensing information see the LICENSE file.
 */

namespace Modules\Templating\Compiler\Operators\TestOperators;

use Modules\Templating\Compiler\Compiler;
use Modules\Templating\Compiler\Nodes\OperatorNode;

class NotDivisibleByOperator extends DivisibleByOperator
{

    public function operators()
    {
        return array('not divisible by', 'is not divisible by');
    }

    public function compile(Compiler $compiler, OperatorNode $node)
    {
        $compiler->add('!');
        parent::compile($compiler, $node);
    }
}

Allow different wording for the divisible by operator.


<?php namespace TightenCo\Jigsaw;

class BasicOutputPathResolver
{
    public function link($path, $name, $type, $page = 1)
    {
        if ($page > 1) {
            return sprintf('%s%s%s%s%s.%s', $this->trimPath($path), '/', $page, '/', $name, $type);
        }
        return sprintf('%s%s%s.%s', $this->trimPath($path), '/', $name, $type);
    }

    public function path($path, $name, $type, $page = 1)
    {
        return $this->link($path, $name, $type, $page);
    }

    public function directory($path, $name, $type, $page = 1)
    {
        if ($page > 1) {
            return $this->trimPath($path) . '/' . $page;
        }
        return $this->trimPath($path);
    }

    private function trimPath($path)
    {
        return rtrim(ltrim($path, '/'), '/');
    }
}

<?php namespace TightenCo\Jigsaw;

class BasicOutputPathResolver
{
    public function link($path, $name, $type, $page = 1)
    {
        if ($page > 1) {
            return $this->clean('/' . $path . '/' . $page . '/' . $name . '.' . $type);
        }
        return $this->clean('/' . $path . '/' . $name . '.' . $type);
    }

    public function path($path, $name, $type, $page = 1)
    {
        return $this->link($path, $name, $type, $page);
    }

    public function directory($path, $name, $type, $page = 1)
    {
        if ($page > 1) {
            return $this->clean($path . '/' . $page);
        }
        return $this->clean($path);
    }

    private function clean($path)
    {
        return str_replace('//', '/', $path);
    }
}

Replace pre-emptive trimming with double slash removal filter