<?php
namespace Dkd\PhpCmis\Enum;

/**
 * This file is part of php-cmis-lib.
 *
 * (c) Sascha Egerer <sascha.egerer@dkd.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Dkd\Enumeration\Enumeration;

/**
 * Binding Type Enum.
 */
final class BindingType extends Enumeration
{
    const ATOMPUB = 'atompub';
    const BROWSER = 'browser';
    const CUSTOM = 'custom';
    const LOCAL = 'local';
    const WEBSERVICES = 'webservices';
}

<?php
namespace Dkd\PhpCmis\Enum;

/**
 * This file is part of php-cmis-lib.
 *
 * (c) Sascha Egerer <sascha.egerer@dkd.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Dkd\Enumeration\Enumeration;

/**
 * Binding Type Enum.
 */
final class BindingType extends Enumeration
{
    const ATOMPUB = 'atompub';
    const BROWSER = 'browser';
    const CUSTOM = 'custom';
    const WEBSERVICES = 'webservices';
}

Remove binding type local from enumeration

Summary:
Remove the binding type local from
the enumeration `BindingType` because it is
not required in the php implementation.

Reviewers: claus.due, #forgetit-dev

Reviewed By: claus.due, #forgetit-dev

Differential Revision: https://phabricator.dkd.de/D263


<?php

return [

    /*
     |--------------------------------------------------------------------------
     | Laravel CORS Defaults
     |--------------------------------------------------------------------------
     |
     | The defaults are the default values applied to all the paths that match,
     | unless overridden in a specific URL configuration.
     | If you want them to apply to everything, you must define a path with *.
     |
     | allowedOrigins, allowedHeaders and allowedMethods can be set to ['*']
     | to accept any value, the allowed methods however have to be explicitly listed.
     |
     */
    'defaults' => [
        'supportsCredentials' => true,
        'allowedOrigins'      => [],
        'allowedHeaders'      => [],
        'allowedMethods'      => [],
        'exposedHeaders'      => [],
        'maxAge'              => 0,
        'hosts'               => [],
    ],

    'paths' => [
        'api/v1/*' => [
            'allowedOrigins' => [],
            'allowedHeaders' => ['X-Cachet-Token'],
            'allowedMethods' => ['*'],
            'maxAge'         => 3600,
        ],
    ],

];

<?php

return [

    /*
     |--------------------------------------------------------------------------
     | Laravel CORS Defaults
     |--------------------------------------------------------------------------
     |
     | The defaults are the default values applied to all the paths that match,
     | unless overridden in a specific URL configuration.
     | If you want them to apply to everything, you must define a path with *.
     |
     | allowedOrigins, allowedHeaders and allowedMethods can be set to ['*']
     | to accept any value, the allowed methods however have to be explicitly listed.
     |
     */
    'defaults' => [
        'supportsCredentials' => true,
        'allowedOrigins'      => ['*'],
        'allowedHeaders'      => [],
        'allowedMethods'      => [],
        'exposedHeaders'      => [],
        'maxAge'              => 0,
        'hosts'               => [],
    ],

    'paths' => [
        'api/v1/*' => [
            'allowedOrigins' => [],
            'allowedHeaders' => ['X-Cachet-Token'],
            'allowedMethods' => ['*'],
            'maxAge'         => 3600,
        ],
    ],

];

Allow all origins by default

Allow all origins by default


<?php
/**
 * This file is part of the CnetSync package.
 *
 * (c) Dries De Peuter <dries@nousefreak.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace CnetSync\Configuration;

/**
 * @author Dries De Peuter <dries@nousefreak.be>
 */
class Configuration
{
    /**
     * @var string
     */
    protected $apiUrl = 'http://build.uitdatabank.be/api';

    /**
     * @var string
     */
    protected $collectionType = 'events';

    /**
     * @var string
     */
    protected $method = 'xmlview';

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

    /**
     * @var array
     */
    protected $params = array();

    /**
     * @param  int    $page
     * @return string
     */
    public function buildApiUrl($page)
    {
        $params = $this->params;

        $params['page'] = $page;
        $params['key'] = $this->apiKey;

        return $this->apiUrl .'/' . $this->collectionType . '/' . $this->method . '?' . http_build_query($params);
    }

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

<?php
/**
 * This file is part of the CnetSync package.
 *
 * (c) Dries De Peuter <dries@nousefreak.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace CnetSync\Configuration;

/**
 * @author Dries De Peuter <dries@nousefreak.be>
 */
class Configuration
{
    /**
     * @var string
     */
    protected $apiUrl = 'http://build.uitdatabank.be/api';

    /**
     * @var string
     */
    protected $collectionType = 'events';

    /**
     * @var string
     */
    protected $method = 'xmlview';

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

    /**
     * @var array
     */
    protected $params = array();

    /**
     * @param  int    $page
     * @return string
     */
    public function buildApiUrl($page)
    {
        $params = $this->params;

        $params['page'] = $page;
        $params['key'] = $this->apiKey;

        return $this->apiUrl .'/' . $this->collectionType . '/' . $this->method . '?' . http_build_query($params);
    }

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

	/**
	 * @param string $name
	 * @param string $value
	 */
	public function setParam($name, $value)
	{
		$this->params[$name] = $value;
	}
}

Add setParam to limit the query results

Add setParam to limit the query results


<?php

namespace CultuurNet\UDB3\Event\ValueObjects;

class AudienceTypeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function it_has_specified_options()
    {
        $options = AudienceType::getConstants();

        $this->assertEquals(
            [
                AudienceType::EVERYONE()->getName() => AudienceType::EVERYONE(),
                AudienceType::MEMBERS()->getName() => AudienceType::MEMBERS(),
                AudienceType::EDUCATION()->getName() => AudienceType::EDUCATION(),
            ],
            $options
        );
    }
}

<?php

namespace CultuurNet\UDB3\Event\ValueObjects;

class AudienceTypeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function it_should_instantiate_audience_type_enums_by_a_name()
    {
        $options = AudienceType::getConstants();

        $this->assertEquals(
            [
                AudienceType::EVERYONE()->getName() => AudienceType::EVERYONE(),
                AudienceType::MEMBERS()->getName() => AudienceType::MEMBERS(),
                AudienceType::EDUCATION()->getName() => AudienceType::EDUCATION(),
            ],
            $options
        );
    }
}

III-1406: Rename audience type enum instantiation spec


<?php

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

namespace Symfony\Component\Finder\Tests;

use Symfony\Component\Finder\Glob;

class GlobTest extends \PHPUnit_Framework_TestCase
{

    public function testGlobToRegexDelimiters()
    {
        $this->assertEquals(Glob::toRegex('.*'), '#^\.[^/]*$#');
        $this->assertEquals(Glob::toRegex('.*', true, true, ''), '^\.[^/]*$');
        $this->assertEquals(Glob::toRegex('.*', true, true, '/'), '/^\.[^/]*$/');
    }
}

<?php

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

namespace Symfony\Component\Finder\Tests;

use Symfony\Component\Finder\Glob;

class GlobTest extends \PHPUnit_Framework_TestCase
{
    public function testGlobToRegexDelimiters()
    {
        $this->assertEquals('#^\.[^/]*$#', Glob::toRegex('.*'));
        $this->assertEquals('^\.[^/]*$', Glob::toRegex('.*', true, true, ''));
        $this->assertEquals('/^\.[^/]*$/', Glob::toRegex('.*', true, true, '/'));
    }
}

Fix param order of assertEquals (expected, actual) in test for Finder\Glob


<?php
/*
 * This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Mage\Task\BuiltIn\Symfony2;

use Mage\Task\BuiltIn\Symfony2\SymfonyAbstractTask;

/**
 * Task for Clearing the Cache
 *
 * @author Andrés Montañez <andres@andresmontanez.com>
 */
class CacheClearTask extends SymfonyAbstractTask
{
    /**
     * (non-PHPdoc)
     * @see \Mage\Task\AbstractTask::getName()
     */
    public function getName()
    {
        return 'Symfony v2 - Cache Clear [built-in]';
    }

    /**
     * Clears the Cache
     * @see \Mage\Task\AbstractTask::run()
     */
    public function run()
    {
        // Options
        $env = $this->getParameter('env', 'dev');

        $command = $this->getAppPath() . ' cache:clear --env=' . $env;
        $result = $this->runCommand($command);

        return $result;
    }
}

<?php
/*
 * This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Mage\Task\BuiltIn\Symfony2;

use Mage\Task\BuiltIn\Symfony2\SymfonyAbstractTask;

/**
 * Task for Clearing the Cache
 *
 * Example of usage:
 *    symfony2/cache-clear: { env: dev }
 *    symfony2/cache-clear: { env: dev, optional: --no-warmup }
 *
 * @author Andrés Montañez <andres@andresmontanez.com>
 * @author Samuel Chiriluta <samuel4x4@gmail.com>
 */
class CacheClearTask extends SymfonyAbstractTask
{
    /**
     * (non-PHPdoc)
     * @see \Mage\Task\AbstractTask::getName()
     */
    public function getName()
    {
        return 'Symfony v2 - Cache Clear [built-in]';
    }

    /**
     * Clears the Cache
     * @see \Mage\Task\AbstractTask::run()
     */
    public function run()
    {
        // Options
        $env = $this->getParameter('env', 'dev');
        $optional = $this->getParameter('optional', '');

        $command = $this->getAppPath() . ' cache:clear --env=' . $env . ' ' . $optional;

        $result = $this->runCommand($command);

        return $result;
    }
}

Add optional parameters for symfony2/cache-clear

Add optional parameters for symfony2/cache-clear task like --no-warmup.


			{if $wp->canCurrentUser(edit_posts) and $message == empty-site}
				{__ 'No posts to display'}
			{else}
				{__ 'Nothing Found'}
			{/if}

			{if $wp->canCurrentUser(edit_posts) and $message == empty-site}

				{!__ 'Ready to publish your first post? Get started here.' |printf:$wp->adminUrl('post-new.php')}

			{elseif $message == nothing-found}

				{__ 'Sorry, but nothing matched your search criteria. Please try again with some different keywords.'}

			{elseif $message == 'no-posts' or (!$wp->canCurrentUser(edit_posts) and $message == empty-site)}

				{__ 'Apologies, but no results were found. Perhaps searching will help find a related post.'}

			{/if}

			{searchForm}

Revert "We don't need wordpress to show us there are no posts yet!"

This reverts commit 6bde41c012291eed5acc3ddaa1217c9fb988ec09.


<?php

class MJPEGStream {

	function output($args) {
		$id = rand(0,100000);
		echo("");
	}

}

?>

<?php

class MJPEGStream {

	function output($args) {
		$id = rand(0,100000);
		echo("

			");
	}

}

?>

Make the MJPEG stream reload itself periodically in case the connection dies


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

require dirname(__DIR__) . '/vendor/autoload.php';

use Icicle\Coroutine;
use Icicle\Dns\Resolver\Resolver;
use Icicle\Loop;

if (2 > $argc) {
    throw new InvalidArgumentException('Too few arguments provided. Usage: {DomainName}');
}

$domain = $argv[1];

$coroutine = Coroutine\create(function ($query, $timeout = 1) {
    printf("Query: %s\n", $query);

    $resolver = new Resolver();

    $ips = yield $resolver->resolve($query, ['timeout' => $timeout]);

    foreach ($ips as $ip) {
        printf("IP: %s\n", $ip);
    }
}, $domain);

$coroutine->capture(function (Exception $e) {
    printf("Exception: %s\n", $e->getMessage());
});

Loop\run();

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

require dirname(__DIR__) . '/vendor/autoload.php';

use Icicle\Coroutine;
use Icicle\Dns\Resolver\Resolver;
use Icicle\Loop;

if (2 > $argc) {
    throw new InvalidArgumentException('Too few arguments provided. Usage: {DomainName}');
}

$domain = $argv[1];

$coroutine = Coroutine\create(function ($query, $timeout = 1) {
    printf("Query: %s\n", $query);

    $resolver = new Resolver();

    $ips = yield from $resolver->resolve($query, ['timeout' => $timeout]);

    foreach ($ips as $ip) {
        printf("IP: %s\n", $ip);
    }
}, $domain);

$coroutine->capture(function (Exception $e) {
    printf("Exception: %s\n", $e->getMessage());
});

Loop\run();

Change yield to yield from

Change yield to yield from

...because yield from does actually work with 2.0.x-dev and PHP 7. I'm sorry. :(


<?php

namespace PiradoIV\Munchitos\Test;

use \PiradoIV\Munchitos\Munchitos;

class ImagesTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();
        $this->html = <<<HTML
<!doctype html>

>
HTML;

        $this->munchitos = new Munchitos;
        $this->munchitos->html($this->html);
    }

    public function testCanFetchImages()
    {
        $images = $this->munchitos->images();
        $this->assertEquals(1, count($images));
    }

    public function testImagesAltText()
    {
        $images = $this->munchitos()->images();
        $this->assertEquals('Testing alt', $images[0]->altText());
    }
}

<?php

namespace PiradoIV\Munchitos\Test;

use \PiradoIV\Munchitos\Munchitos;

class ImagesTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();
        $this->html = <<<HTML
<!doctype html>

>
HTML;

        $this->munchitos = new Munchitos;
        $this->munchitos->html($this->html);
    }

    public function testCanFetchImages()
    {
        $images = $this->munchitos->images();
        $this->assertEquals(1, count($images));
    }

    public function testImagesAltText()
    {
        $images = $this->munchitos->images();
        $this->assertEquals('Testing alt', $images[0]->altText());
    }
}

Fix an error on the test

Fix an error on the test


<?php

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

/**
 * This class defines the frontend, it is the core. Everything starts here.
 * We create all needed instances.
 *
 * @author Tijs Verkoyen <tijs@sumocoders.be>
 */
class Frontend
{
	public function __construct()
	{
		$this->initializeFacebook();

		new FrontendURL();
		new FrontendTemplate();
		new FrontendPage();
	}

	/**
	 * Initialize Facebook
	 */
	private function initializeFacebook()
	{
		// get settings
		$facebookApplicationId = FrontendModel::getModuleSetting('core', 'facebook_app_id');
		$facebookApplicationSecret = FrontendModel::getModuleSetting('core', 'facebook_app_secret');

		// needed data available?
		if($facebookApplicationId != '' && $facebookApplicationSecret != '')
		{
			// require
			require_once 'external/facebook.php';

			// create instance
			$facebook = new Facebook($facebookApplicationSecret, $facebookApplicationId);

			// get the cookie, this will set the access token.
			$facebook->getCookie();

			// store in reference
			Spoon::set('facebook', $facebook);

			// trigger event
			FrontendModel::triggerEvent('core', 'after_facebook_initialization');
		}
	}
}

<?php

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

/**
 * This class defines the frontend, it is the core. Everything starts here.
 * We create all needed instances.
 *
 * @author Tijs Verkoyen <tijs@sumocoders.be>
 */
class Frontend
{
	public function __construct()
	{
		$this->initializeFacebook();

		new FrontendURL();
		new FrontendTemplate();
		new FrontendPage();
	}

	/**
	 * Initialize Facebook
	 */
	private function initializeFacebook()
	{
		// get settings
		$facebookApplicationId = FrontendModel::getModuleSetting('core', 'facebook_app_id');
		$facebookApplicationSecret = FrontendModel::getModuleSetting('core', 'facebook_app_secret');

		// needed data available?
		if($facebookApplicationId != '' && $facebookApplicationSecret != '')
		{
			$config = array(
				'appId' => $facebookApplicationId,
				'secret' => $facebookApplicationSecret,
			);

			// create instance
			$facebook = new Facebook($config);

			// grab the signed request, if a user is logged in the access token will be set
			$facebook->getSignedRequest();

			// store in reference
			Spoon::set('facebook', $facebook);

			// trigger event
			FrontendModel::triggerEvent('core', 'after_facebook_initialization');
		}
	}
}

Use the official Facebook SDK instead of our own.

More information on the official Facebook PHP SDK can be found on
(https://developers.facebook.com/docs/reference/php).


<?php
/**
 * Events - all standard Events are defined here.
 *
 * @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
 * @version 3.0
 */

use Support\Facades\Event;
use Core\View;
use Helpers\Hooks;
use Forensics\Console;

/** Define Events. */

// Add a Listener Class to the Event 'test'.
Event::listen('test', 'App\Events\Test@handle');

// Add a Listener Closure to the Event 'test'.
Event::listen('test', function($data) {
    return '
Closure : ' .var_export($data, true) .'
';
});

// Add a Listener Closure to the Event 'framework.controller.executing'.
Event::listen('framework.controller.executing', function($instance, $method, $params) {
    // Run the Hooks associated to the Views.
    $hooks = Hooks::get();

    foreach (array('afterBody', 'css', 'js') as $hook) {
        $result = $hooks->run($hook);

        // Share the result into Views.
        View::share($hook, $result);
    }
});

// Add a Listener Closure to the Event 'framework.controller.executing'.
Event::listen('framework.controller.executing', function($instance, $method, $params) {
    $className = get_class($instance);

    Console::log("Executing '$className@$method'");
});

<?php
/**
 * Events - all standard Events are defined here.
 *
 * @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
 * @version 3.0
 */

use Support\Facades\Event;
use Core\View;
use Helpers\Hooks;
use Forensics\Console;

/** Define Events. */

// Add a Listener Class to the Event 'test'.
Event::listen('test', 'App\Events\Test@handle');

// Add a Listener Closure to the Event 'test'.
Event::listen('test', function($data) {
    return '
Closure : ' .var_export($data, true) .'
';
});

// Add a Listener Closure to the Event 'framework.controller.executing'.
Event::listen('framework.controller.executing', function($instance, $method, $params) {
    // Run the Hooks associated to the Views.
    $hooks = Hooks::get();

    foreach (array('afterBody', 'css', 'js') as $hook) {
        $result = $hooks->run($hook);

        // Share the result into Views.
        View::share($hook, $result);
    }
});

// Add a Listener Closure to the Event 'nova.framework.booting'.
Event::listen('nova.framework.booting', function() {
    Console::logSpeed("Nova Framework booting");
});

// Add a Listener Closure to the Event 'framework.controller.executing'.
Event::listen('framework.controller.executing', function($instance, $method, $params) {
    $className = get_class($instance);

    Console::logSpeed("Executing '$className@$method'");
});

Add a example Listener for 'nova.framework.booting'


<?php
namespace Rudolf\Modules\Articles\Roll\Admin;

use Rudolf\Modules\A_admin\AdminController;
use Rudolf\Modules\Articles\Roll;
use Rudolf\Component\Libs\Pagination;

class Controller extends AdminController
{
    public function getList($page)
    {
        $page = $this->firstPageRedirect($page, 301, $location = '../../list');

        $list = new Roll\Model();

        $pagination = new Pagination($list->getTotalNumber(), $page);
        $results = $list->getList($pagination);

        $view = new View();

        $view->setData($results, $pagination);

        $view->setActive(['admin/articles', 'admin/articles/list']);

        $view->render('admin');
    }
}

<?php
namespace Rudolf\Modules\Articles\Roll\Admin;

use Rudolf\Modules\A_admin\AdminController;
use Rudolf\Modules\Articles\Roll;
use Rudolf\Component\Libs\Pagination;

class Controller extends AdminController
{
    public function getList($page)
    {
        $page = $this->firstPageRedirect($page, 301, $location = '../../list');

        $list = new Roll\Model();

        $pagination = new Pagination($list->getTotalNumber('1=1'), $page);
        $results = $list->getList($pagination);

        $view = new View();

        $view->setData($results, $pagination);

        $view->setActive(['admin/articles', 'admin/articles/list']);

        $view->render('admin');
    }
}

Fix articles list; now show all

Fix articles list; now show all


<?php

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

$_SERVER["HTTP_HOST"] = Config::get('app.host', '');
$_SERVER["SERVER_NAME"] = Config::get('app.host', '');

# stream links
Route::get("/main.mp3", function() {
	return Redirect::to("//stream.r-a-d.io/main");
});

Route::get("/stream", function() {
	return Redirect::to("//stream.r-a-d.io/main");
});

Route::get("/stream.mp3", function() {
	return Redirect::to("//stream.r-a-d.io/main");
});

Route::get("/R-a-dio", function() {
	return Redirect::to("//stream.r-a-d.io/main");
});

# API controller
Route::controller("/api", "API");

# Admin controller; adds extra auth + security
Route::controller('/admin', 'Admin');

# Artisan password reminder controller
Route::controller('password', 'RemindersController');

# Index.
Route::controller('/', 'Home');

<?php

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

$_SERVER["HTTP_HOST"] = Config::get('app.host', '');
$_SERVER["SERVER_NAME"] = Config::get('app.host', '');

# stream links
Route::get("/main.mp3", function() {
	return Redirect::to("//stream.r-a-d.io/main");
});

Route::get("/stream", function() {
	return Redirect::to("//stream.r-a-d.io/main");
});

Route::get("/stream.mp3", function() {
	return Redirect::to("//stream.r-a-d.io/main");
});

Route::get("/R-a-dio", function() {
	return Redirect::to("//stream.r-a-d.io/main");
});

# API controller
Route::controller("/api", "API");

# Admin controller; adds extra auth + security
Route::controller('/admin', 'Admin');

# Index.
Route::controller('/', 'Home');

Remove the password reset controller

Remove the password reset controller


<?php
class sfAlohaBackendDoctrine extends sfAlohaBackendAbstract
{
  /**
   * {@inheritdoc}
   */
  public function getContentByName($name)
  {
    $doctrineAlohaContent = AlohaContentTable::getInstance()->findOneByName($name);

    if (!$doctrineAlohaContent)
    {
      return null;
    }

    $alohaContent = new sfAlohaContent();
    $alohaContent->setName($doctrineAlohaContent->getName())
                 ->setBody($doctrineAlohaContent->getBody());

    return $alohaContent;
  }

  /**
   * {@inheritdoc}
   */
  public function saveContent(sfAlohaContent $alohaContent)
  {
    // Get the existing content or create a new one
    $doctrineAlohaContent = AlohaContentTable::getInstance()->findOneByName($alohaContent->getName());

    if (!$alohaContent)
    {
      $doctrineAlohaContent = new AlohaContent();
      $doctrineAlohaContent->setName($alohaContent->getName());
    }

    $doctrineAlohaContent->setBody($alohaContent->getBody());
    $doctrineAlohaContent->save();
  }
}

<?php
class sfAlohaBackendDoctrine extends sfAlohaBackendAbstract
{
  /**
   * {@inheritdoc}
   */
  public function getContentByName($name)
  {
    $doctrineAlohaContent = AlohaContentTable::getInstance()->findOneByName($name);

    if (!$doctrineAlohaContent)
    {
      return null;
    }

    $alohaContent = new sfAlohaContent();
    $alohaContent->setName($doctrineAlohaContent->getName())
                 ->setBody($doctrineAlohaContent->getBody());

    return $alohaContent;
  }

  /**
   * {@inheritdoc}
   */
  public function saveContent(sfAlohaContent $alohaContent)
  {
    // Get the existing content or create a new one
    $doctrineAlohaContent = AlohaContentTable::getInstance()->findOneByName($alohaContent->getName());

    if (!$doctrineAlohaContent)
    {
      $doctrineAlohaContent = new AlohaContent();
      $doctrineAlohaContent->setName($alohaContent->getName());
    }

    $doctrineAlohaContent->setBody($alohaContent->getBody());
    $doctrineAlohaContent->save();
  }
}

Fix issue when content is not initialized


<?php

namespace TwigBridge\Tests\Command\Lint;

use TwigBridge\Tests\Base as BridgeBase;
use Mockery as m;
use Symfony\Component\Console\Output\StreamOutput;
use TwigBridge\Command\Lint;

class Base extends BridgeBase
{
    protected function getApplication(array $customConfig = [])
    {
        $app = parent::getApplication($customConfig);
        $app['twig.extension'] = 'twig';
        $app['twig.bridge']    = m::mock('TwigBridge\Bridge');

        $finder = m::mock('Illuminate\View\ViewFinderInterface');
        $finder->shouldReceive('name');
        $finder->shouldReceive('in')->andReturn($finder);

        $viewFinder = m::mock('Illuminate\View\ViewFinderInterface');
        $viewFinder->shouldReceive('getPaths')->andReturn([]); // paths
        $viewFinder->shouldReceive('files')->andReturn($finder);

        $app['view'] = m::mock('Illuminate\View\Factory');
        $app['view']->shouldReceive('getFinder')->andReturn($viewFinder);

        return $app;
    }
}

<?php

namespace TwigBridge\Tests\Command\Lint;

use TwigBridge\Tests\Base as BridgeBase;
use Mockery as m;
use Symfony\Component\Console\Output\StreamOutput;
use TwigBridge\Command\Lint;

class Base extends BridgeBase
{
    protected function getApplication(array $customConfig = [])
    {
        $app = parent::getApplication($customConfig);
        $app['twig.extension'] = 'twig';
        $app['twig']    = m::mock('TwigBridge\Bridge');

        $finder = m::mock('Illuminate\View\ViewFinderInterface');
        $finder->shouldReceive('name');
        $finder->shouldReceive('in')->andReturn($finder);

        $viewFinder = m::mock('Illuminate\View\ViewFinderInterface');
        $viewFinder->shouldReceive('getPaths')->andReturn([]); // paths
        $viewFinder->shouldReceive('files')->andReturn($finder);

        $app['view'] = m::mock('Illuminate\View\Factory');
        $app['view']->shouldReceive('getFinder')->andReturn($viewFinder);

        return $app;
    }
}

Update binding for lint test

Update binding for lint test


<?php
namespace Change\Events;

use Zend\EventManager\SharedListenerAggregateInterface;
use Zend\EventManager\SharedEventManagerInterface;

use Change\Documents\Events\Event as DocumentEvent;
use Change\Http\Event as HttpEvent;

/**
 * @name \Change\Events\DefaultSharedListenerAggregate
 */
class DefaultSharedListenerAggregate implements SharedListenerAggregateInterface
{
	/**
	 * Attach one or more listeners
	 *
	 * Implementors may add an optional $priority argument; the SharedEventManager
	 * implementation will pass this to the aggregate.
	 *
	 * @param SharedEventManagerInterface $events
	 */
	public function attachShared(SharedEventManagerInterface $events)
	{
		$identifiers = array('Documents');

		$callBack = function($event) {
			(new \Change\Documents\Events\ValidateListener())->onValidate($event);
		};
		$events->attach($identifiers, array(DocumentEvent::EVENT_CREATE, DocumentEvent::EVENT_UPDATE), $callBack, 5);

		$callBack = function($event) {
			(new \Change\Documents\Events\DeleteListener())->onDelete($event);
		};
		$events->attach($identifiers, DocumentEvent::EVENT_DELETE, $callBack, 5);
	}

	/**
	 * Detach all previously attached listeners
	 *
	 * @param SharedEventManagerInterface $events
	 */
	public function detachShared(SharedEventManagerInterface $events)
	{

	}
}

<?php
namespace Change\Events;

use Zend\EventManager\SharedListenerAggregateInterface;
use Zend\EventManager\SharedEventManagerInterface;

use Change\Documents\Events\Event as DocumentEvent;
use Change\Http\Event as HttpEvent;

/**
 * @name \Change\Events\DefaultSharedListenerAggregate
 */
class DefaultSharedListenerAggregate implements SharedListenerAggregateInterface
{
	/**
	 * Attach one or more listeners
	 *
	 * Implementors may add an optional $priority argument; the SharedEventManager
	 * implementation will pass this to the aggregate.
	 *
	 * @param SharedEventManagerInterface $events
	 */
	public function attachShared(SharedEventManagerInterface $events)
	{
		$identifiers = array('Documents');

		$callBack = function($event) {
			$l = new \Change\Documents\Events\ValidateListener();
			$l->onValidate($event);
		};

		$events->attach($identifiers, array(DocumentEvent::EVENT_CREATE, DocumentEvent::EVENT_UPDATE), $callBack, 5);

		$callBack = function($event) {
			$l = new \Change\Documents\Events\DeleteListener();
			$l->onDelete($event);
		};
		$events->attach($identifiers, DocumentEvent::EVENT_DELETE, $callBack, 5);
	}

	/**
	 * Detach all previously attached listeners
	 *
	 * @param SharedEventManagerInterface $events
	 */
	public function detachShared(SharedEventManagerInterface $events)
	{

	}
}

Fix tests on php 5.3

Fix tests on php 5.3


<?php
namespace Vda\Query\Projection;

use Vda\Query\Alias;
use Vda\Query\Field;
use Vda\Util\BeanUtil;

class EntityProjection implements IProjection
{
    private $entityClass;
    private $fieldIndices;

    public function __construct($entityClass, $fields)
    {
        $this->entityClass = $entityClass;
        $this->fieldIndices = array();

        $entityFields = BeanUtil::listProperties($entityClass);
        foreach ($fields as $i => $field) {
            if ($field instanceof Field) {
                $name = $field->getName();
            } elseif ($field instanceof Alias) {
                $name = $field->getAlias();
            } else {
                continue;
            }

            if (in_array($name, $entityFields)) {
                $this->fieldIndices[$i] = $name;
            }
        }
    }

    public function project(array $tuple)
    {
        $result = new $this->entityClass;

        foreach ($this->fieldIndices as $idx => $name) {
            $method = 'set' . $name;
            if (method_exists($result, $method)) {
                $result->{$method}($tuple[$idx]);
            } else {
                $result->$name = $tuple[$idx];
            }
        }

        return $result;
    }
}

<?php
namespace Vda\Query\Projection;

use Vda\Query\Alias;
use Vda\Query\Field;
use Vda\Util\BeanUtil;

class EntityProjection implements IProjection
{
    private $entityClass;
    private $fieldIndices;

    public function __construct($entityClass, $fields)
    {
        $this->entityClass = $entityClass;
        $this->fieldIndices = array();

        $entityFields = BeanUtil::listProperties($entityClass);
        foreach ($fields as $i => $field) {
            if ($field instanceof Field) {
                $name = $field->getPropertyName();
            } elseif ($field instanceof Alias) {
                $name = $field->getAlias();
            } else {
                continue;
            }

            if (in_array($name, $entityFields)) {
                $this->fieldIndices[$i] = $name;
            }
        }
    }

    public function project(array $tuple)
    {
        $result = new $this->entityClass;

        foreach ($this->fieldIndices as $idx => $name) {
            $method = 'set' . $name;
            if (method_exists($result, $method)) {
                $result->{$method}($tuple[$idx]);
            } else {
                $result->$name = $tuple[$idx];
            }
        }

        return $result;
    }
}

Use correct property name in the entity mapping projection


<?php
namespace Neos\Flow\Http;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Core\Bootstrap;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Central authority to get hold of the active HTTP request.
 * When no active HTTP request can be determined (for example in CLI context) an exception will be thrown
 *
 * Note: Naturally this class is not being used directly. But it is configured as factory for Psr\Http\Message\ServerRequestInterface instances
 *
 * @Flow\Scope("singleton")
 */
final class ActiveHttpRequestProvider
{
    /**
     * @Flow\Inject
     * @var Bootstrap
     */
    protected $bootstrap;

    /**
     * Returns the currently active HTTP request, if available.
     * If the HTTP request can't be determined (for example in CLI context) a \Neos\Flow\Http\Exception is thrown
     *
     * @return ServerRequestInterface
     * @throws Exception
     */
    public function getActiveHttpRequest(): ServerRequestInterface
    {
        $requestHandler = $this->bootstrap->getActiveRequestHandler();
        if (!$requestHandler instanceof HttpRequestHandlerInterface) {
            throw new Exception(sprintf('The active HTTP request can\'t be determined because the request handler is not an instance of %s but a %s. Use a ServerRequestFactory to create a HTTP requests in CLI context', HttpRequestHandlerInterface::class, get_class($requestHandler)), 1600869131);
        }
        return $requestHandler->getHttpRequest();
    }
}

<?php
namespace Neos\Flow\Http;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Core\Bootstrap;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Central authority to get hold of the active HTTP request.
 * When no active HTTP request can be determined (for example in CLI context) an exception will be thrown
 *
 * Note: Usually this class is not being used directly. But it is configured as factory for Psr\Http\Message\ServerRequestInterface instances
 *
 * @Flow\Scope("singleton")
 */
final class ActiveHttpRequestProvider
{
    /**
     * @Flow\Inject
     * @var Bootstrap
     */
    protected $bootstrap;

    /**
     * Returns the currently active HTTP request, if available.
     * If the HTTP request can't be determined (for example in CLI context) a \Neos\Flow\Http\Exception is thrown
     *
     * @return ServerRequestInterface
     * @throws Exception
     */
    public function getActiveHttpRequest(): ServerRequestInterface
    {
        $requestHandler = $this->bootstrap->getActiveRequestHandler();
        if (!$requestHandler instanceof HttpRequestHandlerInterface) {
            throw new Exception(sprintf('The active HTTP request can\'t be determined because the request handler is not an instance of %s but a %s. Use a ServerRequestFactory to create a HTTP requests in CLI context', HttpRequestHandlerInterface::class, get_class($requestHandler)), 1600869131);
        }
        return $requestHandler->getHttpRequest();
    }
}

Tweak wording in doc comments

Tweak wording in doc comments


<?php

class Unit extends PHPUnit_Framework_TestCase {

	public function subject($params = array(), $options = array()) {
		$options += array(
			'mock' => false,
			'methods' => array(),
		);
		$class = 'alfmarks\\' . str_replace('Test', '', get_called_class());
		if ($options['mock']) {
			return $this->getMock($class, $options['methods'], $params);
		}
		return new $class($params);
	}

}

<?php

class Unit extends PHPUnit_Framework_TestCase {

	public function subject($params = array(), $options = array()) {
		$options += array(
			'mock' => false,
			'methods' => array(),
		);
		$class = 'alfmarks\\' . str_replace('Test', '', get_called_class());
		if ($options['mock']) {
			return $this->getMockBuilder($class)
				->setMethods($options['methods'])
				->getMock();
		}
		return new $class($params);
	}

}

Update for the newer version of phpunit.


<?php
# $Id: get_ganglia.php 2510 2011-03-15 01:12:34Z vvuksan $
# Retrieves and parses the XML output from gmond. Results stored
# in global variables: $clusters, $hosts, $hosts_down, $metrics.
# Assumes you have already called get_context.php.
#

if (! Gmetad($conf['ganglia_ip'], $conf['ganglia_port']) )
   {
      print "
There was an error collecting ganglia data ".
         "(${conf['ganglia_ip']}:${conf['ganglia_port']}): $error
\n";
      exit;
   }

# If we have no child data sources, assume something is wrong.
if (!count($grid) and !count($cluster))
   {
      print "
Ganglia cannot find a data source. Is gmond running?
";
      exit;
   }

# If we only have one cluster source, suppress MetaCluster output.
#if (count($grid) <= 2 and $context=="meta")
#   {
#      # Lets look for one cluster (the other is our grid).
#      foreach($grid as $source)
#         if (isset($source['CLUSTER']) and $source['CLUSTER'])
#            {
#               $standalone = 1;
#               $context = "cluster";
#               # Need to refresh data with new context.
#               Gmetad($conf['ganglia_ip'], $conf['ganglia_port']);
#               $clustername = $source['NAME'];
#            }
#   }

?>

<?php
# $Id: get_ganglia.php 2510 2011-03-15 01:12:34Z vvuksan $
# Retrieves and parses the XML output from gmond. Results stored
# in global variables: $clusters, $hosts, $hosts_down, $metrics.
# Assumes you have already called get_context.php.
#

if (! Gmetad($conf['ganglia_ip'], $conf['ganglia_port']) )
   {
      print "
There was an error collecting ganglia data ".
         "(${conf['ganglia_ip']}:${conf['ganglia_port']}): $error
\n";
      exit;
   }

# If we have no child data sources, assume something is wrong.
if (!count($grid) and !count($cluster))
   {
      print "
Ganglia cannot find a data source. Is gmond running?
";
      exit;
   }

# If we only have one cluster source, suppress MetaCluster output.
if (count($grid) <= 2 and $context=="meta")
   {
      # Lets look for one cluster (the other is our grid).
      foreach($grid as $source)
         if (isset($source['CLUSTER']) and $source['CLUSTER'])
            {
               $standalone = 1;
               $context = "cluster";
               # Need to refresh data with new context.
               Gmetad($conf['ganglia_ip'], $conf['ganglia_port']);
               $clustername = $source['NAME'];
            }
   }

?>

Revert the change to show cluster list even if you only have one


Ninja Miners

    @foreach ($ninjas as $ninja)
        @include('common.card', [
            'size' => 'small',
            'avatar' => $ninja->avatar,
            'name' => $ninja->name . ' (' . $ninja->corporation->name . ')',
            'amount' => $ninja->amount_owed
        ])
    @endforeach

Ninja Miners

    @foreach ($ninjas as $ninja)
        @include('common.card', [
            'size' => 'small',
            'avatar' => $ninja->avatar,
            'name' => $ninja->name . ' (' . (isset($ninja->corporation->name) ? $ninja->corporation->name : 'UNKNOWN') . ')',
            'amount' => $ninja->amount_owed
        ])
    @endforeach

Stop unknown ninja miner corps from breaking the homepage.


@extends('layouts.app')

@section('pageTitle', 'Current Domains')

@section('content')

Current Domains

            ID
            Domain Name
            WordPress
            Status

        @if (isset($domains))
            @foreach ($domains as $domain)

                    {{ $domain->id }}
                    name }}" target="_blank">{{ $domain->name }}
                    {{ $domain->is_word_press == 1 ? 'Yes' : 'No' }}
                    {{ $domain->trashed() ? 'Completed' : 'Queued' }}

            @endforeach
        @else

                There are currently no domains created.

        @endif

@endsection

@extends('layouts.app')

@section('pageTitle', 'Current Domains')

@section('content')

Current Domains

            ID
            Domain Name
            WordPress
            Secure
            Status

        @if (isset($domains))
            @foreach ($domains as $domain)

                    {{ $domain->id }}
                    name }}" target="_blank">{{ $domain->name }}
                    {{ $domain->is_word_press ? 'Yes' : 'No' }}
                    {{ $domain->is_secure ? 'Yes' : 'No' }}
                    {{ $domain->trashed() ? 'Completed' : 'Queued' }}

            @endforeach
        @else

                There are currently no domains created.

        @endif

@endsection

Add Secure Info to Domain Index

Add Secure Info to Domain Index


<?php
namespace MetroPublisher\Api\Models;

use MetroPublisher\Exception\MetroPublisherException;

/**
 * Class AbstractReview
 * @package MetroPublisher\Api\Models
 */
abstract class AbstractReview extends Content
{
    /** @var  string */
    protected $rating;

    /**
     * @inheritdoc
     */
    public static function getMetaFields()
    {
        return array_merge(['rating'], parent::getMetaFields());
    }

    /**
     * @return float
     */
    public function getRating() {
        return floatval($this->rating);
    }

    /**
     * @param int $rating
     *
     * @return $this
     * @throws MetroPublisherException
     */
    public function setRating($rating)
    {
        if ($rating !== 0 && ($rating < 0 || $rating > 5 || $rating % .5 > 0)) {
            throw new MetroPublisherException('Rating must be 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, or 5. ');
        }

        //API expects value to be string. Floats will trigger an error.
        $this->rating = $rating . "";

        return $this;
    }
}

<?php
namespace MetroPublisher\Api\Models;

use MetroPublisher\Exception\MetroPublisherException;

/**
 * Class AbstractReview
 * @package MetroPublisher\Api\Models
 */
abstract class AbstractReview extends Content
{
    /** @var  string */
    protected $rating;

    /**
     * @inheritdoc
     */
    public static function getMetaFields()
    {
        return array_merge(['rating'], parent::getMetaFields());
    }

    /**
     * @return float
     */
    public function getRating() {
        return floatval($this->rating);
    }

    /**
     * @param int $rating
     *
     * @return $this
     * @throws MetroPublisherException
     */
    public function setRating($rating)
    {
        if ($rating !== 0 && ($rating < 0 || $rating > 5 || ($rating / .5) % 1 !== 0)) {
            throw new MetroPublisherException('Rating must be 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, or 5. ');
        }

        //API expects value to be string. Floats will trigger an error.
        $this->rating = $rating . "";

        return $this;
    }
}

Fix for division by 0 warning in review rating validation.


<?php
use Cake\Event\EventManager;

EventManager::instance()
    ->attach(
        function (Cake\Event\Event $event) {
            $controller = $event->subject();
            if ($controller->components()->has('RequestHandler')) {
                $controller->RequestHandler->viewClassMap('pdf', 'CakePdf.Pdf');
            }
        },
        'Controller.initialize'
    );

<?php
use Cake\Event\EventManager;

EventManager::instance()
    ->on(
        'Controller.initialize',
        function (Cake\Event\Event $event) {
            $controller = $event->subject();
            if ($controller->components()->has('RequestHandler')) {
                $controller->RequestHandler->viewClassMap('pdf', 'CakePdf.Pdf');
            }
        }
    );

Resolve an event attaching error

Resolve an event attaching error


<?php

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

namespace Flarum\Api\Serializer;

use Flarum\Mail\DriverInterface;
use InvalidArgumentException;

class MailDriverSerializer extends AbstractSerializer
{
    /**
     * {@inheritdoc}
     */
    protected $type = 'mail-drivers';

    /**
     * {@inheritdoc}
     *
     * @param \Flarum\Mail\DriverInterface $driver
     * @throws InvalidArgumentException
     */
    protected function getDefaultAttributes($driver)
    {
        if (! ($driver['driver'] instanceof DriverInterface)) {
            throw new InvalidArgumentException(
                get_class($this).' can only serialize instances of '.DriverInterface::class
            );
        }

        $driver = $driver['driver'];

        return [
            'fields' => $driver->availableSettings(),
        ];
    }

    public function getId($model)
    {
        return $model['id'];
    }
}

<?php

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

namespace Flarum\Api\Serializer;

use Flarum\Mail\DriverInterface;
use InvalidArgumentException;

class MailDriverSerializer extends AbstractSerializer
{
    /**
     * {@inheritdoc}
     */
    protected $type = 'mail-drivers';

    /**
     * {@inheritdoc}
     *
     * @param \Flarum\Mail\DriverInterface $driver
     * @throws InvalidArgumentException
     */
    protected function getDefaultAttributes($driver)
    {
        if (! ($driver['driver'] instanceof DriverInterface)) {
            throw new InvalidArgumentException(
                get_class($this).' can only serialize instances of '.DriverInterface::class
            );
        }

        $settings = $driver['driver']->availableSettings();

        if (key($settings) === 0) {
            // BACKWARDS COMPATIBILITY: Support a simple list of fields (without
            // type or additional metadata).
            // Turns ["f1", "f2"] into {"f1": "", "f2": ""}
            // @deprecated since 0.1.0-beta.12
            $settings = array_reduce($settings, function ($memo, $key) {
                return [$key => ''] + $memo;
            }, []);
        }

        return [
            'fields' => $settings,
        ];
    }

    public function getId($model)
    {
        return $model['id'];
    }
}

Add backwards compatibility layer for mail drivers

Support the old format (a simple list of available fields), in addition
to the new format (a map from field names to their types + metadata).

This will be removed after beta.12 is released.


<?php
namespace Event;

use Application\BaseDb;

class EventDb extends BaseDb
{
    protected $keyName = 'events';

    public function save(EventEntity $event)
    {
        $data = array(
            "url_friendly_name" => $event->getUrlFriendlyName(),
            "uri" => $event->getUri(),
            "stub" => $event->getStub(),
            "verbose_uri" => $event->getVerboseUri()
        );

        $this->cache->save($this->keyName, $data, 'uri', $event->getUri());
        $this->cache->save($this->keyName, $data, 'url_friendly_name', $event->getUrlFriendlyName());
        $this->cache->save($this->keyName, $data, 'stub', $event->getStub());
    }
}

<?php
namespace Event;

use Application\BaseDb;

class EventDb extends BaseDb
{
    protected $keyName = 'events';

    public function save(EventEntity $event)
    {
        $data = array(
            "url_friendly_name" => $event->getUrlFriendlyName(),
            "uri" => $event->getUri(),
            "stub" => $event->getStub(),
            "verbose_uri" => $event->getVerboseUri(),
            "name" => $event->getName(),
        );

        $this->cache->save($this->keyName, $data, 'uri', $event->getUri());
        $this->cache->save($this->keyName, $data, 'url_friendly_name', $event->getUrlFriendlyName());
        $this->cache->save($this->keyName, $data, 'stub', $event->getStub());
    }
}

Store the event's name in the database

Store the event's name in the database


<?php
/**
* @version      $Id$
* @category		Koowa
* @package		Koowa_Toolbar
* @subpackage	Button
* @copyright    Copyright (C) 2007 - 2009 Johan Janssens and Mathias Verraes. All rights reserved.
* @license      GNU GPL <http://www.gnu.org/licenses/gpl.html>
*/

/**
 * POST button class for a toolbar
 *
 * @author		Mathias Verraes <mathias@koowa.org>
 * @category	Koowa
 * @package		Koowa_Toolbar
 * @subpackage	Button
 */
abstract class KToolbarButtonPost extends KToolbarButtonAbstract
{
	protected $_fields = array();

	public function __construct(array $options = array())
	{
		parent::__construct($options);
		$this->setMethod('post');

		$script = Koowa::getURL('js').'koowa.js';
		KFactory::get('lib.joomla.document')->addScript($script);
	}

	public function getOnClick()
	{
		$js = '';
		foreach($this->_fields as $name => $value) {
			$js .= "Koowa.Form.addField('$name', '$value');";
		}
		$js .= "Koowa.Form.submit('{$this->_method}');";
		return $js;
	}

	public function setField($name, $value)
	{
		$this->_fields[$name] = $value;
		return $this;
	}
}

<?php
/**
* @version      $Id$
* @category		Koowa
* @package		Koowa_Toolbar
* @subpackage	Button
* @copyright    Copyright (C) 2007 - 2009 Johan Janssens and Mathias Verraes. All rights reserved.
* @license      GNU GPL <http://www.gnu.org/licenses/gpl.html>
*/

/**
 * POST button class for a toolbar
 *
 * @author		Mathias Verraes <mathias@koowa.org>
 * @category	Koowa
 * @package		Koowa_Toolbar
 * @subpackage	Button
 */
abstract class KToolbarButtonPost extends KToolbarButtonAbstract
{
	protected $_fields = array();

	public function __construct(array $options = array())
	{
		parent::__construct($options);
		$this->setMethod('post');

		KTemplate::loadHelper('script', Koowa::getURL('js').'koowa.js');
	}

	public function getOnClick()
	{
		$js = '';
		foreach($this->_fields as $name => $value) {
			$js .= "Koowa.Form.addField('$name', '$value');";
		}
		$js .= "Koowa.Form.submit('{$this->_method}');";
		return $js;
	}

	public function setField($name, $value)
	{
		$this->_fields[$name] = $value;
		return $this;
	}
}

Use KTemplate instead of KDocument to load script


<?php

namespace Trotch\Renderer;

use Trotch\Container;
use Trotch\Renderer;

class GeoLike extends Renderer
{

    /**
     * @var string
     */
    protected $template = 'like.php';

    /**
     *
     */
    protected function pre()
    {
        if (isset($_GET['token']) && isset($_SESSION['token']) && $_GET['token'] == $_SESSION['token']) {
            try {
                $fb = Container::get('Facebook');
                $fb->setUserStatus();
                $_SESSION['geoLikingSuccess'] = true;
            }
            catch (\Exception $e) {
                $_SESSION['geoLikingWarning'] = $e->getMessage();
            }
        }
        else {
            $_SESSION['geoLikingWarning']  = 'Invalid token';
        }
    }

    /**
     * @return array
     */
    protected function data()
    {
        return array();
    }

    /**
     *
     */
    protected function post()
    {
        unset($_SESSION['token']);
        $app = Container::get('App');
        $app->redirect($app->request()->getRootUri());
    }
}

<?php

namespace Trotch\Renderer;

use Trotch\Container;
use Trotch\Renderer;

class GeoLike extends Renderer
{

    /**
     * @var string
     */
    protected $template = 'like.php';

    /**
     *
     */
    protected function pre()
    {
        if (isset($_GET['token']) && isset($_SESSION['token']) && $_GET['token'] == $_SESSION['token']) {
            try {
                $fb = Container::get('Facebook');
                $fb->setUserStatus();
                $_SESSION['geoLikingSuccess'] = true;
            }
            catch (\Exception $e) {
                $_SESSION['geoLikingWarning'] = $e->getMessage();
            }
        }
        else {
            $_SESSION['geoLikingWarning']  = 'Invalid token';
        }
    }

    /**
     * @return array
     */
    protected function data()
    {
        return array();
    }

    /**
     *
     */
    protected function post()
    {
        unset($_SESSION['token']);
        $app = Container::get('App');
        $app->redirect('/');
    }
}

Put root URL the way it was.

Put root URL the way it was.


<?php

require_once("tokenstrategy.php");

class CookieStrategy extends TokenStrategy
{
	/**
	 * the name for the cookie
	 */
	const COOKIENAME = "token";

	/**
	 * the path the cookie is valid for
	 */
	private $path;

	public function __construct()
	{
		$this->path = $_SERVER['SCRIPT_NAME'];
	}

	public function getAuthToken()
	{
		return $_COOKIE[self::COOKIENAME];
	}

	public function setNextAuthToken($token)
	{
		$expiry = Configuration::getInstance()->getConfig("cookie_expiry_time");
		if ($expiry == null)
		{
			throw new Exception("no cookie expiry time found in config file", E_NO_EXPIRY_TIME);
		}
		setcookie(
		          self::COOKIENAME,
		          $token,
		          time() + (int)$expiry,
		          $this->path
		         );
	}

	public function removeAuthToken()
	{
		setcookie(self::COOKIENAME, "", time() - 3600, $this->path);
	}

}

<?php

require_once("tokenstrategy.php");

class CookieStrategy extends TokenStrategy
{
	/**
	 * the name for the cookie
	 */
	const COOKIENAME = "token";

	/**
	 * the path the cookie is valid for
	 */
	private $path;

	public function __construct()
	{
		$this->path = dirname($_SERVER['SCRIPT_NAME']).'/';
	}

	public function getAuthToken()
	{
		return $_COOKIE[self::COOKIENAME];
	}

	public function setNextAuthToken($token)
	{
		$expiry = Configuration::getInstance()->getConfig("cookie_expiry_time");
		if ($expiry == null)
		{
			throw new Exception("no cookie expiry time found in config file", E_NO_EXPIRY_TIME);
		}
		setcookie(
		          self::COOKIENAME,
		          $token,
		          time() + (int)$expiry,
		          $this->path
		         );
	}

	public function removeAuthToken()
	{
		setcookie(self::COOKIENAME, "", time() - 3600, $this->path);
	}

}

Allow the login detecting page to find the cookie.

dirname shortens the path the cookie applies to,
to the entire IDE folder, not just the control script.


<?php

namespace DouglasResende\FCM\Channels;

use DouglasResende\FCM\Messages\FirebaseMessage;
use Illuminate\Contracts\Config\Repository as Config;
use GuzzleHttp\Client;
use DouglasResende\FCM\Contracts\FirebaseNotification as Notification;

/**
 * Class FirebaseChannel
 * @package DouglasResende\FCM\Channels
 */
class FirebaseChannel
{
    /**
     * @const api uri
     */
    const API_URI = 'https://fcm.googleapis.com/fcm/send';

    /**
     * @var Client
     */
    private $client;

    /**
     * @var Config
     */
    private $config;

    /**
     * FirebaseChannel constructor.
     * @param Client $client
     * @param Config $config
     */
    public function __construct(Client $client, Config $config)
    {
        $this->client = $client;
        $this->config = $config;
    }

    /**
     * @param $notifiable
     * @param Notification $notification
     */
    public function send($notifiable, Notification $notification)
    {
        $message = $notification->toFCM($notifiable, new FirebaseMessage);

        $this->client->post(FirebaseChannel::API_URI, [
            'headers' => [
                'Authorization' => 'key=' . $this->getApiKey(),
                'Content-Type' => 'application/json',
            ],
            'body' => $message->serialize(),
        ]);
    }

    /**
     * @return mixed
     */
    private function getApiKey()
    {
        return $this->config->get('services.fcm.key');
    }
}

<?php

namespace DouglasResende\FCM\Channels;

use DouglasResende\FCM\Messages\FirebaseMessage;
use Illuminate\Contracts\Config\Repository as Config;
use GuzzleHttp\Client;
use Illuminate\Notifications\Notification;

/**
 * Class FirebaseChannel
 * @package DouglasResende\FCM\Channels
 */
class FirebaseChannel
{
    /**
     * @const api uri
     */
    const API_URI = 'https://fcm.googleapis.com/fcm/send';

    /**
     * @var Client
     */
    private $client;

    /**
     * @var Config
     */
    private $config;

    /**
     * FirebaseChannel constructor.
     * @param Client $client
     * @param Config $config
     */
    public function __construct(Client $client, Config $config)
    {
        $this->client = $client;
        $this->config = $config;
    }

    /**
     * @param $notifiable
     * @param Notification $notification
     */
    public function send($notifiable, Notification $notification)
    {
        $message = $notification->toFCM($notifiable, new FirebaseMessage);

        $this->client->post(FirebaseChannel::API_URI, [
            'headers' => [
                'Authorization' => 'key=' . $this->getApiKey(),
                'Content-Type' => 'application/json',
            ],
            'body' => $message->serialize(),
        ]);
    }

    /**
     * @return mixed
     */
    private function getApiKey()
    {
        return $this->config->get('services.fcm.key');
    }
}

Remove dependency on FirebaseNotification Contract


<?php
/**
 * @link    http://hiqdev.com/hipanel
 * @license http://hiqdev.com/hipanel/license
 * @copyright Copyright (c) 2015 HiQDev
 */

namespace hipanel\base;

trait ModelTrait
{
    /**
     * Overrides default [[attributes()]] method.
     * Extracts attributes from the validation rules described in [[rules()]] method
     *
     * @return array
     */
    public function attributes () {
        $attributes = \yii\base\Model::attributes();
        foreach (static::rules() as $d) {
            if (is_string(reset($d))) continue;
            foreach (reset($d) as $k) $attributes[$k] = $k;
        }
        return array_values($attributes);
    }
}

<?php
/**
 * @link    http://hiqdev.com/hipanel
 * @license http://hiqdev.com/hipanel/license
 * @copyright Copyright (c) 2015 HiQDev
 */

namespace hipanel\base;

trait ModelTrait
{
    /**
     * Overrides default [[attributes()]] method.
     * Extracts attributes from the validation rules described in [[rules()]] method
     *
     * @return array
     */
    public function attributes () {
        $attributes = \yii\base\Model::attributes();
        foreach (self::rules() as $d) {
            if (is_string(reset($d))) continue;
            foreach (reset($d) as $k) $attributes[$k] = $k;
        }
        return array_values($attributes);
    }
}

Replace rules call from static to self

Replace rules call from static to self


<?php

namespace DNADesign\Elemental\GraphQL;

use GraphQL\Type\Definition\ResolveInfo;
use SilverStripe\GraphQL\OperationResolver;
use SilverStripe\ORM\DataList;

class ElementsResolver implements OperationResolver
{
    public function resolve($object, array $args, $context, ResolveInfo $info)
    {
        if (!$object::singleton()->canView($context['currentUser'])) {
            throw new \Exception('Current user cannot view elements');
        }

        /** @var DataList $elements */
        $elements = $object->Elements();
        return $elements;
    }
}

<?php

namespace DNADesign\Elemental\GraphQL;

use GraphQL\Type\Definition\ResolveInfo;
use SilverStripe\GraphQL\OperationResolver;
use SilverStripe\ORM\DataList;

class ElementsResolver implements OperationResolver
{
    public function resolve($object, array $args, $context, ResolveInfo $info)
    {
        if (!$object->canView($context['currentUser'])) {
            throw new \Exception('Current user cannot view elements');
        }

        /** @var DataList $elements */
        $elements = $object->Elements();
        return $elements;
    }
}

FIX Remove singleton call and check view permissions on recorded object


<?php
/**
 * DokuWiki Plugin markdownextra (Action Component)
 *
 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
 * @author  Andreas Gohr <andi@splitbrain.org>
 */

// must be run within Dokuwiki
if (!defined('DOKU_INC')) die();
if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once DOKU_PLUGIN.'action.php';

class action_plugin_markdownextra extends DokuWiki_Action_Plugin {

   function register(&$controller) {
      $controller->register_hook('PARSER_WIKITEXT_PREPROCESS',
'BEFORE', $this, 'handle_parser_wikitext_preprocess');
   }

   function handle_parser_wikitext_preprocess(&$event, $param) {
       global $ID;
       if(substr($ID,-3) != '.md') return true;

       if ($this->getConf('frontmatter')){
           if (preg_match('/^---\s*\n(.*?\n?)^---\s*$\n?(.+)/sm',$event->data, $match)){
               $event->data = sprintf("%s<markdown>\n%s\n</markdown>", $match[1], $match[2]);
           }else{
               $event->data = "<markdown>\n".$event->data."\n</markdown>";
           }
       }else{
           $event->data = "<markdown>\n".$event->data."\n</markdown>";
       }
   }

}

<?php
/**
 * DokuWiki Plugin markdownextra (Action Component)
 *
 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
 * @author  Andreas Gohr <andi@splitbrain.org>
 */

// must be run within Dokuwiki
if (!defined('DOKU_INC')) die();
if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once DOKU_PLUGIN.'action.php';

class action_plugin_markdownextra extends DokuWiki_Action_Plugin {

   function register(&$controller) {
      $controller->register_hook('PARSER_WIKITEXT_PREPROCESS',
'BEFORE', $this, 'handle_parser_wikitext_preprocess');
   }

   function handle_parser_wikitext_preprocess(&$event, $param) {
       global $ID;
       global $TEXT;
       if(substr($ID,-3) != '.md' || $event->data != $TEXT) return true;

       if ($this->getConf('frontmatter')){
           if (preg_match('/^---\s*\n(.*?\n?)^---\s*$\n?(.+)/sm',$event->data, $match)){
               $event->data = sprintf("%s<markdown>\n%s\n</markdown>", $match[1], $match[2]);
           }else{
               $event->data = "<markdown>\n".$event->data."\n</markdown>";
           }
       }else{
           $event->data = "<markdown>\n".$event->data."\n</markdown>";
       }
   }

}

Fix for not-markdown texts on .md pages

Fix for not-markdown texts on .md pages


<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * TraitTypeRepository
 *
 * This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom
 * repository methods below.
 */
class TraitTypeRepository extends EntityRepository
{
    public function getNumber(){
        $query = $this->getEntityManager()->createQuery('SELECT COUNT(tt.id) FROM AppBundle\Entity\TraitType tt');
        return $query->getSingleScalarResult();
    }
}

<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * TraitTypeRepository
 *
 * This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom
 * repository methods below.
 */
class TraitTypeRepository extends EntityRepository
{
    public function getNumber(){
        $query = $this->getEntityManager()->createQuery('SELECT COUNT(tt.id) FROM AppBundle\Entity\TraitType tt');
        return $query->getSingleScalarResult();
    }

    /**
     * @param $trait_type_id
     * @return array type, format, trait_type_id and ontology_url of specific trait
     */
    public function getInfo($trait_type_id){
        $qb = $this->getEntityManager()->createQueryBuilder();
        $qb->select('t.id AS trait_type_id', 't.type', 't.ontologyUrl', 'IDENTITY(t.traitFormat) AS trait_format_id', 't.description', 't.unit')
            ->from('AppBundle\Entity\TraitType', 't')
            ->where('t.id = :trait_type_id')
            ->setParameter('trait_type_id', $trait_type_id);
        $query = $qb->getQuery();
        return $query->getResult();
    }
}

Implement function for getting values to a specific trait type


<?php
/**
 * Main entry point
 *
 * @author    Ivanis Kouamé <ivanis.kouame@smile.fr>
 * @copyright 2015 Smile
 */

const ROOT_PATH = __DIR__;

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

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

$app = new Silex\Application();

$app->post('/', function (Request $request) use ($app, $notificationHandler) {
    $notificationHandler->handleHipayNotification($request->getContent());
    return new Response(null, 204);
});

$app->error(function (Exception $e) use ($app, $notificationHandler) {
    $notificationHandler->handleException($e);
    return new Response($e->getMessage());
});

$app->get('/', function () {
   return 'Hello World';
});

$app->run();

<?php
/**
 * Main entry point
 *
 * @author    Ivanis Kouamé <ivanis.kouame@smile.fr>
 * @copyright 2015 Smile
 */

const ROOT_PATH = __DIR__;

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

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

$app = new Silex\Application();

$app->post('/', function (Request $request) use ($app, $notificationHandler) {
    $notificationHandler->handleHipayNotification(urldecode($request->request->get('xml')));
    return new Response(null, 204);
});

$app->error(function (Exception $e) use ($app, $notificationHandler) {
    $notificationHandler->handleException($e);
    return new Response($e->getMessage());
});

$app->get('/', function () {
   return 'Hello World';
});

$app->run();

Add decoding of the recieved data

Add decoding of the recieved data


<?php

namespace DNADesign\Elemental\Forms;

use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldButtonRow;
use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
use SilverStripe\Forms\GridField\GridFieldFilterHeader;
use SilverStripe\Forms\GridField\GridFieldDataColumns;
use SilverStripe\Forms\GridField\GridFieldEditButton;
use SilverStripe\Forms\GridField\GridFieldDeleteAction;
use SilverStripe\Forms\GridField\GridFieldDetailForm;
use SilverStripe\Versioned\VersionedGridFieldState\VersionedGridFieldState;
use Symbiote\GridFieldExtensions\GridFieldOrderableRows;

class ElementalAreaConfig extends GridFieldConfig
{
    public function __construct()
    {
        parent::__construct();

        $this->addComponent(new GridFieldDeleteAction(false));
        $this->addComponent(new GridFieldDetailForm());

        $this->extend('updateConfig');
    }
}

<?php

namespace DNADesign\Elemental\Forms;

use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldButtonRow;
use SilverStripe\Forms\GridField\GridFieldToolbarHeader;
use SilverStripe\Forms\GridField\GridFieldFilterHeader;
use SilverStripe\Forms\GridField\GridFieldDataColumns;
use SilverStripe\Forms\GridField\GridFieldEditButton;
use SilverStripe\Forms\GridField\GridFieldDeleteAction;
use SilverStripe\Forms\GridField\GridFieldDetailForm;
use SilverStripe\Versioned\VersionedGridFieldState\VersionedGridFieldState;
use Symbiote\GridFieldExtensions\GridFieldOrderableRows;

class ElementalAreaConfig extends GridFieldConfig
{
    public function __construct()
    {
        parent::__construct();

        $this->addComponent(new GridFieldDeleteAction(false));
        $this->addComponent(new GridFieldDetailForm(null, false, false));

        $this->extend('updateConfig');
    }
}

FIX Remove the 'add' better button for ElementalAreaField


<?php

namespace lucidtaz\minimax\engine;

use Closure;
use lucidtaz\minimax\game\Decision;

class DecisionWithScore
{
    /**
     * @var Decision
     */
    public $decision = null;

    /**
     * @var float
     */
    public $score;

    /**
     * @var integer How deep in the execution tree this result was found. Higher
     * means earlier. This is to prefer earlier solutions to later solutions
     * with the same score.
     */
    public $age;

    public function isBetterThan(DecisionWithScore $other): bool
    {
        if (abs($this->score - $other->score) < 0.1) {
            return $this->age > $other->age;
        }
        return $this->score > $other->score;
    }

    public static function getBestComparator(): Closure
    {
        return function (DecisionWithScore $a, DecisionWithScore $b) {
            return $a->isBetterThan($b) ? $a : $b;
        };
    }

    public static function getWorstComparator(): Closure
    {
        return function (DecisionWithScore $a, DecisionWithScore $b) {
            return $b->isBetterThan($a) ? $a : $b;
        };
    }
}

<?php

namespace lucidtaz\minimax\engine;

use Closure;
use lucidtaz\minimax\game\Decision;

class DecisionWithScore
{
    const EPSILON = 0.00001;

    /**
     * @var Decision
     */
    public $decision = null;

    /**
     * @var float
     */
    public $score;

    /**
     * @var integer How deep in the execution tree this result was found. Higher
     * means earlier. This is to prefer earlier solutions to later solutions
     * with the same score.
     */
    public $age;

    public function isBetterThan(DecisionWithScore $other): bool
    {
        if (abs($this->score - $other->score) < self::EPSILON) {
            return $this->age > $other->age;
        }
        return $this->score > $other->score;
    }

    public static function getBestComparator(): Closure
    {
        return function (DecisionWithScore $a, DecisionWithScore $b) {
            return $a->isBetterThan($b) ? $a : $b;
        };
    }

    public static function getWorstComparator(): Closure
    {
        return function (DecisionWithScore $a, DecisionWithScore $b) {
            return $b->isBetterThan($a) ? $a : $b;
        };
    }
}

Make epsilon smaller to be able to compare smaller scores


<?php

function isXml($filename) {
	$xml = XMLReader::open($filename);
	// The validate parser option must be enabled for
	// this method to work properly
	$xml->setParserProperty(XMLReader::VALIDATE, true);
	return $xml->isValid();
}

require_once __DIR__.'/../_functions/glob_recursive.php';
$xml_files = glob_recursive(__DIR__.'/../*.xml');
$result['invalid_files'] = array();
$result['valid_files']   = array();

foreach ( $xml_files as $filename ) {
	// Validate
	if ( isXml($filename) ) {
		$result['valid_files'][] = $filename;
	} else {
		$result['invalid_files'][] = $filename;
	}
}

var_dump($result);

if ( !empty($result['invalid_files']) ) {
	// That's an error
	exit(1);
}

<?php

function isXml($filename) {
	$xml = XMLReader;
	$xml->open($filename);
	// The validate parser option must be enabled for
	// this method to work properly
	$xml->setParserProperty(XMLReader::VALIDATE, true);
	return $xml->isValid();
}

require_once __DIR__.'/../_functions/glob_recursive.php';
$xml_files = glob_recursive(__DIR__.'/../*.xml');
$result['invalid_files'] = array();
$result['valid_files']   = array();

foreach ( $xml_files as $filename ) {
	// Validate
	if ( isXml($filename) ) {
		$result['valid_files'][] = $filename;
	} else {
		$result['invalid_files'][] = $filename;
	}
}

var_dump($result);

if ( !empty($result['invalid_files']) ) {
	// That's an error
	exit(1);
}

Fix XML Checking on HHVM

Fix XML Checking on HHVM


<?php
/*
Plugin Name: SimpleCast
Plugin URI: http://marketing.uoregon.edu
Description: Simple Shoutcast Player
Version: 1.0
Author: Joshua Rose
Author URI: http://marketing.uoregon.edu
*/

function simplecast_shortcode() {
	$output = '<audio id="audioplayer" preload="metadata" controls style="width:100%;" >
    			<source src="http://d55-84.uoregon.edu:8000/;stream.nsv&type=mp3" type="audio/mp3">
			  </audio>';

	return $output;
}

add_shortcode( 'simplecast', 'simplecast_shortcode' );
?>

<?php
/*
Plugin Name: SimpleCast
Plugin URI: http://marketing.uoregon.edu
Description: Simple Shoutcast Player
Version: 1.0
Author: Joshua Rose
Author URI: http://marketing.uoregon.edu
*/

/**
 * Shortcode handler, renders HTML for player
 *
 * @return   String containing audio player HTML.
 */
function simplecast_shortcode() {
	// The basic HTML5 audio component, hopefully this works.
	$output = '<audio id="simplecast_player" controls>
    			<source src="http://d55-84.uoregon.edu:8000/;stream.nsv&type=mp3" type="audio/mp3">
			  </audio>';

	// Setup flash player in case we need it
	$output .= '<script type="text/javascript" src="' . plugins_url('vendor/audio-player/audio-player.js', __FILE__) . '"></script>';
	$output .= '<script type="text/javascript">
            	AudioPlayer.setup("' . plugins_url('vendor/audio-player/player.swf', __FILE__) . '", {
                	width: 290
            	});
        		</script>';

    // Check to see if HTML5 player will work, or failover to flash player.
	$output .= '<script type="text/javascript">
			    var audioTag = document.createElement(\'audio\');
			    if (!(!!(audioTag.canPlayType) && ("no" != audioTag.canPlayType("audio/mpeg")) && ("" != audioTag.canPlayType("audio/mpeg")))) {
			        AudioPlayer.embed("simplecast_player", {soundFile: "http://d55-84.uoregon.edu:8000/;stream.nsv&type=mp3"});
			    }
				</script>';

	return $output;
}

add_shortcode( 'simplecast', 'simplecast_shortcode' );
?>

Implement flash failover on audio player


<?php
namespace Witti\FileConverter\Engine\Convert;

use Witti\FileConverter\Engine\EngineBase;
class LibreOffice extends EngineBase {
  public function getConvertFileShell($source, &$destination) {
    $destination = str_replace('.' . $this->conversion[0], '.'
      . $this->conversion[1], $source);
    return array(
      $this->cmd,
      '--headless',
      '--convert-to',
      $this->conversion[1],
      '--outdir',
      $this->settings['temp_dir'],
      $source
    );
  }

  public function getHelpInstallation($os, $os_version) {
    switch ($os) {
      case 'Ubuntu':
        return "sudo apt-get install libreoffice";
    }

    return parent::getHelpInstallation();
  }

  public function getVersionInfo() {
    $info = array(
      'LibreOffice' => $this->shell($this->cmd . " --version")
    );
    $info["LibreOffice"] = preg_replace('@LibreOffice *@si', '', $info['LibreOffice']);
    return $info;
  }

  public function isAvailable() {
    $this->cmd = $this->shellWhich('soffice');
    return isset($this->cmd);
  }

}

<?php
namespace Witti\FileConverter\Engine\Convert;

use Witti\FileConverter\Engine\EngineBase;
class LibreOffice extends EngineBase {
  protected $cmd_source_safe = FALSE;

  public function getConvertFileShell($source, &$destination) {
    $destination = str_replace('.' . $this->conversion[0], '.'
      . $this->conversion[1], $source);
    return array(
      $this->cmd,
      '--headless',
      '--convert-to',
      $this->conversion[1],
      '--outdir',
      $this->settings['temp_dir'],
      $source
    );
  }

  public function getHelpInstallation($os, $os_version) {
    $help = "";
    switch ($os) {
      case 'Ubuntu':
        $help .= "/usr/bin/libreoffice is symlink to /usr/lib/libreoffice/program/soffice\n";
        $help .= "sudo apt-get install libreoffice\n";
        return $help;
    }

    return parent::getHelpInstallation();
  }

  public function getVersionInfo() {
    $info = array(
      'LibreOffice' => $this->shell($this->cmd . " --version")
    );
    $info["LibreOffice"] = preg_replace('@LibreOffice *@si', '', $info['LibreOffice']);
    return $info;
  }

  public function isAvailable() {
    $this->cmd = $this->shellWhich('libreoffice');
    return isset($this->cmd);
  }

}

Use libreoffice rather than soffice to distinguish from OpenOffice.


<?php namespace Samuell\ContentEditor\Http\Controllers;

use Response;
use Illuminate\Routing\Controller;
use Samuell\ContentEditor\Models\Settings;

class AdditionalStylesController extends Controller
{
    public function render()
    {
        return Response::make(Settings::renderCss(), 200)
            ->header('Content-Type', 'text/css');
    }
}

<?php namespace Samuell\ContentEditor\Http\Controllers;

use Response;
use Illuminate\Routing\Controller;
use Samuell\ContentEditor\Models\Settings;

class AdditionalStylesController extends Controller
{
    public function render()
    {
        return Response::make(Settings::renderCss(), 200)
            ->header('Content-Type', 'text/css')
            ->header('Cache-Control', 'public, max-age=86400');
    }
}

Add Cache-Control for Styles route

Add Cache-Control for Styles route


<?php
/**
 * Created by PhpStorm.
 * User: mark.smith
 * Date: 04/09/2017
 * Time: 19:31
 */

namespace AppBundle\Utils\Api;

use AppBundle\Utils\Api;

class Redis extends Api implements \AppBundle\Utils\Api\ApiInterface
{
    protected $storageClass = 'redis';

    public function __construct()
    {
        $this->setStorageClass($this->storageClass);
    }

    public function read($what)
    {
        $this->setWhat($what);

        return parent::doRead();
    }

    public function update($data, $what)
    {

    }

    public function create($data)
    {
        $this->setData($data);

        parent::doCreate();
    }

    public function delete($what)
    {

    }
}

<?php
/**
 * Created by PhpStorm.
 * User: mark.smith
 * Date: 04/09/2017
 * Time: 19:31
 */

namespace AppBundle\Utils\Api;

use AppBundle\Utils\Api;

class Redis extends Api implements \AppBundle\Utils\Api\ApiInterface
{
    protected $storageClass = 'redis';

    public function __construct()
    {
        $this->setStorageClass($this->storageClass);
    }

    public function read($what)
    {
        $this->setWhat($what);

        return parent::doRead();
    }

    public function update($data, $what)
    {

    }

    public function create($data)
    {
        $this->setData($data);

        return parent::doCreate();
    }

    public function delete($what)
    {

    }
}

Set return on parent when using api::create


<?php

namespace Nilz\Money\PriceTag;

use Nilz\Money\Currency\ExchangeRate;
use Nilz\Money\MoneyInterface;

/**
 * Class CurrencyPriceTag
 * @author Nilz
 */
class CurrencyPriceTag extends PriceTag
{
    /**
     * @var ExchangeRate
     */
    protected $exchangeRate;

    /**
     * @param MoneyInterface $netPrice
     * @param MoneyInterface $grossPrice
     * @param float          $taxPercentage
     * @param ExchangeRate   $exchangeRate
     */
    public function __construct(MoneyInterface $netPrice, MoneyInterface $grossPrice, $taxPercentage, $baseCurrency, ExchangeRate $exchangeRate)
    {
        parent::__construct($netPrice, $grossPrice, $taxPercentage);

        $this->exchangeRate = $exchangeRate;
    }

    /**
     * @return ExchangeRate
     */
    public function getExchangeRate()
    {
        return $this->exchangeRate;
    }
}

<?php

namespace Nilz\Money\PriceTag;

use Nilz\Money\Currency\ExchangeRate;
use Nilz\Money\MoneyInterface;

/**
 * Class CurrencyPriceTag
 * @author Nilz
 */
class CurrencyPriceTag extends PriceTag
{
    /**
     * @var ExchangeRate
     */
    protected $exchangeRate;

    /**
     * @param MoneyInterface $netPrice
     * @param MoneyInterface $grossPrice
     * @param float          $taxPercentage
     * @param ExchangeRate   $exchangeRate
     */
    public function __construct(MoneyInterface $netPrice, MoneyInterface $grossPrice, $taxPercentage, ExchangeRate $exchangeRate)
    {
        parent::__construct($netPrice, $grossPrice, $taxPercentage);

        $this->exchangeRate = $exchangeRate;
    }

    /**
     * @return ExchangeRate
     */
    public function getExchangeRate()
    {
        return $this->exchangeRate;
    }
}

Fix in constructor of currency price tag


<?php

use Illuminate\Support\Facades\Request;
use Orchestra\Support\Facades\Asset; ?>

© 2012 Orchestra Platform

<?php

$asset = Asset::container('orchestra/foundation::footer');

$asset->script('bootstrap', 'packages/orchestra/foundation/vendor/bootstrap/js/bootstrap.min.js');
$asset->script('jquery-ui', 'packages/orchestra/foundation/vendor/jquery.ui.js');
$asset->script('orchestra', 'packages/orchestra/foundation/js/script.min.js', array('bootstrap', 'jquery-ui'));
$asset->script('jui-toggleSwitch', 'packages/orchestra/foundation/vendor/delta/js/jquery-ui.toggleSwitch.js', array('jquery-ui'));
$asset->script('select2', 'packages/orchestra/foundation/vendor/select2/select2.min.js');

echo $asset->styles();
echo $asset->scripts(); ?>

@placeholder("orchestra.layout: footer")

<?php

use Illuminate\Support\Facades\Request;
use Orchestra\Support\Facades\Asset; ?>

			Powered by Orchestra Platform.

<?php

$asset = Asset::container('orchestra/foundation::footer');

$asset->script('bootstrap', 'packages/orchestra/foundation/vendor/bootstrap/js/bootstrap.min.js');
$asset->script('jquery-ui', 'packages/orchestra/foundation/vendor/jquery.ui.js');
$asset->script('orchestra', 'packages/orchestra/foundation/js/script.min.js', array('bootstrap', 'jquery-ui'));
$asset->script('jui-toggleSwitch', 'packages/orchestra/foundation/vendor/delta/js/jquery-ui.toggleSwitch.js', array('jquery-ui'));
$asset->script('select2', 'packages/orchestra/foundation/vendor/select2/select2.min.js');

echo $asset->styles();
echo $asset->scripts(); ?>

@placeholder("orchestra.layout: footer")

Change footer to show "Powered by Orchestra Platform" instead of a copyright.

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

/**
 * Class ExtractorStorage
 */
class ExtractorStorage {
    /**
     * Store Data
     * Stores data in the data store with the given key and category.
     *
     * @param string $cat  Store category
     * @param string $key  File key
     * @param array  $data Data array
     *
     * @return true
     */
    public static function store($cat, $key, $data) {
        if (!file_exists(DATADIR . $cat)) {
            mkdir(DATADIR . $cat, 0755);
        }

        file_put_contents(DATADIR . $cat . DS . $key . '.json', json_encode($data, JSON_PRETTY_PRINT));

        return true;
    }

    /**
     * Fetch Store
     * Fetches the given store key in the given category.
     *
     * @param string $cat Store category
     * @param string $key File key
     *
     * @return array|false
     */
    public static function fetch($cat, $key) {
        if (!file_exists(DATADIR . $cat . DS . $key . '.json')) {
            return false;
        }

        return json_decode(file_get_contents(DATADIR . $cat . DS . $key . '.json'), true);
    }
}

<?php

/**
 * Class ExtractorStorage
 */
class ExtractorStorage {
    /**
     * Store Data
     * Stores data in the data store with the given key and category.
     *
     * @param string $cat  Store category
     * @param string $key  File key
     * @param array  $data Data array
     *
     * @return true
     */
    public static function store($cat, $key, $data) {
        if (!file_exists(DATADIR . $cat)) {
            mkdir(DATADIR . $cat, 0755);
        }

        file_put_contents(DATADIR . $cat . DS . $key . '.json', json_encode($data, JSON_PRETTY_PRINT));

        return true;
    }

    /**
     * Fetch Store
     * Fetches the given store key in the given category.
     *
     * @param string $cat Store category
     * @param string $key File key
     *
     * @return array|false
     */
    public static function fetch($cat, $key) {
        if (!file_exists(DATADIR . $cat . DS . $key . '.json')) {
            return false;
        }

        return json_decode(file_get_contents(DATADIR . $cat . DS . $key . '.json'), true);
    }

    /**
     * Append to Store
     * Appends data to the end of a store.
     *
     * @param string $cat  Store category
     * @param string $key  File key
     * @param array  $data Data array to be appended
     *
     * @return bool
     */
    public static function append($cat, $key, $data) {
        $fetch = self::fetch($cat, $key);

        if ($fetch === false) {
            $fetch = array();
        }

        $fetch[] = $data;

        self::store($cat, $key, $fetch);

        return true;
    }
}

Add append method to store.

Add append method to store.


<?php

  namespace ActiveCollab\Shade\Command;

  use ActiveCollab\Shade\Project, ActiveCollab\Shade\Element\Video;
  use Symfony\Component\Console\Command\Command, Symfony\Component\Console\Input\InputInterface, Symfony\Component\Console\Output\OutputInterface;

  /**
   * Create a new project
   *
   * @package ActiveCollab\Shade\Command
   */
  class ProjectCommand extends Command
  {
    /**
     * Configure the command
     */
    function configure()
    {
      $this->setName('project')->addArgument('name')->setDescription('Create a new project');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
      $project = new Project(getcwd());

      if($project->isValid()) {
        $output->writeln('Project already initialized');
      } else {
        $configuration = [
          'name' => $input->getArgument('name'),
          'video_groups' => [
            Video::GETTING_STARTED => 'Getting Started',
          ]
        ];

        if (empty($configuration['name'])) {
          $configuration['name'] = basename($project->getPath());
        }

        if (file_put_contents($project->getPath() . '/project.json', json_encode($configuration, JSON_PRETTY_PRINT))) {
          $output->writeln('Project initialized');
        } else {
          $output->writeln('<error>Failed to create a project configuration file</error>');
        }
      }
    }
  }

<?php

  namespace ActiveCollab\Shade\Command;

  use ActiveCollab\Shade\Project, ActiveCollab\Shade\Element\Video;
  use Symfony\Component\Console\Command\Command, Symfony\Component\Console\Input\InputInterface, Symfony\Component\Console\Output\OutputInterface;

  /**
   * Create a new project
   *
   * @package ActiveCollab\Shade\Command
   */
  class ProjectCommand extends Command
  {
    /**
     * Configure the command
     */
    function configure()
    {
      $this->setName('project')->addArgument('name')->setDescription('Create a new project');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
      $project = new Project(getcwd());

      if($project->isValid()) {
        $output->writeln('Project already initialized');
      } else {
        $configuration = [
          'name' => $input->getArgument('name'),
          'video_groups' => [
            Video::GETTING_STARTED => 'Getting Started',
          ]
        ];

        if (empty($configuration['name'])) {
          $configuration['name'] = basename($project->getPath());
        }

        if (file_put_contents($project->getPath() . '/project.json', json_encode($configuration, JSON_PRETTY_PRINT))) {
          $output->writeln('Project initialized');
        } else {
          $output->writeln('<error>Failed to create a project configuration file</error>');
        }

        if (!mkdir($project->getPath() . '/temp')) {
          $output->writeln('<error>Failed to create temp folder</error>');
        }
      }
    }
  }

Create a temp folder when project is being created


<?php

use yii\db\Migration;

/**
 * Handles the creation of table `faces`.
 * Has foreign keys to the tables:
 *
 * - `image`
 */
class m170124_153250_create_faces_table extends Migration
{
    /**
     * @inheritdoc
     */
    public function up()
    {
        $this->createTable('faces', [
            'id' => $this->primaryKey(),
            'image_id' => $this->integer()->notNull(),
            'confident_level' => $this->string(),
            'gender' => $this->string(),
        ]);

        // creates index for column `image_id`
        $this->createIndex(
            'idx-faces-image_id',
            'faces',
            'image_id'
        );

        // add foreign key for table `image`
        $this->addForeignKey(
            'fk-faces-image_id',
            'faces',
            'image_id',
            'image',
            'id',
            'CASCADE'
        );
    }

    /**
     * @inheritdoc
     */
    public function down()
    {
        // drops foreign key for table `image`
        $this->dropForeignKey(
            'fk-faces-image_id',
            'faces'
        );

        // drops index for column `image_id`
        $this->dropIndex(
            'idx-faces-image_id',
            'faces'
        );

        $this->dropTable('faces');
    }
}

<?php

use yii\db\Migration;

/**
 * Handles the creation of table `faces`.
 * Has foreign keys to the tables:
 *
 * - `image`
 */
class m170124_153250_create_faces_table extends Migration
{
    /**
     * @inheritdoc
     */
    public function up()
    {
        $this->createTable('faces', [
            'id' => $this->primaryKey(),
            'image_id' => $this->integer()->notNull(),
            'width' => $this->integer()->notNull(),
            'height' => $this->integer()->notNull(),
            'confident_level' => $this->string(),
            'gender' => $this->string(),
        ]);

        // creates index for column `image_id`
        $this->createIndex(
            'idx-faces-image_id',
            'faces',
            'image_id'
        );

        // add foreign key for table `image`
        $this->addForeignKey(
            'fk-faces-image_id',
            'faces',
            'image_id',
            'image',
            'id',
            'CASCADE'
        );
    }

    /**
     * @inheritdoc
     */
    public function down()
    {
        // drops foreign key for table `image`
        $this->dropForeignKey(
            'fk-faces-image_id',
            'faces'
        );

        // drops index for column `image_id`
        $this->dropIndex(
            'idx-faces-image_id',
            'faces'
        );

        $this->dropTable('faces');
    }
}

Add width heigt column to face migration file


<?php
include 'config.sample.inc.php';

$cfg['Servers'][1]['host'] = 'mysql';
$file_with_secret = 'config.inc.secret.php';

if (!file_exists($file_with_secret)) {
	$secret = hash('sha512', openssl_random_pseudo_bytes(1000));
	file_put_contents(
		$file_with_secret,
		"<?php \$cfg['blowfish_secret'] = '$secret';"
	);
}

include $file_with_secret;

<?php
include 'config.sample.inc.php';

$server_host = (!empty($_ENV['MYSQL_SERVER_HOST'])) ? $_ENV['MYSQL_SERVER_HOST'] : 'mysql';

$cfg['Servers'][1]['host'] = $server_host;
$file_with_secret = 'config.inc.secret.php';

if (!file_exists($file_with_secret)) {
	$secret = hash('sha512', openssl_random_pseudo_bytes(1000));
	file_put_contents(
		$file_with_secret,
		"<?php \$cfg['blowfish_secret'] = '$secret';"
	);
}

include $file_with_secret;

Allow external MySQL instance connection

Add the hability to connect to an unlink MySQL database by  passing the MYSQL_SERVER_HOST env variable


<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

/**
 * Enable the EXIF metadata listener
 */
return [
    'eventListeners' => [
        '8BIMMetadataListener' => [
            'listener' => 'Imbo\EventListener\EightbimMetadata',
        ]
    ],
];

<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

/**
 * Enable the 8BIM metadata listener
 */
return [
    'eventListeners' => [
        '8BIMMetadataListener' => [
            'listener' => 'Imbo\EventListener\EightbimMetadata',
        ]
    ],
];

Fix copy'n'paste error in config description


<?php declare(strict_types=1);

namespace Gos\Bundle\WebSocketBundle\EventListener;

use Gos\Bundle\WebSocketBundle\Pusher\PusherRegistry;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Symfony\Component\HttpKernel\Event\TerminateEvent;

final class KernelTerminateListener
{
    private PusherRegistry $pusherRegistry;

    public function __construct(PusherRegistry $pusherRegistry)
    {
        $this->pusherRegistry = $pusherRegistry;
    }

    /**
     * @param PostResponseEvent|TerminateEvent $event
     */
    public function closeConnection(object $event): void
    {
        if (!($event instanceof PostResponseEvent) && !($event instanceof TerminateEvent)) {
            throw new \InvalidArgumentException(sprintf('The $event argument of %s() must be an instance of %s or %s, a %s was given.', __METHOD__, PostResponseEvent::class, TerminateEvent::class, \get_class($event)));
        }

        foreach ($this->pusherRegistry->getPushers() as $pusher) {
            $pusher->close();
        }
    }
}

<?php declare(strict_types=1);

namespace Gos\Bundle\WebSocketBundle\EventListener;

use Gos\Bundle\WebSocketBundle\Pusher\PusherRegistry;
use Symfony\Component\HttpKernel\Event\TerminateEvent;

final class KernelTerminateListener
{
    private PusherRegistry $pusherRegistry;

    public function __construct(PusherRegistry $pusherRegistry)
    {
        $this->pusherRegistry = $pusherRegistry;
    }

    public function closeConnection(TerminateEvent $event): void
    {
        foreach ($this->pusherRegistry->getPushers() as $pusher) {
            $pusher->close();
        }
    }
}

Remove compat check, TerminateEvent exists in 4.4


<?php namespace Morrislaptop\LaravelFivePackageBridges;

use ReflectionClass;

trait LaravelFivePackageBridgeTrait {

	public function boot()
	{
		$this->loadViewsFrom($this->namespace, $this->guessPackagePath() . '/views');
		$this->loadTranslationsFrom($this->namespace, $this->guessPackagePath() . '/lang');
		$this->app['config']->package($this->vendor . '/' . $this->namespace, $this->guessPackagePath() . '/config', $this->namespace);
	}

	protected function guessPackagePath() {
		$path = (new ReflectionClass(get_parent_class()))->getFileName();

		return realpath(dirname($path).'/../../');
	}

}

<?php namespace Morrislaptop\LaravelFivePackageBridges;

use ReflectionClass;

trait LaravelFivePackageBridgeTrait {

	public function boot()
	{
		$this->loadViewsFrom($this->namespace, $this->guessPackagePath() . '/views');
		$this->loadTranslationsFrom($this->namespace, $this->guessPackagePath() . '/lang');
		$this->setConfig();
		$this->app['config']->package($this->vendor . '/' . $this->namespace, $this->guessPackagePath() . '/config', $this->namespace);
	}

	protected function guessPackagePath() {
		$path = (new ReflectionClass(get_parent_class()))->getFileName();

		return realpath(dirname($path).'/../../');
	}

	protected function setConfig() {
		$config = require $this->guessPackagePath() . '/config/config.php';
		$this->app['config']->set($this->namespace, $config);
	}

}

Update for removal of config->package

Update for removal of config->package


<?php

namespace FileNamingResolver\NamingStrategy;

use FileNamingResolver\FileInfo;

/**
 * @author Victor Bocharsky <bocharsky.bw@gmail.com>
 */
class CallbackNamingStrategy extends AbstractNamingStrategy
{
    /**
     * @var callable
     */
    protected $callback;

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

    /**
     * {@inheritdoc}
     */
    public function provideName(FileInfo $srcFileInfo)
    {
        $func = $this->callback;

        return (string)$func($srcFileInfo);
    }

    /**
     * @return callable
     */
    public function getCallback()
    {
        return $this->callback;
    }
}

<?php

namespace FileNamingResolver\NamingStrategy;

use FileNamingResolver\FileInfo;

/**
 * @author Victor Bocharsky <bocharsky.bw@gmail.com>
 */
class CallbackNamingStrategy extends AbstractNamingStrategy
{
    /**
     * @var \Closure
     */
    protected $callback;

    /**
     * @param \Closure $callback
     */
    public function __construct(\Closure $callback)
    {
        $this->callback = $callback;
    }

    /**
     * {@inheritdoc}
     */
    public function provideName(FileInfo $srcFileInfo)
    {
        $func = $this->callback;

        return (string)$func($srcFileInfo);
    }

    /**
     * @return \Closure
     */
    public function getCallback()
    {
        return $this->callback;
    }
}

Fix tests for PHP 5.3

Fix tests for PHP 5.3


{{--
    Copyright (c) ppy Pty Ltd <contact@ppy.sh>.

    This file is part of osu!web. osu!web is distributed with the hope of
    attracting more community contributions to the core ecosystem of osu!.

    osu!web is free software: you can redistribute it and/or modify
    it under the terms of the Affero GNU General Public License version 3
    as published by the Free Software Foundation.

    osu!web is distributed 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 osu!web.  If not, see <http://www.gnu.org/licenses/>.
--}}
@extends('forum.topics.replace_delete_button', ['countDifference' => -1])

@section('moderatorAction')
    $el.addClass("js-forum-post--hidden");
@endsection

{{--
    Copyright (c) ppy Pty Ltd <contact@ppy.sh>.

    This file is part of osu!web. osu!web is distributed with the hope of
    attracting more community contributions to the core ecosystem of osu!.

    osu!web is free software: you can redistribute it and/or modify
    it under the terms of the Affero GNU General Public License version 3
    as published by the Free Software Foundation.

    osu!web is distributed 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 osu!web.  If not, see <http://www.gnu.org/licenses/>.
--}}
@extends('forum.topics.replace_delete_button', ['countDifference' => -1])

@section('moderatorAction')
    $deletedToggle = document.querySelector(".js-forum-topic-moderate--toggle-deleted");

    if ($deletedToggle.dataset.showDeleted === "1") {
        $el.addClass("js-forum-post--hidden");
    } else {
        $el.remove();
    }
@endsection

Remove deleted posts from DOM when not showing deleted posts