<?php

namespace Avanzu\AdminThemeBundle\DependencyInjection;

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

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

        $rootNode->children()
                    ->scalarNode('bower_bin')
                        ->defaultValue('/usr/local/bin/bower')
                    ->end()
                    ->scalarNode('use_assetic')
                        ->defaultValue(true)
                    ->end()
                    ->scalarNode('use_twig')
                        ->defaultValue(true)
                    ->end()
                    ->arrayNode('options')
                        ->defaultValue([])
                    ->end()
                ->end();
        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}

<?php

namespace Avanzu\AdminThemeBundle\DependencyInjection;

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

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

        $rootNode->children()
                    ->scalarNode('bower_bin')
                        ->defaultValue('/usr/local/bin/bower')
                    ->end()
                    ->scalarNode('use_assetic')
                        ->defaultValue(true)
                    ->end()
                    ->scalarNode('use_twig')
                        ->defaultValue(true)
                    ->end()
                    ->arrayNode('options')
                        ->beforeNormalization()->castToArray()->end()
                    ->end()
                ->end();
        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}

Remove default value and cast always to array the options


<?php

namespace Victoire\Widget\PollBundle\DependencyInjection;

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

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

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

        return $treeBuilder;
    }
}

<?php

namespace Victoire\Widget\PollBundle\DependencyInjection;

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

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

        return $treeBuilder;
    }
}

Add configuration for victoire menu item


<?php

namespace SymfonyBundles\JsonRequestBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use SymfonyBundles\JsonRequestBundle\EventListener\RequestTransformerListener;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $builder = new TreeBuilder();

        $builder->root('sb_json_request')
            ->children()
                ->arrayNode('listener')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('request_transformer')
                            ->defaultValue(RequestTransformerListener::class)
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $builder;
    }
}

<?php

namespace SymfonyBundles\JsonRequestBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use SymfonyBundles\JsonRequestBundle\EventListener\RequestTransformerListener;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $builder = new TreeBuilder('sb_json_request');

        $builder->getRootNode()
            ->children()
                ->arrayNode('listener')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('request_transformer')
                            ->defaultValue(RequestTransformerListener::class)
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $builder;
    }
}

Fix the deprecation notice on the TreeBuilder added in Symfony 4.2

See https://symfony.com/blog/new-in-symfony-4-2-important-deprecations


<?php

namespace Uploadify\Casts;

use Uploadify\Casts\Cast as BaseCast;

class ImageCast extends BaseCast
{
    /**
     * Get full url to file
     *
     * @param  int|array  $width
     * @param  int  $height
     * @param  array  $options
     * @return string
     */
    public function url($width = null, $height = null, array $options = [])
    {
        if (is_array($width)) {
            $options = $width;
        } elseif ($width) {
            $options = array_merge(['w' => $width], $options);
        }

        if ($height) {
            $options = array_merge(['h' => $height], $options);
        }

        if (! empty($options)) {
            return $this->getStorage()->url($this->path().'/'.$this->prepareOptions($options).'/'.$this->name());
        }

        return $this->getStorage()->url($this->path().'/'.$this->name());
    }

    /**
     * Prepare and convert options from array to string
     *
     * @param array $options
     */
    protected function prepareOptions(array $options = [])
    {
        $string = implode(',', array_map(
            function ($value, $key) {
                return $key.'_'.$value;
            },
            $options,
            array_keys($options)
        ));

        $from = ['width', 'height'];

        $to = ['w', 'h'];

        return str_replace($from, $to, $string);
    }
}

<?php

namespace Uploadify\Casts;

use Uploadify\Casts\Cast as BaseCast;

class ImageCast extends BaseCast
{
    /**
     * Get full url to file
     *
     * @param  int|array  $width
     * @param  int  $height
     * @param  array  $options
     * @return string
     */
    public function url($width = null, $height = null, array $options = [])
    {
        if (is_array($width)) {
            $options = $width;
        } elseif ($width) {
            if ($height) {
                $options = array_merge(['h' => $height], $options);
            }

            $options = array_merge(['w' => $width], $options);
        }

        if (! empty($options)) {
            return $this->getStorage()->url($this->path().'/'.$this->prepareOptions($options).'/'.$this->name());
        }

        return $this->getStorage()->url($this->path().'/'.$this->name());
    }

    /**
     * Prepare and convert options from array to string
     *
     * @param array $options
     */
    protected function prepareOptions(array $options = [])
    {
        $string = implode(',', array_map(
            function ($value, $key) {
                return $key.'_'.$value;
            },
            $options,
            array_keys($options)
        ));

        $from = ['width', 'height'];

        $to = ['w', 'h'];

        return str_replace($from, $to, $string);
    }
}

Add width parameter before height in options array


<?php

namespace Uploadify\Casts;

use Uploadify\Casts\Cast as BaseCast;

class ImageCast extends BaseCast
{
    /**
     * Get full url to file
     *
     * @param  int|array  $width
     * @param  int  $height
     * @param  array  $options
     * @return string
     */
    public function url($width = null, $height = null, array $options = [])
    {
        if (is_array($width)) {
            $options = $width;
        } elseif ($width) {
            $options['w'] = $width;
        }

        if ($height) {
            $options['h'] = $height;
        }

        if (! empty($options)) {
            return $this->getStorage()->url($this->path().'/'.$this->prepareOptions($options).'/'.$this->name());
        }

        return $this->getStorage()->url($this->path().'/'.$this->name());
    }

    /**
     * Prepare and convert options from array to string
     *
     * @param array $options
     */
    protected function prepareOptions(array $options = [])
    {
        $string = implode(',', array_map(
            function ($value, $key) {
                return $key.'_'.$value;
            },
            $options,
            array_keys($options)
        ));

        $from = ['width', 'height'];

        $to = ['w', 'h'];

        return str_replace($from, $to, $string);
    }
}

<?php

namespace Uploadify\Casts;

use Uploadify\Casts\Cast as BaseCast;

class ImageCast extends BaseCast
{
    /**
     * Get full url to file
     *
     * @param  int|array  $width
     * @param  int  $height
     * @param  array  $options
     * @return string
     */
    public function url($width = null, $height = null, array $options = [])
    {
        if (is_array($width)) {
            $options = $width;
        } elseif ($width) {
            $options = array_merge(['w' => $width], $options);
        }

        if ($height) {
            $options = array_merge(['h' => $height], $options);
        }

        if (! empty($options)) {
            return $this->getStorage()->url($this->path().'/'.$this->prepareOptions($options).'/'.$this->name());
        }

        return $this->getStorage()->url($this->path().'/'.$this->name());
    }

    /**
     * Prepare and convert options from array to string
     *
     * @param array $options
     */
    protected function prepareOptions(array $options = [])
    {
        $string = implode(',', array_map(
            function ($value, $key) {
                return $key.'_'.$value;
            },
            $options,
            array_keys($options)
        ));

        $from = ['width', 'height'];

        $to = ['w', 'h'];

        return str_replace($from, $to, $string);
    }
}

Prepend width and height to options array in url() method


<?php namespace GeneaLabs\MixPanel;

use Illuminate\Support\Facades\App;

class MixPanel extends \Mixpanel
{
    /**
     * @param array $options
     */
    public function __construct(array $options = [])
    {
        parent::__construct(config('services.mixpanel.token'), $options);
    }
}

<?php namespace GeneaLabs\MixPanel;

use Illuminate\Support\Facades\App;

class MixPanel extends \Mixpanel
{
    private $defaults = [
        'connect_timeout' => 2,
        'timeout' => 2,
    ];

    /**
     * @param array $options
     */
    public function __construct(array $options = [])
    {
        $options = array_merge($this->defaults, $options);

        parent::__construct(config('services.mixpanel.token'), $options);
    }
}

Set connection timouts to 2 seconds to prevent site from hanging


@inject('pages', 'BruceCms\Pages\Page')

			Home

		@foreach($pages as $page)

				link) }}">{{ $page->title }}

		@endforeach

@inject('pages', 'BruceCms\Pages\Page')

			Home

		@foreach($pages->unhidden()->get() as $page)

				link) }}">{{ $page->title }}

		@endforeach

Update injection in nav view to actually grab the files we want


<?php
namespace Avh\Network;

use Avh\Utility\Common;

final class Visitor
{

    /**
     * Get the user's IP
     *
     * @return string
     */
    public static function getUserIp()
    {
        $ip = array();
        foreach (array('HTTP_CF_CONNECTING_IP', 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $_key) {
            if (array_key_exists($_key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$_key]) as $_visitors_ip) {
                    $ip[] = str_replace(' ', '', $_visitors_ip);
                }
            }
        }
        // If for some strange reason we don't get an IP we return imemdiately with 0.0.0.0
        if (empty($ip)) {
            return '0.0.0.0';
        }
        $ip = array_values(array_unique($ip));
        $return = null;
        // In PHP 5.3 and up the function filter_var can be used, much quicker as the regular expression check
        foreach ($ip as $_i) {
            if (filter_var($_i, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE)) {
                $return = $_i;
                break;
            }
        }

        if (null === $return) {
            $return = '0.0.0.0';
        }

        return $return;
    }
}

<?php
namespace Avh\Network;

final class Visitor
{

    /**
     * Get the user's IP
     *
     * @return string
     */
    public static function getUserIp()
    {
        $ip = array();
        foreach (array('HTTP_CF_CONNECTING_IP', 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $_key) {
            if (array_key_exists($_key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$_key]) as $_visitors_ip) {
                    $ip[] = str_replace(' ', '', $_visitors_ip);
                }
            }
        }
        // If for some strange reason we don't get an IP we return imemdiately with 0.0.0.0
        if (empty($ip)) {
            return '0.0.0.0';
        }
        $ip = array_values(array_unique($ip));
        $return = null;
        // In PHP 5.3 and up the function filter_var can be used, much quicker as the regular expression check
        foreach ($ip as $_i) {
            if (filter_var($_i, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE)) {
                $return = $_i;
                break;
            }
        }

        if (null === $return) {
            $return = '0.0.0.0';
        }

        return $return;
    }
}

Remove use as it's not used.

Remove use as it's not used.


<?php
use Migrations\AbstractMigration;

class AlterTableNotes extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $this->table('notes')
            ->rename('qobo_notes');
    }
}

<?php
use Migrations\AbstractMigration;

class AlterTableNotes extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $this
            ->table('notes')
            ->rename('qobo_notes')
            ->save();
    }
}

Fix migrations for CakePHP v3.8

Fix migrations for CakePHP v3.8


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    protected $fillable = ['name', 'description'];
    public function assignments(){
    	return $this->hasMany('app\Assignment');
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    protected $fillable = ['name', 'description'];
    public function assignments()
    {
    	return $this->hasMany('app\Assignment');
    }
}

Create relationship for roles table

refactor(roles): Create relationship for roles table

modified:   app/Role.php

see #97


<?php

defined( 'NODEMON_RUNNING') || die( 'Access denied.' );

$nodeconfig = array(
    'serverurl' => 'http://127.0.0.1:9332/',
    'username' => 'username',
    'password' => 'password',
    'services' => array(
        'connect' => false,
        'verify' => true,
        'broadcast' => true,
    ),
    'onionurl' => '',
    'donations' => '',
);

?>

<?php

defined( 'NODEMON_RUNNING') || die( 'Access denied.' );

$nodeconfig = array(
    'serverurl' => 'http://127.0.0.1:9332/',
    'username' => 'username',
    'password' => 'password',
    'services' => array(
        'connect' => false,
        'verify' => false,
        'broadcast' => false,
    ),
    'onionurl' => '',
    'donations' => '',
);

?>

Disable all forms by default

Disable all forms by default


<?php

namespace SlmQueueTest\Worker;

use PHPUnit_Framework_TestCase as TestCase;
use SlmQueue\Worker\WorkerEvent;
use SlmQueue\Queue\QueuePluginManager;
use SlmQueueTest\Asset\SimpleQueue;
use SlmQueueTest\Asset\SimpleJob;
use Zend\ServiceManager\Config;

class WorkerEventTest extends TestCase
{
    protected $queue;

    public function setUp()
    {
        $queuePluginManager = new QueuePluginManager(new Config(array(
            'factories' => array(
                'simpleQueue' => 'SlmQueueTest\Asset\SimpleQueueFactory'
            )
        )));

        $this->queue = $queuePluginManager->get('simpleQueue');
    }
    public function testWorkerEventHoldsStateForQueue()
    {
        $event = new WorkerEvent($this->queue);

        $this->assertEquals($this->queue, $event->getQueue());
    }

    public function getWorkerEventHoldsStateForJob()
    {
        $event = new WorkerEvent($this->queue);

        $job = new SimpleJob;
        $event->setJob($job);

        $this->assertEquals($job, $event->getJob());
    }
}

<?php

namespace SlmQueueTest\Worker;

use PHPUnit_Framework_TestCase as TestCase;
use SlmQueue\Worker\WorkerEvent;
use SlmQueueTest\Asset\SimpleJob;

class WorkerEventTest extends TestCase
{
    protected $queue;

    public function setUp()
    {
        $this->queue = $this->getMock('SlmQueue\Queue\QueueInterface');
    }
    public function testWorkerEventHoldsStateForQueue()
    {
        $event = new WorkerEvent($this->queue);

        $this->assertEquals($this->queue, $event->getQueue());
    }

    public function getWorkerEventHoldsStateForJob()
    {
        $event = new WorkerEvent($this->queue);

        $job = new SimpleJob;
        $event->setJob($job);

        $this->assertEquals($job, $event->getJob());
    }
}

Remove mock from WorkerEvent test class

Remove mock from WorkerEvent test class


<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class FeedbackRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'include_phone'             => 'nullable|required_without_all:include_email,include_facebook,include_line',
            'include_email'             => 'nullable|required_without_all:include_phone,include_facebook,include_line',
            'include_facebook'          => 'nullable|required_without_all:include_phone,include_email,include_line',
            'include_line'              => 'nullable|required_without_all:include_phone,include_email,include_facebook',
            'message'                   => 'nullable|max:255',
            'answer_of_custom_question' => 'nullable|max:255',
            'join_club_intention'       => 'required|in:0,1,2',
            'join_tea_party_intention'  => 'required|in:0,1,2',
        ];
    }
}

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class FeedbackRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'message'                   => 'nullable|max:255',
            'answer_of_custom_question' => 'nullable|max:255',
            'join_club_intention'       => 'required|in:0,1,2',
            'join_tea_party_intention'  => 'required|in:0,1,2',
        ];

        //若非茶會與社團皆不參加，則必須勾選聯絡資訊
        if ($this->request->get('join_club_intention') != 0
            || $this->request->get('join_tea_party_intention') != 0) {
            $rules = array_merge($rules, [
                'include_phone'    => 'nullable|required_without_all:include_email,include_facebook,include_line',
                'include_email'    => 'nullable|required_without_all:include_phone,include_facebook,include_line',
                'include_facebook' => 'nullable|required_without_all:include_phone,include_email,include_line',
                'include_line'     => 'nullable|required_without_all:include_phone,include_email,include_facebook',
            ]);
        }

        return $rules;
    }
}

Use conditional validation on contact info only if user has intention


<?php

namespace App\Http\Controllers;

trait Writer
{
	public function writeHtmlToDisk($content, $directory) {
		$date = date('YmdHis');
		$this->prepareDirectory($directory);
		$directory = $directory . '/' . $date . '.html';
		// try {
			$file = fopen($directory, 'w');
			fwrite($file, $content);
			fclose($file);
		// } catch (\Exception $e) {
			// throw new \Symfony\Component\HttpKernel\Exception\HttpException('Write HTML failed');
		// }

		return true;
	}
	public function prepareDirectory($directory) {
		try {
			if(!is_dir($directory)) {
				mkdir($directory);
			}
		}
		catch(\Exception $e) {
			throw new \Symfony\Component\HttpKernel\Exception\HttpException('Directory preparation failed!');
		}

		return true;
	}
}

<?php

namespace App\Http\Controllers;

trait Writer
{
	public function writeHtmlToDisk($content, $directory) {
		$date = date('YmdHis');
		$this->prepareDirectory($directory);
		$directory = $directory . '/' . $date . '.html';
		// try {
			$file = fopen($directory, 'w');
			fwrite($file, $content);
			fclose($file);
		// } catch (\Exception $e) {
			// throw new \Symfony\Component\HttpKernel\Exception\HttpException('Write HTML failed');
		// }

		return true;
	}
	public function prepareDirectory($directory) {
		try {
			if(!is_dir($directory)) {
				mkdir($directory, 0777, true);
			}
		}
		catch(\Exception $e) {
			throw new \Symfony\Component\HttpKernel\Exception\HttpException('Directory preparation failed!');
		}

		return true;
	}
}

Allow nested directory creation with recursive switch addition


<?php

/*
 * If no business ID has been passed in the URL
 */
if (!isset($_GET['id']))
{
    header($_SERVER["SERVER_PROTOCOL"]." 400 Bad Request", true, 400);
    exit();
}

/*
 * If the business ID has an invalid format
 */
elseif (strlen($_GET['id'] != 9))
{
    header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
    exit();
}

$id = $_GET['id'];

/*
 * Query our own API
 */
$api_url = 'https://vabusinesses.org/api/business/' . $id;
$business_json = get_file_contents($api_url);

$business = json_decode($business_json);
if ($business === FALSE)
{
    header($_SERVER["SERVER_PROTOCOL"]." 500 Internal Server Error", true, 500);
    exit();
}

/*
 * Display a table of all field values
 */
echo '
';
foreach ($business as $field_name => $field_value)
{
    echo '
';
    echo $field_name;
    echo '	';
    echo $field_value;
    echo '
';
}
echo '
';

<?php

function get_content($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $URL);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

/*
 * If no business ID has been passed in the URL
 */
if (!isset($_GET['id']))
{
    header($_SERVER["SERVER_PROTOCOL"]." 400 Bad Request", true, 400);
    exit();
}

/*
 * If the business ID has an invalid format
 */
elseif (strlen($_GET['id'] != 9))
{
    header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
    exit();
}

$id = $_GET['id'];

/*
 * Query our own API
 */
$api_url = 'https://vabusinesses.org/api/business/' . $id;
$business_json = get_content($api_url);

$business = json_decode($business_json);
if ($business === FALSE)
{
    header($_SERVER["SERVER_PROTOCOL"]." 500 Internal Server Error", true, 500);
    exit();
}

/*
 * Display a table of all field values
 */
echo '
';
foreach ($business as $field_name => $field_value)
{
    echo '
';
    echo $field_name;
    echo '	';
    echo $field_value;
    echo '
';
}
echo '
';

Switch to using cURL to fetch data

Switch to using cURL to fetch data

Toward #72.


<?php

namespace Orbt\ResourceMirror\Tests\Event;

use Orbt\ResourceMirror\Event\ResourceEvent;
use Orbt\ResourceMirror\Resource\GenericResource;

class ResourceEventTest extends \PHPUnit_Framework_TestCase
{
    /**
     * A resource event can be instantiated.
     */
    public function testCreate()
    {
        $event = new ResourceEvent(new GenericResource('test'));
        $this->assertInstanceOf('Orbt\ResourceMirror\Event\ResourceEvent', $event);
    }
}

<?php

namespace Orbt\ResourceMirror\Tests\Event;

use Orbt\ResourceMirror\Event\ResourceEvent;
use Orbt\ResourceMirror\Resource\GenericResource;

class ResourceEventTest extends \PHPUnit_Framework_TestCase
{
    /**
     * A resource event can be instantiated.
     */
    public function testCreate()
    {
        $event = new ResourceEvent(new GenericResource('test'));
        $this->assertInstanceOf('Orbt\ResourceMirror\Event\ResourceEvent', $event);
    }

    /**
     * A resource event returns its resource.
     *
     * @depends testCreate
     */
    public function testGetResource()
    {
        $event = new ResourceEvent(new GenericResource('test'));
        $this->assertInstanceOf('Orbt\ResourceMirror\Resource\Resource', $event->getResource());
    }
}

Test event resource getter method.

Test event resource getter method.


<?php

declare(strict_types=1);

namespace Rinvex\Support\Traits;

use Spatie\Sluggable\HasSlug as BaseHasSlug;

trait HasSlug
{
    use BaseHasSlug;

    /**
     * Boot the trait.
     */
    protected static function bootHasSlug()
    {
        // Auto generate slugs early before validation
        static::validating(function (self $model) {
            if ($model->exists && $model->getSlugOptions()->generateSlugsOnUpdate) {
                $model->generateSlugOnUpdate();
            } elseif (! $model->exists && $model->getSlugOptions()->generateSlugsOnCreate) {
                $model->generateSlugOnCreate();
            }
        });
    }
}

<?php

declare(strict_types=1);

namespace Rinvex\Support\Traits;

use Illuminate\Database\Eloquent\Model;
use Spatie\Sluggable\HasSlug as BaseHasSlug;

trait HasSlug
{
    use BaseHasSlug;

    /**
     * Boot the trait.
     */
    protected static function bootHasSlug()
    {
        // Auto generate slugs early before validation
        static::validating(function (Model $model) {
            if ($model->exists && $model->getSlugOptions()->generateSlugsOnUpdate) {
                $model->generateSlugOnUpdate();
            } elseif (! $model->exists && $model->getSlugOptions()->generateSlugsOnCreate) {
                $model->generateSlugOnCreate();
            }
        });
    }
}

Fix HasSlu slug autogeneration issue

Fix HasSlu slug autogeneration issue


<?php namespace Cerbero\Workflow;

/**
 * Interface for classes that run workflow.
 *
 * @author	Andrea Marco Sartori
 */
interface WorkflowRunnerInterface {

	/**
	 * Set the workflows to run.
	 *
	 * @author	Andrea Marco Sartori
	 * @param	Cerbero\Workflow\Workflow	$workflow
	 * @return	void
	 */
	public function setWorkflow(Workflow $workflow);

}

<?php namespace Cerbero\Workflow;

/**
 * Interface for classes that run workflow.
 *
 * @author	Andrea Marco Sartori
 */
interface WorkflowRunner {

	/**
	 * Set the workflows to run.
	 *
	 * @author	Andrea Marco Sartori
	 * @param	Cerbero\Workflow\Workflow	$workflow
	 * @return	void
	 */
	public function setWorkflow(Workflow $workflow);

}

Rename the interface for workflow runners


<?php
namespace Baum\Extensions;

trait ModelExtensions {

  /**
   * Reloads the model from the database.
   *
   * @return \Baum\Node
   */
  public function reload() {
    if ( !$this->exists )
      return $this;

    $dirty = $this->getDirty();
    if ( count($dirty) === 0 )
      return $this;

    $fresh = static::find($this->getKey());

    $this->setRawAttributes($fresh->getAttributes(), true);

    return $this;
  }

  /**
   * Find first model.
   *
   * @return \Illuminate\Database\Eloquent\Model
   */
  public static function first() {
    $instance = new static;

    return $instance->newQuery()->orderBy($instance->getKeyName(), 'asc')->first();
  }

  /**
   * Find last model.
   *
   * @return \Illuminate\Database\Eloquent\Model
   */
  public static function last() {
    $instance = new static;

    return $instance->newQuery()->orderBy($instance->getKeyName(), 'desc')->first();
  }

}

<?php
namespace Baum\Extensions;

trait ModelExtensions {

  /**
   * Reloads the model from the database.
   *
   * @return \Baum\Node
   */
  public function reload() {
    if ( !$this->exists ) {
      $this->syncOriginal();
    } else {
      $fresh = static::find($this->getKey());

      $this->setRawAttributes($fresh->getAttributes(), true);
    }

    return $this;
  }

  /**
   * Find first model.
   *
   * @return \Illuminate\Database\Eloquent\Model
   */
  public static function first() {
    $instance = new static;

    return $instance->newQuery()->orderBy($instance->getKeyName(), 'asc')->first();
  }

  /**
   * Find last model.
   *
   * @return \Illuminate\Database\Eloquent\Model
   */
  public static function last() {
    $instance = new static;

    return $instance->newQuery()->orderBy($instance->getKeyName(), 'desc')->first();
  }

}

Modify Model::reload() function behaviour to sync with original attributes when model is not persisted and to always load from the database otherwise.


<?php

namespace allejo\stakx\Engines;

use Highlight\Highlighter;

class MarkdownEngine extends \Parsedown
{
    protected $highlighter;

    public function __construct ()
    {
        $this->highlighter = new Highlighter();
    }

    protected function blockHeader($Line)
    {
        $Block = parent::blockHeader($Line);

        // Create our unique ids by sanitizing the header content
        $id = strtolower($Block['element']['text']);
        $id = str_replace(' ', '-', $id);
        $id = preg_replace('/[^0-9a-zA-Z-_]/', '', $id);
        $id = preg_replace('/-+/', '-', $id);

        $Block['element']['attributes']['id'] = $id;

        return $Block;
    }

    public function blockFencedCodeComplete ($block)
    {
        // The class has a `language-` prefix, remove this to get the language
        if (isset($block['element']['text']['attributes']))
        {
            $language = substr($block['element']['text']['attributes']['class'], 9);

            try
            {
                $highlighted = $this->highlighter->highlight($language, $block['element']['text']['text']);
                $block['element']['text']['text'] = $highlighted->value;
            }
            catch (\DomainException $exception) {}
        }

        return $block;
    }
}

<?php

namespace allejo\stakx\Engines;

use Highlight\Highlighter;

class MarkdownEngine extends \Parsedown
{
    protected $highlighter;

    public function __construct ()
    {
        $this->highlighter = new Highlighter();
    }

    protected function blockHeader($Line)
    {
        $Block = parent::blockHeader($Line);

        // Create our unique ids by sanitizing the header content
        $id = strtolower($Block['element']['text']);
        $id = str_replace(' ', '-', $id);
        $id = preg_replace('/[^0-9a-zA-Z-_]/', '', $id);
        $id = preg_replace('/-+/', '-', $id);

        $Block['element']['attributes']['id'] = $id;

        return $Block;
    }

    public function blockFencedCodeComplete ($block)
    {
        // The class has a `language-` prefix, remove this to get the language
        if (isset($block['element']['text']['attributes']))
        {
            $language = substr($block['element']['text']['attributes']['class'], 9);

            try
            {
                $highlighted = $this->highlighter->highlight($language, $block['element']['text']['text']);
                $block['element']['text']['text'] = $highlighted->value;
            }
            catch (\DomainException $exception) {}

            return $block;
        }

        return parent::blockFencedCodeComplete($block);
    }
}

Fix fenced code blocks rendering without language

- Closes #19


<?php

/**
 * This file exists to overload the default `render()` function which escapes HTML entities and therefore does not allow
 * for properly highlighted code to render.
 */

namespace Gregwar\RST\HTML\Nodes;

use Gregwar\RST\Nodes\CodeNode as Base;

class CodeNode extends Base
{
    public function render ()
    {
        return "
language . "\">" . $this->value . "
";
    }
}

Make RST code blocks compliant with hljs


<?php namespace Williamson\Laragram\Laravel;

use Config;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
use Log;
use Williamson\Laragram\TgCommands;
use Williamson\Laragram\ClientException;

class LaragramServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $loader  = AliasLoader::getInstance();
        $aliases = Config::get('app.aliases');
        if (empty($aliases['TG'])) {
            $loader->alias('TG', 'Williamson\Laragram\Facades\LaragramFacade');
        }
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('Williamson\Laragram\TgCommands', function () {
            try {
                $tg = new TgCommands('unix:///tmp/tg.sck');
            } catch (ClientException $e) {
                Log::error($e->getMessage());

                return;
            }

            return $tg;
        });
    }
}

<?php namespace Williamson\Laragram\Laravel;

use Config;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
use Log;
use Williamson\Laragram\TgCommands;
use Williamson\Laragram\ClientException;

class LaragramServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $loader  = AliasLoader::getInstance();
        $aliases = Config::get('app.aliases');
        if (empty($aliases['TG'])) {
            $loader->alias('TG', 'Williamson\Laragram\Facades\LaragramFacade');
        }
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('Williamson\Laragram\TgCommands', function () {
            try {
                $tg = new TgCommands(Config::get('services.telegram.socket'));
            } catch (ClientException $e) {
                Log::error($e->getMessage());

                return;
            }

            return $tg;
        });
    }
}

Use config setting to set the type/address of socket to use for telegram


<?php

// src/Corvus/AdminBundle/Form/Type/ChangePasswordType.php
namespace Corvus\AdminBundle\Form\Type;

use Symfony\Component\Form\AbstractType,
    Symfony\Component\Form\FormBuilderInterface,
    Symfony\Component\Security\Core\Validator\Constraints\UserPassword,
    Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ChangePasswordType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('currentPassword', 'password', array(
            'required' => true,
            'label' => 'Current Password',
            'attr' => array('class' => 'form-control'),
            'mapped' => false,
            'constraints' => new UserPassword(),
        ));
        $builder->add('plainPassword', 'repeated', array(
            'required' => true,
            'type' => 'password',
            'first_options' => array(
                'label' => 'New Password',
                'attr' => array('class' => 'form-control')
            ),
            'second_options' => array(
                'label' => 'Confirm New Password',
                'attr' => array('class' => 'form-control')
            )
        ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Corvus\AdminBundle\Entity\User',
        ));
    }

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

<?php

// src/Corvus/AdminBundle/Form/Type/ChangePasswordType.php
namespace Corvus\AdminBundle\Form\Type;

use Symfony\Component\Form\AbstractType,
    Symfony\Component\Form\FormBuilderInterface,
    Symfony\Component\Security\Core\Validator\Constraints\UserPassword,
    Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ChangePasswordType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('currentPassword', 'password', array(
            'required' => true,
            'label' => 'Current Password',
            'attr' => array('class' => 'form-control'),
            'mapped' => false,
            'constraints' => new UserPassword(),
        ));
        $builder->add('plainPassword', 'repeated', array(
            'required' => true,
            'type' => 'password',
            'first_options' => array(
                'label' => 'New Password',
                'attr' => array('class' => 'form-control')
            ),
            'second_options' => array(
                'label' => 'Confirm New Password',
                'attr' => array('class' => 'form-control')
            ),
            'invalid_message' => 'Passwords must match'
        ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Corvus\AdminBundle\Entity\User',
        ));
    }

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

[Admin] Set an Invalid message for ChangePassword confirmation


<?php

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

namespace Symfony\Bundle\FrameworkBundle\Test;

use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;

/**
 * WebTestCase is the base class for functional tests.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
abstract class WebTestCase extends KernelTestCase
{
    /**
     * Creates a KernelBrowser.
     *
     * @param array $options An array of options to pass to the createKernel method
     * @param array $server  An array of server parameters
     *
     * @return KernelBrowser A KernelBrowser instance
     */
    protected static function createClient(array $options = [], array $server = [])
    {
        $kernel = static::bootKernel($options);

        try {
            $client = $kernel->getContainer()->get('test.client');
        } catch (ServiceNotFoundException $e) {
            if (class_exists(Client::class)) {
                throw new \LogicException('You cannot create the client used in functional tests if the "framework.test" config is not set to true.');
            }
            throw new \LogicException('You cannot create the client used in functional tests if the BrowserKit component is not available. Try running "composer require symfony/browser-kit"');
        }

        $client->setServerParameters($server);

        return $client;
    }
}

<?php

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

namespace Symfony\Bundle\FrameworkBundle\Test;

use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;

/**
 * WebTestCase is the base class for functional tests.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
abstract class WebTestCase extends KernelTestCase
{
    /**
     * Creates a KernelBrowser.
     *
     * @param array $options An array of options to pass to the createKernel method
     * @param array $server  An array of server parameters
     *
     * @return KernelBrowser A KernelBrowser instance
     */
    protected static function createClient(array $options = [], array $server = [])
    {
        $kernel = static::bootKernel($options);

        try {
            $client = $kernel->getContainer()->get('test.client');
        } catch (ServiceNotFoundException $e) {
            if (class_exists(KernelBrowser::class)) {
                throw new \LogicException('You cannot create the client used in functional tests if the "framework.test" config is not set to true.');
            }
            throw new \LogicException('You cannot create the client used in functional tests if the BrowserKit component is not available. Try running "composer require symfony/browser-kit"');
        }

        $client->setServerParameters($server);

        return $client;
    }
}

Replace class with new name.

Replace class with new name.


<?php

namespace Test\TestTwoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use Test\TestTwoBundle\Entity\All;
use Test\TestTwoBundle\Form\AllType;

use Test\TestStoreBundle\Entity\User;
use Test\TestStoreBundle\Entity\Address;
use Test\TestStoreBundle\Entity\Personal;

class DefaultController extends Controller
{
    public function indexAction(Request $request)
    {

        $all = new All();
        $all->getUser()->add(new User());
        $all->getAddress()->add(new Address());
        $all->getPersonal()->add(new Personal());

        //  Create Form
        $form = $this->createForm(new AllType(), $all);

        $form->handleRequest($request);

        if ($form->isValid()) {

            // Persist submitted info to Database
            $em = $this->getDoctrine()->getManager();
            $em->persist($all->getUser()->first());
            $em->persist($all->getAddress()->first());
            $em->persist($all->getPersonal()->first());
            $em->flush();

            return new Response('Well done, it worked!');

        }

            return $this->render('TestTestTwoBundle:Default:index.html.twig', array('form' => $form->createView()));

    }
}

<?php

namespace Test\TestTwoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use Test\TestTwoBundle\Entity\All;
use Test\TestTwoBundle\Form\AllType;

use Test\TestStoreBundle\Entity\User;
use Test\TestStoreBundle\Entity\Address;
use Test\TestStoreBundle\Entity\Personal;

class DefaultController extends Controller
{
    public function indexAction(Request $request)
    {

        $all = new All();
        $all->getUser()->add(new User());
        $all->getAddress()->add(new Address());
        $all->getPersonal()->add(new Personal());

        //  Create Form
        $form = $this->createForm(new AllType(), $all);

        $form->handleRequest($request);

        if ($form->isValid()) {

            $all->getUser()->first()->setPersonal($all->getPersonal()->first());
            $all->getUser()->first()->setAddress($all->getAddress()->first());
            $all->getAddress()->first()->setUser($all->getUser()->first());
            $all->getPersonal()->first()->setUser($all->getUser()->first());

            // Persist submitted info to Database
            $em = $this->getDoctrine()->getManager();
            $em->persist($all->getUser()->first());
            $em->persist($all->getAddress()->first());
            $em->persist($all->getPersonal()->first());
            $em->flush();

            return new Response('Well done, it worked!');

        }

            return $this->render('TestTestTwoBundle:Default:index.html.twig', array('form' => $form->createView()));

    }
}

Change to form handling now persists realtionship between associations


<?php
class Dance extends CI_Controller {

        public function __construct()
        {
                parent::__construct();
                $this->load->helper('url_helper');
        }

        public function index()
        {
                $data['title'] = 'The amazing dancer';
                $data['css'] = ['assets/css/dancer.css'];
                $data['js'] = ['https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js',
                                'https://threejs.org/examples/js/controls/OrbitControls.js'];

                $this->load->view('templates/header', $data);
                $this->load->view('dance/index', $data);
        }
}

<?php
class Dance extends CI_Controller {

        public function __construct()
        {
                parent::__construct();
                $this->load->helper('url_helper');
        }

        public function index()
        {
                $data['title'] = 'The amazing dancer';
                $data['css'] = ['/assets/css/dancer.css'];
                $data['js'] = ['https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js',
                                'https://threejs.org/examples/js/controls/OrbitControls.js'];

                $this->load->view('templates/header', $data);
                $this->load->view('dance/index', $data);
        }
}

Fix problem with path to css files

Fix problem with path to css files


<?php

class TestCase extends Illuminate\Foundation\Testing\TestCase {

	/**
	 * Creates the application.
	 *
	 * @return Symfony\Component\HttpKernel\HttpKernelInterface
	 */
	public function createApplication()
	{
		$unitTesting = true;

		$testEnvironment = 'testing';

		return require __DIR__.'/../../bootstrap/start.php';
	}

}

<?php

class TestCase extends Illuminate\Foundation\Testing\TestCase {

	/**
	 * Creates the application.
	 *
	 * @return \Symfony\Component\HttpKernel\HttpKernelInterface
	 */
	public function createApplication()
	{
		$unitTesting = true;

		$testEnvironment = 'testing';

		return require __DIR__.'/../../bootstrap/start.php';
	}

}

Add global class reference in docblock

Add global class reference in docblock


                Get our Newsletter:
                <form action="" method="post">
                    <input type="text" class="form-control form-footer-newsletter" placeholder="Your E-Mail adress" />
                    <input type="submit" value="Subscribe" name="subscribe" id="footer-newsletter-subscribe" class="btn btn-success">
                </form>

            Privacy Policy|
            Terms of service|
            Imprint

                Get our Newsletter:
                <form action="" method="post">
                    <input type="text" class="form-control form-footer-newsletter" placeholder="Your E-Mail adress" />
                    <input type="submit" value="Subscribe" name="subscribe" id="footer-newsletter-subscribe" class="btn btn-success">
                </form>

            Sitemap|
            Privacy Policy|
            Terms of service|
            Imprint

Put Sitemap link in footer

Put Sitemap link in footer


<?php

/*
 * Copyright 2011 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

abstract class PhabricatorDaemon extends PhutilDaemon {

  protected function willRun() {
    parent::willRun();

    // This stores unbounded amounts of log data; make it discard instead so
    // that daemons do not require unbounded amounts of memory.
    DarkConsoleErrorLogPluginAPI::enableDiscardMode();

    $phabricator = phutil_get_library_root('phabricator');
    $root = dirname($phabricator);
    require_once $root.'/scripts/__init_env__.php';
  }
}

<?php

/*
 * Copyright 2011 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

abstract class PhabricatorDaemon extends PhutilDaemon {

  protected function willRun() {
    parent::willRun();

    // This stores unbounded amounts of log data; make it discard instead so
    // that daemons do not require unbounded amounts of memory.
    DarkConsoleErrorLogPluginAPI::enableDiscardMode();

    $phabricator = phutil_get_library_root('phabricator');
    $root = dirname($phabricator);
    require_once $root.'/scripts/__init_env__.php';

    // Daemons may perform writes.
    AphrontWriteGuard::allowDangerousUnguardedWrites(true);
  }
}

Allow daemons to perform writes unconditionally.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Type extends Model
{
  public function content() {
    return $this->hasMany('content');
  }

  // public function page() {
  //   return $this->hasManyThrough('App\Page');
  // }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Type extends Model
{

}

Clear type function (not neccesairy)

Clear type function (not neccesairy)


<?php

require_once __DIR__.'/lib/Pheasant/ClassLoader.php';

function __pheasant_classloader_register()
{
	$classloader = new \Pheasant\ClassLoader();
	$classloader->register();
}

__pheasant_classloader_register();

 __HALT_COMPILER();

Remove halt_compiler to avoid segfaults on lucid


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

/**
 * User Controller Executable Behavior
 *
 * @author      Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Users
 */
class ComUsersControllerBehaviorExecutable extends ComDefaultControllerBehaviorExecutable
{
    public function canLogout()
    {
        $userid = JFactory::getUser()->id;

        //Allow logging out ourselves
        if($this->getModel()->getState()->id === $userid) {
             return true;
        }

        if(JFactory::getUser()->get('gid') > 24) {
            return true;
        }

        return false;
    }
}

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

/**
 * User Controller Executable Behavior
 *
 * @author      Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Users
 */
class ComUsersControllerBehaviorExecutable extends ComDefaultControllerBehaviorExecutable
{
    public function canLogout()
    {
        $user = JFactory::getUser();

        //Allow logging out ourselves
        if($this->getModel()->id == $user->get('id')) {
             return true;
        }

        if($user->get('gid') > 24) {
            return true;
        }

        return false;
    }
}

Fix bug: Users with group below super administrator are unable to logout.


<?php

namespace Wizbii\PipelineBundle\Consumer;

use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
use PhpAmqpLib\Message\AMQPMessage;
use Psr\Log\LoggerInterface;
use Wizbii\PipelineBundle\Dispatcher\Action\ActionDispatcherInterface;
use Wizbii\PipelineBundle\Service\PipelineProvider;

class BackConsumer implements ConsumerInterface
{
    public function execute(AMQPMessage $msg)
    {
        $content = json_decode($msg->body, true);
        $eventName = $content['event_name'];
        $eventContent = json_decode($content['original_body'], true);
        $pipeline = $this->pipelineProvider->getCurrentPipeline();
        $actionCreator = $pipeline->getActionCreatorFor($eventName);

        if (isset($actionCreator)) {
            $action = $actionCreator->buildAction($eventName, $eventContent);
            $this->actionDispatcher->dispatch($action);
        } else {
            $this->logger->error("Can't find any valid action creator for event '$eventName");
        }
    }

    /**
     * @var PipelineProvider
     */
    public $pipelineProvider;

    /**
     * @var ActionDispatcherInterface
     */
    public $actionDispatcher;

    /**
     * @var LoggerInterface
     */
    public $logger;
}

<?php

namespace Wizbii\PipelineBundle\Consumer;

use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
use PhpAmqpLib\Message\AMQPMessage;
use Psr\Log\LoggerInterface;
use Wizbii\PipelineBundle\Dispatcher\Action\ActionDispatcherInterface;
use Wizbii\PipelineBundle\Service\PipelineProvider;

class BackConsumer implements ConsumerInterface
{
    public function execute(AMQPMessage $msg)
    {
        $content = json_decode($msg->body, true, 512, \JSON_THROW_ON_ERROR);
        $eventName = $content['event_name'];
        $eventContent = json_decode($content['original_body'], true, 512, \JSON_THROW_ON_ERROR);
        $pipeline = $this->pipelineProvider->getCurrentPipeline();
        $actionCreator = $pipeline->getActionCreatorFor($eventName);

        if (isset($actionCreator)) {
            $action = $actionCreator->buildAction($eventName, $eventContent);
            $this->actionDispatcher->dispatch($action);
        } else {
            $this->logger->error("Can't find any valid action creator for event '$eventName");
        }
    }

    /**
     * @var PipelineProvider
     */
    public $pipelineProvider;

    /**
     * @var ActionDispatcherInterface
     */
    public $actionDispatcher;

    /**
     * @var LoggerInterface
     */
    public $logger;
}

Throw exception on json_decode errors

Throw exception on json_decode errors


<?php
namespace Vohinc\BotanalyticsPhp\Drivers;

/**
 * Class Facebook
 * @package Vohinc\BotanalyticsPhp\Drivers
 */
class Facebook extends DriverAbstract
{
    /**
     * @var string
     */
    protected $endpoint = 'https://botanalytics.co/api/v1/messages/facebook-messenger';

    /**
     * Make request body
     *
     * @return array
     */
    public function make()
    {
        return [
            'recipient' => $this->message['recipient'],
            'message' => $this->message['message'],
            'timestamp' => time(),
        ];
    }

    /**
     * Send user profile to Botanalytics
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function user()
    {
        return $this->request('https://botanalytics.co/api/v1/facebook-messenger/users/', $this->message);
    }
}

<?php
namespace Vohinc\BotanalyticsPhp\Drivers;

/**
 * Class Facebook
 * @package Vohinc\BotanalyticsPhp\Drivers
 */
class Facebook extends DriverAbstract
{
    /**
     * @var string
     */
    protected $endpoint = 'https://botanalytics.co/api/v1/messages/facebook-messenger';

    /**
     * Make request body
     *
     * @return array
     */
    public function make()
    {
        return [
            'recipient' => $this->message['recipient'],
            'message' => $this->message['message'],
            'timestamp' => time() * 1000,
        ];
    }

    /**
     * Send user profile to Botanalytics
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function user()
    {
        return $this->request('https://botanalytics.co/api/v1/facebook-messenger/users/', $this->message);
    }
}

Fix php time not equal to nodejs getTime()


<?php

/**
 * This file is part of the ramsey/uuid library
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
 * @license http://opensource.org/licenses/MIT MIT
 */

declare(strict_types=1);

namespace Ramsey\Uuid\Rfc4122;

use function hex2bin;

/**
 * Provides common functionality for nil UUIDs
 *
 * The nil UUID is special form of UUID that is specified to have all 128 bits
 * set to zero.
 *
 * @link https://tools.ietf.org/html/rfc4122#section-4.1.7 RFC 4122, § 4.1.7: Nil UUID
 *
 * @psalm-immutable
 */
trait NilTrait
{
    /**
     * Returns the bytes that comprise the fields
     */
    abstract public function getBytes(): string;

    /**
     * Returns true if the byte string represents a nil UUID
     */
    public function isNil(): bool
    {
        return $this->getBytes() === hex2bin('00000000000000000000000000000000');
    }
}

<?php

/**
 * This file is part of the ramsey/uuid library
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
 * @license http://opensource.org/licenses/MIT MIT
 */

declare(strict_types=1);

namespace Ramsey\Uuid\Rfc4122;

/**
 * Provides common functionality for nil UUIDs
 *
 * The nil UUID is special form of UUID that is specified to have all 128 bits
 * set to zero.
 *
 * @link https://tools.ietf.org/html/rfc4122#section-4.1.7 RFC 4122, § 4.1.7: Nil UUID
 *
 * @psalm-immutable
 */
trait NilTrait
{
    /**
     * Returns the bytes that comprise the fields
     */
    abstract public function getBytes(): string;

    /**
     * Returns true if the byte string represents a nil UUID
     */
    public function isNil(): bool
    {
        return $this->getBytes() === "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
    }
}

Use actual byte string instead of hex2bin() on hex string


<?php

namespace Zend\I18n\View;

use IntlDateFormatter;

// @codingStandardsIgnoreStart

/**
 * Trait HelperTrait
 *
 * The trait provides convenience methods for view helpers,
 * defined by the zend-i18n component. It is designed to be used
 * for type-hinting $this variable inside zend-view templates via doc blocks.
 *
 * The base class is PhpRenderer, followed by the helper trait from
 * the zend-i18n component. However, multiple helper traits from different
 * Zend components can be chained afterwards.
 *
 * @example @var \Zend\View\Renderer\PhpRenderer|\Zend\I18n\View\HelperTrait $this
 *
 * @method string currencyFormat($number, $currencyCode = null, $showDecimals = null, $locale = null, $pattern = null)
 * @method string dateFormat($date, $dateType = IntlDateFormatter::NONE, $timeType = IntlDateFormatter::NONE, $locale = null, $pattern = null)
 * @method string numberFormat($number, $formatStyle = null, $formatType = null, $locale = null, $decimals = null, array $textAttributes = null)
 * @method string plural($strings, $number)
 * @method string translate($message, $textDomain = null, $locale = null)
 * @method string translatePlural($singular, $plural, $number, $textDomain = null, $locale = null)
 */
trait HelperTrait
{
}
// @codingStandardsIgnoreEnd

Add ending doc block annotation for ignoring coding standards


FOCUS

Contact Us

Source Code

Free Software

Free Software Movement Karnataka

Other GLUG

PLUGIN

Dr. AIT GLUG

PESCE GLUG

GLUE

PACE GLUG

Creative Commons

FOCUS

Contact Us

Source Code

Free Software

Free Software Movement Karnataka

Creative Commons

Remove other glug links in footer

Remove other glug links in footer


<?php
/**
 *
 * @author Ananaskelly
 */
namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Requests\SearchGameFormRequest;
use Carbon\Carbon;
use Auth;
use App\GameType;
use App\Game;
use App\UserGame;

class GameController extends BaseController
{
    /**
     * Show the form for games params.
     *
     * @return
     */
    public function search()
    {
        $gameTypesColumn = array_column(GameType::all('type_name')->toArray(), 'type_name');
        $gameTypes = array_combine($gameTypesColumn, $gameTypesColumn);
        $gameType = GameType::all('type_name', 'id');
        return view('search', compact('gameTypes'));
    }
    /**
     * Find game with params or create new game
     *
     * @return void
     */
    public function create(SearchGameFormRequest $request)
    {
        $gameType = GameType::where('type_name', '=', $request->type)->first();
        Game::createGame($gameType, $request->status);
        return redirect('/home');
    }
}

<?php
/**
 *
 * @author Ananaskelly
 */
namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Requests\SearchGameFormRequest;
use Carbon\Carbon;
use Auth;
use App\GameType;
use App\Game;
use App\UserGame;

class GameController extends BaseController
{
    /**
     * Show the form for games params.
     *
     * @return
     */
    public function search()
    {
        $gameTypesColumn = array_column(GameType::all('type_name')->toArray(), 'type_name');
        $gameTypes = array_combine($gameTypesColumn, $gameTypesColumn);
        return view('search', compact('gameTypes'));
    }
    /**
     * Find game with params or create new game
     *
     * @return void
     */
    public function create(SearchGameFormRequest $request)
    {
        Game::createGame($request->type, $request->status);
        return redirect('/home');
    }
}

Revert "more fix are coming"

Revert "more fix are coming"

This reverts commit 39e778da34704836de55572f4e08509565a6e613.


@extends('layouts.default')

@section('content')

Successfully created "{{ $sprint->title }}"

			{{ link_to(
				$_ENV['PHABRICATOR_URL'] . 'project/view/' . $sprint->phabricator_id,
				$sprint->title . ' on Phabricator'
			) }}

			{{ link_to_route(
				'sprint_path',
				$sprint->title . ' on Phragile',
				$sprint->phid
			) }}

			{{ link_to_route(
				'project_path',
				$sprint->project->title . ' on Phragile',
				$sprint->project->slug
			) }}

@stop

@extends('layouts.default')

@section('content')

Successfully created "{{ $sprint->title }}"

			{{ link_to(
				$_ENV['PHABRICATOR_URL'] . 'project/view/' . $sprint->phabricator_id,
				$sprint->title . ' on Phabricator'
			) }}

			{{ link_to_route(
				'sprint_path',
				$sprint->title . ' on Phragile',
				$sprint->phabricator_id
			) }}

			{{ link_to_route(
				'project_path',
				$sprint->project->title . ' on Phragile',
				$sprint->project->slug
			) }}

@stop

Fix confirmation page id again.

Fix confirmation page id again.


                @if(Laramin::model('Category')->count() == 0)

You Need To Add A Category For Adding a Post

                @else
        {{ title_case($name) }}

             <select name="{{ $name }}">
                @foreach(Laramin::model('Category')->all() as $category)
                <option @if(old($name) == $category->id || $value == $category->id) selected="selected" @endif value="{{ $category->id }}">{{ ucfirst($category->name) }}</option>
                @endforeach
            </select>

            @endif

                @if(Laramin::model('Category')->count() == 0)

You Need To Add A Category For Adding a Post

                @else
        {{ title_case($name) }}

             <select id="{{ $name }}" name="{{ $name }}">
                @foreach(Laramin::model('Category')->all() as $category)
                <option @if(old($name) == $category->id || $value == $category->id) selected="selected" @endif value="{{ $category->id }}">{{ ucfirst($category->name) }}</option>
                @endforeach
            </select>

            @endif

Modify label with select tag

Modify label with select tag


<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

	use Authenticatable, CanResetPassword;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = ['name', 'email', 'password'];

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = ['password', 'remember_token'];

}

<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

	use Authenticatable, CanResetPassword;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = ['name', 'email', 'password'];

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = ['password', 'remember_token'];

	public function topics()
	{
		return $this->hasMany('Topic');
	}

	public function replies()
	{
		return $this->hasMany('Reply');
	}

	public function notifications()
	{
		return $this->hasMany('Notification');
	}

	public function favoriteTopics()
	{
		return $this->belongsTo('Topic', 'favorites');
	}

	public function attentTopics()
	{
		return $this->belongsTo('Topics', 'attentions');
	}

}

Set the relationships for the user model.


<?php
namespace Dompdf\Tests;

use Dompdf\Helpers;
use PHPUnit\Framework\TestCase;

class HelpersTest extends TestCase
{
    public function testParseDataUriBase64Image()
    {
        $imageParts = array(
            'mime' => 'data:image/png;base64,',
            'data' => 'iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg=='
        );
        $helpers = new Helpers();
        $result = $helpers->parse_data_uri(implode('', $imageParts));
        $this->assertEquals(
            $result['data'],
            base64_decode($imageParts['data'])
        );
    }
}

<?php
namespace Dompdf\Tests;

use Dompdf\Helpers;
use PHPUnit\Framework\TestCase;

class HelpersTest extends TestCase
{
    public function testParseDataUriBase64Image()
    {
        $imageParts = array(
            'mime' => 'data:image/png;base64,',
            'data' => 'iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg=='
        );
        $result = Helpers::parse_data_uri(implode('', $imageParts));
        $this->assertEquals(
            $result['data'],
            base64_decode($imageParts['data'])
        );
    }
}

Use static notation to call helper class methods in unit tests


<?php defined('C5_EXECUTE') or die("Access Denied.");
?>

<?php
$c = Page::getCurrentPage();
?>

<?php if (is_object($f)): ?>

    <?php
    if ($maxWidth > 0 || $maxHeight > 0) {
        $im = Core::make('helper/image');
        $thumb = $im->getThumbnail(
            $f,
            $maxWidth,
            $maxHeight
        ); //<-- set these 2 numbers to max width and height of thumbnails
        $tag = new \HtmlObject\Image();
        $tag->src($thumb->src)->width($thumb->width)->height($thumb->height);
    } else {
        $image = Core::make('html/image', array($f));
        $tag = $image->getTag();
    }
    $tag->addClass('ccm-image-block img-fluid bID-'.$bID);
    if ($altText) {
        $tag->alt($altText);
    }
    if ($title) {
        $tag->title($title);
    }
    if ($linkURL):
        print '';
    endif;
    ?>

    <a class="navbar-brand" href="<?php echo $linkURL; ?>"<?php echo ($openLinkInNewWindow ? ' target="_blank"' : ''); ?>>
        <?php echo $tag; ?>

<?php elseif ($c->isEditMode()): ?>

<?=t('Empty Image Block.')?>

<?php endif; ?>

<?php defined('C5_EXECUTE') or die("Access Denied.");
?>

<?php
$c = Page::getCurrentPage();
?>

<?php if (is_object($f)): ?>

    <?php
    if ($maxWidth > 0 || $maxHeight > 0) {
        $im = Core::make('helper/image');
        $thumb = $im->getThumbnail(
            $f,
            $maxWidth,
            $maxHeight
        ); //<-- set these 2 numbers to max width and height of thumbnails
        $tag = new \HtmlObject\Image();
        $tag->src($thumb->src)->width($thumb->width)->height($thumb->height);
    } else {
        $image = Core::make('html/image', array($f));
        $tag = $image->getTag();
    }
    $tag->addClass('align-baseline img-fluid');
    if ($altText) {
        $tag->alt($altText);
    }
    if ($linkURL):
        print '';
    endif;
    ?>

    <a class="navbar-brand" href="<?php echo $linkURL; ?>"<?php echo ($openLinkInNewWindow ? ' target="_blank"' : ''); ?>>
        <?php echo $tag; ?>
        <?php if ($title): ?>
            <?php echo h($title); ?>
        <?php endif; ?>

<?php elseif ($c->isEditMode()): ?>

<?=t('Empty Image Block.')?>

<?php endif; ?>

Add support for title next to logo in navbar


<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Event\Test;

use PHPUnit\Framework\TestCase;

/**
 * @covers \PHPUnit\Event\Test\AfterTest
 */
final class AfterTestTest extends TestCase
{
    public function testConstructorSetsValues(): void
    {
        $test = new Test();

        $result = $this->createMock(Result::class);

        $event = new AfterTest(
            $test,
            $result
        );

        $this->assertSame($test, $event->test());
        $this->assertSame($result, $event->result());
    }
}

<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Event\Test;

use PHPUnit\Framework\TestCase;

/**
 * @covers \PHPUnit\Event\Test\AfterTest
 */
final class AfterTestTest extends TestCase
{
    public function testConstructorSetsValues(): void
    {
        $test = new Test();

        $result = new class implements Result {
            public function is(Result $other): bool
            {
                return false;
            }

            public function asString(): string
            {
                return get_class($this);
            }
        };

        $event = new AfterTest(
            $test,
            $result
        );

        $this->assertSame($test, $event->test());
        $this->assertSame($result, $event->result());
    }
}

Use anonymous class as test double

Fix: Use anonymous class as test double

Co-authored-by: Andreas Möller <96e8155732e8324ae26f64d4516eb6fe696ac84f@localheinz.com>
Co-authored-by: Arne Blankerts <2d7739f42ebd62662a710577d3d9078342a69dee@Blankerts.de>


<?php
if(isset($CreateGameMessage))
{
	echo $CreateGameMessage;
} ?>

		Players
		Current Turn

<?php
	foreach($ChessGames as $ChessGame)
	{ ?>

			<?php
				echo $ChessGame->getWhitePlayer()->getLinkedDisplayName(false); ?> vs <?php echo $ChessGame->getBlackPlayer()->getLinkedDisplayName(false); ?>

			<?php
				echo $ChessGame->getCurrentTurnPlayer()->getLinkedDisplayName(false); ?>

<a class="buttonA" href="<?php echo $ChessGame->getPlayGameHREF(); ?>"> Play

<?php
	}
?>

<form action="<?php echo Globals::getChessCreateHREF(); ?>" method="POST">
	Challenge:
	<select id="player_id" name="player_id"><?php
		foreach($PlayerList as $PlayerID => $PlayerName)
		{
			?><option value="<?php echo $PlayerID; ?>"><?php echo $PlayerName; ?></option><?php
		} ?>
	</select>

	<input type="submit"/>
</form>

Add markup to table to make AJAX update it.


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

use Curl\MultiCurl;

$multi_curl = new MultiCurl();

// Count the number of completed requests.
$request_count = 0;
$multi_curl->complete(function ($instance) use (&$request_count) {
    $request_count += 1;
});

$multi_curl->success(function ($instance) use (&$request_count, $multi_curl) {
    echo 'call to "' . $instance->url . '" was successful.' . "\n";

    // Stop pending requests and attempt to stop active requests after the first
    // successful request.
    $multi_curl->stop();
});

$multi_curl->addGet('https://httpbin.org/delay/4');
$multi_curl->addGet('https://httpbin.org/delay/1');
$multi_curl->addGet('https://httpbin.org/delay/3');
$multi_curl->addGet('https://httpbin.org/delay/2');

$multi_curl->start();

assert($request_count === 1);

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

use Curl\MultiCurl;

$multi_curl = new MultiCurl();

$multi_curl->beforeSend(function ($instance) {
    echo 'about to make request ' . $instance->id . ': "' . $instance->url . '".' . "\n";
});

$multi_curl->success(function ($instance) use (&$request_count, $multi_curl) {
    echo 'call to "' . $instance->url . '" was successful.' . "\n";

    // Stop pending requests and attempt to stop active requests after the first
    // successful request.
    $multi_curl->stop();
});

$multi_curl->error(function ($instance) {
    echo 'call to "' . $instance->url . '" was unsuccessful.' . "\n";
});

// Count the number of completed requests.
$request_count = 0;
$multi_curl->complete(function ($instance) use (&$request_count) {
    echo 'call to "' . $instance->url . '" completed.' . "\n";
    $request_count += 1;
});

$multi_curl->addGet('https://httpbin.org/delay/4');
$multi_curl->addGet('https://httpbin.org/delay/1');
$multi_curl->addGet('https://httpbin.org/delay/3');
$multi_curl->addGet('https://httpbin.org/delay/2');

$multi_curl->start();

assert($request_count === 1);

Add additional logging to display progression


<?php

namespace QuizBundle\Form\Admin\Quiz;

use CommonBundle\Component\Form\Admin\Element\Text,
    Doctrine\ORM\EntityManager,
    QuizBundle\Entity\Quiz,
    Zend\Form\Element\Submit;

/**
 * Edits a quiz
 * @author Lars Vierbergen <vierbergenlars@gmail.com>
 */
class Edit extends Add {

    /**
     * @param \Doctrine\ORM\EntityManager $entityManager
     * @param \QuizBundle\Entity\Quiz The quiz to populate the form with
     * @param null|string|int $name Optional name for the form
     */
    public function __construct(EntityManager $entityManager, Quiz $quiz, $name = null)
    {
        parent::__construct($entityManager, $name);

        $this->remove('submit');

        $field = new Submit('submit');
        $field->setValue('Edit')
            ->setAttribute('class', 'quiz_edit');
        $this->add($field);

        $this->populateFromQuiz($quiz);
    }
}

<?php

namespace QuizBundle\Form\Admin\Quiz;

use CommonBundle\Component\Form\Admin\Element\Text,
    Doctrine\ORM\EntityManager,
    QuizBundle\Entity\Quiz,
    Zend\Form\Element\Submit;

/**
 * Edits a quiz
 * @author Lars Vierbergen <vierbergenlars@gmail.com>
 */
class Edit extends Add {

    /**
     * @param \Doctrine\ORM\EntityManager $entityManager
     * @param \QuizBundle\Entity\Quiz $quiz The quiz to populate the form with
     * @param null|string|int $name Optional name for the form
     */
    public function __construct(EntityManager $entityManager, Quiz $quiz, $name = null)
    {
        parent::__construct($entityManager, $name);

        $this->remove('submit');

        $field = new Submit('submit');
        $field->setValue('Edit')
            ->setAttribute('class', 'quiz_edit');
        $this->add($field);

        $this->populateFromQuiz($quiz);
    }
}

Implement admin quiz edit form

QuizBundle: Implement admin quiz edit form


@include('core::admin._buttons-form')

{!! BootForm::hidden('id') !!}

        {!! BootForm::text(__('Tag'), 'tag') !!}

has('slug'))has-error @endif">
        {!! Form::label(__('Slug'))->addClass('control-label')->forId('slug') !!}

            {!! Form::text('slug')->addClass('form-control')->id('slug')->data('slug', 'tag') !!}

                <button class="btn btn-default btn-slug @if($errors->has('slug'))btn-danger @endif" type="button">{{ __('Generate') }}</button>

        {!! $errors->first('slug', '
:message
') !!}

@component('core::admin._buttons-form', ['model' => $model])
@endcomponent

{!! BootForm::hidden('id') !!}

        {!! BootForm::text(__('Tag'), 'tag') !!}

has('slug'))has-error @endif">
        {!! Form::label(__('Slug'))->addClass('control-label')->forId('slug') !!}

            {!! Form::text('slug')->addClass('form-control')->id('slug')->data('slug', 'tag') !!}

                <button class="btn btn-default btn-slug @if($errors->has('slug'))btn-danger @endif" type="button">{{ __('Generate') }}</button>

        {!! $errors->first('slug', '
:message
') !!}

Use of @component for buttons in form

Use of @component for buttons in form


<?php
/*
Plugin Name: JW Filter
Pluring URI: net.tutsplus.com
Description: Just for demo purposes.
Author: Jeffrey Way
Author URI: http://net.tutsplus.com
Version: 1.0
*/

//add_filter('the_title', ucwords);

add_filter('the_content', function($content) {
	return $content . ' ' . 'Hello World 1' . ' ' .time();
});

<?php
/*
Plugin Name: JW Filter
Pluring URI: net.tutsplus.com
Description: Just for demo purposes.
Author: Jeffrey Way
Author URI: http://net.tutsplus.com
Version: 1.0
*/

//add_filter('the_title', ucwords);

add_filter('the_content', function($content) {
	return $content . ' ' . time();
});

Revert "Testing a change for FTPloy syncing with the production server."

This reverts commit ef47343a460b69e538b7a0bddc9a86e8a2ed2f5a.


<?php

namespace Frontend\Modules\Mailmotor\Domain\Subscription\Command;

use Frontend\Core\Language\Locale;
use Symfony\Component\Validator\Constraints as Assert;
use Frontend\Modules\Mailmotor\Domain\Subscription\Validator\Constraints as MailingListAssert;

final class Unsubscription
{
    /**
     * @var string
     *
     * @Assert\NotBlank(message="err.FieldIsRequired")
     * @Assert\Email(message="err.FieldIsRequired")
     * @MailingListAssert\EmailUnsubscription
     */
    public $email;

    /**
     * @var Locale
     */
    public $locale;

    /**
     * @param Locale $locale
     * @param null|string $email
     */
    public function __construct(Locale $locale, string $email = null)
    {
        $this->locale = $locale;
        $this->email = $email;
    }
}

<?php

namespace Frontend\Modules\Mailmotor\Domain\Subscription\Command;

use Frontend\Core\Language\Locale;
use Symfony\Component\Validator\Constraints as Assert;
use Frontend\Modules\Mailmotor\Domain\Subscription\Validator\Constraints as MailingListAssert;

final class Unsubscription
{
    /**
     * @var string
     *
     * @Assert\NotBlank(message="err.FieldIsRequired")
     * @Assert\Email(message="err.EmailIsInvalid")
     * @MailingListAssert\EmailUnsubscription
     */
    public $email;

    /**
     * @var Locale
     */
    public $locale;

    /**
     * @param Locale $locale
     * @param null|string $email
     */
    public function __construct(Locale $locale, string $email = null)
    {
        $this->locale = $locale;
        $this->email = $email;
    }
}

Use the proper Email validation message

Use the proper Email validation message


<?php

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

namespace Sonata\Bundle\QABundle\Tests;

class SonataUserTwoStepVerificationCommandTest extends CommandTestCase
{
    /**
     * @expectedException \RuntimeException
     */
    public function testMissingArguments()
    {
        $client = self::createClient();

        $this->runCommand($client, "sonata:user:two-step-verification");
    }

    public function testReset()
    {
        $client = self::createClient();

        $output = $this->runCommand($client, "sonata:user:two-step-verification --reset secure");

        $this->assertContains("Url : https://www.google.com/", $output);

        $user = $client->getContainer()->get('fos_user.user_manager')->findUserBy(array(
            'username' => 'secure'
        ));

        $this->assertContains($user->getTwoStepVerificationCode(), $output);
    }

    public function testGenerateOnGenerateUser()
    {
        $client = self::createClient();

        $output = $this->runCommand($client, "sonata:user:two-step-verification secure");

        $code = $client->getContainer()->get('fos_user.user_manager')->findUserBy(array(
            'username' => 'secure'
        ))->getTwoStepVerificationCode();

        $this->assertContains($code, $output);
    }
}

<?php

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

namespace Sonata\Bundle\QABundle\Tests;

class SonataUserTwoStepVerificationCommandTest extends CommandTestCase
{
    /**
     * @expectedException \RuntimeException
     */
    public function testMissingArguments()
    {
        $client = self::createClient();

        $this->runCommand($client, "sonata:user:two-step-verification");
    }

    public function testReset()
    {
        $client = self::createClient();

        $output = $this->runCommand($client, "sonata:user:two-step-verification --reset secure");

        $this->assertContains("Url : https://chart.googleapis.com/", $output);

        $user = $client->getContainer()->get('fos_user.user_manager')->findUserBy(array(
            'username' => 'secure'
        ));

        $this->assertContains($user->getTwoStepVerificationCode(), $output);
    }

    public function testGenerateOnGenerateUser()
    {
        $client = self::createClient();

        $output = $this->runCommand($client, "sonata:user:two-step-verification secure");

        $code = $client->getContainer()->get('fos_user.user_manager')->findUserBy(array(
            'username' => 'secure'
        ))->getTwoStepVerificationCode();

        $this->assertContains($code, $output);
    }
}

Fix Google Authenticator unit test

Fix Google Authenticator unit test


<?php

namespace Oro\Bundle\EntityBundle\Provider;

use Doctrine\Common\Collections\ArrayCollection;

use Symfony\Component\HttpFoundation\ParameterBag;

class ProviderManager
{
    protected $providers;

    public function __construct()
    {
        $this->providers = new ArrayCollection();
    }

    /**
     * @param AbstractProvider $provider
     */
    public function addProvider(AbstractProvider $provider)
    {
        $this->providers->add($provider);
    }

    /**
     * @param string       $entityName
     * @param ParameterBag $parameters
     *
     * @return AbstractProvider
     */
    public function selectByParams($entityName, ParameterBag $parameters)
    {
        $parameters->set('entityName', $entityName);
        // @TODO: remove this before merge
        $parameters->set('plain-list', '1');

        /** @var AbstractProvider $provider */
        foreach ($this->providers as $provider) {
            if ($provider->isApplied($parameters)) {
                return $provider;
            }
        }

        return $this->providers->first();
    }
}

<?php

namespace Oro\Bundle\EntityBundle\Provider;

use Doctrine\Common\Collections\ArrayCollection;

use Symfony\Component\HttpFoundation\ParameterBag;

class ProviderManager
{
    protected $providers;

    public function __construct()
    {
        $this->providers = new ArrayCollection();
    }

    /**
     * @param AbstractProvider $provider
     */
    public function addProvider(AbstractProvider $provider)
    {
        $this->providers->add($provider);
    }

    /**
     * @param string       $entityName
     * @param ParameterBag $parameters
     *
     * @return AbstractProvider
     */
    public function selectByParams($entityName, ParameterBag $parameters)
    {
        $parameters->set('entityName', $entityName);

        /** @var AbstractProvider $provider */
        foreach ($this->providers as $provider) {
            if ($provider->isApplied($parameters)) {
                return $provider;
            }
        }

        return $this->providers->first();
    }
}

Change UX - remove mock

BAP-4107: Change UX
- remove mock


<?php

namespace Sven\FlexEnv\Commands;

use Symfony\Component\Console\Input\InputArgument;

class EnvDeleteCommand extends EnvCommand
{
    /** @var string */
    protected $name = 'env:delete';

    /** @var string */
    protected $description = 'Delete an entry from your .env file';

    public function handle(): int
    {
        $config = $this->config();

        $config->delete($key = $this->key());
        $config->persist();

        $this->comment("Successfully deleted the entry \"$key\" from your .env file.");

        return 0;
    }

    protected function getArguments()
    {
        return [
            ['key', InputArgument::REQUIRED, 'The name of the environment variable to delete.'],
        ];
    }
}

<?php

namespace Sven\FlexEnv\Commands;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class EnvDeleteCommand extends EnvCommand
{
    /** @var string */
    protected $name = 'env:delete';

    /** @var string */
    protected $description = 'Delete an entry from your .env file';

    public function handle(): int
    {
        $config = $this->config();

        $config->delete($key = $this->key());

        if ($this->option('force') || $this->confirm("Are you sure you want to delete \"$key\" from your .env file?")) {
            $config->persist();

            $this->comment("Successfully deleted the entry \"$key\" from your .env file.");

            return 0;
        }

        $this->comment('Alright, no changes made.');

        return 1;
    }

    protected function getArguments()
    {
        return [
            ['key', InputArgument::REQUIRED, 'The name of the environment variable to delete.'],
        ];
    }

    protected function getOptions()
    {
        return [
            [
                'force',
                null,
                InputOption::VALUE_NONE,
                'Do not ask for confirmation before deleting the key from the environment file.',
            ],
        ];
    }
}

Add '--force' option to env:delete command


<?php
/**
 * @copyright Copyright (C) 2016 AIZAWA Hina
 * @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT
 * @author AIZAWA Hina <hina@bouhime.com>
 */

declare(strict_types=1);

namespace app\assets;

use Yii;
use yii\web\AssetBundle;

class BowserAsset extends AssetBundle
{
    public $sourcePath = '@node/bowser';
    public $js = [
        'es5.js',
    ];
    public $depends = [
        BabelPolyfillAsset::class,
    ];

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

        $prefix = Yii::getAlias($this->sourcePath);
        $this->publishOptions['filter'] = function (string $path) use ($prefix): ?bool {
            if (substr($path, 0, strlen($prefix)) !== $prefix) {
                return false;
            }

            $path = substr($path, strlen($prefix) + 1); // /path/to/es5.js => es5.js
            if ($path === 'LICENSE') {
                return true;
            }

            if (preg_match('![^/]+\.js$!i', $path)) {
                return true;
            }

            return false;
        };
    }
}

<?php
/**
 * @copyright Copyright (C) 2015-2019 AIZAWA Hina
 * @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT
 * @author AIZAWA Hina <hina@bouhime.com>
 */

declare(strict_types=1);

namespace app\assets;

use Yii;
use yii\web\AssetBundle;

class BowserAsset extends AssetBundle
{
    public $sourcePath = '@node/bowser';
    public $js = [
        'es5.js',
    ];
    public $depends = [
        BabelPolyfillAsset::class,
    ];

    public function init()
    {
        parent::init();
        $this->publishOptions['filter'] = [$this, 'filterIsUsableAssets'];
    }

    public function filterIsUsableAssets(string $path): bool
    {
        $prefix = Yii::getAlias($this->sourcePath);
        if (substr($path, 0, strlen($prefix)) !== $prefix) {
            return false;
        }

        $path = substr($path, strlen($prefix) + 1); // /path/to/es5.js => es5.js
        if ($path === 'LICENSE') {
            return true;
        }

        if (preg_match('![^/]+\.js$!i', $path)) {
            return true;
        }

        return false;
    }
}

Fix debug panel for Asset Bundles

Fix debug panel for Asset Bundles

closes #448


<?php

class Auth {

	public static function login($id) {

   		$_SESSION['user_id'] = $id;
   		return true;

	}

	public static function logout() {

		if(isset($_SESSION['user_id'])) {
			unset($_SESSION['user_id']);
			session_destroy();
		}

	}

	public static function loggedIn() {

		return isset($_SESSION['user_id']);

	}

}

?>

<?php

class Auth {

	/**
	 * Login the user with an ID.
	 *
	 * @param  int $id
	 * @return void
	 */
	public static function login($id)
	{
		$_SESSION['user_id'] = $id;
	}

	/**
	 * Logout current user.
	 *
	 * @return void
	 */
	public static function logout()
	{
		if (isset($_SESSION['user_id']))
		{
			unset($_SESSION['user_id']);
			session_destroy();
		}
	}

	/**
	 * Checks if the current visitor is logged-in.
	 *
	 * @return boolean
	 */
	public static function loggedIn()
	{
		return isset($_SESSION['user_id']);
	}

	/**
	 * Returns the current user ID.
	 *
	 * @return int|null
	 */
	public static function getUserId()
	{
		// Use static::loggedIn() if use PHP 5.3 >=
		return self::loggedIn() ? $_SESSION['user_id'] : null;
	}

}

Update docblocks, remove close php tag, add getUserId() method


<?php

/*
* This file is part of the Integrated package.
*
* (c) e-Active B.V. <integrated@e-active.nl>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Integrated\Bundle\ContentBundle\Document\SearchSelection;

use Doctrine\ODM\MongoDB\DocumentRepository;

/**
 * Repository for SearchSelection.
 *
 * @author Ger Jan van den Bosch <gerjan@e-active.nl>
 */
class SearchSelectionRepository extends DocumentRepository
{
    /**
     * @param int $id
     *
     * @return mixed
     *
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
     */
    public function findPublicByUserId($id)
    {
        $builder = $this->createQueryBuilder();

        $builder->addOr($builder->expr()->field('userId')->equals($id));
        $builder->addOr($builder->expr()->field('public')->equals(true));

        return $builder->getQuery()->execute();
    }
}

<?php

/*
* This file is part of the Integrated package.
*
* (c) e-Active B.V. <integrated@e-active.nl>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Integrated\Bundle\ContentBundle\Document\SearchSelection;

use Doctrine\ODM\MongoDB\DocumentRepository;

/**
 * Repository for SearchSelection.
 *
 * @author Ger Jan van den Bosch <gerjan@e-active.nl>
 */
class SearchSelectionRepository extends DocumentRepository
{
    /**
     * @param int $id
     *
     * @return mixed
     *
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
     */
    public function findPublicByUserId($id)
    {
        $builder = $this->createQueryBuilder();

        $builder->addOr($builder->expr()->field('userId')->equals($id));
        $builder->addOr($builder->expr()->field('public')->equals(true));

        $builder->sort('title');

        return $builder->getQuery()->execute();
    }
}

Sort search selections by title

Sort search selections by title


<?php

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

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

Route::get('/.well-known/acme-challenge/KW6aDeVbrfe2blTE8hOuSUYjw8SS6HOc0xhioHjA1OU', function() {
    return 'KW6aDeVbrfe2blTE8hOuSUYjw8SS6HOc0xhioHjA1OU.2tp1B8sKxN_e8tkWiVmqSJC-F3k17yr6vZOI8DbAl6g';
});

Add Let's Encrypt domain validation information


<?php

/*
 * This file is part of WordPlate.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

// Remove menu and submenu items.
add_action('admin_menu', function () {
    $items = get_theme_support('plate-menu');

    foreach (reset($items) as $item) {
        if (
            !strpos($item, '?') ||
            !strpos($item, 'edit.php?post_type=')
        ) {
            remove_menu_page($item);
            continue;
        }

        $path = parse_url($item, PHP_URL_PATH);
        $query = parse_url($item, PHP_URL_QUERY);
        $value = explode('=', $query);

        if (isset($value[1])) {
            $name = $value[1];

            strpos($item, 'admin.php') ? remove_submenu_page($path, $name) : remove_menu_page($name);
        }
    }
}, PHP_INT_MAX);

<?php

/*
 * This file is part of WordPlate.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

// Remove menu and submenu items.
add_action('admin_menu', function () {
    $items = get_theme_support('plate-menu');

    foreach (reset($items) as $item) {
        if (
            strpos($item, '?') === false ||
            strpos($item, 'edit.php?post_type=') === 0
        ) {
            remove_menu_page($item);
            continue;
        }

        $path = parse_url($item, PHP_URL_PATH);
        $query = parse_url($item, PHP_URL_QUERY);
        $value = explode('=', $query);

        if (isset($value[1])) {
            $name = $value[1];

            strpos($item, 'admin.php') !== 0 ? remove_submenu_page($path, $name) : remove_menu_page($name);
        }
    }
}, PHP_INT_MAX);

Fix 0/false strpos outlier problems

Fix 0/false strpos outlier problems


<?php

namespace App\Http\Middleware;

use Closure;

use App\IpBlacklist;
use Log;

class IPBasedBlacklist
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $ip = $request->ip();
        /*$blacklist = IpBlacklist
                ::where('ip_address', $ip)
                ->first();*/

        $blacklistedIps = explode(',', env('BLACKLISTED_IPS', ''));

        if (!in_array($ip, $blacklistedIps)) {
            return $next($request);
        }

        Log::Info(sprintf('Blocked %s from accessing %s due to reason: %s', $ip, $request->fullUrl(), 'Not set.'));
        abort(503);
    }
}

<?php

namespace App\Http\Middleware;

use Closure;

use App\IpBlacklist;
use Log;

class IPBasedBlacklist
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $ip = $request->ip();
        $blacklist = IpBlacklist
                ::where('ip_address', $ip)
                ->first();

        if (empty($blacklist)) {
            return $next($request);
        }

        Log::Info(sprintf('Blocked %s from accessing %s due to reason: %s', $ip, $request->fullUrl(), $blacklist->reason));
        abort(503);
    }
}

Revert temp fix for IP-based blacklist

Revert temp fix for IP-based blacklist