<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use Illuminate\Http\Request;

class EditorServicesController extends Controller
{

	public function __construct(){}

	public function course($question_id) {
		return response()->json(['value' => $question_id]);
	}

	public function submit(Request $request)
	{
		// Get  test case
		//

		// Submit file and test case to compiler
		//

		// return result
	}
}

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;

use Illuminate\Http\Response;
use Illuminate\Http\Request;

use Editor\Connection;
use Editor\CourseInformationConnection;

class EditorServicesController extends Controller
{

	public function __construct(){}

	public function course($question_id) {
		return response()->json(['value' => $question_id]);
	}

	public function submit(Request $request, $id)
	{
		// Get  test case
		$content_url = sprintf(
			config('service.course.testcase'),
			$id
		);
		$content = $this->getContent($content_url);

		return response()->json($content);

		// Submit file and test case to compiler
		//

		// return result
	}

	protected function getContent($url)
	{
		$context = stream_context_create(
			[
				'http' => ['header'=>'Connection: close\r\n']
			]
		);

		return file_get_contents($url, false, $context);
	}

}

Add getContent for getting faster

Add getContent for getting faster


<?php

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

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

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

<?php

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

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

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

Modify the create user table

Modify the create user table


<?php

namespace App\Events;

use App\Notification;
use App\Tag;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class TagCreating {
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(Tag $tag) {
        Notification::create([
            'space_id' => $tag->space_id,
            'action' => 'tag.created'
        ]);
    }
}

<?php

namespace App\Events;

use App\Notification;
use App\Tag;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class TagCreating {
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(Tag $tag) {
        Notification::create([
            'space_id' => $tag->space_id,
            'user_id' => \Auth::user()->id,
            'action' => 'tag.created'
        ]);
    }
}

Add user_id to notifications in existing events


<?php

/*
 * This file is part of the API Platform project.
 *
 * (c) Kévin Dunglas <dunglas@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace ApiPlatform\Core\Api;

/**
 * Filters applicable on a resource.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
interface FilterInterface
{
    /**
     * Gets the description of this filter for the given resource.
     *
     * Returns an array with the filter parameter names as keys and array with the following data as values:
     *   - property: the property where the filter is applied
     *   - type: the type of the filter
     *   - required: if this filter is required
     *   - strategy: the used strategy
     *   - swagger (optional): additional parameters for the path operation,
     *     e.g. 'swagger' => [
     *       'description' => 'My Description',
     *       'name' => 'My Name',
     *       'type' => 'integer',
     *     ]
     * The description can contain additional data specific to a filter.
     *
     * @see ApiPlatform\Core\Swagger\Serializer\DocumentationNormalizer::getFiltersParameters
     *
     * @param string $resourceClass
     *
     * @return array
     */
    public function getDescription(string $resourceClass): array;
}

<?php

/*
 * This file is part of the API Platform project.
 *
 * (c) Kévin Dunglas <dunglas@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace ApiPlatform\Core\Api;

/**
 * Filters applicable on a resource.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
interface FilterInterface
{
    /**
     * Gets the description of this filter for the given resource.
     *
     * Returns an array with the filter parameter names as keys and array with the following data as values:
     *   - property: the property where the filter is applied
     *   - type: the type of the filter
     *   - required: if this filter is required
     *   - strategy: the used strategy
     *   - swagger (optional): additional parameters for the path operation,
     *     e.g. 'swagger' => [
     *       'description' => 'My Description',
     *       'name' => 'My Name',
     *       'type' => 'integer',
     *     ]
     * The description can contain additional data specific to a filter.
     *
     * @see \ApiPlatform\Core\Swagger\Serializer\DocumentationNormalizer::getFiltersParameters
     *
     * @param string $resourceClass
     *
     * @return array
     */
    public function getDescription(string $resourceClass): array;
}

Add backslash in front of the class name


<?php namespace Orchestra\Model\Traits;

use Orchestra\Model\Value\Meta;

trait MetableTrait
{
    /**
     * `meta` field accessor.
     *
     * @param  mixed  $value
     * @return \Orchestra\Model\Value\Meta
     */
    public function getMetaAttribute($value)
    {
        $meta = [];

        if (! is_null($value)) {
            $meta = json_decode($value, true);
        }

        return new Meta($meta);
    }
    /**
     * `meta` field mutator.
     *
     * @param  \Orchestra\Model\Value\Meta|null  $value
     * @return void
     */
    public function setMetaAttribute(Meta $value = null)
    {
        if (is_null($value)) {
            return;
        }

        $this->attributes['meta'] = $value->toJson();
    }
}

<?php namespace Orchestra\Model\Traits;

use Illuminate\Contracts\Support\Arrayable;
use Orchestra\Model\Value\Meta;

trait MetableTrait
{
    /**
     * `meta` field accessor.
     *
     * @param  mixed  $value
     * @return \Orchestra\Model\Value\Meta
     */
    public function getMetaAttribute($value)
    {
        $meta = [];

        if (! is_null($value)) {
            $meta = json_decode($value, true);
        }

        return new Meta($meta);
    }
    /**
     * `meta` field mutator.
     *
     * @param  mixed  $value
     * @return void
     */
    public function setMetaAttribute($value = null)
    {
        $this->attributes['meta'] = $this->mutateMetaAttribute($value);
    }

    /**
     * Get value from mixed content.
     *
     * @param  mixed  $value
     * @return mixed
     */
    protected function mutateMetaAttribute($value)
    {
        if (is_null($value)) {
            return $value;
        }

        if ($value instanceof Arrayable) {
            $value = $value->toArray();
        } elseif (! is_array($value)) {
            $value = (array) $value;
        }

        return json_encode($value);
    }
}

Allow to mutate Arrayable instead of Meta.


<?php

namespace Zeropingheroes\Lanager;

use Eloquent;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\belongsTo;

/* @mixin Eloquent */
class Session extends Model
{
    protected $dates = [
        'last_activity',
    ];

    /**
     * @return belongsTo
     */
    public function user()
    {
        return $this->belongsTo('Zeropingheroes\Lanager\User');
    }
}

<?php

namespace Zeropingheroes\Lanager;

use Eloquent;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\belongsTo;

/* @mixin Eloquent */
class Session extends Model
{
    protected $dates = [
        'last_activity',
    ];

    protected $keyType = 'string';

    /**
     * @return belongsTo
     */
    public function user()
    {
        return $this->belongsTo('Zeropingheroes\Lanager\User');
    }
}

Fix key type for sessions table

Fix key type for sessions table


<?php
$eventDispatcher = \OC::$server->getEventDispatcher();
$eventDispatcher->addListener(
	'OCA\Files::loadAdditionalScripts',
	function () {
		$policy = new \OC\Security\CSP\ContentSecurityPolicy();
		$policy->setAllowedImageDomains(['*']);
		$frameDomains = $policy->getAllowedFrameDomains();
		$frameDomains[] = 'www.youtube.com';
		$frameDomains[] = 'prezi.com';
		$frameDomains[] = 'player.vimeo.com';
		$frameDomains[] = 'vine.co';
		$policy->setAllowedFrameDomains($frameDomains);
		\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy);

		//load the required files
		OCP\Util::addscript('files_markdown', '../build/editor');
		OCP\Util::addStyle('files_markdown', '../build/styles');
		OCP\Util::addStyle('files_markdown', 'preview');
	});

$eventDispatcher->addListener(
	'OCA\Files_Sharing::loadAdditionalScripts',
	function () {
		OCP\Util::addScript('files_markdown', '../build/editor');
		OCP\Util::addStyle('files_markdown', 'preview');
	});

<?php
$eventDispatcher = \OC::$server->getEventDispatcher();
$eventDispatcher->addListener(
	'OCA\Files::loadAdditionalScripts',
	function () {
		$policy = new \OC\Security\CSP\ContentSecurityPolicy();
		$policy->setAllowedImageDomains(['*']);
		$frameDomains = $policy->getAllowedFrameDomains();
		$frameDomains[] = 'www.youtube.com';
		$frameDomains[] = 'prezi.com';
		$frameDomains[] = 'player.vimeo.com';
		$frameDomains[] = 'vine.co';
		$policy->setAllowedFrameDomains($frameDomains);
		\OC::$server->getContentSecurityPolicyManager()->addDefaultPolicy($policy);

		//load the required files
		OCP\Util::addscript('files_markdown', '../build/editor');
		OCP\Util::addStyle('files_markdown', '../build/styles');
		OCP\Util::addStyle('files_markdown', 'preview');
	});

$eventDispatcher->addListener(
	'OCA\Files_Sharing::loadAdditionalScripts',
	function () {
		OCP\Util::addScript('files_markdown', '../build/editor');
		OCP\Util::addStyle('files_markdown', '../build/styles');
		OCP\Util::addStyle('files_markdown', 'preview');
	});

Load all stylesheets for public preview

Load all stylesheets for public preview

fixes #88

Signed-off-by: Robin Appelman <474ee9ee179b0ecf0bc27408079a0b15eda4c99d@icewind.nl>


<?php

namespace Tests\Feature;

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

class AdminTest extends TestCase
{
    /**
     * Test to see that the admin pages can be loaded
     * @dataProvider adminPages
     *
     * @return void
     */
    public function testAdminPages($uri, $value)
    {
        $this->withoutMiddleware()->get($uri)->assertSee($value);
    }

    public function adminPages()
    {
        return [
            ['/admin/locations', 'Locations'],
            ['/admin/manufacturers', 'Manufacturers'],
            ['/admin/modalities', 'Modalities'],
            ['/admin/testers', 'Testers'],
            ['/admin/testtypes', 'Test Types'],
        ];
    }
}

<?php

namespace Tests\Feature;

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

class AdminTest extends TestCase
{
    /**
     * Test to see that the admin pages can be loaded
     * @dataProvider adminPages
     *
     * @return void
     */
    public function testAdminPagesLoadProperly($routeName, $value)
    {
        $this->withoutMiddleware()->get(route($routeName))->assertSee($value);
    }

    public function adminPages()
    {
        return [
            ['locations.index', 'Locations'],
            ['manufacturers.index', 'Manufacturers'],
            ['modalities.index', 'Modalities'],
            ['testers.index', 'Testers'],
            ['testtypes.index', 'Test Types'],
        ];
    }
}

Use route names to get URIs for testing

Use route names to get URIs for testing


<?php
	function get_body_class( $route = null, $sidebar = false ) {
		$defaultClasses = array(
			'route-auth-login',
			'route-auth-register'
		);
		if ( $route ) {
			if ( in_array( get_route_class( $route ), $defaultClasses  ) )
				return config( 'front.dfltBodyClass' );
		}

		if ( config( 'front.progressiveDesktop' ) ) {
			if ( $sidebar ) return 'col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2 col-lg-7 col-lg-offset-4';
			else return config( 'front.progBodyClass' );
		}
		else return config( 'front.dfltBodyClass' );
	}

	function get_route_class( $route = null ) {
		$route_name = 'home';
		if ( !empty( $route ) ) {
			$route_name = str_replace( '/', '-', ( $route->uri == '/' ) ? 'welcome' : $route->uri );
		}
		$determined_class = 'level-1';
		return 'route-' . $route_name . ' ' . $determined_class;
	}

<?php
	function get_body_class( $route = null, $sidebar = false ) {
		$defaultClasses = array(
			'route-auth-login',
			'route-auth-register'
		);
		if ( $route ) {
			if ( in_array( get_route_class( $route ), $defaultClasses  ) )
				return config( 'front.dfltBodyClass' );
		}

		if ( config( 'front.progressiveDesktop' ) ) {
			if ( $sidebar ) return 'col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2 col-lg-7 col-lg-offset-4';
			else return config( 'front.progBodyClass' );
		}
		else return config( 'front.dfltBodyClass' );
	}

	function get_route_class( $route = null ) {
		$route_name = 'not-identified';
		$determined_class = '';

		$level_exceptions = array(
			'/', 'auth/login', 'auth/register'
		);

		if ( !empty( $route ) ) {
			$route_name = str_replace( '/', '-', ( $route->uri == '/' ) ? 'welcome' : $route->uri );

			if ( !in_array( $route->uri, $level_exceptions ) ) {
				$determined_class = 'level-1';
			}
		}

		return 'route-' . $route_name . ' ' . $determined_class;
	}

Fix levels for Logged Out Pages

Fix levels for Logged Out Pages

- Helpers.php conditional updates


<?php
/**
* ownCloud
*
* @author Robin Appelman
* @copyright 2012 Robin Appelman icewind@owncloud.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

class Test_User_Database extends Test_User_Backend {
	/**
	 * get a new unique user name
	 * test cases can override this in order to clean up created user
	 * @return array
	 */
	public function getUser() {
		$user=uniqid('test_');
		$this->users[]=$user;
		return $user;
	}

	public function setUp() {
		$this->backend=new OC_User_Dummy();
	}

	public function tearDown() {
		foreach($this->users as $user) {
			$this->backend->deleteUser($user);
		}
	}
}

<?php
/**
* ownCloud
*
* @author Robin Appelman
* @copyright 2012 Robin Appelman icewind@owncloud.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

class Test_User_Database extends Test_User_Backend {
	/**
	 * get a new unique user name
	 * test cases can override this in order to clean up created user
	 * @return array
	 */
	public function getUser() {
		$user=uniqid('test_');
		$this->users[]=$user;
		return $user;
	}

	public function setUp() {
		$this->backend=new OC_User_Database();
	}

	public function tearDown() {
		foreach($this->users as $user) {
			$this->backend->deleteUser($user);
		}
	}
}

Test OC_User_Database in Test_User_Database instead of OC_User_Dummy.


<?php

return [
    'App\Models\Business' => [
        'start_at'                      => ['type' => 'time', 'value' => '08:00:00'],
        'finish_at'                     => ['type' => 'time', 'value' => '19:00:00'],
        'show_map'                      => ['type' => 'bool', 'value' => false],
        'show_postal_address'           => ['type' => 'bool', 'value' => false],
        'show_phone'                    => ['type' => 'bool', 'value' => false],
        'appointment_annulation_pre_hs' => ['type' => 'int', 'value' => '48', 'icon' => 'hourglass'],
        'appointment_take_today'        => ['type' => 'bool', 'value' => false],
        'appointment_code_length'       => ['type' => 'int', 'value' => 4, 'icon' => 'barcode'],
        'service_default_duration'      => ['type' => 'int', 'value' => 30, 'step' => 5, 'icon' => 'hourglass'],
    ],
];

<?php

return [
    'App\Models\Business' => [
        'start_at'                      => ['type' => 'time', 'value' => '08:00:00'],
        'finish_at'                     => ['type' => 'time', 'value' => '19:00:00'],
        'show_map'                      => ['type' => 'bool', 'value' => false],
        'show_postal_address'           => ['type' => 'bool', 'value' => false],
        'show_phone'                    => ['type' => 'bool', 'value' => false],
        'appointment_annulation_pre_hs' => ['type' => 'int', 'value' => '48', 'step' => 1, 'icon' => 'hourglass'],
        'appointment_take_today'        => ['type' => 'bool', 'value' => false],
        'appointment_code_length'       => ['type' => 'int', 'value' => 4, 'icon' => 'barcode'],
        'service_default_duration'      => ['type' => 'int', 'value' => 30, 'step' => 5, 'icon' => 'hourglass'],
        'annulation_policy_advice'      => ['type' => 'string', 'value' => ''],
    ],
];

Add default step for setting (per hour)

Add default step for setting (per hour)


<?php

/**
 * @desc - path for site.
 * should be set, otherwise content will be served from volcano/site internally.
 * default: volcano/site
 */
define('SITE', dirname(__FILE__) . '/site');

/**
 * @desc - use 404 page or not
 * if "false" redirect to default.md
 * default: true
 */
define('USE_404', true);

/**
 * @desc - use index.php or template as home
 * if `true` template has to be: site/templates/home.php
 * if `false` it will be index.php
 * default: true
 */
define('USE_HOME_TEMPLATE', false);

/**
 * @desc - whether or not to show errors.
 * default: false
 *
 * Should be false when your site is live
 *
 * By setting to true, you'll get error messages.
 */
define('IS_DEV', true);

// require volcano
require './vendor/sebastianks/volcano/index.php';

<?php

/**
 * @desc - path for site.
 * should be set, otherwise content will be served from volcano/site internally.
 * default: volcano/site
 */
define('SITE', dirname(__FILE__) . '/site');

/**
 * @desc - use 404 page or not
 * if "false" redirect to default.md
 * default: true
 */
define('USE_404', true);

/**
 * @desc - use index.php or template as home
 * if `true` template has to be: site/templates/home.php
 * if `false` it will be index.php
 * default: true
 */
define('USE_HOME_TEMPLATE', false);

/**
 * @desc - whether or not to show errors.
 * default: false
 *
 * Should be false when your site is live
 *
 * By setting to true, you'll get error messages.
 */
define('IS_DEV', false);

// require volcano
require './vendor/sebastianks/volcano/index.php';

Switch IS_DEV constant to false

Switch IS_DEV constant to false


<?php

use SkylarK\Purity5\DataStructures\PureTree as PureTree;

class PureTreeTest extends PHPUnit_Framework_TestCase
{
	// Tests

	public function test_SimpleTree() {

		$root = PureTree::buildRoot('<title>Welcome</title>');

		$this->assertEquals("html", $root->name());
		$this->assertEquals(0, count($root->attributes()));
		$this->assertEquals('<title>Welcome</title>', $root->contents());
		$this->assertEquals(0, count($root->children()));

		$c1 = $root->createChild("head", array(), '<title>Welcome</title>');
		$c2 = $c1->createChild("title", array(), 'Welcome');

		$this->assertEquals(1, count($root->children()));
		$this->assertEquals(1, count($c1->children()));
		$this->assertEquals(0, count($c2->children()));

		// Now test querying
		$result = $root->query("title");
		$this->assertEquals(1, count($result));
		$this->assertEquals($c2, $result[0]);
	}
}

<?php

use SkylarK\Purity5\DataStructures\PureTree as PureTree;

class PureTreeTest extends PHPUnit_Framework_TestCase
{
	// Tests

	public function test_SimpleTree() {

		$root = PureTree::buildRoot('<title>Welcome</title>');

		$this->assertEquals("html", $root->name());
		$this->assertEquals(0, count($root->attributes()));
		$this->assertEquals('<title>Welcome</title>', $root->contents());
		$this->assertEquals(0, count($root->children()));

		$c1 = $root->createChild("head", array(), '<title>Welcome</title>');
		$c2 = $c1->createChild("title", array(), 'Welcome');

		$this->assertEquals(1, count($root->children()));
		$this->assertEquals(1, count($c1->children()));
		$this->assertEquals(0, count($c2->children()));

		// Now test querying
		$result = $root->query("title");
		$this->assertEquals(1, count($result));
		$this->assertEquals($c2, $result[0]);

		// More complex query
		$result = $root->query("html > head > title");
		$this->assertEquals(1, count($result));
		$this->assertEquals($c2, $result[0]);

		// Another query
		$result = $root->query("html head title");
		//$this->assertEquals(1, count($result));
		//$this->assertEquals($c2, $result[0]);

		// Another query
		$result = $root->query("html title");
		//$this->assertEquals(1, count($result));
		//$this->assertEquals($c2, $result[0]);

		// Another query
		$result = $root->query("head > title");
		//$this->assertEquals(1, count($result));
		//$this->assertEquals($c2, $result[0]);
	}
}

Add a set of basic queries

Add a set of basic queries


<?php

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

$loop = React\EventLoop\Factory::create();
$factory = new React\Dns\Resolver\Factory();
$resolver = $factory->create('8.8.8.8', $loop);

$connFactory = function ($ip) use ($loop) {
    $fd = stream_socket_client("tcp://$ip:43");
    return new React\Socket\Connection($fd, $loop);
};

$domain = 'igor.io';

$client = new React\Whois\Client($resolver, $connFactory);
$client->query($domain, function ($result) {
    echo $result;
});

echo "Getting whois for $domain...\n";

$loop->run();

<?php

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

$loop = React\EventLoop\Factory::create();
$factory = new React\Dns\Resolver\Factory();
$resolver = $factory->create('8.8.8.8', $loop);

$connFactory = function ($ip) use ($loop) {
    $fd = stream_socket_client("tcp://$ip:43");
    return new React\Socket\Connection($fd, $loop);
};

$domain = 'igor.io';

$client = new React\Whois\Client($resolver, $connFactory);
$client
    ->query($domain)
    ->then(function ($result) {
        echo $result;
    });

echo "Getting whois for $domain...\n";

$loop->run();

Update example to use promise API

Update example to use promise API


<?php

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

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$request = Request::createFromGlobals();

$input = $request->get('name', 'World');

$response = new Response(sprintf('Hello %s', htmlspecialchars($input, ENT_QUOTES, 'UTF-8')));

$response->send();

Update to comply with standards.

Update to comply with standards.


<?php

require "vendor/autoload.php";

use Florence\User;

//$user = User::find(4);
////$user->first_name = "Prosper";
//
//print_r($user);

$user = new User();
$user->first_name = "Shneal";
$user->last_name = "Obama";
$user->stack = "None";

$user->save();

<?php

require "vendor/autoload.php";

use Florence\User;

//
$user = User::find(6);
//$user->first_name = "Prosper";
//$user = User::getAll();
print_r($user);

//$user = new User();
//$user->first_name = "Shneal";
//$user->last_name = "Obama";
//$user->stack = "None";
//
//$user->save();

Test the getAll, Find methods

Test the getAll, Find methods


<?php
header('Lain: Hot');
if (strnatcmp(phpversion(),'5.5') < 0)
  exit("PHP 5.5 or newer is required");

include('config.php');

function PhoxyStart()
{
  if (phoxy_conf()["api_xss_prevent"] && getallheaders()['X-Lain'] !== 'Wake up')
    die("Requiest aborted due API direct XSS warning");

  global $_GET;
  $get_param = phoxy_conf()["get_api_param"];
  $file = $_GET[$get_param];
  unset($_GET[$get_param]);

  if ($file == 'htaccess')
    exit('Rewrite engine work SUCCESS');

  include_once('rpc_string_parser.php');
  $parser = new \phoxy\rpc_string_parser();

  global $_phoxy_process_obj;
  $_phoxy_process_obj = $obj = $parser->GetRpcObject($file, $_GET);
  $a = $obj['obj'];

  $method = $obj['method'];
  if (is_string($method))
    $method = [$method, []];

  try
  {
    echo $a->APICall($method[0], $method[1]);
  } catch (phoxy_protected_call_error $e)
  {
    echo new phoxy_return_worker($e->result);
  }
}

if (phoxy_conf()['autostart'])
  PhoxyStart();

<?php
header('Lain: Hot');
if (strnatcmp(phpversion(),'5.5') < 0)
  exit("PHP 5.5 or newer is required");

include('config.php');

function PhoxyStart()
{
  global $_SERVER;
  if (phoxy_conf()["api_xss_prevent"] && $_SERVER['HTTP_X_LAIN'] !== 'Wake up')
    die("Requiest aborted due API direct XSS warning");

  global $_GET;
  $get_param = phoxy_conf()["get_api_param"];
  $file = $_GET[$get_param];
  unset($_GET[$get_param]);

  if ($file == 'htaccess')
    exit('Rewrite engine work SUCCESS');

  include_once('rpc_string_parser.php');
  $parser = new \phoxy\rpc_string_parser();

  global $_phoxy_process_obj;
  $_phoxy_process_obj = $obj = $parser->GetRpcObject($file, $_GET);
  $a = $obj['obj'];

  $method = $obj['method'];
  if (is_string($method))
    $method = [$method, []];

  try
  {
    echo $a->APICall($method[0], $method[1]);
  } catch (phoxy_protected_call_error $e)
  {
    echo new phoxy_return_worker($e->result);
  }
}

if (phoxy_conf()['autostart'])
  PhoxyStart();

Support php executed in cgi mode

Support php executed in cgi mode


<?php  defined('C5_EXECUTE') or die("Access Denied.");
$dh = Core::make('helper/date'); /* @var $dh \Concrete\Core\Localization\Service\Date */
$page = Page::getCurrentPage();
$date = Core::make('helper/date')->formatDate($page->getCollectionDatePublic(), true);
$user = UserInfo::getByID($page->getCollectionUserID());
?>

<?=h($title)?>

    <? print $date; ?>

    <? if (is_object($user)): ?>

    <? print $user->getUserDisplayName(); ?>

    <? endif; ?>

<?php  defined('C5_EXECUTE') or die("Access Denied.");
$dh = Core::make('helper/date'); /* @var $dh \Concrete\Core\Localization\Service\Date */
$page = Page::getCurrentPage();
$date = $dh->formatDate($page->getCollectionDatePublic(), true);
$user = UserInfo::getByID($page->getCollectionUserID());
?>

<?=h($title)?>

    <? print $date; ?>

    <? if (is_object($user)): ?>

    <? print $user->getUserDisplayName(); ?>

    <? endif; ?>

Use previously declared date helper

Use previously declared date helper

Former-commit-id: d1f51b0a2e69c004f80889a85171df9238c2de59
Former-commit-id: f859ab55bd3f66780e54abeae2dc1f3a460703cb


<?php

namespace React\Promise;

interface ExtendedPromiseInterface extends PromiseInterface
{
    /**
     * @return ExtendedPromiseInterface
     */
    public function done(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null);

    /**
     * @return ExtendedPromiseInterface
     */
    public function otherwise(callable $onRejected);

    /**
     * @return ExtendedPromiseInterface
     */
    public function always(callable $onFulfilledOrRejected);

    /**
     * @return ExtendedPromiseInterface
     */
    public function progress(callable $onProgress);
}

<?php

namespace React\Promise;

interface ExtendedPromiseInterface extends PromiseInterface
{
    /**
     * @return void
     */
    public function done(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null);

    /**
     * @return ExtendedPromiseInterface
     */
    public function otherwise(callable $onRejected);

    /**
     * @return ExtendedPromiseInterface
     */
    public function always(callable $onFulfilledOrRejected);

    /**
     * @return ExtendedPromiseInterface
     */
    public function progress(callable $onProgress);
}

Fix return tag of done()

Fix return tag of done()


<?php

namespace PendoNL\LaravelExactOnline;

use Illuminate\Support\Facades\Facade;

class LaravelExactOnlineFacade extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    public static function getFacadeAccessor()
    {
        return 'laravel-exact-online';
    }
}

<?php

namespace PendoNL\LaravelExactOnline;

use Illuminate\Support\Facades\Facade;

class LaravelExactOnlineFacade extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'laravel-exact-online';
    }
}

Make it a protected static function to comply with best practise


<?php

declare(strict_types=1);

namespace Phpml\Dataset;

use Phpml\Exception\DatasetException;

class CsvDataset extends ArrayDataset
{
    /**
     * @param string $filepath
     * @param int    $features
     * @param bool   $headingRow
     *
     * @throws DatasetException
     */
    public function __construct(string $filepath, int $features, bool $headingRow = true)
    {
        if (!file_exists($filepath)) {
            throw DatasetException::missingFile(basename($filepath));
        }

        if (false === $handle = fopen($filepath, 'r')) {
            throw DatasetException::cantOpenFile(basename($filepath));
        }

        if ($headingRow) {
            fgets($handle);
        }

        while (($data = fgetcsv($handle, 1000, ',')) !== false) {
            $this->samples[] = array_slice($data, 0, $features);
            $this->targets[] = $data[$features];
        }
        fclose($handle);
    }
}

<?php

declare(strict_types=1);

namespace Phpml\Dataset;

use Phpml\Exception\DatasetException;

class CsvDataset extends ArrayDataset
{
    /**
     * @param string $filepath
     * @param int    $features
     * @param bool   $headingRow
     *
     * @throws DatasetException
     */
    public function __construct(string $filepath, int $features, bool $headingRow = true)
    {
        if (!file_exists($filepath)) {
            throw DatasetException::missingFile(basename($filepath));
        }

        if (false === $handle = fopen($filepath, 'rb')) {
            throw DatasetException::cantOpenFile(basename($filepath));
        }

        if ($headingRow) {
            fgets($handle);
        }

        while (($data = fgetcsv($handle, 1000, ',')) !== false) {
            $this->samples[] = array_slice($data, 0, $features);
            $this->targets[] = $data[$features];
        }
        fclose($handle);
    }
}

Make csv reader binary safe

Make csv reader binary safe


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use \App\Manga;

class Library extends Model
{
    //
    protected $fillable = ['name', 'path'];

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getPath()
    {
        return $this->path;
    }

    public function scan()
    {
        // scan and add new directories
        foreach (\File::directories($this->getPath()) as $path) {
            $manga = Manga::updateOrCreate([
                'name' => pathinfo($path, PATHINFO_FILENAME),
                'path' => $path,
                'library_id' => Library::where('name','=',$this->getName())->first()->id
            ]);
        }

        // iterate through all the manga in the library
        // and remove those that no longer exist in the filesystem
        $manga = Manga::where('library_id', '=', $this->getId())->get();
        foreach ($manga as $manga_) {

            if (\File::exists($manga_->getPath()) === false) {

                $manga_->forceDelete();
            }
        }
    }

    public function forceDelete()
    {
        // get all the manga that have library_id to ours
        $manga = Manga::where('library_id', '=', $this->getId())->get();
        // and delete them
        foreach ($manga as $manga_) {

            // Manga::forceDelete deletes all the references to other tables (artists, authors, manga_information, etc..)
            $manga_->forceDelete();
        }

        parent::forceDelete();
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use \App\Manga;

class Library extends Model
{
    //
    protected $fillable = ['name', 'path'];

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getPath()
    {
        return $this->path;
    }

    public function scan()
    {
        // scan and add new directories
        foreach (\File::directories($this->getPath()) as $path) {
            $manga = Manga::updateOrCreate([
                'name' => pathinfo($path, PATHINFO_BASENAME),
                'path' => $path,
                'library_id' => Library::where('name','=',$this->getName())->first()->id
            ]);
        }

        // iterate through all the manga in the library
        // and remove those that no longer exist in the filesystem
        $manga = Manga::where('library_id', '=', $this->getId())->get();
        foreach ($manga as $manga_) {

            if (\File::exists($manga_->getPath()) === false) {

                $manga_->forceDelete();
            }
        }
    }

    public function forceDelete()
    {
        // get all the manga that have library_id to ours
        $manga = Manga::where('library_id', '=', $this->getId())->get();
        // and delete them
        foreach ($manga as $manga_) {

            // Manga::forceDelete deletes all the references to other tables (artists, authors, manga_information, etc..)
            $manga_->forceDelete();
        }

        parent::forceDelete();
    }
}

Fix bug with manga names being cut.

Fix bug with manga names being cut.


<?php

/**
 * Represents the WordPress option for saving the dismissed messages.
 */
class Whip_WPDismissOption implements Whip_DismissStorage {

	/** @var string */
	protected $optionName = 'whip_dismissed_for_wp_version';

	/**
	 * Saves the value to the options.
	 *
	 * @param int $dismissedValue The value to save.
	 *
	 * @return bool True when successful.
	 */
	public function set( $dismissedValue ) {
		return update_option( $this->optionName, $dismissedValue );
	}

	/**
	 * Returns the value of the whip_dismissed option.
	 *
	 * @return int Returns the value of the option or an empty string when not set.
	 */
	public function get() {
		$dismissedOption = get_option( $this->optionName );
		if ( ! $dismissedOption ) {
			return 0;
		}

		return (int) $dismissedOption;
	}

}

<?php

/**
 * Represents the WordPress option for saving the dismissed messages.
 */
class Whip_WPDismissOption implements Whip_DismissStorage {

	/** @var string */
	protected $optionName = 'whip_dismiss_timestamp';

	/**
	 * Saves the value to the options.
	 *
	 * @param int $dismissedValue The value to save.
	 *
	 * @return bool True when successful.
	 */
	public function set( $dismissedValue ) {
		return update_option( $this->optionName, $dismissedValue );
	}

	/**
	 * Returns the value of the whip_dismissed option.
	 *
	 * @return int Returns the value of the option or an empty string when not set.
	 */
	public function get() {
		$dismissedOption = get_option( $this->optionName );
		if ( ! $dismissedOption ) {
			return 0;
		}

		return (int) $dismissedOption;
	}

}

Change the option name to better reflect the contents


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

class Controller_User extends Controller_Website
{
    public function action_logout()
    {
        Auth::instance()->logout(TRUE);

        $this->request->redirect(url::site());
    }

    public function action_login()
    {
        $this->template->title   = 'Login - ';
        $this->template->content = View::factory('user/login');
    }

    public function action_process_login()
    {
        $auth = Auth::instance();

        if ($auth->login($_POST['username'], $_POST['password']))
        {
            $this->request->redirect('admin');
        }
        else
        {
            Notices::add('error', 'Incorrect username or password.');
            $this->request->redirect('user/login');
        }
    }
}

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

class Controller_User extends Controller_Website
{
    public function action_logout()
    {
        Auth::instance()->logout(TRUE);

        $this->redirect(url::site());
    }

    public function action_login()
    {
        $this->template->title   = 'Login - ';
        $this->template->content = View::factory('user/login');
    }

    public function action_process_login()
    {
        $auth = Auth::instance();

        if ($auth->login($_POST['username'], $_POST['password']))
        {
            $this->redirect('admin');
        }
        else
        {
            Notices::add('error', 'Incorrect username or password.');
            $this->redirect('user/login');
        }
    }
}

Use 3.3 api for redirects

Use 3.3 api for redirects


<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

use App\Visit;

class VisitController extends Controller
{
    public function __construct()
    {
        // $this->middleware('auth');
    }

    public function log_visit(Request $request)
    {
        $visit = new Visit($request->all());
        $visit->user_id = Auth::user()->id;
        $visit->save();
        return $visit;
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

use App\Visit;

class VisitController extends Controller
{
    public function __construct()
    {
        // $this->middleware('auth');
    }

    public function log_visit(Request $request)
    {
        $visit = new Visit($request->all());
        if (Auth::check()) {
            $visit->user_id = Auth::user()->id;
        } else {
            $visit->user_id = 0;
        }
        $visit->save();
        return $visit;
    }
}

Fix Log Visit for Unathenticated Users

Fix Log Visit for Unathenticated Users


<?php

namespace Mollie\Api\Exceptions;

class ApiException extends \Exception
{
    /**
     * @var string
     */
    protected $field;

    /**
     * @var string
     */
    protected $documentationUrl;

    /**
     * @param string          $message
     * @param int             $code
     * @param string|null     $field
     * @param string|null     $documentationUrl
     * @param \Throwable|null $previous
     */
    public function __construct($message = "", $code = 0, $field = null, $documentationUrl = null, \Throwable $previous = null)
    {
        if (!empty($field)) {
            $this->field = (string)$field;
            $message .= " Field: {$this->field}.";
        }

        if (!empty($documentationUrl)) {
            $this->documentationUrl = (string)$documentationUrl;
            $message .= " Documentation: {$this->documentationUrl}.";
        }

        parent::__construct($message, $code, $previous);

    }

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

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

<?php

namespace Mollie\Api\Exceptions;

class ApiException extends \Exception
{
    /**
     * @var string
     */
    protected $field;

    /**
     * @var string
     */
    protected $documentationUrl;

    /**
     * @param string          $message
     * @param int             $code
     * @param string|null     $field
     * @param string|null     $documentationUrl
     * @param \Throwable|null $previous
     */
    public function __construct($message = "", $code = 0, $field = null, $documentationUrl = null, \Throwable $previous = null)
    {
        if (!empty($field)) {
            $this->field = (string)$field;
            $message .= ". Field: {$this->field}";
        }

        if (!empty($documentationUrl)) {
            $this->documentationUrl = (string)$documentationUrl;
            $message .= ". Documentation: {$this->documentationUrl}";
        }

        parent::__construct($message, $code, $previous);

    }

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

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

Improve interpunction in error messages

Improve interpunction in error messages


<?php

namespace Moxl\Xec\Payload;

use App\Roster as DBRoster;
use App\User as DBUser;

class Roster extends Payload
{
    public function handle($stanza, $parent = false)
    {
        if ((string)$parent->attributes()->type == 'set') {
            $jid = current(explode('/', (string)$stanza->item->attributes()->jid));

            $contact = DBUser::me()->session->contacts()->where('jid', $jid)->first();

            if ($contact) $contact->delete();

            if ((string)$stanza->item->attributes()->subscription != 'remove') {
                $roster = DBRoster::firstOrNew(['jid' => $jid]);
                $roster->set($stanza->item);
                $roster->save();
            }

            $this->deliver();
        }
    }
}

<?php

namespace Moxl\Xec\Payload;

use App\Roster as DBRoster;
use App\User as DBUser;

class Roster extends Payload
{
    public function handle($stanza, $parent = false)
    {
        if ((string)$parent->attributes()->type == 'set') {
            $jid = current(explode('/', (string)$stanza->item->attributes()->jid));

            $contact = DBUser::me()->session->contacts()->where('jid', $jid)->first();

            if ($contact) $contact->delete();

            if ((string)$stanza->item->attributes()->subscription != 'remove') {
                $roster = DBRoster::firstOrNew(['jid' => $jid, 'session_id' => DBUser::me()->session->id]);
                $roster->set($stanza->item);
                $roster->save();
            }

            $this->deliver();
        }
    }
}

Fix disappearing contact entries after being renamed by another client.

This actually modified a cached roster entry of another random user that
happened to have the same JID in their roster.


<?php

namespace AstritZeqiri\LaravelSearchable\Traits;

use AstritZeqiri\LaravelSearchable\Exceptions\SearchException;

trait Searchable
{
    /**
     * Search on multiple database fields on eloquent models.
     *
     * @param  Illuminate\Database\Eloquent\Builder  $query
     * @param  string  $search
     * @param  array   $fields
     * @param  boolean $exact
     *
     * @throws SearchException [if the search fields are not set on the model or they are not given on the method]
     * @return Illuminate\Database\Eloquent\Builder
     */
    public function scopeSearch($query, $search = "", $fields = [], $exact = false)
    {
        if (! $search) {
            return $query;
        }

        if (! $fields && ! property_exists(static::class, 'searchOn')) {
            throw SearchException::searchOnOrFieldsNotFound();
        }

        $fields = $fields ?: static::$searchOn;

        if (! is_array($fields)) {
            $fields = [$fields];
        }

        if (empty($fields)) {
            return $query;
        }

        return (new Search($query))
                        ->className(static::class)
                        ->searchFor($search)
                        ->onFields($fields)
                        ->exactSearch($exact)
                        ->build();
    }
}

<?php

namespace AstritZeqiri\LaravelSearchable\Traits;

use AstritZeqiri\LaravelSearchable\Search;
use AstritZeqiri\LaravelSearchable\Exceptions\SearchException;

trait Searchable
{
    /**
     * Search on multiple database fields on eloquent models.
     *
     * @param  Illuminate\Database\Eloquent\Builder  $query
     * @param  string  $search
     * @param  array   $fields
     * @param  boolean $exact
     *
     * @throws SearchException [if the search fields are not set on the model or they are not given on the method]
     * @return Illuminate\Database\Eloquent\Builder
     */
    public function scopeSearch($query, $search = "", $fields = [], $exact = false)
    {
        if (! $search) {
            return $query;
        }

        if (! $fields && ! property_exists(static::class, 'searchOn')) {
            throw SearchException::searchOnOrFieldsNotFound();
        }

        $fields = $fields ?: static::$searchOn;

        if (! is_array($fields)) {
            $fields = [$fields];
        }

        if (empty($fields)) {
            return $query;
        }

        return (new Search($query))
                        ->className(static::class)
                        ->searchFor($search)
                        ->onFields($fields)
                        ->exactSearch($exact)
                        ->build();
    }
}

Fix the search class not found

Fix the search class not found


<?php

namespace WP_CLI;

use \Composer\IO\NullIO;
use \WP_CLI;

/**
 * A Composer IO class so we can provide some level of interactivity from WP-CLI
 */
class ComposerIO extends NullIO {

	/**
	 * {@inheritDoc}
	 */
	public function isVerbose() {
		return true;
	}

	/**
     * {@inheritDoc}
     */
	public function write( $messages, $newline = true ) {
		WP_CLI::log( " - " . strip_tags( $messages ) );
	}

}

<?php

namespace WP_CLI;

use \Composer\IO\NullIO;
use \WP_CLI;

/**
 * A Composer IO class so we can provide some level of interactivity from WP-CLI
 */
class ComposerIO extends NullIO {

	/**
	 * {@inheritDoc}
	 */
	public function isVerbose() {
		return true;
	}

	/**
     * {@inheritDoc}
     */
	public function write( $messages, $newline = true ) {
		self::output_clean_message( $messages );
	}

	/**
	 * {@inheritDoc}
	 */
	public function writeError( $messages, $newline = true ) {
		self::output_clean_message( $messages );
	}

	private static function output_clean_message( $message ) {
		$message = preg_replace( '#<(https?)([^>]+)>#', '$1$2', $message );
		WP_CLI::log( strip_tags( trim( $message ) ) );
	}

}

Make `wp package install` more verbose

Make `wp package install` more verbose

* Update `WP_CLI\ComposerIO` to write error messages too.
* Display return code when Composer installer returns one.


<?php
namespace Nsautoload\Tests;

use Nsautoload\Nsautoload;
use Symfony\Component\ClassLoader\ApcClassLoader;

require_once __DIR__.'/AutoloadTest.php';

class CacheTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        if (!class_exists('Symfony\Component\ClassLoader\ApcClassLoader')) {
            $this->markTestSkipped('Class loader not found');
        }
    }

	/**
     * @dataProvider getLoaderTests
     */
    public function testFindFile($className, $location)
    {
        $loader = new ApcClassLoader(md5(__DIR__), new Nsautoload());
        $file   = $loader->findFile($className);

        $this->assertSame(realpath($file), realpath($location));
    }

    public function getLoaderTests()
    {
        return AutoloadTest::getLoaderTests();
    }
}

<?php
namespace Nsautoload\Tests;

use Nsautoload\Nsautoload;
use Symfony\Component\ClassLoader\ApcClassLoader;

require_once __DIR__.'/AutoloadTest.php';

class CacheTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        if (!class_exists('Symfony\Component\ClassLoader\ApcClassLoader')) {
            $this->markTestSkipped('Class loader not found');
        }

        if (!extension_loaded('apc')) {
            $this->markTestSkipped('APC not enabled');
        }

        apc_clear_cache('user');
    }

	/**
     * @dataProvider getLoaderTests
     */
    public function testFindFile($className, $location)
    {
        $loader = new ApcClassLoader(md5(__DIR__), new Nsautoload());
        $file   = $loader->findFile($className);

        $this->assertSame(realpath($file), realpath($location));
    }

    public function getLoaderTests()
    {
        return AutoloadTest::getLoaderTests();
    }
}

Check if apc is enabled during test setup


<?php

/*
Copyright (C) 2016 Teclib'

This file is part of Armadito Plugin for GLPI.

Armadito Plugin for GLPI is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Armadito Plugin for GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>.

**/

class ScanConfigFormTest extends CommonTestCase
{
    /**
     * @test
     */
    public function showForms()
    {
        ob_start();
        $scanconfig = new PluginArmaditoScanConfig();
        $scanconfig->showForm(3);

        PluginArmaditoScanConfig::showNoScanConfigForm();
        PluginArmaditoScanConfig::showNoAntivirusForm();

        ob_end_clean();
    }
}

<?php

/*
Copyright (C) 2016 Teclib'

This file is part of Armadito Plugin for GLPI.

Armadito Plugin for GLPI is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Armadito Plugin for GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>.

**/

class ScanConfigFormTest extends CommonTestCase
{
    /**
     * @test
     */
    public function showForms()
    {
        ob_start();
        $scanconfig = new PluginArmaditoScanConfig();
        $scanconfig->showForm(3);

        PluginArmaditoScanConfig::showNoScanConfigForm();
        PluginArmaditoScanConfig::showNoAntivirusForm();

        $_GET["id"] = 3;
        $scanconfig->manageRequest();

        ob_end_clean();
    }
}

Add manageRequest test in scanconfigform tests


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

use \Curl\Curl;

// curl \
//     -X POST \
//     -d "{"id":"1","content":"Hello world!","date":"2015-06-30 19:42:21"}" \
//     "https://httpbin.org/post"

$data = json_encode(array(
    'id' => '1',
    'content' => 'Hello world!',
    'date' => date('Y-m-d H:i:s'),
));

$curl = new Curl();
$curl->setHeader('Content-Type', 'application/json');
$curl->post('https://httpbin.org/post', $data);
var_dump($curl->response->json);

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

use \Curl\Curl;

// curl \
//     -X POST \
//     -d "{"id":"1","content":"Hello world!","date":"2015-06-30 19:42:21"}" \
//     "https://httpbin.org/post"

$data = array(
    'id' => '1',
    'content' => 'Hello world!',
    'date' => date('Y-m-d H:i:s'),
);

$curl = new Curl();
$curl->setHeader('Content-Type', 'application/json');
$curl->post('https://httpbin.org/post', $data);
var_dump($curl->response->json);

Remove unnecessary json_encode when Content-Type is application/json


<?php
function is_utf8 ($str) {
	$converted = iconv('utf-8', 'utf-8', $str);
	if ($converted == $str) {
		return true;
	} else {
		return false;
	}
}

require_once('lib/FileLog.class.php');

$data = new FileLog('data/data.tsv', array('id', 'page_path', 'page_url', 'category', 'element', 'pass', 'comment'));

$page_path = $_REQUEST['path'];
$page_url = $_REQUEST['url'];

if (!is_utf8($page_path)) {
	$page_path = iconv('euc-kr', 'utf-8', $page_path);
}

$count = 0;
foreach ($_REQUEST['result'] as $category => $seq) {
	foreach ($seq as $item) {
		if (isset($item['pass'])) {
			$data->save(array(uniqid(), $page_path, $page_url, $category, $item['data'], $item['pass'], $item['comment']));
			$count++;
		}
	}
}

header('Content-Type: text/plain');
?>
Saved <?php echo($count); ?> items.

<?php
function is_utf8 ($str) {
	$converted = iconv('utf-8', 'utf-8', $str);
	if ($converted == $str) {
		return true;
	} else {
		return false;
	}
}

require_once('lib/FileLog.class.php');

$data = new FileLog('data/data.tsv', array('id', 'page_path', 'page_url', 'category', 'element', 'pass', 'comment'));

$page_path = $_REQUEST['path'];
$page_url = $_REQUEST['url'];

// if (!is_utf8($page_path)) {
// 	$page_path = iconv('euc-kr', 'utf-8', $page_path);
// }

$count = 0;
foreach ($_REQUEST['result'] as $category => $seq) {
	foreach ($seq as $item) {
		if (isset($item['pass'])) {
			$data->save(array(uniqid(), $page_path, $page_url, $category, $item['data'], $item['pass'], $item['comment']));
			$count++;
		}
	}
}

header('Content-Type: text/plain');
?>
Saved <?php echo($count); ?> items.

Comment out buggy encoding detection.

Comment out buggy encoding detection.


<?php

namespace FOQ\ElasticaBundle\Mapper;

use FOQ\ElasticaBundle\MapperInterface;
use Doctrine\Common\Persistence\ObjectRepository;

/**
 * Maps Elastica documents with Doctrine objects
 * This mapper assumes an exact match between
 * elastica documents ids and doctrine object ids
 */
class DoctrineMapper implements MapperInterface
{
    /**
     * Repository to fetch the objects from
     *
     * @var ObjectRepository
     */
    protected $objectRepository = null;

    /**
     * Doctrine identifier field
     *
     * @var string
     */
    protected $identifier = null;

    /**
     * Instanciates a new Mapper
     *
     * @param ObjectRepository objectRepository
     * @param string $identifier
     */
    public function __construct(ObjectRepository $objectRepository, $identifier = 'id')
    {
        $this->objectRepository = $objectRepository;
        $this->identifier       = $identifier;
    }

    /**
     * Transforms an array of elastica objects into an array of
     * model objects fetched from the doctrine repository
     *
     * @return array
     **/
    public function fromElasticaObjects(array $elasticaObjects)
    {
        $ids = array_map(function($elasticaObject) {
            return $elasticaObject->getId();
        }, $elasticaObjects);

        return $this->objectRepository
            ->createQueryBuilder()
            ->field($this->identifier)->in($ids)
            ->getQuery()
            ->execute();
    }

}

<?php

namespace FOQ\ElasticaBundle\Mapper;

use FOQ\ElasticaBundle\MapperInterface;
use Doctrine\Common\Persistence\ObjectRepository;

/**
 * Maps Elastica documents with Doctrine objects
 * This mapper assumes an exact match between
 * elastica documents ids and doctrine object ids
 */
class DoctrineMapper implements MapperInterface
{
    /**
     * Repository to fetch the objects from
     *
     * @var ObjectRepository
     */
    protected $objectRepository = null;

    /**
     * Doctrine identifier field
     *
     * @var string
     */
    protected $identifier = null;

    /**
     * Optional parameters
     *
     * @var array
     */
    protected $options = array(
        'hydrate' => true
    );

    /**
     * Instanciates a new Mapper
     *
     * @param ObjectRepository objectRepository
     * @param string $identifier
     * @param array $options
     */
    public function __construct(ObjectRepository $objectRepository, $identifier = 'id', array $options = array())
    {
        $this->objectRepository = $objectRepository;
        $this->identifier       = $identifier;
        $this->options          = array_merge($this->options, $options);
    }

    /**
     * Transforms an array of elastica objects into an array of
     * model objects fetched from the doctrine repository
     *
     * @return array
     **/
    public function fromElasticaObjects(array $elasticaObjects)
    {
        $ids = array_map(function($elasticaObject) {
            return $elasticaObject->getId();
        }, $elasticaObjects);

        return $this->objectRepository
            ->createQueryBuilder()
            ->field($this->identifier)->in($ids)
            ->hydrate($this->options['hydrate'])
            ->getQuery()
            ->execute();
    }

}

Add 'hydrate' option to the doctrine mapper


<?php

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

class CreateCoursesTable extends Migration
{
	public function up()
	{
		Schema::create('courses', function($table)
		{
			$table->increments('id');
			$table->string('name', 30);
			$table->string('description', 30);
			$table->enum('category', array('cs', 'math'));
			$table->timestamps();
		});
	}

	public function down()
	{
		Schema::drop('courses');
	}

}

<?php

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

class CreateCoursesTable extends Migration
{
	public function up()
	{
		Schema::create('courses', function($table)
		{
			$table->increments('id');
			$table->string('name', 30);
			$table->string('description', 60);
			$table->enum('category', array('cs', 'math'));
			$table->timestamps();
		});
	}

	public function down()
	{
		Schema::drop('courses');
	}

}

Increase course description column size

Increase course description column size


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\Cart;

final class SyliusCartEvents
{
    const CART_CHANGE = 'sylius.cart_change';
    const CART_INITIALIZE = 'sylius.cart.initialize';
    const CART_ABANDON = 'sylius.cart.abandon';

    private function __construct()
    {
    }
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\Order;

final class SyliusCartEvents
{
    const CART_CHANGE = 'sylius.cart_change';
    const CART_INITIALIZE = 'sylius.cart.initialize';
    const CART_ABANDON = 'sylius.cart.abandon';

    private function __construct()
    {
    }
}

Move CartBundle classes to OrderBundle

[Cart][Order] Move CartBundle classes to OrderBundle


<?php

/**
 * @license MIT, http://opensource.org/licenses/MIT
 * @copyright Aimeos (aimeos.org), 2014-2016
 * @package symfony
 * @subpackage Controller
 */

namespace Aimeos\ShopBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

/**
 * Aimeos controller for all page request.
 *
 * @package symfony
 * @subpackage Controller
 */
class PageController extends Controller
{
	/**
	 * Returns the html for the privacy policy page.
	 *
	 * @return Response Response object containing the generated output
	 */
	public function privacyAction() : Response
	{
		return $this->render( '@AimeosShop/Page/privacy.html.twig' );
	}

	/**
	 * Returns the html for the terms and conditions page.
	 *
	 * @return Response Response object containing the generated output
	 */
	public function termsAction() : Response
	{
		return $this->render( '@AimeosShop/Page/terms.html.twig' );
	}
}

<?php

/**
 * @license MIT, http://opensource.org/licenses/MIT
 * @copyright Aimeos (aimeos.org), 2014-2016
 * @package symfony
 * @subpackage Controller
 */

namespace Aimeos\ShopBundle\Controller;

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

/**
 * Aimeos controller for all page request.
 *
 * @package symfony
 * @subpackage Controller
 */
class PageController extends Controller
{
	/**
	 * Returns the html for the privacy policy page.
	 *
	 * @return Response Response object containing the generated output
	 */
	public function privacyAction() : Response
	{
		return $this->render( '@AimeosShop/Page/privacy.html.twig' );
	}

	/**
	 * Returns the html for the terms and conditions page.
	 *
	 * @return Response Response object containing the generated output
	 */
	public function termsAction() : Response
	{
		return $this->render( '@AimeosShop/Page/terms.html.twig' );
	}
}

Fix for using Response class

Fix for using Response class


<?php

namespace OpenDominion\Listeners\Subscribers;

use Illuminate\Events\Dispatcher;
use OpenDominion\Contracts\Services\Analytics\AnalyticsService;
use OpenDominion\Events\HasAnalyticsEvent;
use OpenDominion\Events\UserRegisteredEvent;

class AnalyticsSubscriber implements SubscriberInterface
{
    /** @var AnalyticsService */
    protected $analyticsService;

    /** @var string[] */
    protected $events = [
        UserRegisteredEvent::class,
    ];

    /**
     * AnalyticsSubscriber constructor.
     *
     * @param AnalyticsService $analyticsService
     */
    public function __construct(AnalyticsService $analyticsService)
    {
        $this->analyticsService = $analyticsService;
    }

    /**
     * {@inheritdoc}
     */
    public function subscribe(Dispatcher $events): void
    {
        $events->listen($this->events, function (HasAnalyticsEvent $event) {
            $this->analyticsService->queueFlashEvent($event->getAnalyticsEvent());
        });
    }
}

<?php

namespace OpenDominion\Listeners\Subscribers;

use Illuminate\Events\Dispatcher;
use OpenDominion\Contracts\Services\Analytics\AnalyticsService;
use OpenDominion\Events\HasAnalyticsEvent;
use OpenDominion\Events\UserActivatedEvent;
use OpenDominion\Events\UserLoggedInEvent;
use OpenDominion\Events\UserRegisteredEvent;

class AnalyticsSubscriber implements SubscriberInterface
{
    /** @var AnalyticsService */
    protected $analyticsService;

    /** @var string[] */
    protected $events = [
        UserActivatedEvent::class,
        UserLoggedInEvent::class,
        UserRegisteredEvent::class,
    ];

    /**
     * AnalyticsSubscriber constructor.
     *
     * @param AnalyticsService $analyticsService
     */
    public function __construct(AnalyticsService $analyticsService)
    {
        $this->analyticsService = $analyticsService;
    }

    /**
     * {@inheritdoc}
     */
    public function subscribe(Dispatcher $events): void
    {
        $events->listen($this->events, function (HasAnalyticsEvent $event) {
            $this->analyticsService->queueFlashEvent($event->getAnalyticsEvent());
        });
    }
}

Add user activated and logged in events to analytics subscriber


<?php
/**
 * @package dompdf
 * @link    http://dompdf.github.com/
 * @author  Benj Carson <benjcarson@digitaljunkies.ca>
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
 */
namespace Dompdf;

use Dompdf\Frame;

/**
 * Executes inline PHP code during the rendering process
 *
 * @package dompdf
 */
class PhpEvaluator
{

    /**
     * @var Canvas
     */
    protected $_canvas;

    function __construct(Canvas $canvas)
    {
        $this->_canvas = $canvas;
    }

    function evaluate($code, $vars = array())
    {
        if (!$this->_canvas->get_dompdf()->get_option("enable_php")) {
            return;
        }

        // Set up some variables for the inline code
        $pdf = $this->_canvas;
        $PAGE_NUM = $pdf->get_page_number();
        $PAGE_COUNT = $pdf->get_page_count();

        // Override those variables if passed in
        foreach ($vars as $k => $v) {
            $$k = $v;
        }

        //$code = html_entity_decode($code); // @todo uncomment this when tested
        eval($code);
    }

    function render(Frame $frame)
    {
        $this->evaluate($frame->get_node()->nodeValue);
    }
}

<?php
/**
 * @package dompdf
 * @link    http://dompdf.github.com/
 * @author  Benj Carson <benjcarson@digitaljunkies.ca>
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
 */
namespace Dompdf;

use Dompdf\Frame;

/**
 * Executes inline PHP code during the rendering process
 *
 * @package dompdf
 */
class PhpEvaluator
{

    /**
     * @var Canvas
     */
    protected $_canvas;

    function __construct(Canvas $canvas)
    {
        $this->_canvas = $canvas;
    }

    function evaluate($code, $vars = array())
    {
        if (!$this->_canvas->get_dompdf()->get_option("enable_php")) {
            return;
        }

        // Set up some variables for the inline code
        $pdf = $this->_canvas;
        $fontMetrics = $pdf->get_dompdf()->getFontMetrics();
        $PAGE_NUM = $pdf->get_page_number();
        $PAGE_COUNT = $pdf->get_page_count();

        // Override those variables if passed in
        foreach ($vars as $k => $v) {
            $$k = $v;
        }

        //$code = html_entity_decode($code); // @todo uncomment this when tested
        eval($code);
    }

    function render(Frame $frame)
    {
        $this->evaluate($frame->get_node()->nodeValue);
    }
}

Make FontMetrics available to inline script as $fontMetrics

Since the FontMetrics class is no longer designed to be used statically a user must instantiate their own copy or reuse the one instantiated by dompdf. While not overly difficult to instantiate
(see load_font.php) there will be less friction and easier migration for the end user if we provide access to the instance used by dompdf.


<?php

namespace Axllent\Gfmarkdown\FieldTypes;

use Parsedown;
use SilverStripe\ORM\FieldType\DBText;

class Markdown extends DBText
{
    public static $casting = array(
        'AsHTML' => 'HTMLText',
        'Markdown' => 'Text'
    );

    public static $escape_type = 'xml';

    private static $options = [];

    /**
     * Render markdown as HTML using Parsedown
     *
     * @return string Markdown rendered as HTML
     */
    public function AsHTML()
    {
        $parsedown = new Parsedown();
        $options = $this->config()->get('options');
        foreach ($options as $fn => $param) {
            if (method_exists($parsedown, $fn)) {
                $parsedown->{$fn}($param);
            }
        }
        return $parsedown->text($this->value);
    }

    /**
     * Renders the field used in the template
     * @return string HTML to be used in the template
     */
    public function forTemplate()
    {
        return $this->AsHTML();
    }
}

<?php

namespace Axllent\Gfmarkdown\FieldTypes;

use Parsedown;
use SilverStripe\ORM\FieldType\DBText;

class Markdown extends DBText
{
    private static $casting = array(
        'AsHTML' => 'HTMLText',
        'Markdown' => 'Text'
    );

    private static $escape_type = 'xml';

    /**
     * Render markdown as HTML using Parsedown
     *
     * @return string Markdown rendered as HTML
     */
    public function AsHTML()
    {
        $parsedown = new Parsedown();
        $options = $this->config()->get('options');
        foreach ($options as $fn => $param) {
            if (method_exists($parsedown, $fn)) {
                $parsedown->{$fn}($param);
            }
        }
        return $parsedown->text($this->value);
    }

    /**
     * Renders the field used in the template
     * @return string HTML to be used in the template
     */
    public function forTemplate()
    {
        return $this->AsHTML();
    }
}

Change static variables to private

Change static variables to private


<?php

namespace BestIt\Mage\Tasks\Release;

use Mage\Task\BuiltIn\Deploy\Release\PrepareTask as MagePrepareTask;

/**
 * Class PrepareTask
 *
 * @author Ahmad El-Bardan <ahmad.el-bardan@bestit-online.de>
 * @package BestIt\Mage\Tasks\Release
 */
class PrepareTask extends MagePrepareTask
{
    /**
     * Executes the task.
     *
     * @return bool
     */
    public function execute()
    {
        $hostPath = rtrim($this->runtime->getEnvOption('host_path'), '/');
        $releaseId = $this->runtime->getReleaseId();

        $cmdMakeDir = sprintf(
            'cp -rp %s/current/ %s/releases/%s',
            $hostPath,
            $hostPath,
            $releaseId
        );

        $process = $this->runtime->runRemoteCommand($cmdMakeDir, false);
        return $process->isSuccessful();
    }
}

<?php

namespace BestIt\Mage\Tasks\Release;

use Mage\Task\BuiltIn\Deploy\Release\PrepareTask as MagePrepareTask;

/**
 * Class PrepareTask
 *
 * @author Ahmad El-Bardan <ahmad.el-bardan@bestit-online.de>
 * @package BestIt\Mage\Tasks\Release
 */
class PrepareTask extends MagePrepareTask
{
    /**
     * Executes the task.
     *
     * @return bool
     */
    public function execute()
    {
        $hostPath = rtrim($this->runtime->getEnvOption('host_path'), '/');
        $releaseId = $this->runtime->getReleaseId();

        $cmdMakeDir = sprintf(
            'cp -rp %s/current/ %s/releases/%s',
            $hostPath,
            $hostPath,
            $releaseId
        );

        $process = $this->runtime->runRemoteCommand($cmdMakeDir, false, 300);
        return $process->isSuccessful();
    }
}

Increase prepare timeout to 300 seconds.


<?php

/**
 * This autoloader is deprecated; please use the bootstrap.php file directly.
 *
 * Usage - see the following example.
 *
 *   https://github.com/Learnosity/learnosity-sdk-php/examples/index.php
 *
 */

$bootstrap = __DIR__ . '/../../bootstrap.php';
error_log('Warning: using ' . __DIR__ . '/autoload.php is deprecated. ' .
          "Please used `require_once '" . realpath($bootstrap) . "';` instead.");
require_once $bootstrap;

<?php

/**
 * This autoloader is deprecated; please use the bootstrap.php file directly.
 *
 * Usage - see the following example.
 *
 *   https://github.com/Learnosity/learnosity-sdk-php/examples/index.php
 *
 */

$bootstrap = __DIR__ . '/../../bootstrap.php';
error_log('Warning: using ' . __DIR__ . '/autoload.php is deprecated. ' .
          "Please use `require_once '" . realpath($bootstrap) . "';` instead.");
require_once $bootstrap;

Fix typo in error message

[POLISH] Fix typo in error message


<?php

namespace Omnipay\Square\Message;

use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RedirectResponseInterface;

/**
* Square Purchase Response
*/
class ChargeResponse extends AbstractResponse implements RedirectResponseInterface
{

    public function isSuccessful()
    {
        if ($this->data['status'] == 'success') {
            return true;
        } else {
            return false;
        }
    }

    public function isRedirect()
    {
        return false;
    }

    public function getRedirectUrl()
    {
        return "";
    }

    public function getRedirectMethod()
    {
        return "";
    }

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

    public function getTransactionId()
    {
        return $this->data['transactionId'];
    }

    public function getTenders()
    {
        return $this->data['tenders'];
    }

    public function getOrderId()
    {
        return $this->data['orderId'];
    }

    public function getCreatedAt()
    {
        return $this->data['created_at'];
    }

    public function getReferenceId()
    {
        return $this->data['referenceId'];
    }

    public function getMessage()
    {
        $message = '';
        if (strlen($this->data['code'])) {
            $message .= $this->data['code'] . ': ';
        }
        return $message . $this->data['error'];
    }
}

<?php

namespace Omnipay\Square\Message;

use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RedirectResponseInterface;

/**
* Square Purchase Response
*/
class ChargeResponse extends AbstractResponse implements RedirectResponseInterface
{

    public function isSuccessful()
    {
        if ($this->data['status'] == 'success') {
            return true;
        } else {
            return false;
        }
    }

    public function isRedirect()
    {
        return false;
    }

    public function getRedirectUrl()
    {
        return "";
    }

    public function getRedirectMethod()
    {
        return "";
    }

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

    public function getTransactionId()
    {
        return $this->data['transactionId'];
    }

    public function getTenders()
    {
        return $this->data['tenders'];
    }

    public function getOrderId()
    {
        return $this->data['orderId'];
    }

    public function getCreatedAt()
    {
        return $this->data['created_at'];
    }

    public function getReferenceId()
    {
        return $this->data['referenceId'];
    }

    public function getMessage()
    {
        $message = '';
        if (isset($this->data['code'])) {
            $message .= $this->data['code'] . ': ';
        }

        return $message . ($this->data['error'] ?? '');
    }
}

Fix 'undefined index `code`' error

Fix 'undefined index `code`' error


<?php namespace Pingpong\Themes;

use Illuminate\Filesystem\Filesystem;
use Pingpong\Modules\Json;
use Symfony\Component\Finder\Finder as SymfonyFinder;

class Finder {

    /**
     * The symfony finder instance.
     *
     * @var SymfonyFinder
     */
    protected $finder;

    /**
     * The constructor.
     *
     * @param $finder SymfonyFinder
     */
    public function __construct(SymfonyFinder $finder = null)
    {
        $this->finder = $finder ?: new SymfonyFinder;
    }

    /**
     * Find the specified theme by searching a 'theme.json' file as identifier.
     *
     * @param  string $path
     * @param  string $filename
     * @return array
     */
    public function find($path, $filename = 'theme.json')
    {
        $themes = [];

        if(is_dir($path))
        {
            $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks();

            foreach ($found as $file) $themes[] = new Theme($this->getInfo($file));
        }

        return $themes;
    }

    /**
     * Get theme info from json file.
     *
     * @param  SplFileInfo $file
     * @return array
     */
    protected function getInfo($file)
    {
        return Json::make($file->getRealPath())->toArray();
    }

}

<?php namespace Pingpong\Themes;

use Illuminate\Filesystem\Filesystem;
use Pingpong\Modules\Json;
use Symfony\Component\Finder\Finder as SymfonyFinder;

class Finder {

    /**
     * The symfony finder instance.
     *
     * @var SymfonyFinder
     */
    protected $finder;

    /**
     * The constructor.
     *
     * @param $finder SymfonyFinder
     */
    public function __construct(SymfonyFinder $finder = null)
    {
        $this->finder = $finder ?: new SymfonyFinder;
    }

    /**
     * Find the specified theme by searching a 'theme.json' file as identifier.
     *
     * @param  string $path
     * @param  string $filename
     * @return array
     */
    public function find($path, $filename = 'theme.json')
    {
        $themes = [];

        if(is_dir($path))
        {
            $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks();

            foreach ($found as $file) $themes[] = new Theme($this->getInfo($file));
        }

        return $themes;
    }

    /**
     * Get theme info from json file.
     *
     * @param  SplFileInfo $file
     * @return array
     */
    protected function getInfo($file)
    {
        $attributes = Json::make($path = $file->getRealPath())->toArray();

        $attributes['path'] = dirname($path);

        return $attributes;
    }

}

Add path to theme attributes

Add path to theme attributes


<?php
class Controller {
	var $layout = 'default';

	public function load_view($view) {
		require(VIEW_DIR . '/' . $view . '.php');
	}

	public function back_with_message($message = '') {
		alert($message);
		back();
	}

	public function back() {
		echo '"<script type="text/javascript">history.back();</script>';
	}

	public function redirect_to($where) {
		echo '<meta http-equiv="refresh" content="0; URL=' . $where . '">';
	}
}

<?php
class Controller {
	var $layout = 'default';

	public function load_view($view) {
		require(VIEW_DIR . '/' . $view . '.php');
	}

	public function back() {
		echo '"<script type="text/javascript">history.back();</script>';
	}

	public function redirect_to($where) {
		echo '<meta http-equiv="refresh" content="0; URL=' . $where . '">';
	}
}

Remove back_with_message function for using flash data structure

git-svn-id: ee4035a36106ffeee36a50f38a2c987ce3004d33@131 cc3e2240-c383-0410-974a-c2160eca7f04


<?php
/**
 * HiDev plugin for license generation.
 *
 * @link      https://github.com/hiqdev/hidev-license
 * @package   hidev-license
 * @license   BSD-3-Clause
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
 */

return [
    'controllerMap' => [
        'LICENSE' => [
            'class' => \hidev\license\console\LicenseController::class,
        ],
    ],
    'components' => [
        'license' => [
            'class' => \hidev\license\components\License::class,
        ],
        'view' => [
            'theme' => [
                'pathMap' => [
                    '@hidev/views' => ['@hidev/license/views'],
                ],
            ],
        ],
    ],
];

<?php
/**
 * HiDev plugin for license generation.
 *
 * @link      https://github.com/hiqdev/hidev-license
 * @package   hidev-license
 * @license   BSD-3-Clause
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
 */

return [
    'controllerMap' => [
        'LICENSE' => [
            'class' => \hidev\license\console\LicenseController::class,
        ],
    ],
    'components' => [
        'license' => [
            'class' => \hidev\license\components\License::class,
        ],
        'view' => [
            'theme' => [
                'pathMap' => [
                    '@hidev/views' => [dirname(__DIR__) . '/src/views'],
                ],
            ],
        ],
    ],
];

Use real path for views instead of alias


<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Zip Address Util</title>
    <link rel="stylesheet" href="/assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="/assets/css/bootstrap-theme.min.css">

Zip Address Util

<form name="search_form" method="get" action="/address/result">
    <button>検索</button>
</form>

    <?php if (isset($results)) {
        foreach ($results as $addr) {
            /** @var App\Models\Address $addr */
            echo '
' . $addr->getWholeAddress() . '
';
        }
    } ?>
    <input type="text" name="search" title="search" id="search"
                   value=<?php
                   /** @var string $searchWord */
                   if (isset($searchWord)) {
                       echo $searchWord;
                   } ?>
            >

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Zip Address Util</title>
    <link rel="stylesheet" href="/assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="/assets/css/bootstrap-theme.min.css">

    <?php if (isset($results)) {
        foreach ($results as $addr) {
            /** @var App\Models\Address $addr */
            echo '
' . $addr->getWholeAddress() . '
';
        }
    } ?>

Zip Address Util

        <form name="search_form" method="get" action="/address/result" class="col-lg-6 col-lg-offset-3">
            <input type="text" class="input-sm col-lg-6" name="search" title="search" id="search"
                   value=<?php
                   /** @var string $searchWord */
                   if (isset($searchWord)) {
                       echo $searchWord;
                   } ?>
            >
            <button class="btn btn-success col-lg-2 glyphicon-search">検索</button>
        </form>

Apply Bootstrap on search form.

Apply Bootstrap on search form.


<?php

const APP_SECRET = '';
const PAGE_ACCESS_TOKEN = '';
const VALIDATION_TOKEN = '';
const SERVER_URL = '';

<?php

// App Secret can be retrieved from the App Dashboard
const APP_SECRET = '';

// Arbitrary value used to validate a webhook
const PAGE_ACCESS_TOKEN = '';

// Generate a page access token for your page from the App Dashboard
const VALIDATION_TOKEN = '';

// URL where the app is running (include protocol). Used to point to scripts and
// assets located at this address.
const SERVER_URL = '';

Add description for config values

Add description for config values


<?php
    # Read GET variables
    $stime = $_POST['stime'];
    $etime = $_POST['etime'];
    $moves = $_POST['moves'];

    # Create output string
    $str = "\"$stime\", \"$etime\", \"$moves\"\n";

    $fh = fopen("postData.txt", "a+");
    fwrite($fh, $str);
    fclose($fh);

    echo $str;
    echo "done";
?>

<?php
    # Database variables
    $dbhost = 'localhost:3036'
    $dbuser = 'c0smic_tyro'
    $dbpass = '2$M*k^4!?oDm'

    # Read GET variables
    $stime = $_POST['stime'];
    $etime = $_POST['etime'];
    $moves = $_POST['moves'];

    # Create output string
    $str = "$stime, $etime, \"$moves\"";

    $conn = mysql_connect($dbhost, $dbuser, $dbpass);
    if(! $conn )
    {
        die('Could not connect: ' . mysql_error());
    }

    mysql_select_db('c0smic_maze-game');

    $sql= "INSERT INTO data (stime, etime, moves)
    VALUES
    ('$stime','$etime','$moves')";

    $retval = mysql_query( $sql, $conn );
    if(! $retval )
    {
        die('Could not enter data: ' . mysql_error());
    }

    mysql_close($conn);
    echo $str;

?>

Add MySQL db connection code

Add MySQL db connection code


<?php

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

class CreateChannelTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('channels', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 64);
            $table->string('password');
            $table->unsignedInteger('creator_id')->index();
            $table->boolean('hidden')->default(false);
            $table->string('image_url');
            $table->timestamps();

            $table->foreign('creator_id')->references('id')->on('users')->onDelete('cascade');

        });
    }

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

<?php

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

class CreateChannelTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('channels', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 64);
            $table->string('password')->nullable();
            $table->unsignedInteger('creator_id')->index();
            $table->boolean('hidden')->default(false);
            $table->string('image_url')->nullable();
            $table->timestamps();

            $table->foreign('creator_id')->references('id')->on('users')->onDelete('cascade');

        });
    }

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

Make nullable fields in channels schema

[*] Make nullable fields in channels schema


[ [COMPONENT name=MenuLanguages]]

[[COMPONENT name=Image style=height:60 id=1]]

[[COMPONENT name=Label text=Título id=title]]

[[COMPONENT name=Label text=Subtítulo id=subtitle]]

			[[COMPONENT name=Breadcrumb]]

			[[COMPONENT name=Menu]]

			[[BODY]]

		© 2012
		Powered By TreeWeb

[[COMPONENT name=Image id=logo style=height:60]]

[[COMPONENT name=Label text=Título id=title]]

[[COMPONENT name=Label text=Subtítulo id=subtitle]]

			[[COMPONENT name=Breadcrumb]]

			[[COMPONENT name=Menu]]

			[[BODY]]

		© 2012
		Powered By TreeWeb

Remove languages from Pencil and update logo image


<?php

namespace PerFi\PerFiBundle\Repository;

use Doctrine\ORM\EntityRepository;
use PerFi\Domain\Account\Account;
use PerFi\Domain\Account\AccountRepository as AccountRepositoryInterface;

/**
 * AccountRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class AccountRepository extends EntityRepository
    implements AccountRepositoryInterface
{
    public function add(Account $account)
    {
    }

    public function getAll() : array
    {
        return [];
    }
}

<?php

namespace PerFi\PerFiBundle\Repository;

use Doctrine\ORM\EntityRepository;
use PerFi\Domain\Account\Account;
use PerFi\Domain\Account\AccountRepository as AccountRepositoryInterface;
use PerFi\PerFiBundle\Entity;

/**
 * AccountRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class AccountRepository extends EntityRepository
    implements AccountRepositoryInterface
{
    public function add(Account $account)
    {
        $entity = new Entity\Account();
        $entity->setAccountId((string) $account->id());

        $em = $this->getEntityManager();
        $em->persist($entity);
        $em->flush();
    }

    public function getAll() : array
    {
        return [];
    }
}

Save account entity to the database

Save account entity to the database


<?php namespace Octommerce\Octommerce\Models;

use Model;
use System\Models\MailTemplate;
// use Octommerce\Octommerce\Models\Order;

/**
 * OrderStatus Model
 */
class OrderStatus extends Model
{
    use \October\Rain\Database\Traits\SimpleTree;

    const PARENT_ID = 'parent_code';

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

    public $timestamps = false;

    public $primaryKey = 'code';

    /**
     * @var array Guarded fields
     */
    protected $guarded = ['*'];

    /**
     * @var array Fillable fields
     */
    protected $fillable = [];

    /**
     * @var array Relations
     */
    public $hasOne = [];
    public $hasMany = [
        'orders' => [
            'Octommerce\Octommerce\Models\Order',
            'key' => 'status_code',
            'otherKey' => 'code'
        ]
    ];
    public $belongsTo = [
        'mail_template'       => 'System\Models\MailTemplate',
        'admin_mail_template' => 'System\Models\MailTemplate',
    ];
    public $belongsToMany = [];
    public $morphTo = [];
    public $morphOne = [];
    public $morphMany = [];
    public $attachOne = [];
    public $attachMany = [];

}

<?php namespace Octommerce\Octommerce\Models;

use Model;
use System\Models\MailTemplate;
// use Octommerce\Octommerce\Models\Order;

/**
 * OrderStatus Model
 */
class OrderStatus extends Model
{
    use \October\Rain\Database\Traits\SimpleTree;

    const PARENT_ID = 'parent_code';

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

    public $timestamps = false;

    public $incrementing = false;

    protected $primaryKey = 'code';

    /**
     * @var array Guarded fields
     */
    protected $guarded = ['*'];

    /**
     * @var array Fillable fields
     */
    protected $fillable = [];

    /**
     * @var array Relations
     */
    public $hasOne = [];
    public $hasMany = [
        'orders' => [
            'Octommerce\Octommerce\Models\Order',
            'key' => 'status_code',
            'otherKey' => 'code'
        ]
    ];
    public $belongsTo = [
        'mail_template'       => 'System\Models\MailTemplate',
        'admin_mail_template' => 'System\Models\MailTemplate',
    ];
    public $belongsToMany = [];
    public $morphTo = [];
    public $morphOne = [];
    public $morphMany = [];
    public $attachOne = [];
    public $attachMany = [];

}

Fix getting "0" value on order status primary key


<?php

class RoboFile extends \Robo\Tasks {

  use DigipolisGent\Robo\Task\DrupalConsole\loadTasks;

  public function test() {
    $this->stopOnFail(true);
    $this->taskPHPUnit()
      ->option('disallow-test-output')
      ->option('report-useless-tests')
      ->option('strict-coverage')
      ->option('-v')
      ->option('-d error_reporting=-1')
      ->arg('tests')
      ->run();
  }

}

Fix coding style in Robofile.php

Fix coding style in Robofile.php


<?php

/*
 * Plugin Name: Hyyan WooCommerce Polylang Integration
 * Plugin URI: https://github.com/hyyan/woo-poly-integration/
 * Description: Integrates Woocommerce with Polylang
 * Author: Hyyan Abo Fakher
 * Author URI: https://github.com/hyyan
 * Text Domain: woo-poly-integration
 * Domain Path: /languages
 * GitHub Plugin URI: hyyan/woo-poly-integration
 * License: MIT License
 * Version: 0.26.2 (Not Released)
 */

/**
 * This file is part of the hyyan/woo-poly-integration plugin.
 * (c) Hyyan Abo Fakher <tiribthea4hyyan@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
if (!defined('ABSPATH')) {
    exit('restricted access');
}

define('Hyyan_WPI_DIR', __FILE__);
define('Hyyan_WPI_URL', plugin_dir_url(__FILE__));

require_once ABSPATH . 'wp-admin/includes/plugin.php';
require_once __DIR__ . '/vendor/class.settings-api.php';
require_once __DIR__ . '/src/Hyyan/WPI/Autoloader.php';

/* register the autoloader */
new Hyyan\WPI\Autoloader(__DIR__ . '/src/');

/* bootstrap the plugin */
new Hyyan\WPI\Plugin();

<?php

/*
 * Plugin Name: Hyyan WooCommerce Polylang Integration
 * Plugin URI: https://github.com/hyyan/woo-poly-integration/
 * Description: Integrates Woocommerce with Polylang
 * Author: Hyyan Abo Fakher
 * Author URI: https://github.com/hyyan
 * Text Domain: woo-poly-integration
 * Domain Path: /languages
 * GitHub Plugin URI: hyyan/woo-poly-integration
 * License: MIT License
 * Version: 0.27
 */

/**
 * This file is part of the hyyan/woo-poly-integration plugin.
 * (c) Hyyan Abo Fakher <tiribthea4hyyan@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
if (!defined('ABSPATH')) {
    exit('restricted access');
}

define('Hyyan_WPI_DIR', __FILE__);
define('Hyyan_WPI_URL', plugin_dir_url(__FILE__));

require_once ABSPATH . 'wp-admin/includes/plugin.php';
require_once __DIR__ . '/vendor/class.settings-api.php';
require_once __DIR__ . '/src/Hyyan/WPI/Autoloader.php';

/* register the autoloader */
new Hyyan\WPI\Autoloader(__DIR__ . '/src/');

/* bootstrap the plugin */
new Hyyan\WPI\Plugin();

Update plugin version to 0.27

Misc: Update plugin version to 0.27


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Type extends Model
{
    public function categories()
    {
        return $this->hasMany('App\Category');
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Type extends Model
{
    public function categories()
    {
        return $this->hasMany('App\Category');
    }
    public function shop()
    {
        retrun $this->belongTo('App\Shop')
    }
}

Create relationship for types table

feat(type): Create relationship for types table

Create relationship for types table

see #137


Entregar Permisos Portafolio

	<a href="<?php echo base_url()?>portafolio">Volver

<?php
	if ($this->session->flashdata('ControllerMessage')!='') {
?>

<?php echo $this->session->flashdata('ControllerMessage'); ?>

<?php
	}
?>

<?php
$atributos = array('id'=>'nuevopermiso','name'=>'nuevopermiso');
echo form_open_multipart(null,$atributos);
?>

Nombre

<select id="permisoid" name="permisoid">
	<?php
		foreach ($permisos as $per)
		{
	?>
			<option value="<?php echo $per->PER_ID ?>"><?php echo $per->PER_DESCRIPCION ?></option>
	<?php
		}
	?>
</select>
<input type="hidden" id="id" name="id" value="<?php echo $id ?>">

<input type="submit" value="Agregar Permiso"/>
<?php
echo form_close();
?>

Entregar Permisos Portafolio

	<a href="<?php echo base_url()?>portafolio">Volver

<?php
	if ($this->session->flashdata('ControllerMessage')!='') {
?>

<?php echo $this->session->flashdata('ControllerMessage'); ?>

<?php
	}
?>

<?php
$atributos = array('id'=>'nuevopermiso','name'=>'nuevopermiso');
echo form_open_multipart(null,$atributos);
?>

Nombre

<input type="text" id="usuarioid" name="usuarioid" placeholder="Ingresa el ID del usuario a agregar!" required/>

<select id="permisoid" name="permisoid">
	<?php
		foreach ($permisos as $per)
		{
	?>
			<option value="<?php echo $per->PER_ID ?>"><?php echo $per->PER_DESCRIPCION ?></option>
	<?php
		}
	?>
</select>
<input type="hidden" id="id" name="id" value="<?php echo $id ?>">

<input type="submit" value="Agregar Permiso"/>
<?php
echo form_close();
?>

Fix vista de nuevo permiso por portafolio


<?php

$this->data['header'] = 'Cron information page';
$this->includeAtTemplateBase('includes/header.php');

?>

Cron is a way to run things regularly on unix systems.

Here is a suggestion for a crontab file:

<?php

		foreach ($this->data['urls'] AS $url ) {
			echo "# " . $url['title'] . "\n";
			echo "" . $url['int'] . " curl --silent --compressed " . $url['href'] . " > /dev/null 2>&1\n";
		}

		?>

Click here to run the cron jobs:

		<?php

		foreach ($this->data['urls'] AS $url ) {
			echo '
' . $url['title'] . '
';
		}

		?>

<?php
$this->includeAtTemplateBase('includes/footer.php');
?>

<?php

$this->data['header'] = 'Cron information page';
$this->includeAtTemplateBase('includes/header.php');

?>

Cron is a way to run things regularly on unix systems.

Here is a suggestion for a crontab file:

<?php

		foreach ($this->data['urls'] AS $url ) {
			echo "# " . $url['title'] . "\n";
			echo "" . $url['int'] . " curl --silent \"" . $url['href'] . "\" > /dev/null 2>&1\n";
		}

		?>

Click here to run the cron jobs:

		<?php

		foreach ($this->data['urls'] AS $url ) {
			echo '
' . $url['title'] . '
';
		}

		?>

<?php
$this->includeAtTemplateBase('includes/footer.php');
?>

Add quotes to cron information page, for the example crontab file

git-svn-id: a243b28a2a52d65555a829a95c8c333076d39ae1@1012 44740490-163a-0410-bde0-09ae8108e29a


<?php

/**
 * Class wpAPIDateTime
 *
 * @package wpAPI\Core\Elements\wpAPIDateTime
 */
class wpAPIDateTime extends BaseElement
{

    function __construct($id, $label,  $permissions=[], $elementPath='')
    {
        parent::__construct($id, $label, $permissions, $elementPath);
    }

    function ReadView($post)
    {
        echo $this->twigTemplate->render('/read_view.mustache', ["value" => $this->GetDatabaseValue($post)]);
    }

    function EditView( $post)
    {
       parent::EditView($post);
       echo $this->twigTemplate->render('/edit_view.mustache', [
           "id" => $this->id,
           "value" => $this->GetDatabaseValue($post)
       ]);
    }

    function ProcessPostData($post_id)
    {
        parent::ProcessPostData($post_id);
        $data = sanitize_text_field($_POST[$this->id]);

        $this->SaveElementData($post_id, $data);

    }
}

<?php

/**
 * Class wpAPIDateTime
 *
 * @package wpAPI\Core\Elements\wpAPIDateTime
 */
class wpAPIDateTime extends BaseElement
{

    function __construct($id, $label,  $permissions=[], $elementPath='')
    {
        parent::__construct($id, $label, $permissions, $elementPath);
    }

    function ReadView($post)
    {
        echo $this->twigTemplate->render('/read_view.mustache', ["value" => $this->GetDatabaseValue($post)]);
    }

    function EditView( $post)
    {
       parent::EditView($post);
       $db_dateTime = $this->GetDatabaseValue($post) == null ?  date("Y-m-d\TH:i:s", time()) : $this->GetDatabaseValue($post);

       echo $this->twigTemplate->render('/edit_view.mustache', [
           "id" => $this->id,
           "value" => $db_dateTime
       ]);
    }

    function ProcessPostData($post_id)
    {
        parent::ProcessPostData($post_id);
        $data = sanitize_text_field($_POST[$this->id]);

        $this->SaveElementData($post_id, $data);

    }
}

Update datatime control, setting default time