<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Listabierta\Bundle\MunicipalesBundle\Validator\Constraints\DNI;

class TownStep7Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Listabierta\Bundle\MunicipalesBundle\Validator\Constraints\DNI;

class TownStep7Type extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    	$resolver->setDefaults(
    			array(
    					'allow_extra_fields' => TRUE
    			)
    	);
    }

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

Allow extra fields in step 7 voters

Allow extra fields in step 7 voters


<?php

final class PhabricatorPasteStatusTransaction
  extends PhabricatorPasteTransactionType {

  const TRANSACTIONTYPE = 'paste.status';

  public function generateOldValue($object) {
    return $object->getStatus();
  }

  public function applyInternalEffects($object, $value) {
    $object->setStatus($value);
  }

  private function isActivate() {
    return ($this->getNewValue() == PhabricatorPaste::STATUS_ARCHIVED);
  }

  public function getIcon() {
    if ($this->isActivate()) {
      return 'fa-check';
    } else {
      return 'fa-ban';
    }
  }

  public function getColor() {
    if ($this->isActivate()) {
      return 'green';
    } else {
      return 'indigo';
    }
  }

  public function getTitle() {
    if ($this->isActivate()) {
      return pht(
        '%s activated this paste.',
        $this->renderAuthor());
    } else {
      return pht(
        '%s archived this paste.',
        $this->renderAuthor());
    }
  }

  public function getTitleForFeed() {
    if ($this->isActivate()) {
      return pht(
        '%s activated %s.',
        $this->renderAuthor(),
        $this->renderObject());
    } else {
      return pht(
        '%s archived %s.',
        $this->renderAuthor(),
        $this->renderObject());
    }
  }

}

<?php

final class PhabricatorPasteStatusTransaction
  extends PhabricatorPasteTransactionType {

  const TRANSACTIONTYPE = 'paste.status';

  public function generateOldValue($object) {
    return $object->getStatus();
  }

  public function applyInternalEffects($object, $value) {
    $object->setStatus($value);
  }

  private function isActivate() {
    return ($this->getNewValue() == PhabricatorPaste::STATUS_ACTIVE);
  }

  public function getIcon() {
    if ($this->isActivate()) {
      return 'fa-check';
    } else {
      return 'fa-ban';
    }
  }

  public function getColor() {
    if ($this->isActivate()) {
      return 'green';
    } else {
      return 'indigo';
    }
  }

  public function getTitle() {
    if ($this->isActivate()) {
      return pht(
        '%s activated this paste.',
        $this->renderAuthor());
    } else {
      return pht(
        '%s archived this paste.',
        $this->renderAuthor());
    }
  }

  public function getTitleForFeed() {
    if ($this->isActivate()) {
      return pht(
        '%s activated %s.',
        $this->renderAuthor(),
        $this->renderObject());
    } else {
      return pht(
        '%s archived %s.',
        $this->renderAuthor(),
        $this->renderObject());
    }
  }

}

Fix a Paste activate/archive status constant in rendering

Summary: Fixes T11280. I extracted this at the last minute and got the constant flipped.

Test Plan: Archived, then activated a paste. Observed correct timeline stories/icons/etc.

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T11280

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


<?php
/**
 * Class VpageController
 */

namespace Delatbabel\ViewPages\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;

/**
 * Class VpageController
 *
 * Handles requests for application pages.
 */
class VpageController extends BaseController
{
    /**
     * Make and return a view relating to the current URL.
     *
     * This is an example controller that can be used or copied or extended in your applications
     * to provide CMS-like functionality.  It returns the view based on the URL in the
     * current request.
     *
     * ### Example
     *
     * <code>
     * // If request contains the URL 1/2/3 then this will return the view with the URL 1/2/3
     * return $this->make($request);
     * </code>
     *
     * @return \Illuminate\Contracts\View\View
     */
    public function make(Request $request)
    {
        $url = $request->path();
        if ($url == '/') {
            $url = 'index';
        }

        # Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' .
        #     'Make page for URL ' . $url);

        return View::make($url);
    }
}

<?php
/**
 * Class VpageController
 */

namespace Delatbabel\ViewPages\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;

/**
 * Class VpageController
 *
 * Handles requests for application pages.
 */
class VpageController extends BaseController
{
    /**
     * Make and return a view relating to the current URL.
     *
     * This is an example controller that can be used or copied or extended in your applications
     * to provide CMS-like functionality.  It returns the view based on the URL in the
     * current request.
     *
     * ### Example
     *
     * <code>
     * // If request contains the URL 1/2/3 then this will return the view with the URL 1/2/3
     * return $this->make($request);
     * </code>
     *
     * @return \Illuminate\Contracts\View\View
     */
    public function make(Request $request)
    {
        $url = $request->path();
        if ($url == '/') {
            $url = 'index';
        }

        # Log::debug(__CLASS__ . ':' . __TRAIT__ . ':' . __FILE__ . ':' . __LINE__ . ':' . __FUNCTION__ . ':' .
        #     'Make page for URL ' . $url);

        return view($url);

        // return View::make($url);
    }
}

Use helper not facade because facade calls the wrong factory


<?php namespace Orchestra\Support\Providers;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

abstract class CommandServiceProvider extends BaseServiceProvider
{
    /**
     * The commands to be registered.
     *
     * @var array
     */
    protected $commands = [];

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        foreach (array_keys($this->commands) as $command) {
            $method = "register{$command}Command";

            call_user_func_array([$this, $method], []);
        }

        $this->commands(array_values($this->commands));
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array_values($this->commands);
    }
}

<?php namespace Orchestra\Support\Providers;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

abstract class CommandServiceProvider extends BaseServiceProvider
{
    /**
     * The commands to be registered.
     *
     * @var array
     */
    protected $commands = [];

    /**
     * Additional provides.
     *
     * @var array
     */
    protected $provides = [];

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        foreach (array_keys($this->commands) as $command) {
            $method = "register{$command}Command";

            call_user_func_array([$this, $method], []);
        }

        $this->commands(array_values($this->commands));
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array_values($this->commands);
    }
}

Allow to register additional service location other than command.

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


<?php

namespace Spatie\MediaLibrary\UrlGenerator;

use Spatie\MediaLibrary\Media;
use Spatie\MediaLibrary\PathGenerator\PathGeneratorFactory;

class UrlGeneratorFactory
{
    public static function createForMedia(Media $media)
    {
        $urlGeneratorClass = 'Spatie\MediaLibrary\UrlGenerator\\'.ucfirst($media->getDiskDriverName()).'UrlGenerator';

        $customUrlClass = config('laravel-medialibrary.custom_url_generator_class');

        $urlGenerator = self::isAValidUrlGeneratorClass($customUrlClass)
            ? $customUrlClass
            : app($urlGeneratorClass);

        $pathGenerator = PathGeneratorFactory::create();

        $urlGenerator->setMedia($media)->setPathGenerator($pathGenerator);

        return $urlGenerator;
    }

    /**
     * Determine if the the given class is a valid UrlGenerator.
     *
     * @param $customUrlClass
     *
     * @return bool
     */
    protected static function isAValidUrlGeneratorClass($customUrlClass)
    {
        if (!$customUrlClass) {
            return false;
        }

        if (!class_exists($customUrlClass)) {
            return false;
        }

        if (!is_subclass_of($customUrlClass, UrlGenerator::class)) {
            return false;
        }

        return true;
    }
}

<?php

namespace Spatie\MediaLibrary\UrlGenerator;

use Spatie\MediaLibrary\Media;
use Spatie\MediaLibrary\PathGenerator\PathGeneratorFactory;

class UrlGeneratorFactory
{
    public static function createForMedia(Media $media)
    {
        $urlGeneratorClass = 'Spatie\MediaLibrary\UrlGenerator\\'.ucfirst($media->getDiskDriverName()).'UrlGenerator';

        $customUrlClass = config('laravel-medialibrary.custom_url_generator_class');

        $urlGenerator = self::isAValidUrlGeneratorClass($customUrlClass)
            ? app($customUrlClass)
            : app($urlGeneratorClass);

        $pathGenerator = PathGeneratorFactory::create();

        $urlGenerator->setMedia($media)->setPathGenerator($pathGenerator);

        return $urlGenerator;
    }

    /**
     * Determine if the the given class is a valid UrlGenerator.
     *
     * @param $customUrlClass
     *
     * @return bool
     */
    protected static function isAValidUrlGeneratorClass($customUrlClass)
    {
        if (!$customUrlClass) {
            return false;
        }

        if (!class_exists($customUrlClass)) {
            return false;
        }

        if (!is_subclass_of($customUrlClass, UrlGenerator::class)) {
            return false;
        }

        return true;
    }
}

Fix bug when using a custom class (defined via string in config)


<?php
namespace Composed;

/**
 * @author Josh Di Fabio <joshdifabio@gmail.com>
 */
class LockFile
{
    private $root;
    private $json;
    private $packages;

    public function __construct(RootPackage $root, JsonObject $json)
    {
        $this->root = $root;
        $this->json = $json;
    }

    public static function fromFilePath(RootPackage $root, string $filePath) : self
    {
        return new self($root, JsonObject::fromFilePath($filePath));
    }

    public function getPackages() : PackageCollection
    {
        if (null === $this->packages) {
            $packages = [];
            $packagesData = $this->json->get(['packages'], []);
            foreach ($packagesData as $packageData) {
                $package = Package::fromArray($this->root, $packageData);
                $packages[$package->getName()] = $package;
            }
            $this->packages = new PackageCollection($packages);
        }

        return $this->packages;
    }

    public function get($keys = [], $default = null)
    {
        return $this->json->get($keys, $default);
    }
}

<?php
namespace Composed;

/**
 * @author Josh Di Fabio <joshdifabio@gmail.com>
 */
class LockFile
{
    private $root;
    private $json;
    private $packages;

    public function __construct(RootPackage $root, JsonObject $json)
    {
        $this->root = $root;
        $this->json = $json;
    }

    public static function fromFilePath(RootPackage $root, string $filePath) : self
    {
        return new self($root, JsonObject::fromFilePath($filePath));
    }

    public function getPackages() : PackageCollection
    {
        if (null === $this->packages) {
            $packages = [];
            $packagesData = $this->json->get(['packages'], []);
            foreach ($packagesData as $packageData) {
                $package = Package::fromArray($this->root, $packageData);
                $packages[$package->getName()] = $package;
            }
            $this->packages = new PackageCollection($packages);
        }

        return $this->packages;
    }

    public function getDevPackages() : PackageCollection
    {
        if (null === $this->packages) {
            $packages = [];
            $packagesData = $this->json->get(['packages-dev'], []);
            foreach ($packagesData as $packageData) {
                $package = Package::fromArray($this->root, $packageData);
                $packages[$package->getName()] = $package;
            }
            $this->packages = new PackageCollection($packages);
        }

        return $this->packages;
    }

    public function get($keys = [], $default = null)
    {
        return $this->json->get($keys, $default);
    }
}

Add method to retrieve dev packages from lock file


<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

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

<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

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

    /**
     * @param $trait_type_id
     * @param $fennec_ids
     * @return array values of specific trait
     */
    public function getValues($trait_type_id, $fennec_ids){
        $qb = $this->getEntityManager()->createQueryBuilder();
        if($fennec_ids !== null){
            $qb->select('IDENTITY(t.fennec) AS id', 't.value')
                ->from('AppBundle\Entity\TraitNumericalEntry', 't')
                ->where('IDENTITY(t.traitType) = :trait_type_id')
                ->setParameter('trait_type_id', $trait_type_id)
                ->andWhere('t.deletionDate IS NOT NULL')
                ->add('where', $qb->expr()->in('t.fennec', $fennec_ids));
        } else {
            $qb->select('IDENTITY(t.fennec) AS id', 't.value')
                ->from('AppBundle\Entity\TraitNumericalEntry', 't')
                ->where('IDENTITY(t.traitType) = :trait_type_id')
                ->setParameter('trait_type_id', $trait_type_id)
                ->expr()->isNotNull('t.deletionDate');
        }
        $query = $qb->getQuery();
        $result = $query->getResult();
        $values = array();
        for($i=0;$i<sizeof($result);$i++) {
            if(!array_key_exists($result[$i]['id'], $values)){
                $values[$result[$i]['id']] = array();
            }
            $values[$result[$i]['id']][] = $result[$i]['value'];
        }
        return $values;
    }
}

Implement function for getting values of numerical trait entries


<?php

namespace App\Http\Controllers;

class ParkingController
{
    public function getAll()
    {
        return Response::json('success', $this->table()->get());
    }

    public function get($id)
    {
        $parking = $this->table()->where('id', $id)->get();

        return Response::json('success', $parking);
    }

    public function rentSpace()
    {
        // Add server side validation check if space is rented
        $id = input('id');

        $parking = $this->getParking($id)->first();

        if ($parking->rented === 'true') {
            return Response::json('fail', [
                'message' => 'The parking space has been rented'
            ]);
        }

        $this->getParking($id)->update(['rented' => 'true']);

        return Response::json('success');
    }

    private function table()
    {
        return \Builder::table('parking');
    }

    private function getParking($id)
    {
        return $this->table()->where('id', $id);
    }
}

<?php

namespace App\Http\Controllers;

class ParkingController
{
    public function getAll()
    {
        return Response::json('success', $this->table()->get());
    }

    public function get($id)
    {
        $parking = $this->table()->where('id', $id)->get();

        if (empty($parking)) {
            return Response::json('fail', [
                'message' => 'The parking space does not exist'
            ]);
        }

        return Response::json('success', $parking);
    }

    public function rentSpace()
    {
        // Add server side validation check if space is rented
        $id = input('id');

        $parking = $this->getParking($id)->first();

        if ($parking->rented === 'true') {
            return Response::json('fail', [
                'message' => 'The parking space has been rented'
            ]);
        }

        $this->getParking($id)->update(['rented' => 'true']);

        return Response::json('success');
    }

    private function table()
    {
        return \Builder::table('parking');
    }

    private function getParking($id)
    {
        return $this->table()->where('id', $id);
    }
}

Return fail message if parking space do not exist


<?php

namespace App\Http\Controllers;

use \Redirect;
use App\Models\Domain;
use App\Models\Hit;

class DomainsController extends Controller
{

    public function index()
    {
        $domain = Domain::matching($_SERVER['SERVER_NAME'])
            ->first();
        if (!$domain || !$domain->active) {
            abort(404);
        }

        // log hit
        $data = array(
            'domain_id' => $domain->id,
            'server_values' => json_encode($_SERVER),
            'path' => $_SERVER['REQUEST_URI'],
        );
        if (isset($_SERVER['HTTP_REFERER'])) {
            $data['referer'] = $_SERVER['HTTP_REFERER'];
        }
        Hit::create($data);

        // redirect to destination
        return Redirect::to(
            $domain->redirect_url,
            $domain->status
        );
    }
}

<?php

namespace App\Http\Controllers;

use \Redirect;
use App\Models\Domain;
use App\Models\Hit;

class DomainsController extends Controller
{

    public function index()
    {
        $domain = Domain::matching($_SERVER['SERVER_NAME'])->first();

        if (!$domain || !$domain->active) {
            abort(404);
        }

        // log hit
        $data = [
            'domain_id' => $domain->id,
            'server_values' => json_encode($_SERVER),
            'path' => $_SERVER['REQUEST_URI'],
        ];

        if (isset($_SERVER['HTTP_REFERER'])) {
            $data['referer'] = $_SERVER['HTTP_REFERER'];
        }

        Hit::create($data);

        // redirect to destination
        return Redirect::to($domain->redirect_url, $domain->status);
    }
}

Clean up and code style

Clean up and code style


<?php /** @var \nochso\WriteMe\Placeholder\PlaceholderDocs\TemplateData $this */ ?>
<?php foreach ($this->getPlaceholders() as $placeholder): ?>
<?php $class = $this->getClassForPlaceholder($placeholder); ?>
<?php $docBlock = $this->getClassDocBlock($class); ?>

<?= $this->header(1, $class->getShortName()) ?> `@@<?= $placeholder->getIdentifier() ?>@@`

<?= $docBlock->getText() ?>

<?= $this->header(2, 'Default options') ?>

```yaml
<?= $this->getOptionListYaml($placeholder->getDefaultOptionList()) ?>
```

<?php foreach ($placeholder->getDefaultOptionList() as $option): ?>
* `<?= $option->getPath() ?>`
<?= $this->indent(1, '*') ?> <?= $option->getDescription() ?>

<?php endforeach; ?>
<?php endforeach; ?>

<?php /** @var \nochso\WriteMe\Placeholder\PlaceholderDocs\TemplateData $this */ ?>
<?php foreach ($this->getPlaceholders() as $placeholder): ?>
<?php $class = $this->getClassForPlaceholder($placeholder); ?>
<?php $docBlock = $this->getClassDocBlock($class); ?>

<?= $this->header(1, $class->getShortName()) ?> `@@<?= $placeholder->getIdentifier() ?>@@`

<?= $docBlock->getText() ?>

<?= $this->header(2, 'Default options') ?>

```yaml
<?= $this->getOptionListYaml($placeholder->getDefaultOptionList()) ?>
```

<?php foreach ($placeholder->getDefaultOptionList()->getOptions() as $option): ?>
* `<?= $option->getPath() ?>`
<?= $this->indent(1, '*') ?> <?= $option->getDescription() ?>

<?php endforeach; ?>
<?php endforeach; ?>

fix: Make PlaceholderDocs iterate over options again


<?php

namespace BlueRegister\Events;

use BlueEvent\Event\BaseEvent;

class RegisterException extends BaseEvent
{
    /**
     * @var \SimpleLog\LogInterface
     */
    protected $log;

    /**
     * @var bool
     */
    protected static $allowKill = false;

    /**
     * Set var that allow to kill application if register exception is throwed away
     *
     * @param bool $allowKill
     */
    public static function allowKill($allowKill)
    {
        self::$allowKill = (bool)$allowKill;
    }

    /**
     * @return bool
     */
    public static function isKillingAllowed()
    {
        return self::$allowKill;
    }

    /**
     * Allow to kill application if register throw an exception
     *
     * @param string $eventName
     * @param array $parameters
     * @throws \Exception
     */
    public function __construct($eventName, array $parameters)
    {
        parent::__construct($eventName, $parameters);

        if (self::$allowKill) {
            $this->log->makeLog('System killed by Register Exception.');
            throw new \RuntimeException('System killed by Register Exception.');
        }
    }
}

<?php

namespace BlueRegister\Events;

use BlueEvent\Event\BaseEvent;

class RegisterException extends BaseEvent
{
    /**
     * @var bool
     */
    protected static $allowKill = false;

    /**
     * Set var that allow to kill application if register exception is throwed away
     *
     * @param bool $allowKill
     */
    public static function allowKill($allowKill)
    {
        self::$allowKill = (bool)$allowKill;
    }

    /**
     * @return bool
     */
    public static function isKillingAllowed()
    {
        return self::$allowKill;
    }

    /**
     * Allow to kill application if register throw an exception
     *
     * @param string $eventName
     * @param array $parameters
     * @throws \Exception
     */
    public function __construct($eventName, array $parameters)
    {
        parent::__construct($eventName, $parameters);

        if (self::$allowKill) {
            throw new \RuntimeException('System killed by Register Exception. Unknown class: ' . $parameters[0]);
        }
    }
}

Exit replaced by Runtime Exception, disable log creation


<?php
namespace Staf\Generator;

use Illuminate\Support\ServiceProvider;

class GeneratorServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // Setup the config file for publishing.
        $this->publishes([__DIR__ . '/config.php' => config_path('generator.php')], 'config');

        // Add the default console command
        if ($this->app->runningInConsole()) {
            $this->commands([PublishCommand::class]);
        }
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(Builder::class, function ($app) {
            return new Builder([
                'source_path' => $app['config']['generator']['source_path'],
                'target_path' => $app['config']['generator']['source_path'],
                'cache_path'  => $app['config']['generator']['source_path'],
            ]);
        });
    }
}

<?php
namespace Staf\Generator;

use Illuminate\Support\ServiceProvider;

class GeneratorServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // Setup the config file for publishing.
        $this->publishes([__DIR__ . '/config.php' => config_path('generator.php')], 'config');

        // Add the default console command
        if ($this->app->runningInConsole()) {
            $this->commands([PublishCommand::class]);
        }
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(Builder::class, function ($app) {
            return new Builder([
                'source_path' => $app['config']['generator']['source_path'],
                'target_path' => $app['config']['generator']['target_path'],
                'cache_path'  => $app['config']['generator']['cache_path'],
            ]);
        });
    }
}

Use correct settings when registering the Builder with Laravel.


<?php namespace Efriandika\LaravelSettings;

use Illuminate\Support\ServiceProvider;

class SettingsServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/config/settings.php' => config_path('settings.php')
        ]);
        $this->publishes([
            __DIR__ . '/database/migrations/' => base_path('/database/migrations')
        ]);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__ . '/config/settings.php', 'settings'
        );
        $this->app['settings'] = $this->app->share(function ($app) {

            $config = $app->config->get('settings', [
                'cache_file' => storage_path('settings.json'),
                'db_table'   => 'settings'
            ]);

            return new Settings($app['db'], new Cache($config['cache_file']), $config);
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array ('settings');
    }

}

<?php namespace Efriandika\LaravelSettings;

use Illuminate\Support\ServiceProvider;

class SettingsServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/config/settings.php' => config_path('settings.php')
        ]);
        $this->publishes([
            __DIR__ . '/database/migrations/' => base_path('/database/migrations')
        ]);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__ . '/config/settings.php', 'settings'
        );
        $this->app->singleton('settings', function ($app) {

            $config = $app->config->get('settings', [
                'cache_file' => storage_path('settings.json'),
                'db_table'   => 'settings'
            ]);

            return new Settings($app['db'], new Cache($config['cache_file']), $config);
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array ('settings');
    }

}

Change share method to singleton. v5.4 fix

5.4. The share method has been removed from the container.


<?php
/**
 * Loader
 */
$loader->add('Aura\Framework_Demo\\', dirname(__DIR__) . DIRECTORY_SEPARATOR . 'src');

/**
 * Aura\Framework\Cli\Factory
 */
$di->params['Aura\Framework\Cli\Factory']['map']["$system/package/Aura.Framework_Demo/cli/hello"] = 'Aura\Framework_Demo\Cli\Hello\Command';

/**
 * Aura\Framework\Web\Controller\Factory
 */
$di->params['Aura\Framework\Web\Controller\Factory']['map']['aura.demo.hello'] = 'Aura\Framework_Demo\Web\Hello\Page';

/**
 * Aura\Router\Map
 */
$di->params['Aura\Router\Map']['attach']['/'] = $di->lazyRequire("$system/package/Aura.Framework_Demo/routes.php");

<?php
/**
 * Loader
 */
$loader->add('Aura\Framework_Demo\\', dirname(__DIR__) . DIRECTORY_SEPARATOR . 'src');

/**
 * Router
 */
$router->attach('/', $di->lazyRequire("$system/package/Aura.Framework_Demo/routes.php"));

/**
 * Aura\Framework\Cli\Factory
 */
$di->params['Aura\Framework\Cli\Factory']['map']["$system/package/Aura.Framework_Demo/cli/hello"] = 'Aura\Framework_Demo\Cli\Hello\Command';

/**
 * Aura\Framework\Web\Controller\Factory
 */
$di->params['Aura\Framework\Web\Controller\Factory']['map']['aura.demo.hello'] = 'Aura\Framework_Demo\Web\Hello\Page';

[CFG] Use the new $router for attaching routes


<?php

namespace Adldap\Connections;

class DetailedError
{
    /**
     * The error code from ldap_errno.
     *
     * @var int
     */
    protected $errorCode = null;

    /**
     * The error message from ldap_error.
     *
     * @var string
     */
    protected $errorMessage = null;

    /**
     * The diagnostic message when retrieved after an ldap_error.
     *
     * @var string
     */
    protected $diagnosticMessage = null;

    /**
     * Constructor.
     *
     * @param int    $errorCode
     * @param string $errorMessage
     * @param string $diagnosticMessage
     */
    public function __construct($errorCode, $errorMessage, $diagnosticMessage)
    {
        $this->errorCode = $errorCode;
        $this->errorMessage = $errorMessage;
        $this->diagnosticMessage = $diagnosticMessage;
    }

    /**
     * Returns the LDAP error code.
     *
     * @return int
     */
    public function getErrorCode()
    {
        return $this->errorCode;
    }

    /**
     * Returns the LDAP error message.
     *
     * @return string
     */
    public function getErrorMessage()
    {
        return $this->errorMessage;
    }

    /**
     * Returns the LDAP diagnostic message.
     *
     * @return string
     */
    public function getDiagnosticMessage()
    {
        return $this->diagnosticMessage;
    }
}

<?php

namespace Adldap\Connections;

class DetailedError
{
    /**
     * The error code from ldap_errno.
     *
     * @var int|null
     */
    protected $errorCode;

    /**
     * The error message from ldap_error.
     *
     * @var string|null
     */
    protected $errorMessage;

    /**
     * The diagnostic message when retrieved after an ldap_error.
     *
     * @var string|null
     */
    protected $diagnosticMessage;

    /**
     * Constructor.
     *
     * @param int    $errorCode
     * @param string $errorMessage
     * @param string $diagnosticMessage
     */
    public function __construct($errorCode, $errorMessage, $diagnosticMessage)
    {
        $this->errorCode = $errorCode;
        $this->errorMessage = $errorMessage;
        $this->diagnosticMessage = $diagnosticMessage;
    }

    /**
     * Returns the LDAP error code.
     *
     * @return int
     */
    public function getErrorCode()
    {
        return $this->errorCode;
    }

    /**
     * Returns the LDAP error message.
     *
     * @return string
     */
    public function getErrorMessage()
    {
        return $this->errorMessage;
    }

    /**
     * Returns the LDAP diagnostic message.
     *
     * @return string
     */
    public function getDiagnosticMessage()
    {
        return $this->diagnosticMessage;
    }
}

Remove default null property sets.

Remove default null property sets.


<?php

namespace MongoDB\Exception;

class BadMethodCallException extends \BadMethodCallException implements Exception
{
    /**
     * Thrown when accessing a result field on an unacknowledged write result.
     */
    public static function unacknowledgedWriteResultAccess($method)
    {
        return new static(sprintf('%s should not be called for an unacknowledged write result', $method));
    }
}

<?php

namespace MongoDB\Exception;

class BadMethodCallException extends \BadMethodCallException implements Exception
{
    /**
     * Thrown when accessing a result field on an unacknowledged write result.
     *
     * @param string $method Method name
     * @return self
     */
    public static function unacknowledgedWriteResultAccess($method)
    {
        return new static(sprintf('%s should not be called for an unacknowledged write result', $method));
    }
}

Add missing doc block info

Add missing doc block info


<?php
    require_once dirname(dirname(__FILE__)).'/Opbeat/utils.php';

    class UtilsTest extends PHPUnit_Framework_TestCase {

        /**
         * @covers Opbeat_Utils::getFileName
         */
        public function testGetFilename () {
            define ('OPBEATOPT_PROJECT_ABS_PATH', '/path/to/script');
            $this->assertEquals(Opbeat_Utils::getFilename('/path/to/script/asdasd'), 'asdasd');
        }

        /**
         * @expectedException Exception
         */
        public function testCheckConstantFailure () {
            Opbeat_Utils::checkSystem();
        }

        /**
         * @covers Opbeat_Utils::checkSystem
         */
        public function testCheckConstantSuccess () {
            define ('OPBEATOPT_ORGANIZATION_ID', 'fake');
            define ('OPBEATOPT_APP_ID', 'fake');
            define ('OPBEATOPT_SECRET_TOKEN', 'fake');
            $this->assertTrue(Opbeat_Utils::checkSystem());
        }

    }

<?php
    require_once dirname(dirname(__FILE__)).'/Opbeat/utils.php';

    class UtilsTest extends PHPUnit_Framework_TestCase {

        /**
         * @covers Opbeat_Utils::getFileName
         */
        public function testGetFilename () {
            define ('OPBEATOPT_PROJECT_ABS_PATH', '/path/to/script');
            $this->assertEquals(Opbeat_Utils::getFilename('/path/to/script/asdasd'), 'asdasd');
        }

        /**
         * @expectedException Exception
         */
        public function testCheckConstantFailure () {
            try {
                Opbeat_Utils::checkSystem();
                $this->assertTrue(false, '\\Exception not raised by Opbeat_Utils::checkSystem when configuration constant are undefined');
            } catch (Exception $e) {
                $this->assertTrue(true);
            }

        }

        /**
         * @covers Opbeat_Utils::checkSystem
         */
        public function testCheckConstantSuccess () {
            define ('OPBEATOPT_ORGANIZATION_ID', 'fake');
            define ('OPBEATOPT_APP_ID', 'fake');
            define ('OPBEATOPT_SECRET_TOKEN', 'fake');
            $this->assertTrue(Opbeat_Utils::checkSystem());
        }

    }

FIX testCheckConstantFailure to works with PHP 5.2


<?php

if (get_option('disable_toolbar')) {
  show_admin_bar(false);
}

if (get_option('disable_dashboard')) {

  if(!function_exists(disableDashboard)) {

    add_action('admin_init', 'disableDashboard');

    function disableDashboard() {
      if (!current_user_can('manage_options') && $_SERVER['DOING_AJAX'] != '/wp-admin/admin-ajax.php') {
        wp_redirect(home_url()); exit;
      }
    }

  }

}

<?php

if (get_option('disable_toolbar')) {
  show_admin_bar(false);
}

if (get_option('disable_dashboard')) {

  if(!function_exists('disableDashboard')) {

    add_action('admin_init', 'disableDashboard');

    function disableDashboard() {
      if (!current_user_can('manage_options') && $_SERVER['DOING_AJAX'] != '/wp-admin/admin-ajax.php') {
        wp_redirect(home_url()); exit;
      }
    }

  }

}

Check as string, not constant..

Check as string, not constant..


<?php
/*
Plugin Name:        Soil
Plugin URI:         http://roots.io/plugins/soil/
Description:        Clean up WordPress markup, use relative URLs, nicer search URLs, and disable trackbacks
Version:            3.0.3
Author:             Roots
Author URI:         http://roots.io/

License:            MIT License
License URI:        http://opensource.org/licenses/MIT
*/

namespace Roots\Soil;

define('SOIL_PATH', plugin_dir_path(__FILE__));

function load_modules() {
  if (current_theme_supports('soil-clean-up')) {
    require_once(SOIL_PATH . 'modules/clean-up.php');
  }

  if (current_theme_supports('soil-relative-urls')) {
    require_once(SOIL_PATH . 'modules/relative-urls.php');
  }

  if (current_theme_supports('soil-nice-search')) {
    require_once(SOIL_PATH . 'modules/nice-search.php');
  }

  if (current_theme_supports('soil-disable-trackbacks')) {
    require_once(SOIL_PATH . 'modules/disable-trackbacks.php');
  }

  if (current_theme_supports('soil-disable-asset-versioning')) {
    require_once(SOIL_PATH . 'modules/disable-asset-versioning.php');
  }
}
add_action('after_setup_theme', __NAMESPACE__ . '\\load_modules');

<?php
/*
Plugin Name:        Soil
Plugin URI:         http://roots.io/plugins/soil/
Description:        Clean up WordPress markup, use relative URLs, nicer search URLs, and disable trackbacks
Version:            3.0.3
Author:             Roots
Author URI:         http://roots.io/

License:            MIT License
License URI:        http://opensource.org/licenses/MIT
*/

namespace Roots\Soil;

function load_modules() {
  foreach (glob(__DIR__ . '/modules/*.php') as $file) {
    if (current_theme_supports('soil-' . basename($file))) {
      require_once $file;
    }
  }
}
add_action('after_setup_theme', __NAMESPACE__ . '\\load_modules');

Refactor Soil to use loop

Refactor Soil to use loop


<?php

/**
 * This file contains fallback functions that might have been disabled but are required nevertheless.
 */

if ( PHP_MAJOR_VERSION >= 8 && ! function_exists( 'ini_set' ) ) {
	function ini_set() {}
}

<?php

/**
 * This file contains fallback functions that might have been disabled but are required nevertheless.
 */

if ( PHP_MAJOR_VERSION >= 8 && ! function_exists( 'ini_set' ) ) {
	function ini_set( $option, $value ) {
		return false;
	}
}

Add arguments to ini_set() fallback

Add arguments to ini_set() fallback


<?php

function dump ($o) {
  $o = serialize($o);
  echo json_encode($o), "\n";
}

class Foo {
  public $bar = 1;
  protected $baz = 2;
  private $xyzzy = array(1,2,3,4,5,6,7,8,9);
  protected $self;
  public function __construct () {
    $this->self = $this;
  }
}
$f = new Foo();
dump($f);

class Bar {
}
$f = new Bar();
$f->self = $f;
dump($f);

$f = new stdClass;
$f->obj1->obj2->obj3->arr = array();
$f->obj1->obj2->obj3->arr[] = 1;
$f->obj1->obj2->obj3->arr[] = 2;
$f->obj1->obj2->obj3->arr[] = 3;
$f->obj1->obj2->obj3->arr['ref1'] = $f->obj1->obj2;
$f->obj1->obj2->obj3->arr['ref2'] = &$f->obj1->obj2->obj3->arr;
dump($f);

<?php

function dump ($o) {
  $o = serialize($o);
  echo json_encode($o), "\n";
}

class Foo {
  public $bar = 1;
  protected $baz = 2;
  private $xyzzy = array(1,2,3,4,5,6,7,8,9);
  protected $self;
  public function __construct () {
    $this->self = $this;
  }
}
$f = new Foo();
dump($f);

class Bar {
}
$f = new Bar();
$f->self = $f;
dump($f);

class Child extends Foo {
    public $lorem = 42;
    protected $ipsum = 37;
    private $dolor = 13;
}
$f = new Child();
dump($f);

$f = new stdClass;
$f->obj1->obj2->obj3->arr = array();
$f->obj1->obj2->obj3->arr[] = 1;
$f->obj1->obj2->obj3->arr[] = 2;
$f->obj1->obj2->obj3->arr[] = 3;
$f->obj1->obj2->obj3->arr['ref1'] = $f->obj1->obj2;
$f->obj1->obj2->obj3->arr['ref2'] = &$f->obj1->obj2->obj3->arr;
dump($f);

Add debug case for serialize sources

Add debug case for serialize sources


<?php
namespace Sil\DevPortal\components;

use Sil\DevPortal\components\ApiAxle\Client as ApiAxleClient;

trait RepopulateApiAxleTrait
{
    abstract public function createOrUpdateInApiAxle($apiAxle = null);

    abstract public function getErrors($attribute = null);

    abstract public function getFriendlyId();

    abstract public static function model($className = __CLASS__);

    public static function repopulateApiAxle(ApiAxleClient $apiAxle)
    {
        $errorsByModel = [];
        foreach (static::model()->findAll() as $model) {
            /* @var $model \CActiveRecord */
            $result = $model->createOrUpdateInApiAxle($apiAxle);
            if ( ! $result) {
                $errorsByModel[$model->getFriendlyId()] = $model->getErrors();
            }
        }
        return $errorsByModel;
    }
}

<?php
namespace Sil\DevPortal\components;

use Sil\DevPortal\components\ApiAxle\Client as ApiAxleClient;

trait RepopulateApiAxleTrait
{
    abstract public function createOrUpdateInApiAxle($apiAxle = null);

    abstract public function getErrors($attribute = null);

    abstract public function getFriendlyId();

    /**
     * NOTE: PHP < 7 does not allow abstract static functions, but for a class
     *       to use this trait it needs to have a model() function... we just
     *       have no way to enforce that until we get to PHP 7.
     * abstract public static function model($className = __CLASS__);
     */

    public static function repopulateApiAxle(ApiAxleClient $apiAxle)
    {
        $errorsByModel = [];
        foreach (static::model()->findAll() as $model) {
            /* @var $model \CActiveRecord */
            $result = $model->createOrUpdateInApiAxle($apiAxle);
            if ( ! $result) {
                $errorsByModel[$model->getFriendlyId()] = $model->getErrors();
            }
        }
        return $errorsByModel;
    }
}

Comment out abstract static function (until we're using PHP 7).


<?php

namespace PSU\Config;

/**
 *
 */
class Factory {
	static $instance = null;

	public function set_config( \PSU\Config $config ) {
		self::$instance = $config;
	}

	public function get_config() {
		if( null === self::$instance ) {
			self::$instance = new \PSU\Config;
			self::$instance->load();
		}

		return self::$instance;
	}
}//end class Factory

<?php

namespace PSU\Config;

/**
 *
 */
class Factory {
	static $instance = null;

	public static function set_config( \PSU\Config $config ) {
		self::$instance = $config;
	}//end set_config

	public static function get_config() {
		if( null === self::$instance ) {
			self::$instance = new \PSU\Config;
			self::$instance->load();
		}

		return self::$instance;
	}//end get_config
}//end class Factory

Mark factory methods as static

Mark factory methods as static

See #105


<?php

namespace Opifer\CmsBundle\Controller\Frontend;

use Opifer\CmsBundle\Event\Events;
use Opifer\CmsBundle\Event\SitemapEvent;
use Opifer\ContentBundle\Model\ContentInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class SitemapController extends Controller
{
    /**
     * Renders the sitemap.
     *
     * @return Response
     */
    public function sitemapAction()
    {
        /* @var ContentInterface[] $content */
        $contents = $this->get('opifer.content.content_manager')->getRepository()->findIndexable();

        $event = new SitemapEvent();

        foreach ($contents as $content) {
            $event->addUrl($this->generateUrl('_content', ['slug' => $content->getSlug()]), $content->getUpdatedAt());
        }

        $dispatcher = $this->get('event_dispatcher');
        $dispatcher->dispatch(Events::POPULATE_SITEMAP, $event);

        return $this->render('OpiferCmsBundle:Sitemap:sitemap.xml.twig', [
            'urls' => $event->getUrls(),
        ]);
    }
}

<?php

namespace Opifer\CmsBundle\Controller\Frontend;

use Opifer\CmsBundle\Event\Events;
use Opifer\CmsBundle\Event\SitemapEvent;
use Opifer\ContentBundle\Model\ContentInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class SitemapController extends Controller
{
    /**
     * Renders the sitemap.
     *
     * @return Response
     */
    public function sitemapAction()
    {
        /* @var ContentInterface[] $content */
        $contents = $this->get('opifer.content.content_manager')->getRepository()->findIndexable();

        $event = new SitemapEvent();

        foreach ($contents as $content) {
            $event->addUrl($this->generateUrl('_content', ['slug' => $content->getSlug()], UrlGeneratorInterface::ABSOLUTE_URL), $content->getUpdatedAt());
        }

        $dispatcher = $this->get('event_dispatcher');
        $dispatcher->dispatch(Events::POPULATE_SITEMAP, $event);

        return $this->render('OpiferCmsBundle:Sitemap:sitemap.xml.twig', [
            'urls' => $event->getUrls(),
        ]);
    }
}

Use Absolute URLs in sitemap.xml

Use Absolute URLs in sitemap.xml


<?php namespace GeneaLabs\LaravelCaffeine\Http\Controllers;

use Illuminate\Routing\Controller;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\Response;

class Drip extends Controller
{
    public function drip() : Response
    {
        return response('', 204);
    }
}

<?php namespace GeneaLabs\LaravelCaffeine\Http\Controllers;

use Illuminate\Routing\Controller;
use Illuminate\View\View;

class Drip extends Controller
{
    public function drip()
    {
        return response('', 204);
    }
}

Fix return type in drip controller

Fix return type in drip controller


<?php namespace Northstar\Handlers\Events;

use Northstar\Events\UserSignedUp;
use Northstar\Models\User;

use Northstar\Services\Parse;

class SendSignupPushNotification {

  /**
   * Parse API wrapper.
   * @var Parse
   */
  protected $parse;

  /**
   * Create the event handler.
   *
   * @return void
   */
  public function __construct(Parse $parse)
  {
    $this->parse = $parse;
  }

  /**
   * Handle the event.
   * @param  UserSignedUp  $event
   * @return void
   */
  public function handle(UserSignedUp $event)
  {
    // Get signup group.
    $group = User::where('campaigns', 'elemMatch', ['signup_id' => (int)$event->signup_id])
            ->orWhere('campaigns', 'elemMatch', ['signup_source' => $event->signup_id])->get();

    // Loop through the users in the group.
    foreach ($group as $user) {
      $drupal_id = $user->drupal_id;
      // Check that this user is not the user that triggered the event.
      if ($drupal_id !== $event->drupal_id) {
        // @TODO - This is placeholder content.
        $data = array("alert" => "I just signed up to your group");

        // Send notifications to the users devices.
        $this->parse->sendPushNotification($user->parse_installation_ids, $data);
      }
    }
  }

}

<?php namespace Northstar\Handlers\Events;

use Northstar\Events\UserSignedUp;
use Northstar\Models\User;

use Northstar\Services\Parse;

class SendSignupPushNotification {

  /**
   * Parse API wrapper.
   * @var Parse
   */
  protected $parse;

  /**
   * Create the event handler.
   *
   * @return void
   */
  public function __construct(Parse $parse)
  {
    $this->parse = $parse;
  }

  /**
   * Handle the event.
   * @param  UserSignedUp  $event
   * @return void
   */
  public function handle(UserSignedUp $event)
  {
    // Get signup group.
    $group = User::where('campaigns', 'elemMatch', ['signup_id' => (int)$event->signup_id])
            ->orWhere('campaigns', 'elemMatch', ['signup_source' => $event->signup_id])->get();

    if (count($group) > 0) {
      // Loop through the users in the group.
      foreach ($group as $user) {
        $drupal_id = $user->drupal_id;
        // Check that this user is not the user that triggered the event.
        if ($drupal_id !== $event->drupal_id) {
          // @TODO - This is placeholder content.
          $data = array("alert" => "I just signed up to your group");

          // Send notifications to the users devices.
          if (!empty($user->parse_installation_ids)) {
            $this->parse->sendPushNotification($user->parse_installation_ids, $data);
          }
        }
      }
    }
  }

}

Add checks for empty values

Add checks for empty values


<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

/**
 * Request for validating check urls.
 */
class StoreCheckUrlRequest extends Request
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title'       => 'required|max:255',
            'url'         => 'required|active_url',
            'period'      => 'required',
            'is_report'   => 'required',
            'project_id'  => 'required|integer|exists:projects,id'
        ];
    }
}

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

/**
 * Request for validating check urls.
 */
class StoreCheckUrlRequest extends Request
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title'      => 'required|max:255',
            'url'        => 'required|url',
            'period'     => 'required',
            'is_report'  => 'required',
            'project_id' => 'required|integer|exists:projects,id',
        ];
    }
}

Change validate rule for url

Change validate rule for url

Some valid url won’t pass the active_url rule.


<?php

Route::get('infusionsoft/auth', 'InfusionsoftController@auth');
Route::get('infusionsoft/auth/callback', 'InfusionsoftController@index');

<?php

Route::get('infusionsoft/auth', 'InfusionsoftController@auth');
Route::get('infusionsoft/auth/callback', 'InfusionsoftController@callback');

Add callback method for authorizing Infusionsoft access tokens


<?php
/*******************************************************************************
 * Copyright (c) 2015 Eclipse Foundation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Christopher Guindon (Eclipse Foundation) - Initial implementation
 *******************************************************************************/
if (!defined('ABSPATH')) exit;
?>

About

Register

Terms

Code of Conduct

Schedule

Sponsorship

<?php
/*******************************************************************************
 * Copyright (c) 2015 Eclipse Foundation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Christopher Guindon (Eclipse Foundation) - Initial implementation
 *******************************************************************************/
if (!defined('ABSPATH')) exit;
?>

Call For Proposals

Register

Terms

Code of Conduct

Schedule

Sponsorship

Change About link to CfP Link

Change About link to CfP Link


<?hh // decl

class Route {
  public static function dispatch(string $path, string $method): void {

    // Get the auto-generated URI Map
    $routes = require('build/URIMap.php');

    // Match the path
    foreach($routes as $route_path => $controller_name) {
      $uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
      if(preg_match(
        "@^$route_path$@i",
        "$uri",
        $_SESSION['route_params'])
      ) {
        $controller = new $controller_name();
        invariant($controller instanceof BaseController);

        Auth::verifyStatus($controller->getConfig()->getUserState());
        Auth::verifyRoles($controller->getConfig()->getUserRoles());

        $content = $controller::$method();
        if(is_object($content) && is_a($content, :xhp::class)) {
          Render::go($content, $controller_name);
        } elseif (
          (is_array($content)) ||
          (is_object($content) && is_a($content, Map::class))
        ) {
          header('Content-Type: application/json');
          print json_encode($content, JSON_PRETTY_PRINT);
        }

        return;
      }
    }

    // No path was matched
    Render::go(FourOhFourController::get(), 'FourOhFourController');
  }

  public static function redirect(string $path): void {
    header('Location: ' . $path);
    exit();
  }
}

<?hh // decl

class Route {
  public static function dispatch(string $path, string $method): void {

    // Get the auto-generated URI Map
    $routes = require('build/URIMap.php');

    // Match the path
    foreach($routes as $route_path => $controller_name) {
      $uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
      if(preg_match(
        "@^$route_path$@i",
        "$uri",
        $_SESSION['route_params'])
      ) {
        $controller = new $controller_name();
        invariant($controller instanceof BaseController);

        Auth::verifyStatus($controller->getConfig()->getUserState());
        Auth::verifyRoles($controller->getConfig()->getUserRoles());

        $content = $controller::$method();
        if(is_object($content) && is_a($content, :xhp::class)) {
          Render::go($content, $controller_name);
        } elseif (
          (is_array($content)) ||
          (is_object($content) && is_a($content, Map::class))
        ) {
          header('Content-Type: application/json');
          print json_encode($content, JSON_PRETTY_PRINT);
        }

        return;
      }
    }

    // No path was matched
    http_response_code(404);
    Render::go(FourOhFourController::get(), 'FourOhFourController');
  }

  public static function redirect(string $path): void {
    header('Location: ' . $path);
    exit();
  }
}

Add 404 head for not found routes

Add 404 head for not found routes


<?php

return [
    'apiURL'    => env('SS_URL', 'https://private-anon-dcf09a12d7-shipstation.apiary-mock.com'),
    'apiKey'    => env('SS_KEY', ''),
    'apiSecret' => env('SS_SECRET', ''),
];

<?php

return [
    'apiURL'    => env('SS_URL', 'https://ssapi.shipstation.comm'),
    'apiKey'    => env('SS_KEY', ''),
    'apiSecret' => env('SS_SECRET', ''),
];

Change default API URL to be production

Change default API URL to be production


<?php

use React\EventLoop\LoopInterface;
use React\Stream\Stream;
use React\HttpClient\ConnectionManagerInterface;

class ConnectionManagerFsockopen implements ConnectionManagerInterface
{
    private $timeout = 5.0;

    public function __construct(LoopInterface $loop)
    {
        $this->loop = $loop;
    }

    public function getConnection($callback, $host, $port)
    {
        $socket = fsockopen($host, $port, $errno, $errstr, $this->timeout);
        if ($socket === false) {
            $stream = null;
            $error = new Exception('Unable to open connection: "'.$errstr.'" ('.$errno.')');
        } else {
            $stream = new Stream($socket, $this->loop);
            $error = null;
        }
        call_user_func($callback, $stream, $error);
    }
}

<?php

use React\Promise\FulfilledPromise;

use React\Promise\RejectedPromise;

use React\Promise\Deferred;

use React\EventLoop\LoopInterface;
use React\Stream\Stream;
use React\HttpClient\ConnectionManagerInterface;

class ConnectionManagerFsockopen implements ConnectionManagerInterface
{
    private $timeout = 5.0;

    public function __construct(LoopInterface $loop)
    {
        $this->loop = $loop;
    }

    public function setTimeout($timeoutSeconds)
    {
        $this->timeout = $timeoutSeconds;
    }

    public function getConnection($host, $port)
    {
        $socket = fsockopen($host, $port, $errno, $errstr, $this->timeout);
        if ($socket === false) {
            return new RejectedPromise(new Exception('Unable to open connection: "'.$errstr.'" ('.$errno.')'));
        } else {
            return new FulfilledPromise(new Stream($socket, $this->loop));
        }
    }
}

Use new Promise interface and support timeout setting


<?php

namespace frontend\assets;

use yii\web\AssetBundle;

class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/style.css',
    ];
    public $js = [
        'js/ekko-lightbox-min.js',
        'js/ie10-viewport-bug-workaround.js',
        'js/jquery.meanmenu.min.js',
        'js/jquery.main.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
//        'yii\bootstrap\BootstrapAsset',
    ];
}

<?php

namespace frontend\assets;

use yii\web\AssetBundle;

class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/style.css',
    ];
    public $js = [
        'js/ekko-lightbox-min.js',
        'js/bootstrap.min.js',
        'js/ie10-viewport-bug-workaround.js',
        'js/jquery.meanmenu.min.js',
        'js/jquery.main.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
    ];
}

Fix front page gallery. Update assets.

Fix front page gallery. Update assets.


      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        Toggle navigation

      </button>
       <a class="brand" href="<?php echo home_url(); ?>/"><img class="logo" src="/wp-content/themes/owncloudorgnew/assets/img/common/logo_owncloud.svg" title="<?php bloginfo('name'); ?>" itemprop="logo">

News

Features

Demo

Documentation

Install

Fix new links in top nacbar

Fix new links in top nacbar


<?php

namespace Tests;

use App\User;
use App\Company;

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

class CompanyCreateFormTest extends \TestCase
{
    use DatabaseTransactions;

    public function test_companies_can_be_created_by_admin()
    {
        $user = factory(User::class, 'admin')->create();
        $this->actingAs($user);

        $companyName = 'Company ' . time();

        $this->visit('/companies')
            ->dontSee($companyName);

        $this->visit('/companies')
            ->dontSee('User is not authorised to Create Company.')
            ->type($companyName, 'name')
            ->press('Add Company')
            ->see($companyName)
            ->seeInDatabase('companies', ['name' => $companyName]);
    }

    public function test_long_companies_cant_be_created()
    {
        $user = factory(User::class, 'admin')->create();
        $this->actingAs($user);

        $this->visit('/companies')
            ->type(str_random(300), 'name')
            ->press('Add Company')
            ->see('Whoops!');
    }

    public function test_companies_cannot_be_created_by_viewer()
    {
        $user = factory(User::class, 'viewer')->create();
        $this->actingAs($user);

        $this->visit('/companies')
            ->see('User is not authorised to Create Company.')
            ->dontSee('Add Company');
    }

}

<?php

namespace Tests;

use App\User;
use App\Company;

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

class CompanyCreateFormTest extends \TestCase
{
    use DatabaseTransactions;

    public function test_companies_can_be_created_by_admin()
    {
        $user = factory(User::class, 'admin')->create();
        $this->actingAs($user);

        $companyName = 'Company ' . time();

        $this->visit('/companies')
            ->dontSee($companyName);

        $this->visit('/companies')
            ->dontSee('User is not authorised to Create Company.')
            ->see('Add Company') // button
            ->type($companyName, 'name')
            ->press('Add Company')
            ->see($companyName)
            ->seeInDatabase('companies', ['name' => $companyName]);
    }

    public function test_long_companies_cant_be_created()
    {
        $user = factory(User::class, 'admin')->create();
        $this->actingAs($user);

        $this->visit('/companies')
            ->type(str_random(300), 'name')
            ->press('Add Company')
            ->see('Whoops!');
    }

    public function test_companies_cannot_be_created_by_viewer()
    {
        $user = factory(User::class, 'viewer')->create();
        $this->actingAs($user);

        $this->visit('/companies')
            ->see('User is not authorised to Create Company.')
            ->dontSee('Add Company');
    }

}

Add check do we have Add Company button in Create Company Form test


<?php

namespace Ddeboer\DocumentManipulationBundle\Manipulator;

use Zend\Service\LiveDocx\MailMerge;
use Symfony\Component\HttpFoundation\File\File;

class DocManipulator
{
    /**
     * @var MailMerge
     */
    private $liveDocx;

    public function getLiveDocx()
    {
        return $this->liveDocx;
    }

    public function setLiveDocx(MailMerge $liveDocx)
    {
        $this->liveDocx = $liveDocx;
    }

    public function merge(File $file, \Traversable $data, $outputFile, $format = 'pdf')
    {
        // Calculate MD5 hash for file
        $hash = md5_file($file->getPathname());
        $tmpFile = sys_get_temp_dir() . '/' . $hash;
        copy($file->getPathname(), $tmpFile);

        // Upload local template to server if it hasn't been uploaded yet
        if (!$this->liveDocx->templateExists($hash)) {
            $this->liveDocx->uploadTemplate($tmpFile);
        }

        $this->liveDocx->setLocalTemplate($file->getPathname());

        foreach ($data as $field => $value) {
            $this->liveDocx->assign($field, $value);
        }

        $this->liveDocx->createDocument();
        $document = $this->liveDocx->retrieveDocument($format);
        file_put_contents($outputFile, $document);

        return $outputFile;
    }
}

<?php

namespace Ddeboer\DocumentManipulationBundle\Manipulator;

use Zend\Service\LiveDocx\MailMerge;
use Symfony\Component\HttpFoundation\File\File;

class DocManipulator
{
    /**
     * @var MailMerge
     */
    private $liveDocx;

    public function getLiveDocx()
    {
        return $this->liveDocx;
    }

    public function setLiveDocx(MailMerge $liveDocx)
    {
        $this->liveDocx = $liveDocx;
    }

    public function merge(File $file, \Traversable $data, $outputFile, $format = 'pdf')
    {
        // Calculate MD5 hash for file; the template must have an extension,
        // or LiveDocx will be confused.
        $hash = md5_file($file->getPathname()) . '.' . $file->getExtension();

        $tmpFile = sys_get_temp_dir() . '/' . $hash;
        copy($file->getPathname(), $tmpFile);

        // Upload local template to server if it hasn't been uploaded yet
        if (!$this->liveDocx->templateExists($hash)) {
            $this->liveDocx->uploadTemplate($tmpFile);
        }

        $this->liveDocx->setRemoteTemplate($hash);

        foreach ($data as $field => $value) {
            $this->liveDocx->assign($field, $value);
        }

        $this->liveDocx->createDocument();
        $document = $this->liveDocx->retrieveDocument($format);
        file_put_contents($outputFile, $document);

        return $outputFile;
    }
}

Add file extension to hash

Add file extension to hash


<?php

namespace Oro\Bundle\GridBundle\Filter;

use Sonata\AdminBundle\Filter\FilterInterface as BaseFilterInterface;

interface FilterInterface extends BaseFilterInterface
{
    /**
     * Allowed filter types
     */
    const TYPE_BOOLEAN          = 'oro_grid_orm_boolean';
    const TYPE_CALLBACK         = 'oro_grid_orm_callback';
    const TYPE_CHOICE           = 'oro_grid_orm_choice';
    const TYPE_DATE             = 'oro_grid_orm_date';
    const TYPE_DATE_RANGE       = 'oro_grid_orm_date_range';
    const TYPE_DATETIME         = 'oro_grid_orm_datetime';
    const TYPE_DATETIME_RANGE   = 'oro_grid_orm_datetime_range';
    const TYPE_NUMBER           = 'oro_grid_orm_number';
    const TYPE_STRING           = 'oro_grid_orm_string';
    const TYPE_FLEXIBLE_STRING  = 'oro_grid_orm_flexible_string';
    const TYPE_FLEXIBLE_OPTIONS = 'oro_grid_orm_flexible_options';
}

BAP-135: Implement AJAX grid using backbons.js
 - fixed filter interface code style


<?php

namespace UoMCS\OpenBadges\Backend;

class EarnerTest extends DatabaseTestCase
{
  const EARNER_COUNT = 2;
  const EARNER_EXISTS_ID = 1;
  const EARNER_DOES_NOT_EXIST_ID = 99999;

  public function testAllEarnersDB()
  {
    $earners = Earner::getAll();
    $this->assertInternalType('array', $earners);
    $this->assertCount(self::EARNER_COUNT, $earners);
  }

  public function testEarnerExistsDB()
  {
    $earner = Earner::get(self::EARNER_EXISTS_ID);
    $this->assertInstanceOf('UoMCS\\OpenBadges\\Backend\\Earner', $earner);
  }

  public function testEarnerDoesNotExistDB()
  {
    $earner = Earner::get(self::EARNER_DOES_NOT_EXIST_ID);
    $this->assertNull($earner);
  }
}

<?php

namespace UoMCS\OpenBadges\Backend;

class EarnerTest extends DatabaseTestCase
{
  const EARNER_COUNT = 2;
  const EARNER_EXISTS_ID = 1;
  const EARNER_DOES_NOT_EXIST_ID = 99999;

  public function testAllEarnersDB()
  {
    $earners = Earner::getAll();
    $this->assertInternalType('array', $earners);
    $this->assertCount(self::EARNER_COUNT, $earners);

    foreach ($earners as $earner)
    {
      $this->assertInstanceOf('UoMCS\\OpenBadges\\Backend\\Earner', $earner);
    }
  }

  public function testEarnerExistsDB()
  {
    $earner = Earner::get(self::EARNER_EXISTS_ID);
    $this->assertInstanceOf('UoMCS\\OpenBadges\\Backend\\Earner', $earner);
  }

  public function testEarnerDoesNotExistDB()
  {
    $earner = Earner::get(self::EARNER_DOES_NOT_EXIST_ID);
    $this->assertNull($earner);
  }
}

Check that all results from Earner::getAll() are of type Earner


<?php

/**
 * MIT License
 * Copyright (c) 2017 Electronic Student Services @ Appalachian State University
 *
 * See LICENSE file in root directory for copyright and distribution permissions.
 *
 * @author Matthew McNaney <mcnaneym@appstate.edu>
 * @license https://opensource.org/licenses/MIT
 */

namespace stories\Factory;

use stories\Exception\ResourceNotFound;

/**
 *
 * @author Matthew McNaney <mcnaneym@appstate.edu>
 */
abstract class BaseFactory extends \phpws2\ResourceFactory
{

    abstract public function build();

    public function load($id)
    {
        if (empty($id)) {
            throw new ResourceNotFound;
        }
        $resource = $this->build();
        $resource->setId($id);
        if (!parent::loadByID($resource)) {
            throw new ResourceNotFound($id);
        }
        return $resource;
    }

    protected function walkingCase($name)
    {
        if (stripos($name, '_')) {
            return preg_replace_callback('/^(\w)(\w*)_(\w)(\w*)/',
                    function($letter) {
                $str = strtoupper($letter[1]) . $letter[2] . strtoupper($letter[3]) . $letter[4];
                return $str;
            }, $name);
        } else {
            return ucfirst($name);
        }
    }

}

<?php

/**
 * MIT License
 * Copyright (c) 2017 Electronic Student Services @ Appalachian State University
 *
 * See LICENSE file in root directory for copyright and distribution permissions.
 *
 * @author Matthew McNaney <mcnaneym@appstate.edu>
 * @license https://opensource.org/licenses/MIT
 */

namespace stories\Factory;

use stories\Exception\ResourceNotFound;

/**
 *
 * @author Matthew McNaney <mcnaneym@appstate.edu>
 */
abstract class BaseFactory extends \phpws2\ResourceFactory
{

    abstract public function build();

    public function load($id)
    {
        if (empty($id)) {
            throw new ResourceNotFound;
        }
        $resource = $this->build();
        $resource->setId($id);
        if (!parent::loadByID($resource)) {
            throw new ResourceNotFound($id);
        }
        return $resource;
    }

    protected function walkingCase($name)
    {
        if (stripos($name, '_')) {
            return preg_replace_callback('/^(\w)(\w*)_(\w)(\w*)/',
                    function($letter) {
                $str = strtoupper($letter[1]) . $letter[2] . strtoupper($letter[3]) . $letter[4];
                return $str;
            }, $name);
        } else {
            return ucfirst($name);
        }
    }

    protected function sendCurl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

}

Create method to send curl commands.

Create method to send curl commands.


<?php

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

class CreateMediaTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('media', function (Blueprint $table) {
            $table->increments('id');
            $table->morphs('model');
            $table->string('collection_name');
            $table->string('name');
            $table->string('file_name');
            $table->string('mime_type')->nullable();
            $table->string('disk');
            $table->unsignedInteger('size');
            $table->json('manipulations');
            $table->json('custom_properties');
            $table->json('responsive_images');
            $table->unsignedInteger('order_column')->nullable();
            $table->nullableTimestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::dropIfExists('media');
    }
}

<?php

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

class CreateMediaTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('media', function (Blueprint $table) {
            $table->increments('id');
            $table->morphs('model');
            $table->string('collection_name');
            $table->string('name');
            $table->string('file_name');
            $table->string('mime_type')->nullable();
            $table->string('disk');
            $table->unsignedInteger('size');
            $table->text('manipulations');
            $table->text('custom_properties');
            $table->text('responsive_images');
            $table->unsignedInteger('order_column')->nullable();
            $table->nullableTimestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::dropIfExists('media');
    }
}

Update column type (json to text) for media table


<?php namespace Elegant\Relations;

use Countable;
use ArrayIterator;
use IteratorAggregate;
use Elegant\Model;
use Elegant\Result;
use Elegant\Row;

abstract class Relation implements Countable, IteratorAggregate {

	protected $parent;
	protected $related;

	protected $related_items = null;

	function __construct(Model $parent, Model $related)
	{
		$this->parent = $parent;
		$this->related = $related;
	}

	abstract public function getResults();

	// Implements IteratorAggregate function
	public function getIterator()
	{
		if(empty($this->related_items)) $this->related_items = $this->related->get();

		return $this->related_items;
	}

	// Implements Countable function
	public function count()
	{
		if(empty($this->related_items)) $this->related_items = $this->related->get();

		return count($this->related_items);
	}

	function __call($name, $param)
	{
		if(is_callable( array($this->related, $name) ))
		{
			$return = call_user_func_array(array( $this->related, $name ), $param);

			if($return instanceof Result or $return instanceof Row) return $return;

			return $this;
		}
	}

}

<?php namespace Elegant\Relations;

use Countable;
use ArrayIterator;
use IteratorAggregate;
use Elegant\Model;
use Elegant\Result;
use Elegant\Row;

abstract class Relation implements Countable, IteratorAggregate {

	protected $parent;
	protected $related;

	function __construct(Model $parent, Model $related)
	{
		$this->parent = $parent;
		$this->related = $related;
	}

	abstract public function getResults();

	// Implements IteratorAggregate function so the result can be looped without needs to call get() first.
	public function getIterator()
	{
		return $this->getResults();
	}

	// Implements Countable function
	public function count()
	{
		return count( $this->getResults() );
	}

	function __call($name, $param)
	{
		if(is_callable( array($this->related, $name) ))
		{
			$return = call_user_func_array(array( $this->related, $name ), $param);

			if($return instanceof Result or $return instanceof Row) return $return;

			return $this;
		}
	}

}

Call getResults() instead of accessing the get() method manually for the IteratorAggregate and Countable functions


<?php

/*
 * This file is part of the Incipio package.
 *
 * (c) Florian Lefevre
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

// src/Sdz/BlogBundle/Form/ArticleHandler.php

namespace Mgate\SuiviBundle\Form\Type;

use Doctrine\ORM\EntityManager;
use Mgate\SuiviBundle\Entity\ClientContact;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;

class ClientContactHandler
{
    protected $form;
    protected $request;
    protected $em;

    public function __construct(Form $form, Request $request, EntityManager $em)
    {
        $this->form = $form;
        $this->request = $request;
        $this->em = $em;
    }

    public function process()
    {
        if ($this->request->getMethod() == 'POST') {
            $this->form->bind($this->request);

            if ($this->form->isValid()) {
                $this->onSuccess($this->form->getData());

                return true;
            }
        }

        return false;
    }

    public function onSuccess(ClientContact $clientcontact)
    {
        $this->em->persist($clientcontact);

        $this->em->flush();
    }
}

<?php

/*
 * This file is part of the Incipio package.
 *
 * (c) Florian Lefevre
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Mgate\SuiviBundle\Form\Type;

use Doctrine\ORM\EntityManager;
use Mgate\SuiviBundle\Entity\ClientContact;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;

class ClientContactHandler
{
    protected $form;
    protected $request;
    protected $em;

    public function __construct(Form $form, Request $request, EntityManager $em)
    {
        $this->form = $form;
        $this->request = $request;
        $this->em = $em;
    }

    public function process()
    {
        if ($this->request->getMethod() == 'POST') {
            $this->form->handleRequest($this->request);

            if ($this->form->isValid()) {
                $this->onSuccess($this->form->getData());

                return true;
            }
        }

        return false;
    }

    public function onSuccess(ClientContact $clientcontact)
    {
        $this->em->persist($clientcontact);

        $this->em->flush();
    }
}

Replace sf2 form->bind by handlerequest

Replace sf2 form->bind by handlerequest


<?php

/**
 * This file is part of the AmazonSQS package.
 *
 * (c) Christian Eikermann <christian@chrisdev.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

<?php

/**
 * This file is part of the AmazonSQS package.
 *
 * (c) Christian Eikermann <christian@chrisdev.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

Update autoloader path to work with newer versions of composer


<?php
//# admin.php #
/*
PPSF

sprawdza czy wywoływacz jest serwerem

*/

if(!(isset($_GET['server'])&&($_GET['server']==="super tajne hasło"))){
	echo -418296719726;
	exit;
}
?>

<?php
//# admin.php #
/*
PPSF

sprawdza czy wywoływacz jest serwerem

*/

if(!(isset($_GET['server'])&&($_GET['server']==="super tajne hasło"))){
	echo -3;
	exit;
}
?>

Change noserver error to -3

Change noserver error to -3


<?php

namespace Tests\AppBundle\API\Mapping;

use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;

class FullByOrganismNameTest extends WebserviceTestCase
{
    public function testExecute()
    {
        $service = $this->webservice->factory('mapping', 'fullByOrganismName');
        $result = $service->execute(new ParameterBag(array('dbversion' => $this->default_db)), null);
        $this->assertEquals(195203, count($result));
        $this->assertEquals(10, $result['Dunaliella tertiolecta']);
        $this->assertEquals([213,196104], $result['Onoclea sensibilis']);
        $this->assertEquals(353, $result['Ranunculaceae']);
        $this->assertEquals(1224, $result['Nymphaea']);
        $this->assertEquals(12341, $result['Diphasiastrum alpinum']);
    }
}

<?php

namespace Tests\AppBundle\API\Mapping;

use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;
use AppBundle\API\Mapping;

class FullByOrganismNameTest extends WebserviceTestCase
{
    private $em;
    private $fullByOrganismName;
    public function setUp()
    {
        $kernel = self::bootKernel();

        $this->em = $kernel->getContainer()
            ->get('doctrine')
            ->getManager('test');
        $this->fullByOrganismName = $kernel->getContainer()->get(Mapping\FullByOrganismName::class);

    }

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

        $this->em->close();
        $this->em = null; // avoid memory leaks
    }

    public function testExecute()
    {
        $result = $this->fullByOrganismName->execute();
        $this->assertEquals(195203, count($result));
        $this->assertEquals(10, $result['Dunaliella tertiolecta']);
        $this->assertEquals([213,196104], $result['Onoclea sensibilis']);
        $this->assertEquals(353, $result['Ranunculaceae']);
        $this->assertEquals(1224, $result['Nymphaea']);
        $this->assertEquals(12341, $result['Diphasiastrum alpinum']);
    }
}

Update test function for testing mapping of full organism names


<?php
/**
 * Created by PhpStorm.
 * User: Administrador
 * Date: 03/10/2017
 * Time: 09:47 AM.
 */

namespace Greenter\Ws\Services;

use Greenter\Ws\Header\WSSESecurityHeader;

/**
 * Class SoapClient.
 */
class SoapClient implements WsClientInterface
{
    private $client;

    /**
     * SoapClient constructor.
     *
     * @param string $wsdl       Url of WSDL
     * @param array  $parameters Soap's parameters
     */
    public function __construct($wsdl = '', array $parameters = null)
    {
        if (empty($wsdl)) {
            $wsdl = WsdlProvider::getBillPath();
        }
        $this->client = new \SoapClient($wsdl, $parameters);
    }

    /**
     * @param $user
     * @param $password
     */
    public function setCredentials($user, $password)
    {
        $this->client->__setSoapHeaders(new WSSESecurityHeader($user, $password));
    }

    /**
     * Set Url of Service.
     *
     * @param string $url
     */
    public function setService($url)
    {
        $this->client->__setLocation($url);
    }

    /**
     * @return \SoapClient
     */
    public function getClient()
    {
        return $this->client;
    }

    /**
     * @param $function
     * @param $arguments
     *
     * @return mixed
     */
    public function call($function, $arguments)
    {
        return $this->client->__soapCall($function, $arguments);
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: Administrador
 * Date: 03/10/2017
 * Time: 09:47 AM.
 */

namespace Greenter\Ws\Services;

use Greenter\Ws\Header\WSSESecurityHeader;

/**
 * Class SoapClient.
 */
class SoapClient implements WsClientInterface
{
    private $client;

    /**
     * SoapClient constructor.
     *
     * @param string $wsdl       Url of WSDL
     * @param array  $parameters Soap's parameters
     */
    public function __construct($wsdl = '', $parameters = [])
    {
        if (empty($wsdl)) {
            $wsdl = WsdlProvider::getBillPath();
        }
        $this->client = new \SoapClient($wsdl, $parameters);
    }

    /**
     * @param $user
     * @param $password
     */
    public function setCredentials($user, $password)
    {
        $this->client->__setSoapHeaders(new WSSESecurityHeader($user, $password));
    }

    /**
     * Set Url of Service.
     *
     * @param string $url
     */
    public function setService($url)
    {
        $this->client->__setLocation($url);
    }

    /**
     * @param $function
     * @param $arguments
     *
     * @return mixed
     */
    public function call($function, $arguments)
    {
        return $this->client->__soapCall($function, $arguments);
    }
}

Revert "set null soap parameters"

Revert "set null soap parameters"

This reverts commit 0000599


<?php

class Billmate_BillmateInvoice_Helper_Total extends Mage_Core_Helper_Abstract
{

    public function addToBlock($block)
    {
        $order = $block->getOrder();
        $info = $order->getPayment()->getMethodInstance()->getInfoInstance();
        $storeId = Mage::app()->getStore()->getId();
        $vatOption = Mage::getStoreConfig("tax/sales_display/price", $storeId);

        $invoiceFee = $info->getAdditionalInformation('billmateinvoice_fee');

		$extra = '';

        $fee = new Varien_Object();
        $fee->setCode('billmateinvoice_fee');
        $label = Mage::helper('billmateinvoice')->__('Billmate Invoice Fee (Incl. Vat)');

        $fee->setLabel($label);
        $fee->setBaseValue($invoiceFee);
        $fee->setValue($invoiceFee);
        $block->addTotalBefore($fee, 'shipping');

        return $block;
    }

}

<?php

class Billmate_BillmateInvoice_Helper_Total extends Mage_Core_Helper_Abstract
{

    public function addToBlock($block)
    {
        $order = $block->getOrder();
        $info = $order->getPayment()->getMethodInstance()->getInfoInstance();
        $storeId = Mage::app()->getStore()->getId();
        $vatOption = Mage::getStoreConfig("tax/sales_display/price", $storeId);

        $invoiceFee = $info->getAdditionalInformation('billmateinvoice_fee');
        $invoiceTax = $info->getAdditionalInformation('billmateinvoice_fee_tax');
        $origInvFee = Mage::getStoreConfig('payment/billmateinvoice/billmate_fee');
        if($invoiceTax != 0 && ($invoiceFee == $origInvFee)){
            $invoiceFee += $invoiceTax;
        }
		$extra = '';

        $fee = new Varien_Object();
        $fee->setCode('billmateinvoice_fee');
        $label = Mage::helper('billmateinvoice')->__('Billmate Invoice Fee (Incl. Vat)');

        $fee->setLabel($label);
        $fee->setBaseValue($invoiceFee);
        $fee->setValue($invoiceFee);
        $block->addTotalBefore($fee, 'shipping');

        return $block;
    }

}

Fix for if tax is set and not shown correct in backend


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Classes\EsiConnection;
use Illuminate\Support\Facades\Log;

class SearchController extends Controller
{
    public function search(Request $request)
    {
        $esi = new EsiConnection;

        $result = $esi->esi->setQueryString([
            'categories' => 'character',
            'search' => $request->q,
            'strict' => 'true',
        ])->invoke('get', '/search/');

        Log::info('SearchController: results returned by /search query', [
            'result' => $result,
        ]);

        // If there are more than ten matching results, we want them to keep typing.
        if (isset($result) && isset($result->character))
        {
            $character_id = $result->character[0];
            $character = $esi->esi->invoke('get', '/characters/{character_id}/', [
                'character_id' => $character_id,
            ]);
            $character->id = $character_id;
            $portrait = $esi->esi->invoke('get', '/characters/{character_id}/portrait/', [
                'character_id' => $character_id,
            ]);
            $character->portrait = $portrait->px128x128;
            $corporation = $esi->esi->invoke('get', '/corporations/{corporation_id}/', [
                'corporation_id' => $character->corporation_id,
            ]);
            $character->corporation = $corporation->corporation_name;
            return $character;
        }
        else
        {
            return 'No matches returned, API may be unreachable...';
        }

    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Classes\EsiConnection;
use Illuminate\Support\Facades\Log;

class SearchController extends Controller
{
    public function search(Request $request)
    {
        $esi = new EsiConnection;

        $result = $esi->esi->setQueryString([
            'categories' => 'character',
            'search' => $request->q,
            'strict' => 'true',
        ])->invoke('get', '/search/');

        Log::info('SearchController: results returned by /search query', [
            'result' => $result,
        ]);

        // If there are more than ten matching results, we want them to keep typing.
        if (isset($result) && isset($result->character))
        {
            $character_id = $result->character[0];
            $character = $esi->esi->invoke('get', '/characters/{character_id}/', [
                'character_id' => $character_id,
            ]);
            $character->id = $character_id;
            $portrait = $esi->esi->invoke('get', '/characters/{character_id}/portrait/', [
                'character_id' => $character_id,
            ]);
            $character->portrait = $portrait->px128x128;
            $corporation = $esi->esi->invoke('get', '/corporations/{corporation_id}/', [
                'corporation_id' => $character->corporation_id,
            ]);
            $character->corporation = $corporation->name;
            return $character;
        }
        else
        {
            return 'No matches returned, API may be unreachable...';
        }

    }
}

Update property of corporation name returned in search.


<?php namespace App\Http\Controllers;

use App\Console\Commands\UpdatePvpLeaderboard;
use Redis;

class LeaderboardController extends Controller
{

    /**
     * Get all leaderboard data
     *
     * @return $this
     */
    public function pvpIndex()
    {

        $collection = Redis::get(UpdatePvpLeaderboard::$key);
        $collection = unserialize($collection);
        return $this->apiResponse($collection, 12 * 60 * 60);

    }

    /**
     * Get a single user
     *
     * @param $name
     * @return $this
     */
    public function pvpByUser($name)
    {

        $collection = Redis::get(UpdatePvpLeaderboard::$key);
        $collection = unserialize($collection);

        // Grab the elements matching the name from all regions
        $eu = array_where($collection['eu'], function ($key, $value) use ($name) {
            return $value['name'] == $name;
        });

        $na = array_where($collection['na'], function ($key, $value) use ($name) {
            return $value['name'] == $name;
        });

        $element = array_values(array_merge($eu, $na));

        // Return the first element!
        $json = count($element) == 0 ? 'false' : $element[0];

        return $this->apiResponse($json, 12 * 60 * 60);

    }

}

<?php namespace App\Http\Controllers;

use App\Console\Commands\UpdatePvpLeaderboard;
use Redis;

class LeaderboardController extends Controller
{

    /**
     * Get all leaderboard data
     *
     * @return $this
     */
    public function pvpIndex()
    {

        $collection = Redis::get(UpdatePvpLeaderboard::$key);
        $collection = unserialize($collection);
        return $this->apiResponse($collection, 12 * 60 * 60);

    }

    /**
     * Get a single user
     *
     * @param $name
     * @return $this
     */
    public function pvpByUser($name)
    {

        $name = urldecode($name);

        $collection = Redis::get(UpdatePvpLeaderboard::$key);
        $collection = unserialize($collection);

        // Grab the elements matching the name from all regions
        $eu = array_where($collection['eu'], function ($key, $value) use ($name) {
            return $value['name'] == $name;
        });

        $na = array_where($collection['na'], function ($key, $value) use ($name) {
            return $value['name'] == $name;
        });

        $element = array_values(array_merge($eu, $na));

        // Return the first element!
        $json = count($element) == 0 ? 'false' : $element[0];

        return $this->apiResponse($json, 12 * 60 * 60);

    }

}

Fix for names with spaces

Fix for names with spaces


<?php

final class PhabricatorRemarkupBlockInterpreterFiglet
  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.'));
    }

    $future = id(new ExecFuture('figlet'))
      ->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 PhabricatorRemarkupBlockInterpreterFiglet
  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);
  }

}

Enable figlet to render text using custom fonts

Summary:
Figlet with more fonts will make Phabricator
```
    _/    _/      _/    _/_/    _/
 _/_/  _/  _/  _/  _/  _/_/  _/
  _/  _/  _/  _/  _/      _/
 _/  _/  _/  _/  _/    _/  _/_/
_/    _/      _/    _/    _/_/

   _/_/_/  _/_/      _/_/    _/  _/_/    _/_/
  _/    _/    _/  _/    _/  _/_/      _/_/_/_/
 _/    _/    _/  _/    _/  _/        _/
_/    _/    _/    _/_/    _/          _/_/_/

                                  _/
     _/_/_/    _/_/    _/  _/_/        _/_/    _/    _/    _/_/_/
  _/_/      _/_/_/_/  _/_/      _/  _/    _/  _/    _/  _/_/
     _/_/  _/        _/        _/  _/    _/  _/    _/      _/_/
_/_/_/      _/_/_/  _/        _/    _/_/      _/_/_/  _/_/_/
```

Test Plan:
Use figlet in comment with no font/various fonts as argument (e.g. lean, script)
and see preview with no errors.

Reviewers: #blessed_reviewers, epriestley

Reviewed By: epriestley

CC: epriestley, aran

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


<?php

namespace Backend\Modules\MediaGalleries\Domain\MediaGallery\Command;

use Backend\Modules\MediaGalleries\Domain\MediaGallery\MediaGalleryDataTransferObject;
use Backend\Modules\MediaLibrary\Domain\MediaGroup\MediaGroup;
use Backend\Modules\MediaLibrary\Domain\MediaGroup\Type as MediaGroupType;

final class CreateMediaGallery extends MediaGalleryDataTransferObject
{
    public function __construct(int $userId, MediaGroupType $mediaGroupType)
    {
        parent::__construct();

        $this->userId = $userId;
        $this->mediaGroup = MediaGroup::create($mediaGroupType);
    }
}

<?php

namespace Backend\Modules\MediaGalleries\Domain\MediaGallery\Command;

use Backend\Modules\MediaGalleries\Domain\MediaGallery\MediaGalleryDataTransferObject;
use Backend\Modules\MediaGalleries\Domain\MediaGallery\Status;
use Backend\Modules\MediaLibrary\Domain\MediaGroup\MediaGroup;
use Backend\Modules\MediaLibrary\Domain\MediaGroup\Type as MediaGroupType;

final class CreateMediaGallery extends MediaGalleryDataTransferObject
{
    public function __construct(int $userId, MediaGroupType $mediaGroupType)
    {
        parent::__construct();

        $this->userId = $userId;
        $this->status = Status::active();
        $this->mediaGroup = MediaGroup::create($mediaGroupType);
    }
}

Set the default status for media galleries to active


<?php

function debug_collectionInfoStart($debug, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Collecting data\n", $log);
    }
}

function debug_collectionInfoEnd($debug, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Finished collecting data\n\n", $log);
    }
}

function debug_collectionInterval($debug, $interval, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Collecting data every " . $interval . " seconds\n\n", $log);
    }
}

function debug($echo, $log) {

    if ($echo != "" && $echo !== NULL) {
        echo $echo;
    }

    if ($log == TRUE) {
    	if (!file_exists("logs/debug.log")) {
    		$dbglog = fopen("logs/debug.log", "w");
			fclose($dbglog);
    	}

        file_put_contents("logs/debug.log", date("r") . "  -  " . $echo, FILE_APPEND);
    }
}
?>

<?php

function debug_collectionInfoStart($debug, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Collecting data\n", $log);
    }
}

function debug_collectionInfoEnd($debug, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Finished collecting data\n\n", $log);
    }
}

function debug_collectionInterval($debug, $interval, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Collecting data every " . $interval . " seconds\n\n", $log);
    }
}

function debug($echo, $log) {

    if ($echo != "" && $echo !== NULL) {
        echo $echo;
    }

    if ($log == TRUE) {
    	if (!file_exists("logs/debug.log")) {
    		mkdir("logs");
    		$dbglog = fopen("logs/debug.log", "w");
			fclose($dbglog);
    	}

        file_put_contents("logs/debug.log", date("r") . "  -  " . $echo, FILE_APPEND);
    }
}
?>

Make logs dir if missing

Make logs dir if missing


<?php

namespace Trejjam\Utils\Helpers\Form;

use Trejjam;
use Nextras;

class Rule
{
	const IPV4      = '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)';
	const IPV6      = '(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}';
	const MAC       = '([a-fA-F0-9]{2}[:.-]?){7}[[a-fA-F0-9]{2}';

	const DateTimeCompare = 'Trejjam\Utils\Helpers\Form::dateTimeCompare';
	const DateCompare     = 'Trejjam\Utils\Helpers\Form::dateCompare';

	static function dateTimeCompare(Nextras\Forms\Controls\DateTimePicker $item, array $arg)
	{
		return $arg[0] <= $arg[1];
	}

	static function dateCompare(Nextras\Forms\Controls\DatePicker $item, array $arg)
	{
		return $arg[0] <= $arg[1];
	}
}

Add Form time compare rule

Add Form time compare rule


<?php

namespace Jacobemerick\CommentService\Serializer;

use DateTime;
use Jacobemerick\CommentService\Serializer\Commenter as CommenterSerializer;

class Comment
{

    public function __construct() {}

    /**
     * @param array $comment
     * @returns array
     */
    public function __invoke(array $comment)
    {
        $commenterSerializer = new CommenterSerializer();

        return [
            'id' => $comment['id'],
            'commenter' => $commenterSerializer([
                'id' => $comment['commenter_id'],
                'name' => $comment['commenter_name'],
                'website' => $comment['commenter_website'],
            ]),
            'body' => $comment['body'],
            'date' => (new DateTime($comment['date']))->format('c'),
            'url' => $comment['url'], // todo magic replacement
            'reply_to' => $comment['reply_to'],
            'thread' => $comment['thread'],
        ];
    }
}

<?php

namespace Jacobemerick\CommentService\Serializer;

use DateTime;
use Jacobemerick\CommentService\Serializer\Commenter as CommenterSerializer;

class Comment
{

    public function __construct() {}

    /**
     * @param array $comment
     * @returns array
     */
    public function __invoke(array $comment)
    {
        $commenterSerializer = new CommenterSerializer();

        return [
            'id' => $comment['id'],
            'commenter' => $commenterSerializer([
                'id' => $comment['commenter_id'],
                'name' => $comment['commenter_name'],
                'website' => $comment['commenter_website'],
            ]),
            'body' => $comment['body'],
            'date' => (new DateTime($comment['date']))->format('c'),
            'url' => $this->prepareUrl($comment['url'], $comment),
            'reply_to' => $comment['reply_to'],
            'thread' => $comment['thread'],
        ];
    }

    protected function prepareUrl($url, array $comment)
    {
        return str_replace('{{id}}}', $comment['id'], $url);
    }
}

Replace placeholders in comment url

Replace placeholders in comment url