<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
}

<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestResponse;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    function setUp()
    {
        parent::setUp();

        // Define an assertion method to test if an
        // HTTP response has a given conten-type.
        //
        // The macro signature is as follows:
        // TestResponse assertContentType(string $contentType)
        TestResponse::macro('assertContentType', function ($contentType) {

            $utf8Formats = ['text/html', 'text/xml', 'text/csv'];

            if (in_array($contentType, $utf8Formats)) {
                $contentType .= '; charset=UTF-8';
            }

            $this->assertHeader('Content-Type', $contentType);

            // Return the instance to allow chaining.
            return $this;
        });
    }
}

Define test assertion for content type of response


<?php

final class PhabricatorFileUploadDialogController
  extends PhabricatorFileController {

  public function processRequest() {
    $request = $this->getRequest();
    $user = $request->getUser();

    $dialog = id(new AphrontDialogView())
      ->setUser($user)
      ->setTitle(pht('Upload Image'))
      ->appendChild(pht(
        'To add files, drag and drop them into the comment text area.'))
      ->addCancelButton('/', pht('Close'));

    return id(new AphrontDialogResponse())->setDialog($dialog);
  }

}

<?php

final class PhabricatorFileUploadDialogController
  extends PhabricatorFileController {

  public function processRequest() {
    $request = $this->getRequest();
    $user = $request->getUser();

    $dialog = id(new AphrontDialogView())
      ->setUser($user)
      ->setTitle(pht('Upload File'))
      ->appendChild(pht(
        'To add files, drag and drop them into the comment text area.'))
      ->addCancelButton('/', pht('Close'));

    return id(new AphrontDialogResponse())->setDialog($dialog);
  }

}

Rename "Upload Image" dialog to "Upload File" to match purpose

Summary: Fixes T3940.

Test Plan: Clicked button, looked at dialog.

Reviewers: epriestley, #blessed_reviewers

Reviewed By: epriestley

CC: nmalcolm, Korvin, epriestley, aran

Maniphest Tasks: T3940

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


<?php

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

class CreateUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('users', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('email')->nullable();
			$table->string('password')->nullable();
			$table->string('displayName')->nullable();
			$table->string('facebook')->nullable();
			$table->string('foursquare')->nullable();
			$table->string('instagram')->nullable();
			$table->string('github')->nullable();
			$table->string('google')->nullable();
			$table->string('linkedin')->nullable();
			$table->string('twitter')->nullable();
			$table->timestamps();
		});
	}

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

}

<?php

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

class CreateUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('users', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('email')->nullable();
			$table->string('password')->nullable();
			$table->string('displayName')->nullable();
			$table->string('facebook')->nullable();
			$table->string('foursquare')->nullable();
			$table->string('instagram')->nullable();
			$table->string('github')->nullable();
			$table->string('google')->nullable();
			$table->string('linkedin')->nullable();
			$table->string('twitter')->nullable();
			$table->string('picture')->nullable();
			$table->timestamps();
		});
	}

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

}

Add picture field in user schema

Add picture field in user schema

for loading from google profile data


<?php

namespace JBBCode\validators;

require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'InputValidator.php';

/**
 * An InputValidator that allows for shortcut implementation
 * of a validator using callable types (a function or a \Closure).
 *
 * @author Kubo2
 * @since Feb 2020
 */
class FnValidator implements \JBBCode\InputValidator
{
	/**
	 * @var callable
	 */
	private $validator;

	/**
	 * Construct a custom validator from a callable.
	 * @param callable $validator
	 */
	public function __construct(callable $validator)
	{
		$this->validator = $validator;
	}

	/**
	 * Returns true iff the given input is valid, false otherwise.
	 * @param string $input
	 * @return boolean
	 */
	public function validate($input)
	{
		return (bool) ($this->validator)($input);
	}
}

<?php

namespace JBBCode\validators;

require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'InputValidator.php';

/**
 * An InputValidator that allows for shortcut implementation
 * of a validator using callable types (a function or a \Closure).
 *
 * @author Kubo2
 * @since Feb 2020
 */
class FnValidator implements \JBBCode\InputValidator
{
	/**
	 * @var callable
	 */
	private $validator;

	/**
	 * Construct a custom validator from a callable.
	 * @param callable $validator
	 */
	public function __construct(callable $validator)
	{
		$this->validator = $validator;
	}

	/**
	 * Returns true iff the given input is valid, false otherwise.
	 * @param string $input
	 * @return boolean
	 */
	public function validate($input)
	{
		$validator = $this->validator; // FIXME: for PHP>=7.0 replace with ($this->validator)($input)
		return (bool) $validator($input);
	}
}

Fix callable validator BC for PHP<=5.6

Fix callable validator BC for PHP<=5.6


<?php

/*
 * This file is part of Feefo.
 *
 * (c) Blue Bay Travel <developers@bluebaytravel.co.uk>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace BlueBayTravel\Feefo;

class FeefoItem
{
    /**
     * Array of data.
     *
     * @var array
     */
    protected $data = [];

    /**
     * Create a new feefo item instance.
     *
     * @param array $data
     *
     * @return void
     */
    public function __construct(array $data)
    {
        $this->data = $data;
    }

    /**
     * Magic method to get back from Feefo item.
     *
     * @param string $key
     *
     * @return mixed
     */
    public function __get($key)
    {
        $safeKey = strtoupper($key);
        if (isset($data[$safeKey])) {
            return $data[$safeKey];
        }
    }
}

<?php

/*
 * This file is part of Feefo.
 *
 * (c) Blue Bay Travel <developers@bluebaytravel.co.uk>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace BlueBayTravel\Feefo;

class FeefoItem
{
    /**
     * Array of data.
     *
     * @var array
     */
    protected $data = [];

    /**
     * Create a new feefo item instance.
     *
     * @param array $data
     *
     * @return void
     */
    public function __construct(array $data)
    {
        $this->data = $data;
    }

    /**
     * Magic method to get back from Feefo item.
     *
     * @param string $key
     *
     * @return mixed
     */
    public function __get($key)
    {
        $safeKey = str_replace('_', '', strtoupper($key));
        if (isset($data[$safeKey])) {
            return $data[$safeKey];
        }
    }
}

Allow for underscores in magic method names


<?php

namespace ilateral\SilverStripe\Searchable\Extensions;

use ilateral\SilverStripe\Searchable\Model\SearchTable;
use ilateral\SilverStripe\Searchable\Searchable;
use SilverStripe\Core\Config\Config;
use SilverStripe\ORM\DataExtension;

class SearchableObjectExtension extends DataExtension
{
    private static $belongs_to = [
        'SearchRecord' => SearchTable::class
    ];

    /**
     * After base object is written, sync fields to search table
     *
     * @return null
     */
    public function onAfterWrite()
    {
        /** @var \SilverStripe\ORM\DataObject */
        $owner = $this->getOwner();
        $ancestors = $owner->getClassAncestry();
        $search = $owner->SearchRecord();
        $objects = Config::inst()->get(Searchable::class, 'objects');

        // if objects isn't set cancel
        if (!is_array($objects)) {
            return;
        }

        $write = false;

        foreach (array_keys($objects) as $classname) {
            if (in_array($classname, $ancestors)) {
                foreach ($objects[$classname] as $field) {
                    if (isset($owner->$field)) {
                        $search->$field = $owner->$field;
                        $write = true;
                    }
                }
            }
        }

        if ($write) {
            $search->write();
        }
    }

    /**
     * Delete the linked search record if this record is deleted
     *
     * @return null
     */
    public function onAfterDelete()
    {
        $this->getOwner()->SearchRecord()->delete();
    }
}

<?php

namespace ilateral\SilverStripe\Searchable\Extensions;

use ilateral\SilverStripe\Searchable\Model\SearchTable;
use ilateral\SilverStripe\Searchable\Searchable;
use SilverStripe\Core\Config\Config;
use SilverStripe\ORM\DataExtension;

class SearchableObjectExtension extends DataExtension
{
    private static $belongs_to = [
        'SearchRecord' => SearchTable::class . '.BaseObject'
    ];

    /**
     * After base object is written, sync fields to search table
     *
     * @return null
     */
    public function onAfterWrite()
    {
        /** @var \SilverStripe\ORM\DataObject */
        $owner = $this->getOwner();
        $ancestors = $owner->getClassAncestry();
        $search = $owner->SearchRecord();
        $objects = Config::inst()->get(Searchable::class, 'objects');

        // if objects isn't set cancel
        if (!is_array($objects)) {
            return;
        }

        $write = false;

        foreach (array_keys($objects) as $classname) {
            if (in_array($classname, $ancestors)) {
                foreach ($objects[$classname] as $field) {
                    if (isset($owner->$field)) {
                        $search->$field = $owner->$field;
                        $write = true;
                    }
                }
            }
        }

        if ($write) {
            $search->write();
        }
    }

    /**
     * Delete the linked search record if this record is deleted
     *
     * @return null
     */
    public function onAfterDelete()
    {
        $this->getOwner()->SearchRecord()->delete();
    }
}

Add dot notation to search record belongs to


<?php
namespace wcf\system\form\builder\field;
use wcf\data\language\Language;
use wcf\system\form\builder\field\validation\FormFieldValidationError;
use wcf\util\Url;

/**
 * Implementation of a form field to enter a url.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2019 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Form\Builder\Field
 * @since	5.2
 */
class UrlFormField extends TextFormField {
	/**
	 * @inheritDoc
	 */
	protected function validateText($text, Language $language = null) {
		if ($this->isRequired() && ($this->getValue() === null || $this->getValue() === '')) {
			if (!Url::is($text)) {
				$this->addValidationError(new FormFieldValidationError(
					'invalid',
					'wcf.form.field.url.error.invalid',
					['language' => $language]
				));
			}
			else {
				parent::validateText($text, $language);
			}
		}
	}
}

<?php
namespace wcf\system\form\builder\field;
use wcf\data\language\Language;
use wcf\system\form\builder\field\validation\FormFieldValidationError;
use wcf\util\Url;

/**
 * Implementation of a form field to enter a url.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2020 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Form\Builder\Field
 * @since	5.2
 */
class UrlFormField extends TextFormField {
	/**
	 * @inheritDoc
	 */
	protected function validateText($text, Language $language = null) {
		if ($this->isRequired() && ($this->getValue() === null || $this->getValue() === '')) {
			$this->addValidationError(new FormFieldValidationError('empty'));
		}
		else if ($this->getValue() !== null && $this->getValue() !== '') {
			if (!Url::is($text)) {
				$this->addValidationError(new FormFieldValidationError(
					'invalid',
					'wcf.form.field.url.error.invalid',
					['language' => $language]
				));
			}
			else {
				parent::validateText($text, $language);
			}
		}
	}
}

Fix validation of url form field value

Fix validation of url form field value

Close #3390


<?php
namespace Oro\Bundle\OrganizationBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr;

use Oro\Bundle\OrganizationBundle\Entity\Organization;

class OrganizationRepository extends EntityRepository
{
    /**
     * Finds the first record
     *
     * @return Organization
     */
    public function getFirst()
    {
        return $this->getEntityManager()
            ->createQuery('SELECT org FROM OroOrganizationBundle:Organization org ORDER BY org.id')
            ->setMaxResults(1)
            ->getSingleResult();
    }

    public function getOrganizationById($id)
    {
        return $this->getEntityManager()
            ->createQuery('SELECT org FROM OroOrganizationBundle:Organization org WHERE org.id = :id')
            ->setParameter('id', $id)
            ->getSingleResult();
    }

    /**
     * Update all records in given table with organization id
     *
     * @param string  $tableName table name to update, example: OroCRMAccountBundle:Account or OroUserBundle:Group
     * @param integer $id        Organization id
     *
     * @return integer Number of rows affected
     */
    public function updateWithOrganization($tableName, $id)
    {
        return $this->getEntityManager()
            ->createQueryBuilder()
            ->update($tableName, 't')
            ->set('t.organization', ':id')
            ->setParameter('id', $id)
            ->getQuery()
            ->execute();
    }
}

<?php
namespace Oro\Bundle\OrganizationBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr;

use Oro\Bundle\OrganizationBundle\Entity\Organization;

class OrganizationRepository extends EntityRepository
{
    /**
     * Finds the first record
     *
     * @return Organization
     */
    public function getFirst()
    {
        return $this->getEntityManager()
            ->createQuery('SELECT org FROM OroOrganizationBundle:Organization org ORDER BY org.id')
            ->setMaxResults(1)
            ->getSingleResult();
    }

    /**
     * Get organization by id
     *
     * @param $id
     * @return Organization
     */
    public function getOrganizationById($id)
    {
        return $this->getEntityManager()
            ->createQuery('SELECT org FROM OroOrganizationBundle:Organization org WHERE org.id = :id')
            ->setParameter('id', $id)
            ->getSingleResult();
    }

    /**
     * Update all records in given table with organization id
     *
     * @param string  $tableName table name to update, example: OroCRMAccountBundle:Account or OroUserBundle:Group
     * @param integer $id        Organization id
     *
     * @return integer Number of rows affected
     */
    public function updateWithOrganization($tableName, $id)
    {
        return $this->getEntityManager()
            ->createQueryBuilder()
            ->update($tableName, 't')
            ->set('t.organization', ':id')
            ->setParameter('id', $id)
            ->getQuery()
            ->execute();
    }
}

OEE-54: Modify ACL. Refactor ACL Walker.
   - Add set organization listener


<?php
/**
 * Created by PhpStorm.
 * User: Michal
 * Date: 8.1.14
 * Time: 19:02
 */

namespace AnnotateCms\Themes\DI;

use AnnotateCms\Themes\Loaders\ThemesLoader;
use Kdyby\Events\DI\EventsExtension;
use Nette\DI\CompilerExtension;

class ThemesExtension extends CompilerExtension
{

	private $defaults = array(
		"frontend" => "Sandbox",
	);

	public function loadConfiguration()
	{
		$builder = $this->getContainerBuilder();

		$config = $this->getConfig($this->defaults);

		$builder->addDefinition($this->prefix("themesLoader"))
			->setClass(ThemesLoader::classname)
			->addTag(EventsExtension::SUBSCRIBER_TAG)
			->addSetup("setFrontendTheme", array("name" => $config["frontend"]))
			->addSetup("setBackendTheme", array("name" => $config["backend"]));
	}

}

<?php
/**
 * Created by PhpStorm.
 * User: Michal
 * Date: 8.1.14
 * Time: 19:02
 */

namespace AnnotateCms\Themes\DI;

use AnnotateCms\Themes\Loaders\ThemesLoader;
use Kdyby\Events\DI\EventsExtension;
use Nette\DI\CompilerExtension;

class ThemesExtension extends CompilerExtension
{

	private $defaults = array(
		"frontend" => "Sandbox",
		"backend" => "Flatty",
	);

	public function loadConfiguration()
	{
		$builder = $this->getContainerBuilder();

		$config = $this->getConfig($this->defaults);

		$builder->addDefinition($this->prefix("themesLoader"))
			->setClass(ThemesLoader::classname)
			->addTag(EventsExtension::SUBSCRIBER_TAG)
			->addSetup("setFrontendTheme", array("name" => $config["frontend"]))
			->addSetup("setBackendTheme", array("name" => $config["backend"]));
	}

}

Fix backend theme key in configuration

Fix backend theme key in configuration


<?php

namespace Oro\Bundle\CurrencyBundle\Provider;

use Oro\Bundle\OrganizationBundle\Entity\Organization;

interface RepositoryCurrencyProviderInterface
{
    /**
     * Return translated label of entity
     *
     * @return string
     */
    public function getEntityLabel();

    /**
     * @param array             $availableCurrencies
     * @param Organization|null $organization
     *
     * @return bool
     */
    public function hasRecordsInUnavailableCurrencies(
        array $availableCurrencies,
        Organization $organization = null
    );
}

<?php

namespace Oro\Bundle\CurrencyBundle\Provider;

use Oro\Bundle\OrganizationBundle\Entity\Organization;

interface RepositoryCurrencyProviderInterface
{
    /**
     * Return translated label of entity
     *
     * @return string
     */
    public function getEntityLabel();

    /**
     * @param array             $currenciesOnRemove
     * @param Organization|null $organization
     *
     * @return bool
     */
    public function hasRecordsInCurrenciesOnRemove(
        array $currenciesOnRemove,
        Organization $organization = null
    );
}

OEE-1164: Add multi-curency validator to available currency form
- Fixed issue with organization


<?php

namespace Liip\ImagineBundle\Templating;

use Liip\ImagineBundle\Imagine\Cache\CacheManager;

class ImagineExtension extends \Twig_Extension
{
    /**
     * @var CacheManager
     */
    private $cacheManager;

    /**
     * Constructor.
     *
     * @param CacheManager $cacheManager
     */
    public function __construct(CacheManager $cacheManager)
    {
        $this->cacheManager = $cacheManager;
    }

    /**
     * {@inheritDoc}
     */
    public function getFilters()
    {
        return array(
            'imagine_filter' => new \Twig_Filter_Method($this, 'filter'),
        );
    }

    /**
     * Gets the browser path for the image and filter to apply.
     *
     * @param string $path
     * @param string $filter
     * @param array  $runtimeConfig
     *
     * @return \Twig_Markup
     */
    public function filter($path, $filter, array $runtimeConfig = array())
    {
        return $this->cacheManager->getBrowserPath($path, $filter, $runtimeConfig);
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'liip_imagine';
    }
}

<?php

namespace Liip\ImagineBundle\Templating;

use Liip\ImagineBundle\Imagine\Cache\CacheManager;

class ImagineExtension extends \Twig_Extension
{
    /**
     * @var CacheManager
     */
    private $cacheManager;

    /**
     * Constructor.
     *
     * @param CacheManager $cacheManager
     */
    public function __construct(CacheManager $cacheManager)
    {
        $this->cacheManager = $cacheManager;
    }

    /**
     * {@inheritDoc}
     */
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFunction('imagine_filter', array($this, 'filter')),
        );
    }

    /**
     * Gets the browser path for the image and filter to apply.
     *
     * @param string $path
     * @param string $filter
     * @param array  $runtimeConfig
     *
     * @return \Twig_Markup
     */
    public function filter($path, $filter, array $runtimeConfig = array())
    {
        return $this->cacheManager->getBrowserPath($path, $filter, $runtimeConfig);
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'liip_imagine';
    }
}

Fix deprecated twig filter syntax

Fix deprecated twig filter syntax


<?php namespace Bsharp\Laralytics;

use Illuminate\Translation\TranslationServiceProvider;

/**
 * Class LaralyticsServiceProvider
 * @package Bsharp\Laralytics
 */
class LaralyticsServiceProvider extends TranslationServiceProvider
{
    protected $defer = false;

    public function boot()
    {
        // Include Laralytics routes for API
        include __DIR__ . '/../publish/routes.php';

        /**
         * Register publish config
         */
        $this->publishes([
            __DIR__ . '/../publish/config/laralytics.php' => config_path('laralytics.php')
        ], 'config');

        /**
         * Register publish migrations
         */
        $this->publishes([
            __DIR__ . '/../publish/database/migrations/' => database_path('/migrations')
        ], 'migrations');

        /**
         * register publish middleware
         */
        $this->publishes([
            __DIR__ . '/../publish/Http/Middleware/' => app_path('/Http/Middleware')
        ], 'middleware');

        /**
         * register publish Eloquent model
         */
        $this->publishes([
            __DIR__ . '/../publish/Eloquent/' => app_path()
        ], 'eloquent');
    }

    public function register()
    {
        $this->app->bind('laralytics', function () {
            return new Laralytics();
        });
    }
}

<?php namespace Bsharp\Laralytics;

use Illuminate\Translation\TranslationServiceProvider;

/**
 * Class LaralyticsServiceProvider
 * @package Bsharp\Laralytics
 */
class LaralyticsServiceProvider extends TranslationServiceProvider
{
    protected $defer = false;

    public function boot()
    {
        // Include Laralytics routes for API
        include __DIR__ . '/../publish/routes.php';

        /**
         * Register publish config
         */
        $this->publishes([
            __DIR__ . '/../publish/config/laralytics.php' => config_path('laralytics.php')
        ], 'config');

        /**
         * Register publish migrations
         */
        $this->publishes([
            __DIR__ . '/../publish/database/migrations/' => database_path('/migrations')
        ], 'migrations');

        /**
         * register publish middleware
         */
        $this->publishes([
            __DIR__ . '/../publish/Http/Middleware/' => app_path('/Http/Middleware')
        ], 'middleware');

        /**
         * register publish Eloquent model
         */
        $this->publishes([
            __DIR__ . '/../publish/Eloquent/' => app_path()
        ], 'eloquent');

        /**
         * Register public js file
         */
        $this->publishes([
            __DIR__ . '/../publish/public/' => public_path('js')
        ], 'js');
    }

    public function register()
    {
        $this->app->bind('laralytics', function () {
            return new Laralytics();
        });
    }
}

Add command to publish js file

Add command to publish js file


<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Orm;

use EasyCorp\Bundle\EasyAdminBundle\Contracts\Orm\EntityUpdaterInterface;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use Symfony\Component\PropertyAccess\PropertyAccessor;

/**
 * @author Javier Eguiluz <javier.eguiluz@gmail.com>
 */
final class EntityUpdater implements EntityUpdaterInterface
{
    private $propertyAccesor;

    public function __construct(PropertyAccessor $propertyAccesor)
    {
        $this->propertyAccesor = $propertyAccesor;
    }

    public function updateProperty(EntityDto $entityDto, string $propertyName, $value): void
    {
        if (!$this->propertyAccesor->isWritable($entityDto->getInstance(), $propertyName)) {
            throw new \RuntimeException(sprintf('The "%s" property of the "%s" entity is not writable.', $propertyName, $entityDto->getName()));
        }

        $entityInstance = $entityDto->getInstance();
        $this->propertyAccesor->setValue($entityInstance, $propertyName, $value);
        $entityDto->setInstance($entityInstance);
    }
}

<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Orm;

use EasyCorp\Bundle\EasyAdminBundle\Contracts\Orm\EntityUpdaterInterface;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;

/**
 * @author Javier Eguiluz <javier.eguiluz@gmail.com>
 */
final class EntityUpdater implements EntityUpdaterInterface
{
    private $propertyAccesor;

    public function __construct(PropertyAccessorInterface $propertyAccesor)
    {
        $this->propertyAccesor = $propertyAccesor;
    }

    public function updateProperty(EntityDto $entityDto, string $propertyName, $value): void
    {
        if (!$this->propertyAccesor->isWritable($entityDto->getInstance(), $propertyName)) {
            throw new \RuntimeException(sprintf('The "%s" property of the "%s" entity is not writable.', $propertyName, $entityDto->getName()));
        }

        $entityInstance = $entityDto->getInstance();
        $this->propertyAccesor->setValue($entityInstance, $propertyName, $value);
        $entityDto->setInstance($entityInstance);
    }
}

Use interfaces instead of concrete implementations


<?php

/**
 * Class GACodeField
 */
class GACodeField extends TextField
{
    /**
     * @return string
     */
    public function Type()
    {
        return 'text';
    }

    /**
     * Simple validation to make sure the input matches the expected pattern.
     *
     * @param $validator
     * @return bool
     */
    public function validate($validator)
    {
        $parts = explode("-", $this->value);

        if ($parts[0] === "GTM" && mb_strlen($parts[1]) === 6) {
            return true;

        } else if (($parts[0] === "UA") && mb_strlen($parts[1]) === 8 && mb_strlen($parts[2]) === 1) {
            return true;

        } else {
            $validator->validationError($this->name, "ERROR: Isn't a valid Universal or Tag Manager code. Must be in either UA-XXXXXXXX-X or
            GTM-XXXXXX format.", "validation", false);
        }

        return false;
    }
}

<?php

/**
 * Class GACodeField
 */
class GACodeField extends TextField
{
    /**
     * @return string
     */
    public function Type()
    {
        return 'text';
    }

    /**
     * Simple validation to make sure the input matches the expected pattern.
     *
     * @param $validator
     * @return bool
     */
    public function validate($validator)
    {

        if (is_null($this->value)) {
            return true;
        } else {
            $parts = explode("-", $this->value);
        }

        if ($parts[0] === "GTM" && mb_strlen($parts[1]) === 6) {
            return true;

        } else if (($parts[0] === "UA") && mb_strlen($parts[1]) === 8 && mb_strlen($parts[2]) === 1) {
            return true;

        } else {
            $validator->validationError($this->name, "ERROR: Isn't a valid Universal or Tag Manager code. Must be in either UA-XXXXXXXX-X or
            GTM-XXXXXX format.", "validation", false);
        }

        return false;
    }
}

Allow no tag to be set

Allow no tag to be set


	@if ($status["thread"] === "none" or $status["thread"] === "None")

There is currently no thread up.

	@else

Thread up!

	@endif

Fix thread display on front page for certain themes.


<?php

/*
 * This file is part of the TecnoCreaciones package.
 *
 * (c) www.tecnocreaciones.com.ve
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Tecnocreaciones\Bundle\AjaxFOSUserBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

/**
 * Description of ValidationPass
 *
 * @author Carlos Mendoza <inhack20@tecnocreaciones.com>
 */
class ValidationPass implements CompilerPassInterface
{
    public function process(\Symfony\Component\DependencyInjection\ContainerBuilder $container) {
        if (!$container->hasParameter('fos_user.registration.confirmation.enabled')) {
            return;
        }
        if($container->getParameter('fos_user.registration.confirmation.enabled') == true){
            $definition = $container->getDefinition('fos_user.listener.email_confirmation');
            $definition
                    ->setClass('Tecnocreaciones\Bundle\AjaxFOSUserBundle\EventListener\EmailConfirmationListener')
                    ->addMethodCall('setTranslator',array($container->getDefinition('translator.default')))
                    ;
        }

    }
}

<?php

/*
 * This file is part of the TecnoCreaciones package.
 *
 * (c) www.tecnocreaciones.com.ve
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Tecnocreaciones\Bundle\AjaxFOSUserBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

/**
 * Description of ValidationPass
 *
 * @author Carlos Mendoza <inhack20@tecnocreaciones.com>
 */
class ValidationPass implements CompilerPassInterface
{
    public function process(\Symfony\Component\DependencyInjection\ContainerBuilder $container) {
        if (!$container->hasParameter('fos_user.registration.confirmation.enabled')) {
            return;
        }
        if($container->getParameter('fos_user.registration.confirmation.enabled') == true){
            //Backward compatibility with Fos User 1.3
            if(class_exists('FOS\UserBundle\FOSUserEvents')){
                $definition = $container->getDefinition('fos_user.listener.email_confirmation');
                $definition
                        ->setClass('Tecnocreaciones\Bundle\AjaxFOSUserBundle\EventListener\EmailConfirmationListener')
                        ->addMethodCall('setTranslator',array($container->getDefinition('translator.default')))
                        ;
            }
        }

    }
}

Fix bug de compatibilidad con FOSUser 1.3


<?php

final class PhabricatorFeedPublicStreamController
  extends PhabricatorFeedController {

  public function shouldRequireLogin() {
    return false;
  }

  public function processRequest() {
    if (!PhabricatorEnv::getEnvConfig('feed.public')) {
      return new Aphront404Response();
    }

    $request = $this->getRequest();
    $viewer = $request->getUser();

    $query = new PhabricatorFeedQuery();
    $query->setViewer($viewer);
    $query->setLimit(100);
    $stories = $query->execute();

    $builder = new PhabricatorFeedBuilder($stories);
    $builder
      ->setFramed(true)
      ->setUser($viewer);

    $view = hsprintf('
%s
',
      $builder->buildView());

    return $this->buildStandardPageResponse(
      $view,
      array(
        'title' => pht('Public Feed'),
        'public' => true,
      ));
  }
}

<?php

final class PhabricatorFeedPublicStreamController
  extends PhabricatorFeedController {

  public function shouldRequireLogin() {
    return false;
  }

  public function processRequest() {
    if (!PhabricatorEnv::getEnvConfig('feed.public')) {
      return new Aphront404Response();
    }

    $request = $this->getRequest();
    $viewer = PhabricatorUser::getOmnipotentUser();

    $query = new PhabricatorFeedQuery();
    $query->setViewer($viewer);
    $query->setLimit(100);
    $stories = $query->execute();

    $builder = new PhabricatorFeedBuilder($stories);
    $builder
      ->setFramed(true)
      ->setUser($viewer);

    $view = hsprintf('
%s
',
      $builder->buildView());

    return $this->buildStandardPageResponse(
      $view,
      array(
        'title' => pht('Public Feed'),
        'public' => true,
      ));
  }
}

Make public feed show all stories, using the omnipotent user

Auditors: chad


@extends('dashboard')
@section('main')

			Dashboard

Weekly patients traffic

@stop

Revert "added doctor main page"

Revert "added doctor main page"

This reverts commit 96257fe855ce5b4d21de00eb465d1f3bf1db0a60.


<?php

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

class CreateTopicCoversTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('forum_topic_covers', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('topic_id')->nullable();
            $table->integer('user_id')->nullable();
            $table->string('hash');
            $table->string('ext');
            $table->timestamps();

            $table->index(['topic_id']);
        });
    }

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

<?php

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

class CreateTopicCoversTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('forum_topic_covers', function (Blueprint $table) {
            $table->increments('id');
            $table->mediumInteger('topic_id')->unsigned()->nullable();
            $table->mediumInteger('user_id')->unsigned()->nullable();
            $table->string('hash');
            $table->string('ext');
            $table->timestamps();

            $table->index('topic_id');
            $table->index('user_id');

            $table->foreign('topic_id')
                ->references('topic_id')
                ->on('phpbb_topics')
                ->onDelete('set null');

            $table->foreign('user_id')
                ->references('user_id')
                ->on('phpbb_users')
                ->onDelete('set null');
        });
    }

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

Fix foreign key declaration and add index


<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Lifecycle Building Center</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width" />

        <link rel="stylesheet" type="text/css" href="../../assets/style/bootstrap.min.css" media="screen,projection" />

								Link

								Link

								Link

								Link

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Lifecycle Building Center</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width" />

        <link rel="stylesheet" type="text/css" href="/assets/style/bootstrap.min.css" media="screen,projection" />

								Link

								Link

								Link

								Link

Use absolute path for assets

Use absolute path for assets


<?php

namespace Atsys\Blog\Http\Controllers\Blog;

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

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

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

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

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

<?php

namespace Atsys\Blog\Http\Controllers\Blog;

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

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

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

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

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

Fix bug querying latest posts

Fix bug querying latest posts


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

$dbpath = getenv('DBPATH');
$dbhost = getenv('DBHOST');
$dbname = getenv('DBNAME');
$dbuser = getenv('DBUSER');
$dbpass = getenv('DBPASS');

return array(
	'mysql' => array(
		'type' => 'pdo',
		'connection' => array(
			'dsn'      => "mysql:host=$dbhost;dbname=$dbname",
			'username' => $dbuser,
			'password' => $dbpass,
		),
		'charset'      => 'utf8',
	),
	'pgsql' => array(
		'type' => 'pdo',
		'connection' => array(
			'dsn'      => "pgsql:host=$dbhost;dbname=$dbname",
			'username' => $dbuser,
			'password' => $dbpass,
		),
		'charset'      => 'utf8',
	),
	'sqlite' => array(
		'type' => 'pdo',
		'connection' => array(
			'dsn'      => "sqlite:$dbpath",
		),
	),
);

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

$dbpath = getenv('DBPATH');
$dbhost = getenv('DBHOST');
$dbname = getenv('DBNAME');
$dbuser = getenv('DBUSER');
$dbpass = getenv('DBPASS');

return array(
	'mysql' => array(
		'type' => 'pdo',
		'connection' => array(
			'dsn'      => "mysql:host=$dbhost;dbname=$dbname",
			'username' => $dbuser,
			'password' => $dbpass,
		),
		'charset'      => 'utf8',
	),
	'pgsql' => array(
		'type' => 'postgresql',
		'connection' => array(
			'hostname' => $dbhost,
			'username' => $dbuser,
			'password' => $dbpass,
			'database' => $dbname,
		),
		'charset'      => 'utf8',
	),
	'sqlite' => array(
		'type' => 'pdo',
		'connection' => array(
			'dsn'      => "sqlite:$dbpath",
		),
	),
);

Configure to use PostgreSQL driver in Kohana.


<?php

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

class MakeTicketedEventImageUrlLonger extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('ticketed_events', function (Blueprint $table) {
            $table->text('image_url')->nbullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('ticketed_events', function (Blueprint $table) {
            $table->string('image_url')->nbullable()->change();
        });
    }
}

<?php

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

class MakeTicketedEventImageUrlLonger extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('ticketed_events', function (Blueprint $table) {
            $table->text('image_url')->nullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('ticketed_events', function (Blueprint $table) {
            $table->string('image_url')->nullable()->change();
        });
    }
}

Fix typo in `ticketed_events` migration

Fix typo in `ticketed_events` migration


<?php

use FireflyIII\Models\Role;
use Illuminate\Database\Seeder;

/**
 * Class PermissionSeeder
 */
class PermissionSeeder extends Seeder
{
    public function run()
    {
        $owner               = new Role;
        $owner->name         = 'owner';
        $owner->display_name = 'Site Owner';
        $owner->description  = 'User runs this instance of FF3'; // optional
        $owner->save();

    }

}

Add new line to file.

Add new line to file.


<?php
/** Production */
ini_set('display_errors', 0);
define('WP_DEBUG_DISPLAY', false);
define('SCRIPT_DEBUG', false);
/** Disable all file modifications including updates and update notifications */
define('DISALLOW_FILE_MODS', true);

/**
 * S3 Keys
 */
define('AS3CF_AWS_ACCESS_KEY_ID', env('AS3CF_AWS_ACCESS_KEY_ID'));
define('AS3CF_AWS_SECRET_ACCESS_KEY', env('AS3CF_AWS_SECRET_ACCESS_KEY'));

Add vars for WP Offload Site plugin

Add vars for WP Offload Site plugin


<?php namespace net\xp_framework\unittest\io\streams;

use unittest\TestCase;
use io\streams\MemoryOutputStream;

/**
 * Unit tests for streams API
 *
 * @see      xp://io.streams.OutputStream
 * @purpose  Unit test
 */
class MemoryOutputStreamTest extends TestCase {
  protected $out= null;

  /**
   * Setup method. Creates the fixture.
   *
   */
  public function setUp() {
    $this->out= new MemoryOutputStream();
  }

  /**
   * Test string writing
   *
   */
  #[@test]
  public function writeString() {
    $this->out->write('Hello');
    $this->assertEquals('Hello', $this->out->getBytes());
  }

  /**
   * Test number writing
   *
   */
  #[@test]
  public function writeNumber() {
    $this->out->write(5);
    $this->assertEquals('5', $this->out->getBytes());
  }

  /**
   * Test closing a stream twice has no effect.
   *
   * @see   xp://lang.Closeable#close
   */
  #[@test]
  public function closingTwice() {
    $this->out->close();
    $this->out->close();
  }
}

<?php namespace net\xp_framework\unittest\io\streams;

use io\streams\MemoryOutputStream;

/**
 * Unit tests for streams API
 *
 * @see   xp://io.streams.OutputStream
 * @see   xp://lang.Closeable#close
 */
class MemoryOutputStreamTest extends \unittest\TestCase {
  private $out;

  /**
   * Setup method. Creates the fixture.
   */
  public function setUp() {
    $this->out= new MemoryOutputStream();
  }

  #[@test]
  public function writing_a_string() {
    $this->out->write('Hello');
    $this->assertEquals('Hello', $this->out->getBytes());
  }

  #[@test]
  public function writing_a_number() {
    $this->out->write(5);
    $this->assertEquals('5', $this->out->getBytes());
  }

  #[@test]
  public function closingTwice() {
    $this->out->close();
    $this->out->close();
  }
}

Adjust to new unittest coding standards

QA: Adjust to new unittest coding standards


<?php
/**
 * CmcSiteLogo
 *
 * @author cmc
 *
 * @usage -
 *      In _config/config.yml
 *
 *          SiteConfig:
 *              extensions:
 *                  - CmcSiteLogo
 *
 *      In template
 *
 *          $SiteConfig.LogoImage.SetRatio(250,250)
 *
 */
class CmcSiteLogo extends DataExtension {
    public static $has_one = array(
        'LogoImage' => 'Image',
        'Logo2Image' => 'Image',
    );

    public static $db = array(
        'LogoUrl'   => 'Varchar(250)',
        'Logo2Url'   => 'Varchar(250)',
    );

    public function updateCMSFields(FieldList $fields) {
        $fields->addFieldsToTab('Root.Main', new UploadField('LogoImage', 'Choose an image for your site logo'));
        $fields->addFieldToTab("Root.Main", new TextField("LogoUrl", "Optionally enter URL to link to from logo image"));
        $fields->addFieldsToTab('Root.Main', new UploadField('Logo2Image', 'Choose an image for your 2nd site logo'));
        $fields->addFieldToTab("Root.Main", new TextField("Logo2Url", "Optionally enter URL to link to from 2nd logo image"));
    }
}

<?php
/**
 * CmcSiteLogo
 *
 * @author cmc
 *
 * @usage -
 *      In _config/config.yml
 *
 *          SiteConfig:
 *              extensions:
 *                  - CmcSiteLogo
 *
 *      In template
 *
 *          $SiteConfig.LogoImage.SetRatio(250,250)
 *
 */
class CmcSiteLogo extends DataExtension {
    public static $has_one = array(
        'LogoImage' => 'Image',
        'Logo2Image' => 'Image',
    );

    public static $db = array(
        'LogoUrl'       => 'Varchar(250)',
        'LogoUrlTitle'  => 'Varchar(120)',
        'Logo2Url'      => 'Varchar(250)',
        'Logo2UrlTitle' => 'Varchar(120)',
    );

    public function updateCMSFields(FieldList $fields) {
        $fields->addFieldsToTab('Root.Main', new UploadField('LogoImage', 'Choose an image for your site logo'));
        $fields->addFieldToTab("Root.Main", new TextField("LogoUrl", "Optionally enter URL to link to from logo image"));
        $fields->addFieldToTab("Root.Main", new TextField("LogoUrlTitle", "Title/Tooltip text for URL above"));
        $fields->addFieldsToTab('Root.Main', new UploadField('Logo2Image', 'Choose an image for your 2nd site logo'));
        $fields->addFieldToTab("Root.Main", new TextField("Logo2Url", "Optionally enter URL to link to from 2nd logo image"));
        $fields->addFieldToTab("Root.Main", new TextField("Logo2UrlTitle", "Title/Tooltip text for URL above"));
    }
}

Add Title text for URLs

Add Title text for URLs


<?php
class Scores extends CI_Controller {

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

        }

        public function index()
        {
                $data['scores'] = $this->scores_model->get_scores();
                $this->load->view('scores/index', $data);
        }

        public function view($slug = NULL)
        {
        }

        public function create()
        {
                $this->scores_model->set_scores();
                $data['scores'] = $this->scores_model->get_scores();
                $this->load->view('scores/index', $data);
        }
}

<?php
class Scores extends CI_Controller {

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

        }

        public function index()
        {

            $limit = 0;

            $data['scores'] = $this->scores_model->get_scores($limit);

            $data['title'] = 'Scores';

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

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

        public function view($slug = NULL)
        {
        }

        public function create()
        {
                $this->scores_model->set_scores();
                $data['scores'] = $this->scores_model->get_scores();
                $this->load->view('scores/index', $data);
        }
}

Index function of scores controller now returns all results


<?php

namespace Oro\Bundle\EntityExtendBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

use Oro\Bundle\EntityExtendBundle\Model\EnumValue as EnumValueEntity;
use Oro\Bundle\EntityExtendBundle\Tools\ExtendHelper;

class EnumValueValidator extends ConstraintValidator
{
    /**
     * {@inheritdoc}
     */
    public function validate($entity, Constraint $constraint)
    {
        if (!$entity instanceof EnumValueEntity) {
            throw new UnexpectedTypeException(
                $entity,
                'Oro\Bundle\EntityExtendBundle\Model\EnumValue'
            );
        }

        /* @var $entity EnumValueEntity */
        if ($entity->getId() || !$entity->getLabel()) {
            return;
        }

        $valueId = ExtendHelper::buildEnumValueId($entity->getLabel(), false);

        if (empty($valueId)) {
            $this->context->addViolationAt('label', $constraint->message, ['{{ value }}' => $entity->getLabel()]);
        }
    }
}

<?php

namespace Oro\Bundle\EntityExtendBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

use Oro\Bundle\EntityExtendBundle\Model\EnumValue as EnumValueEntity;
use Oro\Bundle\EntityExtendBundle\Tools\ExtendHelper;

class EnumValueValidator extends ConstraintValidator
{
    /**
     * {@inheritdoc}
     */
    public function validate($entity, Constraint $constraint)
    {
        if ($entity instanceof EnumValueEntity) {
            $entity = $entity->toArray();
        }

        if (!empty($entity['id']) || empty($entity['label'])) {
            return;
        }

        $valueId = ExtendHelper::buildEnumValueId($entity['label'], false);

        if (empty($valueId)) {
            $this->context
                ->buildViolation($constraint->message, ['{{ value }}' => $entity['label']])
                ->atPath('[label]')
                ->addViolation()
            ;
        }
    }
}

BB-1412: Apply validation rules for import data
- fixed validator


<?php

namespace App\Transformers\Outbound\Web;

use App\Transformers\Outbound\Web\Page as BaseTransformer;

class GenericPage extends BaseTransformer
{

    protected function getPageFields()
    {
        return [
            // TODO: Add `HasSearchTags` trait? See Event.
            'search_tags' => [
                'doc' => 'Editor-specified list of tags to aid in internal search',
                'type' => 'array',
                'elasticsearch' => [
                    'default' => true,
                    'type' => 'text',
                ],
                'value' => function ($item) {
                    if (!$item->search_tags) {
                        return null;
                    }

                    return collect(explode(',', $item->search_tags))->map(function ($item) {
                        return trim($item);
                    });
                },
            ],
        ];
    }

}

<?php

namespace App\Transformers\Outbound\Web;

use App\Transformers\Outbound\Web\Page as BaseTransformer;

class GenericPage extends BaseTransformer
{

    protected function getPageFields()
    {
        return [
            // TODO: Add `HasSearchTags` trait? See Event.
            'search_tags' => [
                'doc' => 'Editor-specified list of tags to aid in internal search',
                'type' => 'array',
                'elasticsearch' => [
                    'default' => true,
                    'boost' => 5,
                    'type' => 'text',
                ],
                'value' => function ($item) {
                    if (!$item->search_tags) {
                        return null;
                    }

                    return collect(explode(',', $item->search_tags))->map(function ($item) {
                        return trim($item);
                    })->filter();
                },
            ],
        ];
    }

}

Boost matches on `search_tags` for webpages [WEB-922]


<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* Dbman
*
* @package        Dbman
* @author         Robert-Jan de Dreu
* @copyright      (c) 2010 Robert-Jan de Dreu
* @license        http://www.opensource.org/licenses/isc-license.txt
*/

return array
(
	/**
	 * Dbman settings
	 *
	 * string   path		the path to the update files
	 */
	'path' => MODPATH.'dbman/migrations/'
);

<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* Dbman
*
* @package        Dbman
* @author         Robert-Jan de Dreu
* @copyright      (c) 2010 Robert-Jan de Dreu
* @license        http://www.opensource.org/licenses/isc-license.txt
*/

return array
(
	/**
	 * Dbman settings
	 *
	 * string   path		the path to the update files
	 */
	'path' => 'config/dbman/migrations/'
);

Change default path, as it's now relative to the APPROOT or module


<?php
namespace ker0x\CakeGcm\Test\TestCase\Controller\Component;

use Cake\Controller\ComponentRegistry;
use Cake\Controller\Controller;
use Cake\Network\Request;
use Cake\Network\Response;
use Cake\TestSuite\IntegrationTestCase;
use ker0x\CakeGcm\Controller\Component\GcmComponent;

class GcmComponentTest extends IntegrationTestCase
{
    public $component = null;

    public $controller = null;

    public $ids = [];

    public function setUp()
    {
        parent::setUp();
         // Setup our component and fake test controller
        $request = new Request();
        $response = new Response();
        $this->controller = $this->getMock(
            'Cake\Controller\Controller',
            null,
            [$request, $response]
        );
        $registry = new ComponentRegistry($this->controller);
        $this->component = new GcmComponent($registry);
    }

    public function testIdsError()
    {
        $this->component->send($this->ids);
        $this->expectExceptionMessage('Ids must be a string or an array with at least 1 token.');
    }

    public function tearDown()
    {
        parent::tearDown();
        // Clean up after we're done
        unset($this->component, $this->controller);
    }
}

<?php
namespace ker0x\CakeGcm\Test\TestCase\Controller\Component;

use Cake\Controller\ComponentRegistry;
use Cake\Controller\Controller;
use Cake\Network\Request;
use Cake\Network\Response;
use Cake\TestSuite\IntegrationTestCase;
use ker0x\CakeGcm\Controller\Component\GcmComponent;

class GcmComponentTest extends IntegrationTestCase
{
    public $component = null;

    public $controller = null;

    public $ids = null;

    public function setUp()
    {
        parent::setUp();
         // Setup our component and fake test controller
        $request = new Request();
        $response = new Response();
        $this->controller = $this->getMock(
            'Cake\Controller\Controller',
            null,
            [$request, $response]
        );
        $registry = new ComponentRegistry($this->controller);
        $this->component = new GcmComponent($registry, [
            'api' => [
                'key' => getenv('GCM_API_KEY')
            ]
        ]);
    }

    public function testIds()
    {
        $this->ids = getenv('TOKEN');

        $this->component->send($this->ids, [
            'notification' => [
                'title' => 'Hello World',
                'body' => 'My awesome Hello World!'
            ]
        ]);
        $this->assertResponseCode(200);
    }

    public function tearDown()
    {
        parent::tearDown();
        // Clean up after we're done
        unset($this->component, $this->controller);
    }
}

Update test with environnement variables


<?php

class Twitter {
  private static $connection = null;

  public static function getConnection() {
    $user = sfContext::getInstance()->getUser();

    if (!$user->isAuthenticated()) {
      return false;
    }

    if(self::$connection === null) {
      self::$connection = new TwitterOAuth(sfConfig::get('app_sf_twitter_auth_consumer_key'), sfConfig::get('app_sf_twitter_auth_consumer_secret'), $user->getAttribute('oauth_access_token', null, 'sfTwitterAuth'), $user->getAttribute('oauth_access_token_secret', null, 'sfTwitterAuth'));
    }

    return self::$connection;
  }
}

<?php

class Twitter {
  private static $connection = null;

  public static function getConnection() {
    $user = sfContext::hasInstance() && sfContext::getInstance()->getUser()->isAuthenticated() ? sfContext::getInstance()->getUser() : false;

    if(self::$connection === null) {
      self::$connection = new TwitterOAuth(
        sfConfig::get('app_sf_twitter_auth_consumer_key'),
        sfConfig::get('app_sf_twitter_auth_consumer_secret'),
        $user ? $user->getAttribute('oauth_access_token', null, 'sfTwitterAuth') : sfConfig::get('app_sf_twitter_auth_access_token') ,
        $user ? $user->getAttribute('oauth_access_token_secret', null, 'sfTwitterAuth') : sfConfig::get('app_sf_twitter_auth_access_token_secret')
      );
    }

    return self::$connection;
  }
}

Allow specification of default OAuth creds to perform requests using if no authenticated user is present.


<?php

namespace SumoCoders\FrameworkMultiUserBundle\DataTransferObject;

use SumoCoders\FrameworkMultiUserBundle\User\User;
use SumoCoders\FrameworkMultiUserBundle\User\UserWithPassword;

class UserWithPasswordDataTransferObject implements UserDataTransferObject
{
    /**
     * @var int
     */
    public $id;

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

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

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

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

    /**
     * @var User
     */
    private $user;

    /**
     * @param User $user
     *
     * @return User
     */
    public static function fromUser(User $user)
    {
        $baseUserTransferObject = new self();
        $baseUserTransferObject->user = $user;
        $baseUserTransferObject->id = $user->getId();
        $baseUserTransferObject->userName = $user->getUsername();
        $baseUserTransferObject->displayName = $user->getDisplayName();
        $baseUserTransferObject->email = $user->getEmail();

        return $baseUserTransferObject;
    }

    /**
     * @return UserWithPassword
     */
    public function getEntity()
    {
        $this->user->change($this);

        return $this->user;
    }
}

<?php

namespace SumoCoders\FrameworkMultiUserBundle\DataTransferObject;

use SumoCoders\FrameworkMultiUserBundle\User\User;
use SumoCoders\FrameworkMultiUserBundle\User\UserWithPassword;

class UserWithPasswordDataTransferObject implements UserDataTransferObject
{
    /**
     * @var int
     */
    public $id;

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

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

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

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

    /**
     * @var User
     */
    private $user;

    /**
     * @param User $user
     *
     * @return User
     */
    public static function fromUser(User $user)
    {
        $baseUserTransferObject = new self();
        $baseUserTransferObject->user = $user;
        $baseUserTransferObject->id = $user->getId();
        $baseUserTransferObject->userName = $user->getUsername();
        $baseUserTransferObject->displayName = $user->getDisplayName();
        $baseUserTransferObject->email = $user->getEmail();
        if ($user->hasPlainPassword()) {
            $baseUserTransferObject->plainPassword = $user->getPlainPassword();
        }

        return $baseUserTransferObject;
    }

    /**
     * @return UserWithPassword
     */
    public function getEntity()
    {
        if ($this->user) {
            $this->user->change($this);

            return $this->user;
        }

        return new UserWithPassword(
            $this->userName,
            $this->plainPassword,
            $this->displayName,
            $this->email
        );
    }
}

Use the user's getters to check if we need to set the plainpassword


<?php
/**
 *
 *
 *
 *
 */

class Hackathon_AsyncIndex_Model_Manager
{

    /**
     * Tells the core indexer to do a partial reindex
     * @param Mage_Index_Model_Process $process
     * @throws Exception
     */
    public function executePartialIndex( Mage_Index_Model_Process $process )
    {
        /** @var $resourceModel Mage_Index_Model_Resource_Process */
        $resourceModel = Mage::getResourceSingleton('index/process');
        $resourceModel->beginTransaction();

        try
        {
            $process->setMode(Mage_Index_Model_Process::MODE_SCHEDULE);
            $process->indexEvents();
            if ( count(Mage::getResourceSingleton('index/event')->getUnprocessedEvents($process)) === 0 ) {
                $process->changeStatus(Mage_Index_Model_Process::STATUS_PENDING);
            }
            $resourceModel->commit();
        }
        catch (Exception $e)
        {
            $resourceModel->rollBack();
            throw $e;
        }

    }

}

<?php
/**
 *
 *
 *
 *
 */

class Hackathon_AsyncIndex_Model_Manager
{

    /**
     * Tells the core indexer to do a partial reindex
     * @param Mage_Index_Model_Process $process
     * @throws Exception
     */
    public function executePartialIndex( Mage_Index_Model_Process $process )
    {
        /** @var $resourceModel Mage_Index_Model_Resource_Process */
        $resourceModel = Mage::getResourceSingleton('index/process');
        $resourceModel->beginTransaction();

        $indexMode = 'schedule';
        $pendingMode = 'pending';

        //Fallback for 1.6.2 installations > Undefined class constant 'MODE_SCHEDULE'
        $refl = new ReflectionClass('Mage_Index_Model_Process');
        if ( in_array('MODE_SCHEDULE', $refl->getConstants() ) )
        {
            $indexMode = Mage_Index_Model_Process::MODE_SCHEDULE;
        }
        if ( in_array('MODE_SCHEDULE', $refl->getConstants() ) )
        {
            $pendingMode = Mage_Index_Model_Process::STATUS_PENDING;
        }

        try
        {
            $process->setMode($indexMode);
            $process->indexEvents();
            if ( count(Mage::getResourceSingleton('index/event')->getUnprocessedEvents($process)) === 0 ) {
                $process->changeStatus($pendingMode);
            }
            $resourceModel->commit();
        }
        catch (Exception $e)
        {
            $resourceModel->rollBack();
            throw $e;
        }

    }

}

Fix for Mage 1.6.2 in partial reindex - can't acces class constant there: Undefined class constant 'MODE_SCHEDULE'


<?php

namespace hipanel\widgets;

use Yii;
use yii\helpers\Html;
use yii\widgets\LinkPager;

class PagerHook extends LinkPager implements HookInterface
{
    use HookTrait;

    public string $tag = 'div';

    public string $content;

    public function init()
    {
        $this->registerJsHook('pager');
    }

    public function run()
    {
        return Html::tag($this->tag, $this->content ?? $this->getLoader(), array_merge(['id' => $this->getId()], $this->options));
    }

    private function getLoader(): string
    {
        return Html::tag('span', null, ['class' => 'fa fa-spinner fa-pulse', 'style' => 'margin-right: .7rem;']) . Yii::t('hipanel', 'loading pager...');
    }
}

<?php

namespace hipanel\widgets;

use Yii;
use yii\helpers\Html;
use yii\widgets\LinkPager;

class PagerHook extends LinkPager implements HookInterface
{
    use HookTrait;

    public string $tag = 'div';

    public string $content;

    public $options = [];

    public function init()
    {
        $this->registerJsHook('pager');
    }

    public function run()
    {
        return Html::tag($this->tag, $this->content ?? $this->getLoader(), array_merge(['id' => $this->getId()], $this->options));
    }

    private function getLoader(): string
    {
        return Html::tag('span', null, ['class' => 'fa fa-spinner fa-pulse', 'style' => 'margin-right: .7rem;']) . Yii::t('hipanel', 'loading pager...');
    }
}

Fix `LinkPager` css class duplicate

Fix `LinkPager` css class duplicate


<?php

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

class AddSourceDetailsColumnToPosts extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('source_details')->after('source')->nullable()->comment('Extra details about the post source, like newsletter ID');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('source_details');
        });
    }
}

<?php

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

class AddSourceDetailsColumnToPosts extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('source_details')->after('source')->index()->nullable()->comment('Extra details about the post source, like newsletter ID');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('source_details');
        });
    }
}

Make source_details column an index

Make source_details column an index


<?php

return array (
  'ADMINISTRATION' => 'مدیریت کل',
  'Control Panel' => 'پنل کنترل',
  'Dashboard' => 'داشبورد',
  'Files' => '',
  'Forgot Password?' => 'فراموشی رمزعبور؟',
  'Logout' => 'خروج',
  'Member since {0}' => 'عضو از {0}',
  'Profile' => 'پروفایل',
  'Roles' => 'وظیفه ها',
  'Settings' => 'تنظیمات',
  'Sign In' => 'ورود',
  'Sign Up' => 'عضویت',
  'Sign out' => 'خروج',
  'Users' => 'کاربران',
);

<?php

return array (
  'ADMINISTRATION' => 'مدیریت کل',
  'Control Panel' => 'پنل کنترل',
  'Dashboard' => 'داشبورد',
  'Files' => 'فایل ها',
  'Forgot Password?' => 'فراموشی رمزعبور؟',
  'Logout' => 'خروج',
  'Member since {0}' => 'عضو از {0}',
  'Profile' => 'پروفایل',
  'Roles' => 'وظیفه ها',
  'Settings' => 'تنظیمات',
  'Sign In' => 'ورود',
  'Sign Up' => 'عضویت',
  'Sign out' => 'خروج',
  'Users' => 'کاربران',
);

Update Persian language for AdminLte template


<?
defined('C5_EXECUTE') or die("Access Denied.");
$u = new User();
$form = Loader::helper('form');

$ci = Loader::helper('concrete/urls');
$f = File::getByID($_REQUEST['fID']);
$fv = $f->getApprovedVersion();

$fp = new Permissions($f);
if (!$fp->canEditFileContents()) {
	die(t("Access Denied."));
}

$to = $fv->getTypeObject();
if ($to->getPackageHandle() != '') {
	Loader::packageElement('files/edit/' . $to->getEditor(), $to->getPackageHandle(), array('fv' => $fv));
} else {
    Loader::element('files/edit/' . $to->getEditor(), array('fv' => $fv));
}

<?
defined('C5_EXECUTE') or die("Access Denied.");
$u = new User();
$form = Loader::helper('form');

$ci = Loader::helper('concrete/urls');
$f = File::getByID($_REQUEST['fID']);
if (!is_object($f)) {
    die(t('File Not Found.'));
}
$fv = $f->getApprovedVersion();

$fp = new Permissions($f);
if (!$fp->canEditFileContents()) {
    die(t("Access Denied."));
}

$to = $fv->getTypeObject();
if ($to->getPackageHandle() != '') {
    Loader::packageElement('files/edit/' . $to->getEditor(), $to->getPackageHandle(), array('fv' => $fv));
} else {
    Loader::element('files/edit/' . $to->getEditor(), array('fv' => $fv));
}

Add an extra check for when files don't exist

Former-commit-id: a74ca99ebad8d185c5392e4240e43963564b5aed
Former-commit-id: e6cb976c5570465fabca0bd8570d74aa4ce4a1ee


<?php
/**
 * This file is part of the Kappa\FileSystem package.
 *
 * (c) Ondřej Záruba <zarubaondra@gmail.com>
 *
 * For the full copyright and license information, please view the license.md
 * file that was distributed with this source code.
 */

namespace Kappa\FileSystem;

/**
 * Class FileSystem
 * @package Kappa\FileSystem
 */
class FileSystem
{
	/**
	 * @param File|Directory $object
	 * @throws InvalidArgumentException
	 */
	public static function remove($object)
	{
		if (!$object instanceof File && !$object instanceof Directory) {
			throw new InvalidArgumentException(__METHOD__ . ": Argument must be instance of File or Directory");
		}
		\Nette\Utils\FileSystem::delete($object->getInfo()->getPathname());
	}

	/**
	 * @param File|Directory $object
	 * @param string $newName
	 * @param bool $overwrite
	 * @return Directory|File
	 * @throws InvalidArgumentException
	 */
	public static function rename($object, $newName, $overwrite = false)
	{
		if (!$object instanceof File && !$object instanceof Directory) {
			throw new InvalidArgumentException(__METHOD__ . ": Argument must be instance of File or Directory");
		}
		$newName = $object->getInfo()->getPath() . DIRECTORY_SEPARATOR . $newName;
		\Nette\Utils\FileSystem::rename($object->getInfo()->getPathname(), $newName, $overwrite);
		if ($object instanceof File) {
			return File::open($newName);
		} else {
			return Directory::open($newName);
		}
	}
}

<?php
/**
 * This file is part of the Kappa\FileSystem package.
 *
 * (c) Ondřej Záruba <zarubaondra@gmail.com>
 *
 * For the full copyright and license information, please view the license.md
 * file that was distributed with this source code.
 */

namespace Kappa\FileSystem;

/**
 * Class FileSystem
 * @package Kappa\FileSystem
 */
class FileSystem
{
	/**
	 * @param File|Directory $object
	 * @throws InvalidArgumentException
	 */
	public static function remove($object)
	{
		if (!$object instanceof File && !$object instanceof Directory) {
			throw new InvalidArgumentException(__METHOD__ . ": Argument must be instance of File or Directory");
		}
		\Nette\Utils\FileSystem::delete($object->getInfo()->getPathname());
	}

	/**
	 * @param File|Directory $object
	 * @param string $newName
	 * @param bool $overwrite
	 * @return Directory|File
	 * @throws InvalidArgumentException
	 */
	public static function rename($object, $newName, $overwrite = true)
	{
		if (!$object instanceof File && !$object instanceof Directory) {
			throw new InvalidArgumentException(__METHOD__ . ": Argument must be instance of File or Directory");
		}
		$newName = $object->getInfo()->getPath() . DIRECTORY_SEPARATOR . $newName;
		\Nette\Utils\FileSystem::rename($object->getInfo()->getPathname(), $newName, $overwrite);
		if ($object instanceof File) {
			return File::open($newName);
		} else {
			return Directory::open($newName);
		}
	}
}

Change default value for overwire

Change default value for overwire


<?php

namespace Spatie\Skeleton;

use Illuminate\Support\ServiceProvider;
use Spatie\LaravelSlack\SlashCommandHandler\Collection;
use Spatie\LaravelSlack\SlashCommandRequest;

class LaravelSlackServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../config/laravel-slack.php' => config_path('laravel-slack.php'),
        ], 'config');

        $this->app['router']->get(config('laravel-slack.slash_command_url'), function () {

            $slashCommandRequest = SlashCommandRequest::createForRequest(request());

            $slashCommandHandlers = new Collection(config('laravel-slack.slash_command_handlers'), $slashCommandRequest);

            return $slashCommandHandlers->getResponse();
        });
    }

    /**
     * Register the application services.
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../config/laravel-slack.php', 'laravel-slack');
    }
}

<?php

namespace Spatie\LaravelSlack;

use Illuminate\Support\ServiceProvider;
use Spatie\LaravelSlack\SlashCommandHandler\Collection;
use Spatie\LaravelSlack\SlashCommandRequest;

class LaravelSlackServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../config/laravel-slack.php' => config_path('laravel-slack.php'),
        ], 'config');

        $this->app['router']->get(config('laravel-slack.slash_command_url'), function () {

            $slashCommandRequest = SlashCommandRequest::createForRequest(request());

            $slashCommandHandlers = new Collection(config('laravel-slack.slash_command_handlers'), $slashCommandRequest);

            return $slashCommandHandlers->getResponse();
        });
    }

    /**
     * Register the application services.
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../config/laravel-slack.php', 'laravel-slack');
    }
}

Fix name space in the service provider.

Fix name space in the service provider.


<?php

namespace Deployer;

task('media:move', function () {
    if (null === input()->getArgument('stage')) {
        throw new \RuntimeException("The target instance is required for media:move command. [Error code: 1488149866477]");
    }
    if (null !== input()->getArgument('targetStage')) {
        $targetInstanceName = input()->getArgument('targetStage');
        if ($targetInstanceName == 'live') {
            throw new \RuntimeException(
                "FORBIDDEN: For security its forbidden to move media to live instance!"
            );
        }
        if ($targetInstanceName == 'local') {
            throw new \RuntimeException(
                "FORBIDDEN: For synchro local media use: \ndep media:pull " . $targetInstanceName
            );
        }
    } else {
        throw new \RuntimeException(
            "You must set the target instance the media will be copied to as second parameter."
        );
    }
    $targetServer = get('current_server')->get('server')['name'];

    runLocally('{{bin/php}} {{bin/deployer}} media:pull ' . get('server')['name']);
    runLocally('{{bin/php}} {{bin/deployer}} media:push ' . $targetServer);
})->desc('Synchronize media between instances.');

<?php

namespace Deployer;

task('media:move', function () {
    if (null === input()->getArgument('stage')) {
        throw new \RuntimeException("The target instance is required for media:move command. [Error code: 1488149866477]");
    }
    if (null !== input()->getArgument('targetStage')) {
        $targetInstanceName = input()->getArgument('targetStage');
        if ($targetInstanceName == 'live') {
            throw new \RuntimeException(
                "FORBIDDEN: For security its forbidden to move media to live instance!"
            );
        }
        if ($targetInstanceName == 'local') {
            throw new \RuntimeException(
                "FORBIDDEN: For synchro local media use: \ndep media:pull " . $targetInstanceName
            );
        }
    } else {
        throw new \RuntimeException(
            "You must set the target instance the media will be copied to as second parameter."
        );
    }
    $targetServer = get('current_server')->get('server')['name'];

    runLocally('{{bin/php}} {{local/bin/deployer}} media:pull ' . get('server')['name']);
    runLocally('{{bin/php}} {{local/bin/deployer}} media:push ' . $targetServer);
})->desc('Synchronize media between instances.');

Use local/bin/deployer for media move

[BUGFIX] Use local/bin/deployer for media move


<?php

use Illuminate\Database\Seeder;

class UserTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->delete();

        $data['name'] = 'Tim Joosten';
        $data['email'] = 'Topairy@gmail.com';
        $data['gsm'] = '0474834880';
        $data['password'] = bcrypt('admin');

        $id = DB::table('users')->insertGetId($data);

        $user = App\User::find($id);
        Bouncer::assign('active')->to($user);
    }
}

<?php

use Illuminate\Database\Seeder;

class UserTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->delete();

        $data['name'] = 'Tim Joosten';
        $data['email'] = 'Topairy@gmail.com';
        $data['gsm'] = '0474834880';
        $data['password'] = bcrypt('admin');
        $data['api_token'] = str_random(30);

        $id = DB::table('users')->insertGetId($data);

        $user = App\User::find($id);
        Bouncer::assign('active')->to($user);
    }
}

Add api token to the user table seed

Add api token to the user table seed


<?php

namespace Myjob\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel {
	/**
	 * The Artisan commands provided by your application.
	 *
	 * @var array
	 */
	protected $commands = [
		\Myjob\Console\Commands\Inspire::class,
		\Myjob\Console\Commands\SendNotificationMails::class,
		\Myjob\Console\Commands\SyncLDAPStudents::class,
	];

	/**
	 * Define the application's command schedule.
	 *
	 * @param  \Illuminate\Console\Scheduling\Schedule $schedule
	 * @return void
	 */
	protected function schedule(Schedule $schedule) {
		// Synchronise student list with the LDAP
		$schedule->command('syncstudents')
			->weeklyOn(5, '4:00');

		// Send notification mails
		$schedule->command('sendnotificationmails --subscribed=instantly')
			->everyThirtyMinutes();
		$schedule->command('sendnotificationmails --subscribed=daily')
			->dailyAt('4:00');
		$schedule->command('sendnotificationmails --subscribed=weekly')
			->weeklyOn(6, '4:00');
	}
}

<?php

namespace Myjob\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel {
	/**
	 * The Artisan commands provided by your application.
	 *
	 * @var array
	 */
	protected $commands = [
		\Myjob\Console\Commands\Inspire::class,
		\Myjob\Console\Commands\SendNotificationMails::class,
		\Myjob\Console\Commands\SyncLDAPStudents::class,
	];

	/**
	 * Define the application's command schedule.
	 *
	 * @param  \Illuminate\Console\Scheduling\Schedule $schedule
	 * @return void
	 */
	protected function schedule(Schedule $schedule) {
		// Synchronise student list with the LDAP
		$schedule->command('syncstudents')
			->weeklyOn(6, '4:00'); // 6 = Saturday

		// Send notification mails
		$schedule->command('sendnotificationmails --subscribed=instantly')
			->everyThirtyMinutes();
		$schedule->command('sendnotificationmails --subscribed=daily')
			->dailyAt('4:00');
		$schedule->command('sendnotificationmails --subscribed=weekly')
			->weeklyOn(0, '4:00'); // 0 = Sunday
	}
}

Update scheduler tasks day of week

Update scheduler tasks day of week

After testing it comes that day 0 = Sunday, 1 = Monday, ..., 6 = Saturday


<?php

class Project extends Eloquent {

	protected $fillable = ['title', 'slug'];

	/**
	 * @return \Illuminate\Database\Eloquent\Collection
	 */
	public function sprints()
	{
		return $this->hasMany('Sprint')->orderBy('sprint_start', 'desc');
	}

	/**
	 * @return \Illuminate\Validation\Validator
	 */
	public function validate()
	{
		return Validator::make(
			$this->getAttributes(),
			['title' => 'required|unique:projects'],
			['unique' => 'A project with this title already exists.']
		);
	}

	public function currentSprint()
	{
		return $this->newestPastSprint() ?: $this->closestFutureSprint();
	}

	private function newestPastSprint()
	{
		return Sprint::where('sprint_start', '<=', date('Y-m-d'))
			->where('project_id', $this->id)
			->orderBy('sprint_start', 'desc')
			->first();
	}

	private function closestFutureSprint()
	{
		return Sprint::where('sprint_start', '>', date('Y-m-d'))
			->where('project_id', $this->id)
			->orderBy('sprint_start', 'asc')
			->first();
	}
}

<?php

class Project extends Eloquent {

	protected $fillable = ['title', 'slug', 'closed_statuses', 'workboard_mode'];

	/**
	 * @return \Illuminate\Database\Eloquent\Collection
	 */
	public function sprints()
	{
		return $this->hasMany('Sprint')->orderBy('sprint_start', 'desc');
	}

	/**
	 * @return \Illuminate\Validation\Validator
	 */
	public function validate()
	{
		return Validator::make(
			$this->getAttributes(),
			['title' => 'required|unique:projects'],
			['unique' => 'A project with this title already exists.']
		);
	}

	public function currentSprint()
	{
		return $this->newestPastSprint() ?: $this->closestFutureSprint();
	}

	private function newestPastSprint()
	{
		return Sprint::where('sprint_start', '<=', date('Y-m-d'))
			->where('project_id', $this->id)
			->orderBy('sprint_start', 'desc')
			->first();
	}

	private function closestFutureSprint()
	{
		return Sprint::where('sprint_start', '>', date('Y-m-d'))
			->where('project_id', $this->id)
			->orderBy('sprint_start', 'asc')
			->first();
	}
}

Add fields to the project model.

Add fields to the project model.


<?php

namespace Oro\Bundle\WorkflowBundle\Migrations\Data\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

use Oro\Bundle\WorkflowBundle\Entity\WorkflowDefinition;
use Oro\Bundle\WorkflowBundle\Translation\TranslationProcessor;

class UpdateDefinitionTranslations extends AbstractFixture implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        /* @var $processor TranslationProcessor */
        $processor = $this->container->get('oro_workflow.translation.processor');

        /* @var $definitions WorkflowDefinition[] */
        $definitions = $manager->getRepository(WorkflowDefinition::class)->findBy(['system' => false]);

        foreach ($definitions as $definition) {
            $configuration = $this->process($processor, $definition);

            $definition->setConfiguration($configuration);
            $definition->setLabel($configuration['label']);
        }

        $manager->flush();
    }

    /**
     * @param TranslationProcessor $processor
     * @param WorkflowDefinition $definition
     * @return array
     */
    protected function process(TranslationProcessor $processor, WorkflowDefinition $definition)
    {
        $configuration = array_merge(
            $definition->getConfiguration(),
            [
                'name' => $definition->getName(),
                'label' => $definition->getLabel(),
            ]
        );

        return $processor->prepare($definition->getName(), $processor->handle($configuration));
    }
}

<?php

namespace Oro\Bundle\WorkflowBundle\Migrations\Data\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

use Oro\Bundle\WorkflowBundle\Entity\WorkflowDefinition;
use Oro\Bundle\WorkflowBundle\Translation\TranslationProcessor;

class UpdateDefinitionTranslations extends AbstractFixture implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        /* @var $processor TranslationProcessor */
        $processor = $this->container->get('oro_workflow.translation.processor');

        /* @var $definitions WorkflowDefinition[] */
        $definitions = $manager->getRepository(WorkflowDefinition::class)->findBy(['system' => false]);

        foreach ($definitions as $definition) {
            $configuration = $this->process($processor, $definition);

            $definition->setConfiguration($configuration);
            $definition->setLabel($configuration['label']);

            foreach ($definition->getSteps() as $step) {
                $step->setLabel($configuration['steps'][$step->getName()]['label']);
            }
        }

        $manager->flush();
    }

    /**
     * @param TranslationProcessor $processor
     * @param WorkflowDefinition $definition
     * @return array
     */
    protected function process(TranslationProcessor $processor, WorkflowDefinition $definition)
    {
        $configuration = array_merge(
            $definition->getConfiguration(),
            [
                'name' => $definition->getName(),
                'label' => $definition->getLabel(),
            ]
        );

        return $processor->prepare($definition->getName(), $processor->handle($configuration));
    }
}

BAP-12112: Add migration to update current workflow definitions
- added save of step labels


<?php

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

/**
 * Class CreateSettingsListsTable
 */
class CreateSettingsListsTable extends Migration
{

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('settings__lists', function (Blueprint $table)
		{
			$table->string('setting_key')->index()->unique();
			$table->json('setting_value')->nullable();
		});
	}

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

}

<?php

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

/**
 * Class CreateSettingsListsTable
 */
class CreateSettingsListsTable extends Migration
{

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('settings__lists', function (Blueprint $table)
		{
			$table->string('setting_key')->index()->unique();
			$table->binary('setting_value')->nullable();
		});
	}

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

}

Change JSON database column to binary

Change JSON database column to binary

When using certain databases with certain character sets & collations, we are unable to create JSON columns, however a binary column is perfectly fine in this instance.


<?php

$gadgets = Witi::fetchGadgets();

?>

Add new gadget

    <?php foreach ($gadgets as $gadget) { ?>

            <?php if ($gadget['image']) { ?>

                    <img src="storage/thumb/<?php print $gadget['image']; ?>" alt="">
                    <?php $people = Witi::fetchPeopleById($gadget['personId']); ?>
                    <?php if ($people) { ?>

                                <?php foreach ($people as $person) { ?>

<a href="/?view=person&id=<?php print $person['id']; ?>"><?php print $person['name']; ?>

                                <?php } ?>

                    <?php }; ?>

            <?php } ?>

<?php print $gadget['name']; ?>

    <?php } ?>

<?php require_once 'views/parts/add_gadget.php'; ?>

<?php

$gadgets = Witi::fetchGadgets();

?>

Add new gadget

    <?php foreach ($gadgets as $gadget) { ?>

            <?php if ($gadget['image']) { ?>

                    <img src="storage/thumb/<?php print $gadget['image']; ?>" alt="">
                    <?php $people = Witi::fetchPeopleById($gadget['personId']); ?>
                    <?php if ($people) { ?>

                                <?php foreach ($people as $person) { ?>

<?php print $person['name']; ?>

                                <?php } ?>

                    <?php }; ?>

            <?php } ?>

<?php print $gadget['name']; ?>

    <?php } ?>

<?php require_once 'views/parts/add_gadget.php'; ?>

Remove person link in gadget

Remove person link in gadget


<?php

final class PhabricatorRemarkupFigletBlockInterpreter
  extends PhutilRemarkupBlockInterpreter {

  public function getInterpreterName() {
    return 'figlet';
  }

  public function markupContent($content, array $argv) {
    if (!Filesystem::binaryExists('figlet')) {
      return $this->markupError(
        pht('Unable to locate the `figlet` binary. Install figlet.'));
    }

    $font = idx($argv, 'font', 'standard');
    $safe_font = preg_replace('/[^0-9a-zA-Z-_.]/', '', $font);
    $future = id(new ExecFuture('figlet -f %s', $safe_font))
      ->setTimeout(15)
      ->write(trim($content, "\n"));

    list($err, $stdout, $stderr) = $future->resolve();

    if ($err) {
      return $this->markupError(
        pht(
          'Execution of `figlet` failed:', $stderr));
    }

    if ($this->getEngine()->isTextMode()) {
      return $stdout;
    }

    return phutil_tag(
      'div',
      array(
        'class' => 'PhabricatorMonospaced remarkup-figlet',
      ),
      $stdout);
  }

}

<?php

final class PhabricatorRemarkupFigletBlockInterpreter
  extends PhutilRemarkupBlockInterpreter {

  public function getInterpreterName() {
    return 'figlet';
  }

  public function markupContent($content, array $argv) {
    if (!Filesystem::binaryExists('figlet')) {
      return $this->markupError(
        pht('Unable to locate the `figlet` binary. Install figlet.'));
    }

    $font = idx($argv, 'font', 'standard');
    $safe_font = preg_replace('/[^0-9a-zA-Z-_.]/', '', $font);
    $future = id(new ExecFuture('figlet -f %s', $safe_font))
      ->setTimeout(15)
      ->write(trim($content, "\n"));

    list($err, $stdout, $stderr) = $future->resolve();

    if ($err) {
      return $this->markupError(
        pht(
          'Execution of `%s` failed: %s',
          'figlet',
          $stderr));
    }

    if ($this->getEngine()->isTextMode()) {
      return $stdout;
    }

    return phutil_tag(
      'div',
      array(
        'class' => 'PhabricatorMonospaced remarkup-figlet',
      ),
      $stdout);
  }

}

Fix a `pht` method call

Fix a `pht` method call

Summary: Ref T7046. I missed this in D11680.

Test Plan: `arc lint`

Reviewers: #blessed_reviewers, epriestley

Reviewed By: #blessed_reviewers, epriestley

Subscribers: Korvin, epriestley

Maniphest Tasks: T7046

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


Coming to us from FP&C Consultants, Inc. is Dennis Bradshaw. He will be speaking about major updates in the 2015 Indiana Building Code.

Dennis Bradshaw’s code experience dates back to his days with the Indiana Department of Fire and Building Services. His work for the Department included; plan review, interpretation of building code requirements and assisting applicants through the building code review process as well as training of State and Local Building and Fire Officials. From there Dennis has spent the last 16 years in private practice as a code consultant. He has been involved in many of the major projects in the State of Indiana as well as uncounted other projects across the country ranging from industrial to residential to institutional. This experience on both sides of the fence allows Dennis to apply the codes to a wide range of building designs from both the Code Official’s and Designer’s perspectives. Dennis has also been a member on past Indiana Building Code committees as well as a committee member for the NFPA 5000 Building Code. Dennis is a certified member of the International Code Council and a member of the National Fire Protection Association.

Update speaker for the 2014-08-28.

Update speaker for the 2014-08-28.


<?php

namespace Oro\Bundle\EntityBundle\Tests\Functional\DataFixtures;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;

use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LoadBusinessUnitData extends AbstractFixture implements ContainerAwareInterface
{
    /** @var ContainerInterface */
    protected $container;

    /**
     * {@inheritdoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        $organization = $manager->getRepository('OroOrganizationBundle:Organization')->getFirst();

        $businessUnit = new BusinessUnit();
        $businessUnit->setOrganization($organization);
        $businessUnit->setName('TestBusinessUnit');

        $manager->persist($businessUnit);
        $this->setReference('TestBusinessUnit', $businessUnit);
        $manager->flush();
    }
}

<?php

namespace Oro\Bundle\EntityBundle\Tests\Functional\DataFixtures;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit;

class LoadBusinessUnitData extends AbstractFixture implements ContainerAwareInterface
{
    /** @var ContainerInterface */
    protected $container;

    /**
     * {@inheritdoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        $organization = $manager->getRepository('OroOrganizationBundle:Organization')->getFirst();

        $businessUnit = new BusinessUnit();
        $businessUnit->setOrganization($organization);
        $businessUnit->setName('TestBusinessUnit');

        $manager->persist($businessUnit);
        $this->setReference('TestBusinessUnit', $businessUnit);
        $manager->flush();
    }
}

CRM-4573: Add ability to save multiple values for patch API


<?php

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

namespace Surfnet\StepupSelfService\SelfServiceBundle\Controller;

use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;

class EntryPointController extends Controller
{
    public function decideSecondFactorFlowAction()
    {
        $identity = $this->getIdentity();

        /** @var SecondFactorService $service */
        $service = $this->get('surfnet_stepup_self_service_self_service.service.second_factor');

        if ($service->doSecondFactorsExistForIdentity($identity->id)) {
            return $this->redirect($this->generateUrl('ss_second_factor_list'));
        } else {
            $this->get('session')->getFlashBag()->add('notice', 'ss.registration.selector.alert.no_second_factors_yet');

            return $this->redirect(
                $this->generateUrl('ss_registration_display_types')
            );
        }
    }
}

<?php

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

namespace Surfnet\StepupSelfService\SelfServiceBundle\Controller;

use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;

class EntryPointController extends Controller
{
    public function decideSecondFactorFlowAction()
    {
        $identity = $this->getIdentity();

        /** @var SecondFactorService $service */
        $service = $this->get('surfnet_stepup_self_service_self_service.service.second_factor');

        if ($service->doSecondFactorsExistForIdentity($identity->id)) {
            return $this->redirect($this->generateUrl('ss_second_factor_list'));
        } else {
            return $this->redirect(
                $this->generateUrl('ss_registration_display_types')
            );
        }
    }
}

Remove the "no second factors yet" flash message


<?php

namespace Application\Migrations;

use SimplyTestable\BaseMigrationsBundle\Migration\BaseMigration,
    Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20130607130241_add_AccountPlan_isPremium extends BaseMigration
{
    public function up(Schema $schema)
    {
        $this->statements['mysql'] = array(
            "ALTER TABLE AccountPlan ADD isPremium TINYINT(1) NOT NULL"
        );

        $this->statements['sqlite'] = array(
            "ALTER TABLE AccountPlan ADD isPremium TINYINT(1) NOT NULL",

        );

        parent::up($schema);
    }

    public function down(Schema $schema)
    {
        $this->addCommonStatement("ALTER TABLE AccountPlan DROP isPremium");

        parent::down($schema);
    }
}

<?php

namespace Application\Migrations;

use SimplyTestable\BaseMigrationsBundle\Migration\BaseMigration,
    Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20130607130241_add_AccountPlan_isPremium extends BaseMigration
{
    public function up(Schema $schema)
    {
        $this->statements['mysql'] = array(
            "ALTER TABLE AccountPlan ADD isPremium TINYINT(1) NOT NULL"
        );

        $this->statements['sqlite'] = array(
            "ALTER TABLE AccountPlan ADD isPremium TINYINT(1) NOT NULL DEFAULT 1",

        );

        parent::up($schema);
    }

    public function down(Schema $schema)
    {
        $this->addCommonStatement("ALTER TABLE AccountPlan DROP isPremium");

        parent::down($schema);
    }
}

Set default isPremium=true on Account/Plan to happify sqlite


<?php

namespace app;

class MyPhixApp extends \Phix\App
{
    public function __construct($config = null)
    {
        $this
            ->viewsDir(__DIR__ . '/views')
            ->layout('layout')
            ->reg('site_title', 'My Application')
            ->get('/', function($app) {
                $app->render('home');
            })
            ->get('/unreachable', function($app) {
                $app->redirect('/');
            })
            ->get('/notfound', function($app) {
                $app->notFound('Ooops. The URL ' . $app->escape($app->requestUri()) . ' is not there.');
            });

        parent::__construct($config);
    }
}

<?php

namespace app;

class MyPhixApp extends \Phix\App
{
    public function __construct($config = null)
    {
        parent::__construct($config);

        $this
            ->viewsDir(__DIR__ . '/views')
            ->layout('layout')
            ->reg('site_title', 'My Application')
            ->get('/', function($app) {
                $app->render('home');
            })
            ->get('/unreachable', function($app) {
                $app->redirect('/');
            })
            ->get('/notfound', function($app) {
                $app->notFound('Ooops. The URL ' . $app->escape($app->requestUri()) . ' is not there.');
            });
    }
}

Move call to parent constructor to top

Move call to parent constructor to top