<?php

namespace Flagbit\Bundle\CurrencyBundle\Tests;

use Flagbit\Bundle\CurrencyBundle\DependencyInjection\FlagbitCurrencyExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class FlagbitCurrencyExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testCurrencyServiceIntegration()
    {
        $container = new ContainerBuilder();
        $config = array();

        $extension = new FlagbitCurrencyExtension();
        $extension->load($config, $container);

        $container->compile();

        $currencyBundle = $container->get('flagbit_currency.intl_bundle');
        $currency = $container->get('flagbit_currency');

        $this->assertInstanceOf('Symfony\Component\Intl\ResourceBundle\CurrencyBundleInterface', $currencyBundle);
        $this->assertInstanceOf('Flagbit\Bundle\CurrencyBundle\Service\Currency', $currency);
    }
}

<?php

namespace Flagbit\Bundle\CurrencyBundle\Tests;

use Flagbit\Bundle\CurrencyBundle\DependencyInjection\FlagbitCurrencyExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class FlagbitCurrencyExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testCurrencyServiceIntegration()
    {
        $container = new ContainerBuilder();
        $config = array();

        $extension = new FlagbitCurrencyExtension();
        $extension->load($config, $container);

        $definition = $container->findDefinition('flagbit_currency.twig');
        $definition->setPublic(true);

        $container->compile();

        $currencyBundle = $container->get('flagbit_currency.intl_bundle');
        $currency = $container->get('flagbit_currency');
        $currencyExtension = $container->get('flagbit_currency.twig');

        $this->assertInstanceOf('Symfony\Component\Intl\ResourceBundle\CurrencyBundleInterface', $currencyBundle);
        $this->assertInstanceOf('Flagbit\Bundle\CurrencyBundle\Service\Currency', $currency);
        $this->assertInstanceOf('Flagbit\Bundle\CurrencyBundle\Twig\FlagbitCurrencyExtension', $currencyExtension);
    }
}

Add assertion for flagbit_currency.twig Twig extension service


<?php
namespace Respect\Validation\Rules;

class CallbackTest extends \PHPUnit_Framework_TestCase
{
    public function thisIsASampleCallbackUsedInsideThisTest()
    {
        return true;
    }

    public function testCallbackValidatorShouldReturnTrueIfCallbackReturnsTrue()
    {
        $v = new Callback(function() {
                    return true;
                });
        $this->assertTrue($v->assert('wpoiur'));
    }

    /**
     * @expectedException Respect\Validation\Exceptions\CallbackException
     */
    public function testCallbackValidatorShouldReturnFalseIfCallbackReturnsFalse()
    {
        $v = new Callback(function() {
                    return false;
                });
        $this->assertTrue($v->assert('w poiur'));
    }

    public function testCallbackValidatorShouldAcceptArrayCallbackDefinitions()
    {
        $v = new Callback(array($this, 'thisIsASampleCallbackUsedInsideThisTest'));
        $this->assertTrue($v->assert('test'));
    }

    public function testCallbackValidatorShouldAcceptFunctionNamesAsString()
    {
        $v = new Callback('is_string');
        $this->assertTrue($v->assert('test'));
    }

    /**
     * @expectedException Respect\Validation\Exceptions\ComponentException
     */
    public function testInvalidCallbacksShouldRaiseComponentExceptionUponInstantiation()
    {
        $v = new Callback(new \stdClass);
        $this->assertTrue($v->assert('w poiur'));
    }
}

<?php
namespace Respect\Validation\Rules;

class CallbackTest extends \PHPUnit_Framework_TestCase
{
    private $truthy, $falsy;

    function setUp() {
        $this->truthy = new Callback(function() {
            return true;
        });
        $this->falsy = new Callback(function() {
            return false;
        });
    }

    public function thisIsASampleCallbackUsedInsideThisTest()
    {
        return true;
    }

    public function testCallbackValidatorShouldReturnTrueIfCallbackReturnsTrue()
    {
        $this->assertTrue($this->truthy->assert('wpoiur'));
    }

    /**
     * @expectedException Respect\Validation\Exceptions\CallbackException
     */
    public function testCallbackValidatorShouldReturnFalseIfCallbackReturnsFalse()
    {
        $this->assertTrue($this->falsy->assert('w poiur'));
    }

    public function testCallbackValidatorShouldAcceptArrayCallbackDefinitions()
    {
        $v = new Callback(array($this, 'thisIsASampleCallbackUsedInsideThisTest'));
        $this->assertTrue($v->assert('test'));
    }

    public function testCallbackValidatorShouldAcceptFunctionNamesAsString()
    {
        $v = new Callback('is_string');
        $this->assertTrue($v->assert('test'));
    }

    /**
     * @expectedException Respect\Validation\Exceptions\ComponentException
     */
    public function testInvalidCallbacksShouldRaiseComponentExceptionUponInstantiation()
    {
        $v = new Callback(new \stdClass);
        $this->assertTrue($v->assert('w poiur'));
    }
}

Make test Callback a little more reusable


<?php

namespace App\Console\Commands\Report;

use App\Models\Collections\Agent;

use League\Csv\Writer;
use Illuminate\Support\Facades\Storage;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ReportTerms extends BaseCommand
{

    protected $signature = 'report:terms {artistId}';

    protected $description = 'Export all terms associated with an artist\'s artworks';

    public function handle()
    {
        $artistId = $this->argument('artistId');

        $terms = Agent::findOrFail($artistId)
            ->createdArtworks
            ->pluck('terms')
            ->collapse()
            ->unique('lake_uid')
            ->sortBy([
                ['subtype', 'asc'],
                ['lake_uid', 'asc'],
            ])
            ->values();

        $csv = Writer::createFromString('');

        $csv->insertOne([
            'term_type',
            'term_id',
            'term_title',
            'aat_id',
        ]);

        foreach ($terms as $term) {
            $row = [
                'term_type' => $term->getSubtypeDisplay(),
                'term_id' => $term->lake_uid,
                'term_title' => $term->title,
                'aat_id' => null,
            ];

            $this->info(json_encode(array_values($row)));
            $csv->insertOne($row);
        }

        Storage::put('terms-for-' . $artistId . '.csv', $csv->getContent());
    }
}

<?php

namespace App\Console\Commands\Report;

use App\Models\Collections\Agent;

use League\Csv\Writer;
use Illuminate\Support\Facades\Storage;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ReportTerms extends BaseCommand
{

    protected $signature = 'report:terms {artistId}';

    protected $description = 'Export all terms associated with an artist\'s artworks';

    public function handle()
    {
        $artistId = $this->argument('artistId');

        $terms = Agent::findOrFail($artistId)
            ->createdArtworks
            ->pluck('terms')
            ->collapse()
            ->unique('lake_uid')
            ->sortBy([
                ['subtype', 'asc'],
                ['title', 'asc'],
            ])
            ->values();

        $csv = Writer::createFromString('');

        $csv->insertOne([
            'term_type',
            'term_id',
            'term_title',
            'aat_id',
        ]);

        foreach ($terms as $term) {
            $row = [
                'term_type' => $term->getSubtypeDisplay(),
                'term_id' => $term->lake_uid,
                'term_title' => $term->title,
                'aat_id' => null,
            ];

            $this->info(json_encode(array_values($row)));
            $csv->insertOne($row);
        }

        Storage::put('terms-for-' . $artistId . '.csv', $csv->getContent());
    }
}

Sort by title instead of id in `report:terms` [API-224]


<?php
ini_set('display_errors', 1);
require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
    'oauth_access_token' => "",
    'oauth_access_token_secret' => "",
    'consumer_key' => "",
    'consumer_secret' => ""
);

/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
$url = 'https://api.twitter.com/1.1/blocks/create.json';
$requestMethod = 'POST';

/** POST fields required by the URL above. See relevant docs as above **/
$postfields = array(
    'screen_name' => 'usernameToBlock',
    'skip_status' => '1'
);

/** Perform a POST request and echo the response **/
$twitter = new TwitterAPIExchange($settings);
echo $twitter->buildOauth($url, $requestMethod)
             ->setPostfields($postfields)
             ->performRequest();

/** Perform a GET request and echo the response **/
/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?username=J7mbo';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();

<?php
ini_set('display_errors', 1);
require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
    'oauth_access_token' => "",
    'oauth_access_token_secret' => "",
    'consumer_key' => "",
    'consumer_secret' => ""
);

/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
$url = 'https://api.twitter.com/1.1/blocks/create.json';
$requestMethod = 'POST';

/** POST fields required by the URL above. See relevant docs as above **/
$postfields = array(
    'screen_name' => 'usernameToBlock',
    'skip_status' => '1'
);

/** Perform a POST request and echo the response **/
$twitter = new TwitterAPIExchange($settings);
echo $twitter->buildOauth($url, $requestMethod)
             ->setPostfields($postfields)
             ->performRequest();

/** Perform a GET request and echo the response **/
/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?screen_name=J7mbo';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();

Use correct parameter for screen names

Use correct parameter for screen names


<?php

namespace Nam\Commander;

/**
 * Class RegisterUserCommandHandler
 *
 * @author  Nam Hoang Luu <nam@mbearvn.com>
 * @package Mbibi\Core\Commands
 *
 */
interface CommandHandler
{
    /**
     * @param BaseCommand $command
     *
     * @throws InvalidCommandException
     * @return mixed
     */
    public function handle(BaseCommand $command);
}

<?php

namespace Nam\Commander;

use Nam\Commander\Exceptions\InvalidCommandException;

/**
 * Class RegisterUserCommandHandler
 *
 * @author  Nam Hoang Luu <nam@mbearvn.com>
 * @package Mbibi\Core\Commands
 *
 */
interface CommandHandler
{
    /**
     * @param BaseCommand $command
     *
     * @throws InvalidCommandException
     * @return mixed
     */
    public function handle(BaseCommand $command);
}

Fix error class InvalidCommandException does exists


    <title>VAW</title>
    <link href="app/bootstrap/css/bootstrap.css" rel="stylesheet" />

                            Home

                            Login

        <?php
        if(isset($_GET["page"]))
            require_once('app/pages/'.$_GET['page'].".php");
        else
            require_once('app/pages/home.php');
        ?>

    <title>VAW</title>
    <link href="app/bootstrap/css/bootstrap.css" rel="stylesheet" />

                            Home

                            Audio

        <?php
        if(isset($_GET["page"]))
            require_once('app/pages/'.$_GET['page'].".php");
        else
            require_once('app/pages/home.php');
        ?>

Replace login link with the audio link

Replace login link with the audio link


<?php

	namespace MikeVrind\Deployer\Controllers;

	use Illuminate\Routing\Controller;
	use MikeVrind\Deployer\Deployer;

	class DeployController extends Controller
	{

		/**
		 * Parse the incoming webhook to the deployer
		 *
		 * @param Deployer $deployer
		 * @return mixed
		 */
		public function handle( Deployer $deployer )
		{

			if( $deployer->deploy() )
			{

				return response()->json( [
					'status'  => 200,
					'message' => 'Deployment successful'
				], 200 );

			}
			else
			{
				return response()->json( [
					'status'  => 503,
					'message' => $deployer->getErrorMessage()
				], 503 );

			}

		}

	}

<?php

	namespace MikeVrind\Deployer\Controllers;

	use Illuminate\Routing\Controller;
	use MikeVrind\Deployer\Deployer;

	class DeployController extends Controller
	{

		/**
		 * Parse the incoming webhook to the deployer
		 *
		 * @param Deployer $deployer
		 * @return mixed
		 */
		public function handle( Deployer $deployer )
		{
			if( $deployer->deploy() )
			{

				return response()->json( [
					'status'  => 200,
					'message' => 'Deployment successful'
				], 200 );

			}

			return response()->json( [
				'status'  => 503,
				'message' => $deployer->getErrorMessage()
			], 503 );
		}

	}

Remove else for return statement

Remove else for return statement


<?php

final class PhabricatorSettingsAdjustController
  extends PhabricatorController {

  public function handleRequest(AphrontRequest $request) {
    $user = $request->getUser();

    $prefs = $user->loadPreferences();
    $prefs->setPreference(
      $request->getStr('key'),
      $request->getStr('value'));
    $prefs->save();

    return id(new AphrontAjaxResponse())->setContent(array());
  }
}

<?php

final class PhabricatorSettingsAdjustController
  extends PhabricatorController {

  public function handleRequest(AphrontRequest $request) {
    $viewer = $this->getViewer();

    $preferences = PhabricatorUserPreferences::loadUserPreferences($viewer);

    $editor = id(new PhabricatorUserPreferencesEditor())
      ->setActor($viewer)
      ->setContentSourceFromRequest($request)
      ->setContinueOnNoEffect(true)
      ->setContinueOnMissingFields(true);

    $key = $request->getStr('key');
    $value = $request->getStr('value');

    $xactions = array();
    $xactions[] = $preferences->newTransaction($key, $value);

    $editor->applyTransactions($preferences, $xactions);

    return id(new AphrontAjaxResponse())->setContent(array());
  }
}

Use transactions to apply Ajax settings mutations

Summary:
Ref T4103. Some settings (mostly nav collapsed/expanded states) use this endpoint to make adjustments when users press keys (like `\` to toggle the durable column).

All of these settings are now formal, so swap things over to transactions.

Test Plan: Collapsed/expanded various navs, reloaded pages, settings stuck.

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T4103

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


<?php

/**
 * @package         Billing
 * @copyright       Copyright (C) 2012 BillRun Technologies Ltd. All rights reserved.
 * @license         GNU Affero General Public License Version 3; see LICENSE.txt
 */

/**
 * Calculates a monthly charge
 *
 * @package  Plans
 * @since    5.2
 */
class Billrun_Plans_Charge_Arrears_Notprorated_Month extends Billrun_Plans_Charge_Arrears_Month {

	/**
	 * Get the price of the current plan.
	 */
	public function getPrice($quantity = 1) {
		$charges = array();

		foreach ($this->price as $tariff) {
			$price = Billrun_Plan::getPriceByTariff($tariff, max(0, floor($this->startOffset)), ceil($this->endOffset));
			if (!empty($price)) {
				$charges[] = array('value' => $price['price'], 'cycle' => $tariff['from']);
			}
		}

		return $charges;
	}
}

<?php

/**
 * @package         Billing
 * @copyright       Copyright (C) 2012 BillRun Technologies Ltd. All rights reserved.
 * @license         GNU Affero General Public License Version 3; see LICENSE.txt
 */

/**
 * Calculates a monthly charge
 *
 * @package  Plans
 * @since    5.2
 */
class Billrun_Plans_Charge_Arrears_Notprorated_Month extends Billrun_Plans_Charge_Arrears_Month {

	/**
	 * Get the price of the current plan.
	 */
	public function getPrice($quantity = 1) {
		$charges = array();

		foreach ($this->price as $tariff) {
			$price = Billrun_Plan::getPriceByTariff($tariff, max(0, floor($this->startOffset+1)), floor($this->endOffset+1));
			if (!empty($price)) {
				$charges[] = array('value' => $price['price'], 'cycle' => $tariff['from']);
			}
		}

		return $charges;
	}
}

Fix for BRCD_798 : align non-prorated services/plans with the per cycle limits/rates


<?php

namespace Atsys\Blog\Http\Controllers\Blog;

use App\Http\Controllers\Controller;
use Atsys\Blog\Post;
use Atsys\Blog\PostCategory;

class PostsController extends Controller
{
    public function index()
    {
        $posts = Post::with('postCategory')->latest()->paginate(10);

        $latest_posts = Post::latest()->take(5);

        $categories = PostCategory::has('posts')->latest()->get()->sortBy('title_translated');

        return view('blog::frontend.posts.index', compact('post', 'latest_posts', 'categories'));
    }
}

<?php

namespace Atsys\Blog\Http\Controllers\Blog;

use App\Http\Controllers\Controller;
use Atsys\Blog\Post;
use Atsys\Blog\PostCategory;

class PostsController extends Controller
{
    public function index()
    {
        $posts = Post::with('postCategory')->latest()->paginate(10);

        $latest_posts = Post::latest()->take(5);

        $categories = PostCategory::has('posts')->latest()->get()->sortBy('title_translated');

        return view('blog::frontend.posts.index', compact('posts', 'latest_posts', 'categories'));
    }
}

Fix bug adding posts variable to view

Fix bug adding posts variable to view


<?php

namespace Frontend\Modules\Instagram\Widgets;

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

use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget;
use Frontend\Modules\Instagram\Engine\Model as FrontendInstagramModel;

/**
 * This is the instagram feed widget
 *
 * @author Jesse Dobbelaere <jesse@dobbelae.re>
 */
class InstagramFeed extends FrontendBaseWidget
{
    /**
    * Execute the extra
    *
    * @return	void
    */
    public function execute()
    {
        // call the parent
        parent::execute();

        // load template
        $this->loadTemplate();

        // parse
        $this->parse();
    }

    /**
    * Parse the data into the template
    *
    * @return	void
    */
    private function parse()
    {
        // add css
        $this->header->addCSS('/src/Frontend/Modules/' . $this->getModule() . '/Layout/Css/Instagram.css');

        // fetch instagram user
        $instagramUser = FrontendInstagramModel::get($this->data['id']);

        // pass user info to javascript
        $this->addJSData('user', $instagramUser);

        // parse user info in template
        $this->tpl->assign('user', $instagramUser);
    }
}

<?php

namespace Frontend\Modules\Instagram\Widgets;

use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget;
use Frontend\Modules\Instagram\Engine\Model as FrontendInstagramModel;

/**
 * This is the instagram feed widget
 *
 * @author Jesse Dobbelaere <jesse@dobbelae.re>
 */
class InstagramFeed extends FrontendBaseWidget
{
    /**
    * Execute the extra
    *
    * @return	void
    */
    public function execute()
    {
        // call the parent
        parent::execute();

        // load template
        $this->loadTemplate();

        // parse
        $this->parse();
    }

    /**
    * Parse the data into the template
    *
    * @return	void
    */
    private function parse()
    {
        // add css
        $this->header->addCSS('/src/Frontend/Modules/' . $this->getModule() . '/Layout/Css/Instagram.css');

        // fetch instagram user
        $instagramUser = FrontendInstagramModel::get($this->data['id']);

        // pass user info to javascript
        $this->addJSData('user', $instagramUser);

        // parse user info in template
        $this->tpl->assign('user', $instagramUser);
    }
}

Remove Fork Cms copyright comments.

Remove Fork Cms copyright comments.


<?php

namespace EdpGithub\ApiClient\Service;

use EdpGithub\ApiClient\Model\Repo as RepoModel;

class Repo extends AbstractService
{
    // list of github allowed types for fetching repositories
    protected $allowedTypes = array(
        'all',
        'owner',
        'public',
        'private',
        'member',
    );

    public function listRepositories($username = null, $type = null)
    {
        $api = $this->getApiClient();

        $params['access_token'] = $api->getOAuthToken();

        if($type !== null) {
            if(!in_array($type, $this->allowedTypes)) {
                throw new Exception\DomainException("Wrong type '$type' provided.");
            }
            $params['type'] = $type;
        }

        if ($username == null) {
            $repos = $api->request('/user/repos', $params);
        } else {
            $repos = $this->getApiClient()->request('/users/' . $username . '/repos');
        }

        return $this->hydrate($repos);
    }

    public function hydrate($repos)
    {
        $repoList = null;
        foreach($repos as $repo)
        {
            $repolist[] = new RepoModel($repo);
        }

        return $repolist;
    }
}

<?php

namespace EdpGithub\ApiClient\Service;

use EdpGithub\ApiClient\Model\Repo as RepoModel;

class Repo extends AbstractService
{
    // list of github allowed types for fetching repositories
    protected $allowedTypes = array(
        'all',
        'owner',
        'public',
        'private',
        'member',
    );

    public function listRepositories($username = null, $type = null)
    {
        $api = $this->getApiClient();

        $params['access_token'] = $api->getOAuthToken();

        //hotfix to display more then 30 results
        //@todo implement proper pagination
        $params['per_page'] = 100;

        if($type !== null) {
            if(!in_array($type, $this->allowedTypes)) {
                throw new Exception\DomainException("Wrong type '$type' provided.");
            }
            $params['type'] = $type;
        }

        if ($username == null) {
            $repos = $api->request('/user/repos', $params);
        } else {
            $repos = $this->getApiClient()->request('/users/' . $username . '/repos');
        }

        return $this->hydrate($repos);
    }

    public function hydrate($repos)
    {
        $repoList = null;
        foreach($repos as $repo)
        {
            $repolist[] = new RepoModel($repo);
        }

        return $repolist;
    }
}

Fix for pagination only showing 30 results


        @if ($notification['body']['name'] == 'user.booked')
            {!! Icon::calendar() !!}
        @endif
        @if ($notification['body']['name'] == 'appointment.cancel')
            {!! Icon::calendar() !!}
        @endif
        @if ($notification['body']['name'] == 'appointment.confirm')
            {!! Icon::calendar() !!}
        @endif
        @if ($notification['body']['name'] == 'appointment.serve')
            {!! Icon::calendar() !!}
        @endif

        @if ($notification['extra'])
            {{trans('notifications.'.$notification['body']['name'], ['user' => $notification['from']['name']] + json_decode($notification['extra'], true)) }}
        @else
            {{trans('notifications.'.$notification['body']['name'], ['user' => $notification['from']['name']]) }}
        @endif
         toDateTimeString()}}">{{$timestamp->diffForHumans() }}

        @if ($notification['body']['name'] == 'user.booked')
            {!! Icon::calendar() !!}
        @endif
        @if ($notification['body']['name'] == 'appointment.cancel')
            {!! Icon::calendar() !!}
        @endif
        @if ($notification['body']['name'] == 'appointment.confirm')
            {!! Icon::calendar() !!}
        @endif
        @if ($notification['body']['name'] == 'appointment.serve')
            {!! Icon::calendar() !!}
        @endif

        @if ($notification['extra'])
            {{trans('notifications.'.$notification['body']['name'], ['user' => $notification['from']['name']] + $notification['extra']) }}
        @else
            {{trans('notifications.'.$notification['body']['name'], ['user' => $notification['from']['name']]) }}
        @endif
         toDateTimeString()}}">{{$timestamp->diffForHumans() }}

Fix exception json_decode() expects parameter 1 to be string, array given

Since Notifynder fixes Extra array is empty if you call toArray,
no longer json_decode is required.

https://github.com/fenos/Notifynder/issues/126


<?php

if (!defined('APP_DIR')) {
  define('APP_DIR',dirname(__DIR__));
}

if (!defined('DB_HOST')) {
  define('DB_HOST','127.0.0.1');
}

if (!defined('DB_NAME')) {
  define('DB_NAME','sqlayer_test');
}

if (!defined('DB_USER')) {
  define('DB_USER','sqlayer_test');
}

if (!defined('DB_PASS')) {
  define('DB_PASS','sqlayer_test');
}

<?php

/**
 * @package SQLayer
 * @version 0.0.3
 * @date    2016-11-08
 * @author  Roderic Linguri <linguri@digices.com>
 * @license MIT
 */

/** Main Configuration File **/

if (!defined('APP_DIR')) {
  define('APP_DIR',dirname(__DIR__));
}

Add comments, remove constant definitions


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

namespace Darvin\Utils\Form\Type;

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

/**
 * Anti-spam form type
 */
class AntiSpamType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'attr'     => array(
                'class' => 'title_field',
            ),
            'mapped'   => false,
            'required' => false,
        ));
    }

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

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

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

namespace Darvin\Utils\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Blank;

/**
 * Anti-spam form type
 */
class AntiSpamType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'attr'        => array(
                'class' => 'title_field',
            ),
            'constraints' => new Blank(),
            'mapped'      => false,
            'required'    => false,
        ));
    }

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

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

Configure anti-spam form type constraints.


<?php
class Kwf_Update_20160824ComponentLinkViewCache extends Kwf_Update
{
    protected $_tags = array('kwc');

    public function update()
    {
        Kwf_Component_Cache::getInstance()->deleteViewCache(array(
            'type' => 'componentLink'
        ));
    }
}

<?php
class Kwf_Update_20160824ComponentLinkViewCache extends Kwf_Update
{
    protected $_tags = array('kwc');

    public function update()
    {
        //required for addition of Kwf_Component_Data::getLinkClass
        Kwf_Component_Cache::getInstance()->deleteViewCache(array(
            'type' => 'componentLink'
        ));
    }
}

Add comment why this update script is required


<?php

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

class CreateEveCorporationRolemap extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('eve_corporation_rolemap', function(Blueprint $table)
        {
          $table->increments('id');

          $table->bigInteger('roleID');
          $table->string('roleName');

          // Indexes
          $table->index('roleID');

          $table->timestamps();
        });
    }

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

}

<?php

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

class CreateSeatCorporationRoleMap extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('seat_corporation_rolemap', function(Blueprint $table)
        {
          $table->increments('id');

          $table->bigInteger('roleID');
          $table->string('roleName');

          // Indexes
          $table->index('roleID');

          $table->timestamps();
        });
    }

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

}

Fix class & table name

Fix class & table name


<?php

namespace jjok\Scheduler;

final class Time
{
    private $hour;
    private $minutes;
    private $seconds;

    public function __construct(int $hour, int $minutes = 0, int $seconds = 0)
    {
        if($hour < 0 || $hour > 23) {
            throw new \InvalidArgumentException('Hour must be between 0 and 23.');
        }

        if($minutes < 0 || $minutes > 59) {
            throw new \InvalidArgumentException('Minutes must be between 0 and 59.');
        }

        if($seconds < 0 || $seconds > 59) {
            throw new \InvalidArgumentException('Seconds must be between 0 and 59.');
        }

        $this->hour = $hour;
        $this->minutes = $minutes;
        $this->seconds = $seconds;
    }

    public static function fromString($time) : Time
    {
        list($hour, $minutes, $seconds) = sscanf($time, '%u:%u:%u');

        return new static($hour, $minutes, $seconds);
    }

    public function __toString()
    {
        return sprintf('%u:%u:%u', $this->hour, $this->minutes, $this->seconds);
    }
}

<?php

namespace jjok\Scheduler;

final class Time
{
    private $hour;
    private $minutes;
    private $seconds;

    public function __construct(int $hour, int $minutes = 0, int $seconds = 0)
    {
        if($hour < 0 || $hour > 23) {
            throw new \InvalidArgumentException('Hour must be between 0 and 23.');
        }

        if($minutes < 0 || $minutes > 59) {
            throw new \InvalidArgumentException('Minutes must be between 0 and 59.');
        }

        if($seconds < 0 || $seconds > 59) {
            throw new \InvalidArgumentException('Seconds must be between 0 and 59.');
        }

        $this->hour = $hour;
        $this->minutes = $minutes;
        $this->seconds = $seconds;
    }

    public static function fromString($time) : Time
    {
        list($hour, $minutes, $seconds) = sscanf($time, '%u:%u:%u');

        return new static($hour, $minutes, $seconds);
    }

    public function __toString()
    {
        return sprintf(
            '%s:%s:%s',
            str_pad($this->hour, 2, '0', \STR_PAD_LEFT),
            str_pad($this->minutes, 2, '0', \STR_PAD_LEFT),
            str_pad($this->seconds, 2, '0', \STR_PAD_LEFT)
        );
    }

    public function isDuring(Period $period) {
        return $period->contains($this);
    }
}

Make sure time has leading zeros

Make sure time has leading zeros


<!DOCTYPE html>

<head>
	<title>ClinicCases - Online Case Management Software for Law School Clinics</title>
	<meta name="robots" content="noindex">
	<link rel="stylesheet" href="html/css/cm.css" type="text/css">
	<link rel="stylesheet" href="html/css/cm_tabs.css" type="text/css">
	<link rel="stylesheet" href="lib/jqueryui/css/custom-theme/jquery-ui-1.8.9.custom.css" type="text/css">
	<link rel="stylesheet" href="lib/DataTables-1.7.5/media/css/data_table.css" type="text/css">
	<link rel="stylesheet" href="lib/DataTables-1.7.5/extras/TableTools-2.0.0/media/css/TableTools.css" type="text/css">

	<script src="lib/jqueryui/js/jquery-1.4.4.min.js" type="text/javascript"></script>
	<script src="lib/jqueryui/js/jquery-ui-1.8.9.custom.min.js" type="text/javascript"></script>
	<script src="lib/javascripts/jquery.idletimer.js" type="text/javascript"></script>
	<script src="lib/javascripts/jquery.idletimeout.js" type="text/javascript"></script>

<!DOCTYPE html>

<head>
	<title>ClinicCases - Online Case Management Software for Law School Clinics</title>
	<meta name="robots" content="noindex">
	<link rel="stylesheet" href="html/css/cm.css" type="text/css">
	<link rel="stylesheet" href="html/css/cm_tabs.css" type="text/css">
	<link rel="stylesheet" href="lib/jqueryui/css/custom-theme/jquery-ui-1.8.9.custom.css" type="text/css">

	<script src="lib/jqueryui/js/jquery-1.4.4.min.js" type="text/javascript"></script>
	<script src="lib/jqueryui/js/jquery-ui-1.8.9.custom.min.js" type="text/javascript"></script>
	<script src="lib/javascripts/jquery.idletimer.js" type="text/javascript"></script>
	<script src="lib/javascripts/jquery.idletimeout.js" type="text/javascript"></script>

Remove datatables css from general header, move to cases header

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


<?php
class Kwc_Favourites_Box_Component extends Kwc_Abstract
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['assets']['files'][] = 'kwf/Kwc/Favourites/Box/Component.js';
        $ret['favouritesPageComponentClass'] = null; //TODO set to kwc-favourites-page
        $ret['viewCache'] = false;
        $ret['placeholder']['linkText'] = trlStatic('FAVORITEN ({0})');
        return $ret;
    }

    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        $user = Kwf_Model_Abstract::getInstance('Users')->getAuthedUser();
        if ($user) {
            $model = Kwf_Model_Abstract::getInstance('Kwc_Favourites_Model');
            $select = new Kwf_Model_Select();
            $select->whereEquals('user_id', $user->id);
            $count = $model->countRows($select);
            $ret['linkText'] = str_replace('{0}', "$count",
                            $this->_getPlaceholder('linkText'));
        }
        $class = Kwc_Abstract::getSetting($this->getData()->getComponentClass(),
                         'favouritesPageComponentClass');
        if (!$class) {
            throw new Kwf_Exception('Set favouritesComponent (favourites-page) in getSettings');
        }
        $ret['favourite'] = Kwf_Component_Data_Root::getInstance()
            ->getComponentByClass($class);
        return $ret;
    }
}

<?php
class Kwc_Favourites_Box_Component extends Kwc_Abstract
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['assets']['files'][] = 'kwf/Kwc/Favourites/Box/Component.js';
        $ret['favouritesPageComponentClass'] = 'Kwc_Favourites_Page_Component';
        $ret['viewCache'] = false;
        $ret['placeholder']['linkText'] = trlStatic('FAVORITEN ({0})');
        return $ret;
    }

    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        $user = Kwf_Model_Abstract::getInstance('Users')->getAuthedUser();
        if ($user) {
            $model = Kwf_Model_Abstract::getInstance('Kwc_Favourites_Model');
            $select = new Kwf_Model_Select();
            $select->whereEquals('user_id', $user->id);
            $count = $model->countRows($select);
            $ret['linkText'] = str_replace('{0}', "$count",
                            $this->_getPlaceholder('linkText'));
        }
        $class = Kwc_Abstract::getSetting($this->getData()->getComponentClass(),
                         'favouritesPageComponentClass');
        if (!$class) {
            throw new Kwf_Exception('Set favouritesComponent (favourites-page) in getSettings');
        }
        $ret['favourite'] = Kwf_Component_Data_Root::getInstance()
            ->getComponentByClass($class);
        return $ret;
    }
}

Resolve todo (set correct class)

Resolve todo (set correct class)


<?php

namespace LAG\AdminBundle\Tests\DependencyInjection;

use LAG\AdminBundle\DependencyInjection\LAGAdminExtension;
use LAG\AdminBundle\Tests\AdminTestBase;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class LAGAdminExtensionTest extends AdminTestBase
{
    /**
     * The load should allow the container to compile without errors.
     */
    public function testLoad()
    {
        $builder = $this->getMockWithoutConstructor(ContainerBuilder::class);
        $builder
            ->expects($this->exactly(3))
            ->method('setParameter')
            ->willReturnCallback(function ($parameter, $value) {
                $this->assertContains($parameter, [
                    'lag.admin.enable_extra_configuration',
                    'lag.admin.application_configuration',
                    'lag.admins',
                ]);

                if ('lag.admin.enable_extra_configuration' === $parameter) {
                    $this->assertContains($value, [
                        true,
                    ]);
                }
            })
        ;

        $extension = new LAGAdminExtension();
        $extension->load([
            'enable_extra_configuration' => true,
        ], $builder);
    }

    /**
     * The load should allow the container to compile without errors.
     */
    public function testLoadWithoutConfiguration()
    {
        $builder = $this->getMockWithoutConstructor(ContainerBuilder::class);

        $extension = new LAGAdminExtension();
        $extension->load([], $builder);
        // Every thing went fine
        $this->assertTrue(true);
    }
}

<?php

namespace LAG\AdminBundle\Tests\DependencyInjection;

use LAG\AdminBundle\DependencyInjection\LAGAdminExtension;
use LAG\AdminBundle\Tests\AdminTestBase;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class LAGAdminExtensionTest extends AdminTestBase
{
    /**
     * The load should allow the container to compile without errors.
     */
    public function testLoad()
    {
        $builder = $this->getMockWithoutConstructor(ContainerBuilder::class);
        $builder
            ->expects($this->atLeastOnce())
            ->method('setParameter')
            ->willReturnCallback(function ($parameter, $value) {
                $this->assertContains($parameter, [
                    'lag.admin.enable_extra_configuration',
                    'lag.admin.application_configuration',
                    'lag.admins',
                    'lag.menus',
                ]);

                if ('lag.admin.enable_extra_configuration' === $parameter) {
                    $this->assertContains($value, [
                        true,
                    ]);
                }
            })
        ;

        $extension = new LAGAdminExtension();
        $extension->load([
            'enable_extra_configuration' => true,
        ], $builder);
    }

    /**
     * The load should allow the container to compile without errors.
     */
    public function testLoadWithoutConfiguration()
    {
        $builder = $this->getMockWithoutConstructor(ContainerBuilder::class);

        $extension = new LAGAdminExtension();
        $extension->load([], $builder);
        // Every thing went fine
        $this->assertTrue(true);
    }
}

Fix LAG Admin extension test

Fix LAG Admin extension test


<?php
date_default_timezone_set('UTC');

define('MMS_DEBUG', false); // Turns off tweeting, outputs to the console instead

define('MMS_HOMEPAGE_URL', 'http://www.metrolink.co.uk');
define('MMS_LINE_XPATH', "//*[contains(@class,'line-symbol')]");
define('MMS_STATUS_XPATH', '//*[@class="service-status"]');
define('MMS_GOOD_SERVICE_STRING', 'Good Service');

define('TWITTER_CONSUMERKEY',    '');
define('TWITTER_CONSUMERSECRET', '');
define(
    'TWITTER_ACCESSTOKEN',
    ''
);
define('TWITTER_ACCESSTOKENSECRET', '');

<?php
date_default_timezone_set('Europe/London');

define('MMS_DEBUG', false); // Turns off tweeting, outputs to the console instead

define('MMS_HOMEPAGE_URL', 'http://www.metrolink.co.uk');
define('MMS_LINE_XPATH', "//*[contains(@class,'line-symbol')]");
define('MMS_STATUS_XPATH', '//*[@class="service-status"]');
define('MMS_GOOD_SERVICE_STRING', 'Good Service');

define('TWITTER_CONSUMERKEY',    '');
define('TWITTER_CONSUMERSECRET', '');
define(
    'TWITTER_ACCESSTOKEN',
    ''
);
define('TWITTER_ACCESSTOKENSECRET', '');

Change the timezone to Europe/London.

Change the timezone to Europe/London.


<?php

namespace Miaoxing\User\Controller\Admin;

class UserSettings extends \Miaoxing\Plugin\BaseController
{
    protected $controllerName = '用户设置';

    protected $actionPermissions = [
        'index,update' => '设置',
    ];

    public function indexAction()
    {
        $bgImage = &$this->setting('user.bgImage');
        wei()->event->trigger('postImageLoad', [&$bgImage]);

        return get_defined_vars();
    }

    public function updateAction($req)
    {
        $settings = (array)$req['settings'];
        wei()->event->trigger('preImageDataSave', [&$settings, ['user.bgImage']]);

        $this->setting->setValues($settings, 'user.');
        return $this->suc();
    }
}

<?php

namespace Miaoxing\User\Controller\Admin;

class UserSettings extends \Miaoxing\Plugin\BaseController
{
    protected $controllerName = '用户设置';

    protected $actionPermissions = [
        'index,update' => '设置',
    ];

    public function indexAction()
    {
        $bgImage = &$this->setting('user.bgImage');
        wei()->event->trigger('postImageLoad', [&$bgImage]);

        return get_defined_vars();
    }

    public function updateAction($req)
    {
        $settings = (array) $req['settings'];
        wei()->event->trigger('preImageDataSave', [&$settings, ['user.bgImage']]);

        $this->setting->setValues($settings, 'user.');

        return $this->suc();
    }
}

Fix coding standard [skip fix]

Fix coding standard [skip fix]


<?php

$app->get('/mod/{id}[/{name}]', function($request, $response, $args) {
    return $this->view->render($response, 'templates/mod.html', [
        'modid' => $args['id']
    ]);
})->setName('mod.view');

$app->get('/random', function($request, $response, $args) {
    $backend_url = $this->get('settings')['backend-url'];
    $gameshort = $this->get('settings')['gameshort'];
    $json = file_get_contents('http://'  . $backend_url . '/api/mods/' . $gameshort . '/random');
    $random_mod = json_decode($json);

    return $response->withRedirec('/mod/ '.$random_mod->data[0]->id);
})->setName('mod.random');

?>

<?php

$app->get('/mod/{id}[/{name}]', function($request, $response, $args) {
    return $this->view->render($response, 'templates/mod.html', [
        'modid' => $args['id']
    ]);
})->setName('mod.view');

$app->get('/random', function($request, $response, $args) {
    $backend_url = $this->get('settings')['backend-url'];
    $gameshort = $this->get('settings')['gameshort'];
    $json = file_get_contents("http://{$backend_url}/api/mods/{$gameshort}/random");
    $random_mod = json_decode($json, true);

    return $response->withRedirect("mod/{$random_mod['data']['id']}/{$random_mod['data']['name']}", 302);
})->setName('mod.random');

?>

Append mod name to /random redirect, use 302 redirect


<?php namespace Barryvdh\TranslationManager;

use Illuminate\Translation\Translator as LaravelTranslator;
use Illuminate\Events\Dispatcher;

class Translator extends LaravelTranslator {

    /** @var  Dispatcher */
    protected $events;

    /**
     * Get the translation for the given key.
     *
     * @param  string  $key
     * @param  array   $replace
     * @param  string  $locale
     * @return string
     */
    public function get($key, array $replace = array(), $locale = null, $fallback = true)
    {
        $result = parent::get($key, $replace, $locale);
        if($result === $key){
            $this->notifyMissingKey($key);

            // Reget with fallback if true
            if ($fallback) {
                $result = parent::get($key, $replace, $locale, $fallback);
            }
        }

        return $result;
    }

    public function setTranslationManager(Manager $manager)
    {
        $this->manager = $manager;
    }

    protected function notifyMissingKey($key)
    {
        list($namespace, $group, $item) = $this->parseKey($key);
        if($this->manager && $namespace === '*' && $group && $item ){
            $this->manager->missingKey($namespace, $group, $item);
        }
    }

}

<?php namespace Barryvdh\TranslationManager;

use Illuminate\Translation\Translator as LaravelTranslator;
use Illuminate\Events\Dispatcher;

class Translator extends LaravelTranslator {

    /** @var  Dispatcher */
    protected $events;

    /**
     * Get the translation for the given key.
     *
     * @param  string  $key
     * @param  array   $replace
     * @param  string  $locale
     * @return string
     */
    public function get($key, array $replace = array(), $locale = null, $fallback = true)
    {
        // Get without fallback
        $result = parent::get($key, $replace, $locale, false);
        if($result === $key){
            $this->notifyMissingKey($key);

            // Reget with fallback
            $result = parent::get($key, $replace, $locale, $fallback);

        }

        return $result;
    }

    public function setTranslationManager(Manager $manager)
    {
        $this->manager = $manager;
    }

    protected function notifyMissingKey($key)
    {
        list($namespace, $group, $item) = $this->parseKey($key);
        if($this->manager && $namespace === '*' && $group && $item ){
            $this->manager->missingKey($namespace, $group, $item);
        }
    }

}

Fix logic, first get without fallback, then reget


<?php
/**
 * Utility functions for the grid fields extension module.
 */
class GridFieldExtensions {

	public static function include_requirements() {
		Requirements::css('gridfieldextensions/css/GridFieldExtensions.css');
		Requirements::javascript('gridfieldextensions/javascript/GridFieldExtensions.js');
	}

}

<?php
/**
 * Utility functions for the grid fields extension module.
 */
class GridFieldExtensions {

	public static function include_requirements() {
		$moduleDir = self::get_module_dir();
		Requirements::css($moduleDir.'/css/GridFieldExtensions.css');
		Requirements::javascript($moduleDir.'/javascript/GridFieldExtensions.js');
	}

	public static function get_module_dir() {
		return basename(dirname(__DIR__));
	}

}

Fix - Support for module to be named other than "gridfieldextensions"


    /**
     * Returns a new query instance.
     *
     * @return <?php echo $queryClassName; ?>

     */
    public function getQuery()
    {
        $query = <?php echo $queryClassName; ?>::create();

        return $query;
    }

    /**
     * Returns a new Model instance.
     *
     * @return <?php echo $objectClassName; ?>

     */
    public function getModel()
    {
        $model = new <?php echo $objectClassName; ?>();

        return $model;
    }

    /**
     * Returns a new Peer Instance;
     *
     * @return <?php echo $peerClassName; ?>

     */
    public function getPeer()
    {
        $peer = new <?php echo $peerClassName; ?>();

        return $peer;
    }

    /**
     * Returns the connection for this table.
     *
     * @return \PropelPDO
     */
    public function getConnection()
    {
        $peer = $this->getPeer();
        $connection = Propel::getConnection($peer::DATABASE_NAME);

        return $connection;
    }

    /**
     * Returns a new query instance.
     *
     * @param     string $modelAlias The alias of a model in the query
     * @param   <?php echo $queryClassName; ?>|Criteria $criteria Optional Criteria to build the query from
     *
     * @return <?php echo $queryClassName; ?>

     */
    public function getQuery($modelAlias = null, $criteria = null)
    {
        $query = <?php echo $queryClassName; ?>::create($modelAlias, $criteria);

        return $query;
    }

    /**
     * Returns a new Model instance.
     *
     * @return <?php echo $objectClassName; ?>

     */
    public function getModel()
    {
        $model = new <?php echo $objectClassName; ?>();

        return $model;
    }

    /**
     * Returns a new Peer Instance;
     *
     * @return <?php echo $peerClassName; ?>

     */
    public function getPeer()
    {
        $peer = new <?php echo $peerClassName; ?>();

        return $peer;
    }

    /**
     * Returns the connection for this table.
     *
     * @return \PropelPDO
     */
    public function getConnection()
    {
        $peer = $this->getPeer();
        $connection = Propel::getConnection($peer::DATABASE_NAME);

        return $connection;
    }

Add missing query create parameters

Add missing query create parameters


<?php
/**
 * Mongo Record, anonymous Mongo Record when an entire class isn't needed
 *
 * Used when only an anonymous Mongo Record is needed
 *
 * @author Lu Wang <https://github.com/lunaru/>
 * @version 1.0.1
 * @package MongoRecord
 */

 final class MongoRecord extends BaseMongoRecord {

   protected $__meta;

   public static function find($collection, $query = array(), $options = array()) {
     return parent::find($query, $options, $collection);
   }

   public static function findOne($collection, $query = array(), $options = array()) {
     return parent::findOne($query, $options, $collection);
   }

   public static function count($collection, $query = array()) {
     return parent::count($query, $collection);
   }

   protected static function instantiate($collection, $document) {
     return parent::instantiate($document, $collection);
   }

 }

<?php
/**
 * Mongo Record, anonymous Mongo Record when an entire class isn't needed
 *
 * Used when only an anonymous Mongo Record is needed
 *
 * @author Lu Wang <https://github.com/lunaru/>
 * @version 1.0.1
 * @package MongoRecord
 */

 final class MongoRecord extends BaseMongoRecord {

   protected $__meta;

   public static function find($collection, $query = array(), $options = array()) {
     return parent::find($query, $options, $collection);
   }

   public static function findOne($collection, $query = array(), $options = array()) {
     return parent::findOne($query, $options, $collection);
   }

   public static function count($collection, $query = array()) {
     return parent::count($query, $collection);
   }

   protected static function instantiate($collection, $document) {
     return parent::instantiate($document, $collection);
   }

   protected static function registerEvent($collection, $event, $callback) {
     return parent::registerEvent($event, $callback, $collection);
   }

   protected static function triggerEvent($collection, &$scope, $event) {
     return parent::registerEvent($scope, $event, $collection);
   }

 }

Fix invalid registerEvent and triggerEvent anon MR


<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Payment / Inc / Class
 */

namespace PH7;

use PH7\Framework\Mvc\Model\DbConfig;

class GroupId
{
    const UNDELETABLE_GROUP_IDS = [
        UserCoreModel::VISITOR_GROUP,
        UserCoreModel::PENDING_GROUP
    ];

    /**
     * Checks if a membership group can be deleted or not.
     *
     * @param int $iMembershipId
     *
     * @return bool
     */
    public static function undeletable($iMembershipId)
    {
        $aUndeletableGroups = self::UNDELETABLE_GROUP_IDS;
        $aUndeletableGroups[] = (int)DbConfig::getSetting('defaultMembershipGroupId');
        $iMembershipId = (int)$iMembershipId;

        return in_array($iMembershipId, $aUndeletableGroups, true);
    }
}

<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Payment / Inc / Class
 */

namespace PH7;

use PH7\Framework\Mvc\Model\DbConfig;

class GroupId
{
    const UNDELETABLE_GROUP_IDS = [
        UserCoreModel::VISITOR_GROUP,
        UserCoreModel::PENDING_GROUP
    ];

    /**
     * Checks if a membership group can be deleted or not.
     *
     * @param int $iMembershipId
     * @param int|null $iDefaultMembershipId Specify another value than the default membership ID set. Optional.
     *
     * @return bool
     */
    public static function undeletable($iMembershipId, $iDefaultMembershipId = null)
    {
        if ($iDefaultMembershipId === null) {
            $iDefaultMembershipId = (int)DbConfig::getSetting('defaultMembershipGroupId');
        }

        $aUndeletableGroups = self::UNDELETABLE_GROUP_IDS;
        $aUndeletableGroups[] = $iDefaultMembershipId;
        $iMembershipId = (int)$iMembershipId;

        return in_array($iMembershipId, $aUndeletableGroups, true);
    }
}

Make Default Membership ID value modifiable from the method


<?php
/**
 * @package Wsdl2PhpGenerator
 */
use Wsdl2PhpGenerator\Console\Application;
use Wsdl2PhpGenerator\Console\GenerateCommand;
use Wsdl2PhpGenerator\Generator;

// Require Composer autoloader depending on usage:
// From own project...
if (file_exists('vendor/autoload.php')) {
    require 'vendor/autoload.php';
// ... or when included in another project.
} else {
    require __DIR__ . '/../../autoload.php';
}

$app = new Application('wsdl2php', '2.5.0');
$command = new GenerateCommand();
$command->setGenerator(Generator::getInstance());
$app->add($command);
$app->run();

<?php
/**
 * @package Wsdl2PhpGenerator
 */
use Wsdl2PhpGenerator\Console\Application;
use Wsdl2PhpGenerator\Console\GenerateCommand;
use Wsdl2PhpGenerator\Generator;

// Require Composer autoloader depending on usage:
// From own project...
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
    require __DIR__ . '/vendor/autoload.php';
// ... or when included in another project.
} else {
    require __DIR__ . '/../../autoload.php';
}

$app = new Application('wsdl2php', '2.5.0');
$command = new GenerateCommand();
$command->setGenerator(Generator::getInstance());
$app->add($command);
$app->run();

Fix autoloading in Phar files.

Fix autoloading in Phar files.

Include __DIR__ when checking file paths. This is required for us to find and load the correct autoloader from the generated Phar file.

This fixes #141.


<?php

namespace Becklyn\AssetsBundle\Finder;

use Symfony\Component\Finder\Finder;

/**
 * Finds all template files in a given directory
 */
class TemplateFinder
{
    /**
     * @param string $directory
     *
     * @return string[]
     */
    public function findInDirectory (string $directory) : array
    {
        $result = [];

        $finder = new Finder();
        $finder
            ->in($directory)
            ->files()
            ->name('*.html.twig')
            ->contains('/{%\s+?(javascripts|stylesheets) /i')
            ->followLinks()
            ->ignoreUnreadableDirs();

        /** @var \SplFileInfo $file */
        foreach ($finder as $file)
        {
            $result[] = $file->getPathname();
        }

        return $result;
    }
}

<?php

namespace Becklyn\AssetsBundle\Finder;

use Symfony\Component\Finder\Finder;

/**
 * Finds all template files in a given directory
 */
class TemplateFinder
{
    /**
     * @param string $directory
     *
     * @return \SplFileInfo[]
     */
    public function findInDirectory (string $directory) : array
    {
        $result = [];

        $finder = new Finder();
        $finder
            ->in($directory)
            ->files()
            ->name('*.html.twig')
            ->contains('/{%\s+?(javascripts|stylesheets) /i')
            ->followLinks()
            ->ignoreUnreadableDirs();

        /** @var \SplFileInfo $file */
        foreach ($finder as $file)
        {
            $result[] = $file;
        }

        return $result;
    }
}

Return SplFileInfo objects instead of strings


<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'mail@extravaganzainnovations.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Quote Request:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: info@extravaganzainnovations.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'contact@zuhaibahmad.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Quote Request:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: info@extravaganzainnovations.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

Update email to temporarily available one


<?php
/**
 * This file is part of PMG\Queue
 *
 * Copyright (c) PMG <https://www.pmg.com>
 *
 * For full copyright information see the LICENSE file distributed
 * with this source code.
 *
 * @license     http://opensource.org/licenses/Apache-2.0 Apache-2.0
 */

namespace PMG\Queue\Driver;

use PMG\Queue\Envelope;
use PMG\Queue\Serializer\Serializer;
use PMG\Queue\Serializer\NativeSerializer;

/**
 * Base class for drivers that deal with persistent backends. This provides
 * some utilities for serialization.
 *
 * @since   2.0
 */
abstract class AbstractPersistanceDriver implements \PMG\Queue\Driver
{
    /**
     * @var Serializer
     */
    private $serializer;

    public function __construct(Serializer $serializer=null)
    {
        $this->serializer = $serializer;
    }

    protected function serialize(Envelope $env)
    {
        return $this->getSerializer()->serialize($env);
    }

    protected function unserialize($data)
    {
        return $this->getSerializer()->unserialize($data);
    }

    protected function getSerializer()
    {
        if (!$this->serializer) {
            $this->serializer = new NativeSerializer();
        }

        return $this->serializer;
    }
}

<?php
/**
 * This file is part of PMG\Queue
 *
 * Copyright (c) PMG <https://www.pmg.com>
 *
 * For full copyright information see the LICENSE file distributed
 * with this source code.
 *
 * @license     http://opensource.org/licenses/Apache-2.0 Apache-2.0
 */

namespace PMG\Queue\Driver;

use PMG\Queue\Envelope;
use PMG\Queue\Serializer\Serializer;
use PMG\Queue\Serializer\NativeSerializer;

/**
 * Base class for drivers that deal with persistent backends. This provides
 * some utilities for serialization.
 *
 * @since   2.0
 */
abstract class AbstractPersistanceDriver implements \PMG\Queue\Driver
{
    /**
     * @var Serializer
     */
    private $serializer;

    public function __construct(Serializer $serializer=null)
    {
        $this->serializer = $serializer ?: static::createDefaultSerializer();
    }

    protected function serialize(Envelope $env)
    {
        return $this->getSerializer()->serialize($env);
    }

    protected function unserialize($data)
    {
        return $this->getSerializer()->unserialize($data);
    }

    protected function getSerializer()
    {
        return $this->serializer;
    }

    protected static function createDefaultSerializer()
    {
        return new NativeSerializer();
    }
}

Create a Serializer in the Constructor of Persistent Drivers

Rather than creating it on demand (which is not as intuitive).


<?php

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

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

return [
    'up' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->index(['is_sticky', 'created_at']);
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->dropIndex(['is_sticky', 'created_at']);
        });
    }
];

<?php

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

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

return [
    'up' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) use ($schema) {
            $table->index(['is_sticky', 'created_at']);

            Migration::fixIndexNames($schema, $table);
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) use ($schema) {
            $table->dropIndex(['is_sticky', 'created_at']);

            Migration::fixIndexNames($schema, $table);
        });
    }
];

Fix index names in migrations

Fix index names in migrations

This can be reverted when we upgrade to Laravel 5.7.


<?php
/**
 * Go! OOP&AOP PHP framework
 *
 * @copyright     Copyright 2013, Lissachenko Alexander <lisachenko.it@gmail.com>
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */

namespace Go\Instrument\ClassLoading;

use Go\Instrument\ClassLoading\UniversalClassLoader;

/**
* Ensures that autoloader of Go! library is first in the stack of autoloaders
*
* This fix problems with autoloaders that was prepended, for example, composer.
*
* @return void
*/
function ensureLibraryAutoloaderIsFirst()
{
    $loaders = spl_autoload_functions();
    if (isset($loaders[0]) && ($loaders[0][0] instanceof UniversalClassLoader)) {
        return;
    }
    $newLoaders = array();
    foreach ($loaders as $loader) {
        spl_autoload_unregister($loader);
        if (is_array($loader) && ($loader[0] instanceof UniversalClassLoader)) {
            array_unshift($newLoaders, $loader);
        } else {
            array_push($newLoaders, $loader);
        }
    }
    foreach ($newLoaders as $loader) {
        spl_autoload_register($loader);
    }
}

ensureLibraryAutoloaderIsFirst();

<?php
/**
 * Go! OOP&AOP PHP framework
 *
 * @copyright     Copyright 2013, Lissachenko Alexander <lisachenko.it@gmail.com>
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */

namespace Go\Instrument\ClassLoading;

use Go\Instrument\ClassLoading\UniversalClassLoader;

/**
* Ensures that autoloader of Go! library is first in the stack of autoloaders
*
* This fix problems with autoloaders that was prepended, for example, composer.
*
* @return void
*/
function ensureLibraryAutoloaderIsFirst()
{
    $loaders = spl_autoload_functions();
    if ($loaders && isset($loaders[0]) && is_array($loaders[0])) {
        if ($loaders[0][0] instanceof UniversalClassLoader) {
            return;
        }
    }
    $newLoaders = array();
    foreach ($loaders as $loader) {
        spl_autoload_unregister($loader);
        if (is_array($loader) && ($loader[0] instanceof UniversalClassLoader)) {
            array_unshift($newLoaders, $loader);
        } else {
            array_push($newLoaders, $loader);
        }
    }
    foreach ($newLoaders as $loader) {
        spl_autoload_register($loader);
    }
}

ensureLibraryAutoloaderIsFirst();

Add a check for an array to prevent fatal error


<?php

namespace Lily\Middleware\Session;

class NativeStore
{
    public function get(array $request)
    {
        $request['session'] = $_SESSION;
        return $request;
    }

    public function set(array $response)
    {
        if (isset($response['session'])) {
            $_SESSION = $response['session'];
        }

        return $response;
    }
}

<?php

namespace Lily\Middleware\Session;

class NativeStore
{
    public function __construct()
    {
        if ( ! session_id()) {
            session_start();
        }
    }

    public function get(array $request)
    {
        $request['session'] = $_SESSION;
        return $request;
    }

    public function set(array $response)
    {
        if (isset($response['session'])) {
            $_SESSION = $response['session'];
        }

        return $response;
    }
}

Call session_start() if not already started

This happens on construction although I could have opted to do it on demand.


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

namespace Darvin\UtilsBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class DarvinUtilsExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
//        $configuration = new Configuration();
//        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('cloner.yml');
        $loader->load('flash.yml');
        $loader->load('mapping.yml');
        $loader->load('security.yml');
        $loader->load('sluggable.yml');
        $loader->load('stringifier.yml');
        $loader->load('transliterator.yml');
    }
}

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

namespace Darvin\UtilsBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class DarvinUtilsExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
//        $configuration = new Configuration();
//        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('cloner.yml');
        $loader->load('flash.yml');
        $loader->load('mapping.yml');
        $loader->load('security.yml');
        $loader->load('stringifier.yml');
        $loader->load('transliterator.yml');
    }
}

Move sluggable transliterator to content bundle.


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * VoterRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class VoterRepository extends EntityRepository
{
}

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\User\UserInterface;

use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\NoResultException;

/**
 * VoterRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class VoterRepository extends EntityRepository
{
	public function loadUserByUsername($username)
	{
		$q = $this
		->createQueryBuilder('u')
		->where('u.username = :username')
		->setParameter('username', $username)
		->getQuery();

		try
		{
			// The Query::getSingleResult() method throws an exception
			// if there is no record matching the criteria.
			$user = $q->getSingleResult();
		}
		catch (NoResultException $e)
		{
			$message = sprintf(
					'Unable to find an active voter MunicipalesBundle:Voter object identified by "%s".',
					$username
			);
			throw new UsernameNotFoundException($message, 0, $e);
		}

		return $user;
	}

	/**
	 * {@inheritdoc}
	 */
	protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token)
	{
		$currentUser = $token->getUser();

		if ($currentUser instanceof UserInterface) {
			if ($currentUser->getPassword() !== $user->getPassword()) {
				throw new BadCredentialsException('The credentials were changed from another session.');
			}
		} else {
			if (!$presentedPassword = $token->getCredentials()) {
				throw new BadCredentialsException('The presented password cannot be empty.');
			}

			if (! $this->service->authenticate($token->getUser(), $presentedPassword)) {
				throw new BadCredentialsException('The presented password is invalid.');
			}
		}
	}

	public function refreshUser(UserInterface $user)
	{
		$class = get_class($user);
		if (!$this->supportsClass($class)) {
			throw new UnsupportedUserException(
					sprintf(
							'Instances of "%s" are not supported.',
							$class
					)
			);
		}

		return $this->find($user->getId());
	}

	public function supportsClass($class)
	{
		return $this->getEntityName() === $class
		|| is_subclass_of($class, $this->getEntityName());
	}
}

Add voters repository methods for login

Add voters repository methods for login


<?php

namespace Agile\InvoiceBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

/**
 * Company Controller.
 *
 * @Route("/company")
 */
class CompanyController extends Controller
{

}

<?php

namespace Agile\InvoiceBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Agile\InvoiceBundle\Form\Type\CompanyPreferencesFormType;

/**
 * Company Controller.
 *
 * @Route("/company")
 */
class CompanyController extends Controller
{

    /**
     * @Route("/account", name="company_account")
     * @Template()
     */
    public function accountAction()
    {
        $company = $this->get('context.company');

        return array(
            'company' => $company,
        );
    }

    /**
     * @Route("/preferences", name="company_preferences")
     * @Template()
     */
    public function preferencesAction()
    {
        $company = $this->get('context.company');

        $form = $this->createForm(new CompanyPreferencesFormType(), $company);

        return array(
            'form' => $form->createView(),
        );
    }

    /**
     * @Route("/preferences", name="company_preferences_update")
     * @Method("PUT")
     * @Template("AgileInvoiceBundle:Company:preferences.html.twig")
     */
    public function preferencesUpdateAction(Request $request)
    {
        # code...
    }
}

Create actions "accountAction()", "preferencesAction()", "preferencesUpdateAction()"


<?php

namespace Project\AppBundle\Form\Type;

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

class RegistrationFormType extends BaseType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder
            ->add('username', null, array(/*'label' => 'form.username',*/ 'translation_domain' => 'FOSUserBundle'))
            ->add('email', 'email', array(/*'label' => 'form.email',*/ 'translation_domain' => 'FOSUserBundle'))
            ->add('plainPassword', 'repeated', array(
                'type' => 'password',
                'options' => array('translation_domain' => 'FOSUserBundle'),
                'first_options' => array('label' => 'Password'),
                'second_options' => array('label' => 'Password confirmation'),
                'invalid_message' => 'fos_user.password.mismatch',
            ))
        ;
    }

    public function getName()
    {
        return 'override_fosuser_registration';
    }

}

<?php

namespace Project\AppBundle\Form\Type;

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

class RegistrationFormType extends BaseType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder
            ->add('username', null, array(/*'label' => 'form.username',*/ 'translation_domain' => 'FOSUserBundle'))
            ->add('email', 'email', array(/*'label' => 'form.email',*/ 'translation_domain' => 'FOSUserBundle'))
            ->add('plainPassword', 'repeated', array(
                'type' => 'password',
                'options' => array('translation_domain' => 'FOSUserBundle'),
                'first_options' => array('label' => 'Password'),
                'second_options' => array('label' => 'Password confirmation'),
                'invalid_message' => 'fos_user.password.mismatch',
            ))
            ->add('surname', null)
        ;
    }

    public function getName()
    {
        return 'override_fosuser_registration';
    }

}

Add surname in the registration

Add surname in the registration


<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });

        DB::statement('ALTER TABLE users ADD FULLTEXT search(name, email)');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropIndex('search');
        });

        Schema::drop('users');
    }
}

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();

            $table->engine = 'MyISAM';
        });

        DB::statement('ALTER TABLE users ADD FULLTEXT search(name, email)');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropIndex('search');
        });

        Schema::drop('users');
    }
}

Change engine type of users table because sucks hosting


<?php

namespace wcf\action;

use wcf\system\exception\InvalidSecurityTokenException;
use wcf\system\WCF;

/**
 * Extends AbstractAction by a function to validate a given security token.
 * A missing or invalid token will be result in a throw of a IllegalLinkException.
 *
 * @author  Marcel Werk
 * @copyright   2001-2019 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Action
 */
abstract class AbstractSecureAction extends AbstractAction
{
    /**
     * @inheritDoc
     */
    public function readParameters()
    {
        parent::readParameters();

        // check security token (unless it is a guest)
        if (WCF::getSession()->userID) {
            $this->checkSecurityToken();
        }
    }

    /**
     * Validates the security token.
     */
    protected function checkSecurityToken()
    {
        if (!isset($_REQUEST['t']) || !WCF::getSession()->checkSecurityToken($_REQUEST['t'])) {
            throw new InvalidSecurityTokenException();
        }
    }
}

<?php

namespace wcf\action;

use wcf\system\exception\InvalidSecurityTokenException;
use wcf\system\WCF;

/**
 * Extends AbstractAction by a function to validate a given security token.
 * A missing or invalid token will be result in a throw of a IllegalLinkException.
 *
 * @author  Marcel Werk
 * @copyright   2001-2019 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Action
 */
abstract class AbstractSecureAction extends AbstractAction
{
    /**
     * @inheritDoc
     */
    public function readParameters()
    {
        parent::readParameters();

        $this->checkSecurityToken();
    }

    /**
     * Validates the security token.
     */
    protected function checkSecurityToken()
    {
        if (!isset($_REQUEST['t']) || !WCF::getSession()->checkSecurityToken($_REQUEST['t'])) {
            throw new InvalidSecurityTokenException();
        }
    }
}

Revert "Ignore security token for guests"

Due to the age of this commit it's a bit unclear why exactly it was necessary
at that time, but records indicate that it was related to the URL based session
system (`?s=…`) in combination with with virtual sessions effectively changing
the session ID during login, the `SID` constants being constant and the CSRF
token being stored in the session.

As none of this applies any longer, this workaround should no longer be
necessary and thus reverted. It certainly violates the principle of least
astonishment, because it only applies to AbstractSecureAction, but not forms
and it's questionable from a security perspective.

This reverts commit e5c2467f717632b47f935a0e59a310de2e2867f3.


<?php namespace Pingpong\Modules\Commands;

use Illuminate\Support\Str;
use Pingpong\Generators\Stub;
use Pingpong\Modules\Traits\ModuleCommandTrait;
use Symfony\Component\Console\Input\InputArgument;

class GenerateProviderCommand extends GeneratorCommand {

    use ModuleCommandTrait;

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'module:provider';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a new service provider for the specified module.';

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('name', InputArgument::REQUIRED, 'The service provider name.'),
            array('module', InputArgument::OPTIONAL, 'The name of module will be used.'),
        );
    }

    /**
     * @return mixed
     */
    protected function getTemplateContents()
    {
        return new Stub('provider', [
            'MODULE' => $this->getModuleName(),
            'NAME' => $this->getFileName()
        ]);
    }

    /**
     * @return mixed
     */
    protected function getDestinationFilePath()
    {
        $path = $this->laravel['modules']->getModulePath($this->getModuleName());

        $generatorPath = $this->laravel['modules']->get('paths.generator.provider');

        return $path . $generatorPath . '/' . $this->getFileName() . '.php';
    }

    /**
     * @return string
     */
    private function getFileName()
    {
        return Str::studly($this->argument('name'));
    }
}

<?php namespace Pingpong\Modules\Commands;

use Illuminate\Support\Str;
use Pingpong\Generators\Stub;
use Pingpong\Modules\Traits\ModuleCommandTrait;
use Symfony\Component\Console\Input\InputArgument;

class GenerateProviderCommand extends GeneratorCommand {

    use ModuleCommandTrait;

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'module:provider';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a new service provider for the specified module.';

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('name', InputArgument::REQUIRED, 'The service provider name.'),
            array('module', InputArgument::OPTIONAL, 'The name of module will be used.'),
        );
    }

    /**
     * @return mixed
     */
    protected function getTemplateContents()
    {
        return new Stub('provider', [
            'MODULE' => $this->getModuleName(),
            'NAME' => $this->getFileName()
        ]);
    }

    /**
     * @return mixed
     */
    protected function getDestinationFilePath()
    {
        $path = $this->laravel['modules']->getModulePath($this->getModuleName());

        $generatorPath = $this->laravel['modules']->config('paths.generator.provider');

        return $path . $generatorPath . '/' . $this->getFileName() . '.php';
    }

    /**
     * @return string
     */
    private function getFileName()
    {
        return Str::studly($this->argument('name'));
    }
}

Fix generator path for service provider

Fix generator path for service provider


<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// 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(0002);

// 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';
Debug::enable();

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

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

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// 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(0002);

// 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';
Debug::enable();

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

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

Revert to secure DEV environment

Revert to secure DEV environment


<?php
/**
 * jsonAPI - Slim extension to implement fast JSON API's
 *
 * @package Slim
 * @subpackage View
 * @author Jonathan Tavares <the.entomb@gmail.com>
 * @license GNU General Public License, version 3
 * @filesource
 *
 *
*/

/**
 * JsonApiView - view wrapper for json responses (with error code).
 *
 * @package Slim
 * @subpackage View
 * @author Jonathan Tavares <the.entomb@gmail.com>
 * @license GNU General Public License, version 3
 * @filesource
 */
class JsonApiView extends \Slim\View {

    public function render($status=200) {
        $app = \Slim\Slim::getInstance();

        $status = intval($status);

        //append error bool
        if (!$this->has('error')) {
            $this->set('error', false);
        }

        //append status code
        $this->set('status', $status);

        $app->response()->status($status);
        $app->response()->header('Content-Type', 'application/json');
        $app->response()->body(json_encode($this->all()));

        $app->stop();
    }

}

<?php
/**
 * jsonAPI - Slim extension to implement fast JSON API's
 *
 * @package Slim
 * @subpackage View
 * @author Jonathan Tavares <the.entomb@gmail.com>
 * @license GNU General Public License, version 3
 * @filesource
 *
 *
*/

/**
 * JsonApiView - view wrapper for json responses (with error code).
 *
 * @package Slim
 * @subpackage View
 * @author Jonathan Tavares <the.entomb@gmail.com>
 * @license GNU General Public License, version 3
 * @filesource
 */
class JsonApiView extends \Slim\View {

    public function render($status=200) {
        $app = \Slim\Slim::getInstance();

        $status = intval($status);

        $response = $this->all();

        //append error bool
        if (!$this->has('error')) {
            $response['error'] = false;
        }

        //append status code
        $response['status'] = $status;

        //add flash messages
        $response['flash'] = $this->data->flash->getMessages();

        $app->response()->status($status);
        $app->response()->header('Content-Type', 'application/json');
        $app->response()->body(json_encode($response));

        $app->stop();
    }

}

Add flash messages to the response

Add flash messages to the response


<?php

namespace SymfonyDay\Bundle\BlogBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        // Set a crawler to make a fake request
        $crawler = $client->request('GET', '/blog');

        // Count instances with CSS3 syntax
        $this->assertEquals(2, $crawler->filter('.post')->count());
        $this->assertEquals(1, $crawler->filter('html:contains("Symfony Day")')->count());

        // Use a regexp to look for a certain word
        $response = $client->getResponse();
        $this->assertRegExp('/Second/', $response->getContent());

        // Check if there are more than five SQL queries
        $profile = $client->getProfile();
        $this->assertLessThanOrEqual(5, $profile->getCollector('db')->getQueryCount());
    }
}

<?php

namespace SymfonyDay\Bundle\BlogBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        // Set a crawler to make a fake request
        $crawler = $client->request('GET', '/blog');

        // Count instances with CSS3 syntax
        $this->assertEquals(2, $crawler->filter('.post')->count());
        $this->assertEquals(1, $crawler->filter('html:contains("Symfony Day")')->count());

        // Use a regexp to look for a certain word
        $response = $client->getResponse();
        $this->assertRegExp('/Second/', $response->getContent());

        // Check if there are more than five SQL queries
        $profile = $client->getProfile();
        $this->assertLessThanOrEqual(5, $profile->getCollector('db')->getQueryCount());

        // Click a link a move to another page
        $title = 'Welcome To The Symfony Day Conference';
        $link = $crawler
            ->selectLink($title)
            ->link()
        ;

        $crawler = $client->click($link);

        $this->assertEquals(1, $crawler->filter('title:contains("'.$title.'")')->count());
    }
}

Add test for clicking a link and confirming the page


<?php

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

class CreateTwoFactorAuthsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('two_factor_auths', function (Blueprint $table) {
            $table->string('id')->nullable();
            $table->bigIncrements('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

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

<?php

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

class CreateTwoFactorAuthsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('two_factor_auths', function (Blueprint $table) {
            $table->string('id')->nullable();

            // Laravel 5.8 changed the type of "id" on "users" from "increments"
            // to "bigIncrements". Hence, we potentially could run into trouble:
            //
            // 1. We update from 5.7 to 5.8 and keep using "increments"
            // 2. We start a fresh Laravel project which uses "bigIncrements"
            //
            // Both scenarios are possible and we need to be able to account for
            // it. The only way to do that in a reliable way is to check the type
            // of "id" on "users" before we create our foreign key.
            //
            // Why is this not ideal?
            //
            // 1. There now is a dependency on doctrine/dbal
            // 2. This sort of conditional logic has no place in a migration file
            if (DB::getDoctrineSchemaManager()->listTableDetails('users')->getColumn('id')->getType() instanceof \Doctrine\DBAL\Types\IntegerType) {
                $table->increments('user_id');
            } else {
                $table->bigIncrements('user_id');
            }

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

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

Use conditional to determine the correct type for 'user_id' col to keep the project backwards compatible and make it compatible with Laravel 5.8 (not ideal)


<?php

namespace App\Console\Commands;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ImportScheduleDaily extends BaseCommand
{

    protected $signature = 'import:daily';

    protected $description = 'Run all increment commands on sources that we\'re able to, and do a full refresh on sources that require it.';

    public function handle()
    {

        $this->call('import:collections');
        $this->call('import:collections-delete');
        $this->call('import:exhibitions-legacy');
        $this->call('import:events-ticketed');
        $this->call('import:events-legacy');
        $this->call('import:mobile');
        $this->call('import:set-ulan-uris');
        $this->call('import:products');
        $this->call('import:web');
        $this->call('import:analytics');
        $this->call('import:digital-labels');

        // EventOccurrence is not included in import:web to avoid duplication
        $this->call('import:web-full', ['endpoint' => 'events/occurrences']);
    }

}

<?php

namespace App\Console\Commands;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ImportScheduleDaily extends BaseCommand
{

    protected $signature = 'import:daily';

    protected $description = 'Run all increment commands on sources that we\'re able to, and do a full refresh on sources that require it.';

    public function handle()
    {

        $this->call('import:collections');
        $this->call('import:collections-delete');
        $this->call('import:exhibitions-legacy');
        $this->call('import:events-ticketed');
        $this->call('import:events-legacy');
        $this->call('import:mobile');
        $this->call('import:set-ulan-uris');
        $this->call('import:products');
        $this->call('import:web');
        $this->call('import:analytics');
        $this->call('import:digital-labels');

        // EventOccurrence is not included in import:web to avoid duplication
        $this->call('import:web-full', ['endpoint' => 'events/occurrences', '--yes' => 'default']);
    }

}

Fix "Aborted" schedule error due to prompt


<?php

namespace TMCms\Admin;

use TMCms\Files\Finder;
use TMCms\Traits\singletonOnlyInstanceTrait;

defined ('INC') or exit;

class AdminTranslations {
    use singletonOnlyInstanceTrait;

	private static $init_data;

	public function getActualValueByKey($key) {
		if (!self::$init_data) {
			$this->init_data();
		}

		return is_string($key) && isset(self::$init_data[$key]) ? self::$init_data[$key] : $key;
	}

	private function init_data()
	{
		$data = [];
		foreach (Finder::getInstance()->getPathFolders(Finder::TYPE_TRANSLATIONS) as $file) {
			$file_path = $file . Users::getInstance()->getUserLng() . '.php';
			if (stripos($file_path, DIR_BASE) === false) {
				$file_path = DIR_BASE . $file_path;
			}
			if (file_exists($file_path)) {
				$data += require_once $file_path;
			}
		}

		self::$init_data = $data;
	}
}

<?php

namespace TMCms\Admin;

use TMCms\Config\Settings;
use TMCms\Files\Finder;
use TMCms\Traits\singletonOnlyInstanceTrait;

defined ('INC') or exit;

class AdminTranslations {
    use singletonOnlyInstanceTrait;

	private static $init_data = [];

	public function getActualValueByKey($key) {
		if (!self::$init_data) {
			$this->init_data();
		}

		return is_string($key) && isset(self::$init_data[$key]) ? self::$init_data[$key] : $key;
	}

	private function init_data()
	{
		if (Settings::getInstance()->get('disable_cms_translations')) {
			return; // No translations
		}

		$data = [];
		foreach (Finder::getInstance()->getPathFolders(Finder::TYPE_TRANSLATIONS) as $file) {
			$file_path = $file . Users::getInstance()->getUserLng() . '.php';
			if (stripos($file_path, DIR_BASE) === false) {
				$file_path = DIR_BASE . $file_path;
			}
			if (file_exists($file_path)) {
				$data += require_once $file_path;
			}
		}

		self::$init_data = $data;
	}
}

Disable admin panel element translations, if appropriate options is activated