<?php

class DefaultController extends BaseEventTypeController
{

    public function volumeRemaining($event_id)
    {
        $volume_remaining = 0;
        if ($api = Yii::app()->moduleAPI->get('OphInDnaextraction')) {
            $volume_remaining = $api->volumeRemaining($event_id);
        }

        return $volume_remaining;
    }

    public function checkCreateAccess()
    {
        return $this->checkAccess('OprnEditDnaSample')||;
    }

    public function checkUpdateAccess()
    {
        return $this->checkAccess('OprnEditDnaSample');
    }

    public function checkViewAccess()
    {
        return $this->checkAccess('OprnEditDnaSample') || $this->checkAccess('OprnViewDnaSample')
    }

    public function checkPrintAccess()
    {
        return $this->checkAccess('OprnEditDnaSample') || $this->checkAccess('OprnViewDnaSample');
    }

    public function actionCreate()
    {
        parent::actionCreate();
    }

    public function actionUpdate($id)
    {
        parent::actionUpdate($id);
    }

    public function actionView($id)
    {
        parent::actionView($id);
    }

    public function actionPrint($id)
    {
        parent::actionPrint($id);
    }

    public function isRequiredInUI(BaseEventTypeElement $element)
    {
        return true;
    }
}

<?php

class DefaultController extends BaseEventTypeController
{

    public function volumeRemaining($event_id)
    {
        $volume_remaining = 0;
        if ($api = Yii::app()->moduleAPI->get('OphInDnaextraction')) {
            $volume_remaining = $api->volumeRemaining($event_id);
        }

        return $volume_remaining;
    }

    public function accessRules()
    {
        return array(
            array('allow',
                'actions' => array('Create', 'Update', 'View', 'Print','saveCanvasImages','PDFprint' ),
                'roles' => array('OprnEditDnaSample'),
            ),
            array('allow',
                'actions' => array('View', 'Print','saveCanvasImages','PDFprint'),
                'roles' => array('OprnViewDnaSample'),
            ),
        );
    }

    public function actionCreate()
    {
        parent::actionCreate();
    }

    public function actionUpdate($id)
    {
        parent::actionUpdate($id);
    }

    public function actionView($id)
    {
        parent::actionView($id);
    }

    public function actionPrint($id)
    {
        parent::actionPrint($id);
    }

    public function isRequiredInUI(BaseEventTypeElement $element)
    {
        return true;
    }
}

Revert "fix genetics accessRules problem"

This reverts commit 6284919a9db8b401b0506cffea048da399b765cf.


<?php
/**
 * @package Awoods/World
 */
namespace Awoods\World;

interface CountryInterface {

	/**
	 * @return string
	 */
	public function getName();

	/**
	 * @return string
	 */
	public function getFullName();

}

<?php
/**
 * @package Awoods\World
 */
namespace Awoods\World;

interface CountryInterface
{

    /**
     * @return string
     */
    public function getName();

    /**
     * @return string
     */
    public function getFullName();

}

Reformat file to coding standard

Reformat file to coding standard

I used the coding standard and my IDE
and formatted code automatically
to shift things around
and align them a bit
to increase it's quality


<?php

namespace OpenDominion\Tests;

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

class ExampleTest extends BaseTestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->visit('/')
             ->see('OpenDominion');
    }
}

<?php

namespace OpenDominion\Tests;

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

class ExampleTest extends BaseTestCase
{
    public function testBasicExample()
    {
        $this->visit('/')
             ->see('OpenDominion');
    }
}

Remove redundant docblock comment of redundancy


<?php

namespace SlmQueue\Job;

interface Job
{
    public function __invoke();
    public function getId();
}

<?php

namespace SlmQueue\Job;

interface Job
{
    public function __invoke();
    public function setParams (array $params);
    public function getId();
}

Update interface to set parameters

Update interface to set parameters


<?php

namespace Occupied\MainBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/app/example');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertTrue($crawler->filter('html:contains("Homepage")')->count() > 0);
    }
}

<?php

namespace Occupied\MainBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertTrue($crawler->filter('html:contains("occupied.city")')->count() > 0);
    }
}

Fix trivial home page test for our home route & content


<?php

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

class CreateActionlogTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('action_logs', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->nullable();
            $table->string('action_type');
            $table->integer('target_id')->nullable();  // Was checkedout_to
            $table->integer('target_type')->nullable(); // For polymorphic thingies
            $table->integer('location_id')->nullable();
            $table->text('note')->nullable();
            $table->text('filename')->nullable();
            $table->string('item_type');
            $table->integer('item_id');  // Replaces asset_id, accessory_id, etc.
            $table->date('expected_checkin')->nullable()->default(null);
            $table->integer('accepted_id')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->integer('thread_id')
                ->nullable()
                ->default(null);
            $table->index('thread_id');
        });
    }

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

<?php

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

class CreateActionlogTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('action_logs')) {
            Schema::create('action_logs', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('user_id')->nullable();
                $table->string('action_type');
                $table->integer('target_id')->nullable();  // Was checkedout_to
                $table->integer('target_type')->nullable(); // For polymorphic thingies
                $table->integer('location_id')->nullable();
                $table->text('note')->nullable();
                $table->text('filename')->nullable();
                $table->string('item_type');
                $table->integer('item_id');  // Replaces asset_id, accessory_id, etc.
                $table->date('expected_checkin')->nullable()->default(null);
                $table->integer('accepted_id')->nullable();
                $table->timestamps();
                $table->softDeletes();

                $table->integer('thread_id')
                    ->nullable()
                    ->default(null);
                $table->index('thread_id');
            });
        }
    }

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

Fix stupid migration? Maybe? Might be more trouble later


<?php
require_once('Bootstrap.php');

/**
 * Error logging
 *
 * default error log path for process "/var/log/httpd/error_log"
 * to change error log path:
 * ini_set('error_log', "/var/www/vhosts/dev/api-test/logs/error_log");
 */

// Get pass-in Multiprocess Object
$multiProcess = $argv[1];
$multiProcess = unserialize(base64_decode($multiProcess));

// Fork each single process contain in multiprocess
foreach( $multiProcess->getProcesses() as $name => $process ){

    // Inject service manager to each process
    $process->setServiceManager($sm);

    // Fork process
    $pid = pcntl_fork();

    if($pid == -1) {
        // TODO: throw exception
        exit("Error forking...\n");
    }
    // In child process
    else if($pid == 0) {
        /**
         * Set the Process title
         * Terminal Command to check process
         * ps -ef | grep "Fork Process"
         * watch 'ps -ef | grep "Fork Process"'
         */
        $class = get_class($process);
        cli_set_process_title("Fork Process CLASS:[{$class}] - NAME:[{$name}].");

        try{
            $process->run();
        }catch(Exception $e){
            throw $e;
            //echo "Executing process [$name]\r\n";
        }
        exit();
    }
}

<?php
require_once(__DIR__.'/../../../../../public/Bootstrap.php');
//require_once('Bootstrap.php');

/**
 * Error logging
 *
 * default error log path for process "/var/log/httpd/error_log"
 * to change error log path:
 * ini_set('error_log', "/var/www/vhosts/dev/api-test/logs/error_log");
 */

// Get pass-in Multiprocess Object
$multiProcess = $argv[1];
$multiProcess = unserialize(base64_decode($multiProcess));

// Fork each single process contain in multiprocess
foreach( $multiProcess->getProcesses() as $name => $process ){

    // Inject service manager to each process
    $process->setServiceManager($sm);

    // Fork process
    $pid = pcntl_fork();

    if($pid == -1) {
        // TODO: throw exception
        exit("Error forking...\n");
    }
    // In child process
    else if($pid == 0) {
        /**
         * Set the Process title
         * Terminal Command to check process
         * ps -ef | grep "Fork Process"
         * watch 'ps -ef | grep "Fork Process"'
         */
        $class = get_class($process);
        cli_set_process_title("Fork Process CLASS:[{$class}] - NAME:[{$name}].");

        try{
            $process->run();
        }catch(Exception $e){
            throw $e;
            //echo "Executing process [$name]\r\n";
        }
        exit();
    }
}

Add absolute path for including autoloader


<?php

if (!defined('PHPUNIT_RUN')) {
	define('PHPUNIT_RUN', 1);
}

require_once __DIR__.'/../../../lib/base.php';

if(!class_exists('PHPUnit_Framework_TestCase')) {
	require_once('PHPUnit/Autoload.php');
}

OC_Hook::clear();

<?php

if (!defined('PHPUNIT_RUN')) {
	define('PHPUNIT_RUN', 1);
}

require_once __DIR__.'/../../../lib/base.php';

// Fix for "Autoload path not allowed: .../tests/lib/testcase.php"
\OC::$loader->addValidRoot(OC::$SERVERROOT . '/tests');

// Fix for "Autoload path not allowed: .../announcementcenter/tests/testcase.php"
\OC_App::loadApp('announcementcenter');

if(!class_exists('PHPUnit_Framework_TestCase')) {
	require_once('PHPUnit/Autoload.php');
}

OC_Hook::clear();

Fix loading of the files

Fix loading of the files


<?php
/*
 * This file is part of Alom Graphviz.
 * (c) Alexandre Salomé <alexandre.salome@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Alom\Graphviz;

/**
 * Base class for Graphviz instructions.
 *
 * @author Alexandre Salomé <alexandre.salome@gmail.com>
 */
abstract class BaseInstruction implements InstructionInterface
{
    /**
     * Renders an inline assignment (without indent or end return line).
     *
     * It will handle escaping, according to the value.
     *
     * @param string $name A name
     *
     * @param string $value A value
     */
    protected function renderInlineAssignment($name, $value)
    {
        return sprintf('%s=%s', $this->escape($name), $this->escape($value));
    }

    /**
     * Escapes a value if needed.
     *
     * @param string $value The value to set
     *
     * @return string The escaped string
     */
    protected function escape($value)
    {
        if ($this->needsEscaping($value)) {
            return '"'.str_replace('"', '""', $value).'"';
        } else {
            return $value;
        }
    }

    /**
     * Tests if a string needs escaping.
     *
     * @return boolean Result of test
     */
    protected function needsEscaping($value)
    {
        return preg_match('/[ "#:]/', $value) || in_array($value, array('graph', 'node', 'edge')) || empty($value);
    }
}

<?php
/*
 * This file is part of Alom Graphviz.
 * (c) Alexandre Salomé <alexandre.salome@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Alom\Graphviz;

/**
 * Base class for Graphviz instructions.
 *
 * @author Alexandre Salomé <alexandre.salome@gmail.com>
 */
abstract class BaseInstruction implements InstructionInterface
{
    /**
     * Renders an inline assignment (without indent or end return line).
     *
     * It will handle escaping, according to the value.
     *
     * @param string $name A name
     *
     * @param string $value A value
     */
    protected function renderInlineAssignment($name, $value)
    {
        return sprintf('%s=%s', $this->escape($name), $this->escape($value));
    }

    /**
     * Escapes a value if needed.
     *
     * @param string $value The value to set
     *
     * @return string The escaped string
     */
    protected function escape($value)
    {
        if ($this->needsEscaping($value)) {
            return '"'.str_replace('"', '""', $value).'"';
        } else {
            return $value;
        }
    }

    /**
     * Tests if a string needs escaping.
     *
     * @return boolean Result of test
     */
    protected function needsEscaping($value)
    {
        return preg_match('/[ "#:\\/\\.,]/', $value) || in_array($value, array('graph', 'node', 'edge')) || empty($value);
    }
}

Add more characters to escaping

Add more characters to escaping


<?php namespace Orchestra\Testbench\Exceptions;

use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Testing\HttpException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class ApplicationHandler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     *
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     *
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        return parent::render($request, $e);
    }
}

<?php namespace Orchestra\Testbench\Exceptions;

use Exception;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Testing\HttpException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class ApplicationHandler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        TokenMismatchException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     *
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     *
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        return parent::render($request, $e);
    }
}

Add TokenMismatchException to dontReport array.

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


<?php
namespace Neuron\Interfaces\Models;

interface User
	extends \Neuron\Interfaces\Model {

	/**
	 * @return string
	 */
	public function getUsername ();

	/**
	 * @return string
	 */
	public function getEmail ();

}

<?php
namespace Neuron\Interfaces\Models;

interface User
	extends \Neuron\Interfaces\Model {

	/**
	 * @param bool $formal
	 * @return string
	 */
	public function getDisplayName ($formal = false);

	/**
	 * @return string
	 */
	public function getEmail ();

}

Change the user interface (i can do that since nobody is using this project)


<?php

namespace Politix\PolitikportalBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Politix\PolitikportalBundle\Model;

class SourcesController extends Controller {

    public function indexAction($name) {

		$out['items'] = $this->getSource('tagesschau');
		$out['name'] = $name;

        return $this->render('PolitikportalBundle:Default:items.html.twig', $out);

    }

    function getSourceAction($source) {

    	$out['source'] = $source;

    	$sql = 'SELECT * FROM rss_items WHERE source LIKE "' . $source . '" ORDER BY pubDate DESC LIMIT 0,10';
    	$out['items'] = $this->getDB($sql);

        return $this->render('PolitikportalBundle:Default:items.html.twig', $out);

    }

    function getSourcesAction() {

    	require ('/var/www/vhosts/politikportal.eu/subdomains/new/httpdocs/politix/src/Politix/PolitikportalBundle/Model/SourceModel.php');
    	$db = new Politix\PolitikportalBundle\Model\SourceModel();
    	$out['sources'] = $db->getSources;

    	return $this->render('PolitikportalBundle:Default:sources.html.twig', $out);

    }

    function getDB($sql) {

    	$conn = $this->container->get('database_connection');
		return $conn->query($sql);

    }

}

<?php

namespace Politix\PolitikportalBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
// use Politix\PolitikportalBundle\Model;

class SourcesController extends Controller {

    public function indexAction($name) {

		$out['items'] = $this->getSource('tagesschau');
		$out['name'] = $name;

        return $this->render('PolitikportalBundle:Default:items.html.twig', $out);

    }

    function getSourceAction($source) {

    	$out['source'] = $source;

    	$sql = 'SELECT * FROM rss_items WHERE source LIKE "' . $source . '" ORDER BY pubDate DESC LIMIT 0,10';
    	$out['items'] = $this->getDB($sql);

        return $this->render('PolitikportalBundle:Default:items.html.twig', $out);

    }

    function getSourcesAction() {

    	require ('/var/www/vhosts/politikportal.eu/subdomains/new/httpdocs/politix/src/Politix/PolitikportalBundle/Model/SourceModel.php');
    	$db = new \Politix\PolitikportalBundle\Model\SourceModel();
    	$out['sources'] = $db->getSources;

    	return $this->render('PolitikportalBundle:Default:sources.html.twig', $out);

    }

    function getDB($sql) {

    	$conn = $this->container->get('database_connection');
		return $conn->query($sql);

    }

}

Call function with full path and leading backslash


<?php

namespace {

    use PHPUnit\Framework\BaseTestListener;
    use PHPUnit\Framework\TestSuite;
    use Symfony\Component\Process\Process;

    final class PhpUnitStartServerListener extends BaseTestListener
    {
        /**
         * @var string
         */
        private $suiteName;

        /**
         * @var string
         */
        private $socket;

        /**
         * @var string
         */
        private $documentRoot;

        /**
         * PhpUnitStartServerListener constructor.
         *
         * @param string $suiteName
         * @param string $socket
         * @param string $documentRoot
         */
        public function __construct(string $suiteName, string $socket, string $documentRoot)
        {
            $this->suiteName = $suiteName;
            $this->socket = $socket;
            $this->documentRoot = $documentRoot;
        }

        /**
         * @inheritdoc
         */
        public function startTestSuite(TestSuite $suite): void
        {
            parent::startTestSuite($suite);

            if ($suite->getName() === $this->suiteName) {
                $process = new Process(
                    sprintf(
                        'php -S %s %s',
                        $this->socket,
                        $this->documentRoot
                    )
                );
                $process->start();

                // Wait for the server.
                sleep(1);
            }
        }
    }
}

<?php

namespace {

    use PHPUnit\Framework\TestListener;
    use PHPUnit\Framework\TestListenerDefaultImplementation;
    use PHPUnit\Framework\TestSuite;
    use Symfony\Component\Process\Process;

    final class PhpUnitStartServerListener implements TestListener
    {
        use TestListenerDefaultImplementation;

        /**
         * @var string
         */
        private $suiteName;

        /**
         * @var string
         */
        private $socket;

        /**
         * @var string
         */
        private $documentRoot;

        /**
         * PhpUnitStartServerListener constructor.
         *
         * @param string $suiteName
         * @param string $socket
         * @param string $documentRoot
         */
        public function __construct(string $suiteName, string $socket, string $documentRoot)
        {
            $this->suiteName = $suiteName;
            $this->socket = $socket;
            $this->documentRoot = $documentRoot;
        }

        /**
         * @inheritdoc
         */
        public function startTestSuite(TestSuite $suite): void
        {
            if ($suite->getName() === $this->suiteName) {
                $process = new Process(
                    sprintf(
                        'php -S %s %s',
                        $this->socket,
                        $this->documentRoot
                    )
                );
                $process->start();

                // Wait for the server.
                sleep(1);
            }
        }
    }
}

Use interface TestListener instead of deprecated abstract class BaseTestListener


<?php

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

namespace Sylius\Component\Core\Promotion\Checker\Rule;

use Sylius\Component\Core\Model\CustomerInterface;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Promotion\Checker\Rule\RuleCheckerInterface;
use Sylius\Component\Promotion\Exception\UnsupportedTypeException;
use Sylius\Component\Promotion\Model\PromotionSubjectInterface;

/**
 * @author Antonio Perić <antonio@locastic.com>
 */
class CustomerGroupRuleChecker implements RuleCheckerInterface
{
    /**
     * {@inheritdoc}
     */
    public function isEligible(PromotionSubjectInterface $subject, array $configuration)
    {
        if (!$subject instanceof OrderInterface) {
            throw new UnsupportedTypeException($subject, OrderInterface::class);
        }

        if (null === $customer = $subject->getCustomer()) {
            return false;
        }

        if (!$customer instanceof CustomerInterface) {
            return false;
        }

        if ($configuration['groups'] === $customer->getGroup()->getId()) {
            return true;
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getConfigurationFormType()
    {
        return 'sylius_promotion_rule_customer_group_configuration';
    }
}

<?php

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

namespace Sylius\Component\Core\Promotion\Checker\Rule;

use Sylius\Component\Core\Model\CustomerInterface;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Promotion\Checker\Rule\RuleCheckerInterface;
use Sylius\Component\Promotion\Exception\UnsupportedTypeException;
use Sylius\Component\Promotion\Model\PromotionSubjectInterface;

/**
 * @author Antonio Perić <antonio@locastic.com>
 */
class CustomerGroupRuleChecker implements RuleCheckerInterface
{
    /**
     * {@inheritdoc}
     */
    public function isEligible(PromotionSubjectInterface $subject, array $configuration)
    {
        if (!$subject instanceof OrderInterface) {
            throw new UnsupportedTypeException($subject, OrderInterface::class);
        }

        if (null === $customer = $subject->getCustomer()) {
            return false;
        }

        if (!$customer instanceof CustomerInterface) {
            return false;
        }

        if (is_null($customer->getGroup())) {
            return false;
        }

        if ($configuration['group'] === $customer->getGroup()->getId()) {
            return true;
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getConfigurationFormType()
    {
        return 'sylius_promotion_rule_customer_group_configuration';
    }
}

Fix Customer Group Type and RuleChecker

Fix Customer Group Type and RuleChecker


<?php

use Laracasts\Presenter\Presenter;

class CandidatePresenter extends Presenter {

  public function thumbnail()
  {
    if($this->photo) {
      return "/images/thumb-" . $this->photo;
    } else {
      return "/placeholder.png";
    }
  }

  public function twitter()
  {
    if(isset($this->twitter)) {
      return $this->twitter;
    } else {
      return $this->name;
    }
  }

}

<?php

use Laracasts\Presenter\Presenter;

class CandidatePresenter extends Presenter {

  public function thumbnail()
  {
    if($this->photo) {
      return "/images/thumb-" . $this->photo;
    } else {
      return "/placeholder.png";
    }
  }
}

Remove twitter handle from presenter.

Remove twitter handle from presenter.


<?php

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

namespace Sylius\Component\Order\Repository;

use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Sequence\Repository\HashSubjectRepositoryInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface OrderRepositoryInterface extends RepositoryInterface, HashSubjectRepositoryInterface
{
    /**
     * @param int $amount
     *
     * @return OrderInterface[]
     */
    public function findRecentOrders($amount = 10);

    /**
     * @param int|string $number
     *
     * @return bool
     */
    public function isNumberUsed($number);

    /**
     * @param string $orderNumber
     *
     * @return OrderInterface|null
     */
    public function findOneByNumber($orderNumber);
}

<?php

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

namespace Sylius\Component\Order\Repository;

use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Sequence\Repository\HashSubjectRepositoryInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface OrderRepositoryInterface extends RepositoryInterface, HashSubjectRepositoryInterface
{
    /**
     * @return int
     */
    public function count();

    /**
     * @return int
     */
    public function getTotalSales();

    /**
     * @param int $amount
     *
     * @return OrderInterface[]
     */
    public function findRecentOrders($amount = 10);

    /**
     * @param int|string $number
     *
     * @return bool
     */
    public function isNumberUsed($number);

    /**
     * @param string $orderNumber
     *
     * @return OrderInterface|null
     */
    public function findOneByNumber($orderNumber);
}

Implement basic stats for the dashboard

Implement basic stats for the dashboard


<?php

namespace Kibo\Phast\Filters\JavaScript\Minification;

use Kibo\Phast\PhastTestCase;
use Kibo\Phast\ValueObjects\Resource;
use Kibo\Phast\ValueObjects\URL;

class JSMinifierFilterTest extends PhastTestCase {
    public function testGetCacheSalt() {
        $filter1 = new JSMinifierFilter(false);
        $filter2 = new JSMinifierFilter(true);
        $resource = Resource::makeWithContent(URL::fromString(self::BASE_URL), 'the-content');
        $this->assertNotEquals($filter1->getCacheSalt($resource, []), $filter2->getCacheSalt($resource, []));
    }
}

<?php

namespace Kibo\Phast\Filters\JavaScript\Minification;

use Kibo\Phast\PhastTestCase;
use Kibo\Phast\ValueObjects\Resource;
use Kibo\Phast\ValueObjects\URL;

class JSMinifierFilterTest extends PhastTestCase {
    public function testGetCacheSalt() {
        $filter1 = new JSMinifierFilter(false);
        $filter2 = new JSMinifierFilter(true);
        $resource = Resource::makeWithContent(URL::fromString(self::BASE_URL), 'the-content');
        $this->assertNotEquals($filter1->getCacheSalt($resource, []), $filter2->getCacheSalt($resource, []));
    }

    public function testControlCharacters() {
        $filter = new JSMinifierFilter(true);
        $resource = Resource::makeWithContent(URL::fromString(self::BASE_URL), " alert( '\x13' ); ");
        $result = $filter->apply($resource, []);
        $this->assertEquals("alert('\x13');", $result->getContent());
    }
}

Add test for control chars in minified JS


<?php

namespace Botonomous;

use Botonomous\utility\FileUtility;

/**
 * Class Dictionary.
 */
class Dictionary
{
    const DICTIONARY_DIR = 'dictionary';
    const DICTIONARY_FILE_SUFFIX = 'json';

    private $data;

    /**
     * @param $key
     *
     * @throws \Exception
     *
     * @return array|mixed
     */
    private function load($key)
    {
        $stopWordsPath = __DIR__.DIRECTORY_SEPARATOR.self::DICTIONARY_DIR.DIRECTORY_SEPARATOR.$key.'.'.
            self::DICTIONARY_FILE_SUFFIX;

        return (new FileUtility())->jsonFileToArray($stopWordsPath);
    }

    /**
     * @return array
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @param array $data
     */
    public function setData(array $data)
    {
        $this->data = $data;
    }

    /**
     * @param $key
     *
     * @return mixed
     */
    public function get($key)
    {
        $data = $this->getData();

        if (!isset($data[$key])) {
            $data[$key] = $this->load($key);
            $this->setData($data);
        }

        return $data[$key];
    }
}

<?php

namespace Botonomous;

use Botonomous\utility\FileUtility;

/**
 * Class Dictionary.
 */
class Dictionary
{
    const DICTIONARY_DIR = 'dictionary';
    const DICTIONARY_FILE_SUFFIX = 'json';

    private $data;

    /**
     * @param $key
     *
     * @throws \Exception
     *
     * @return array|mixed
     */
    private function load($key)
    {
        $stopWordsPath = __DIR__.DIRECTORY_SEPARATOR.self::DICTIONARY_DIR.DIRECTORY_SEPARATOR.$key.'.'.
            self::DICTIONARY_FILE_SUFFIX;

        return (new FileUtility())->jsonFileToArray($stopWordsPath);
    }

    /**
     * @return array
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @param array $data
     */
    public function setData(array $data)
    {
        $this->data = $data;
    }

    /**
     * @param $fileName
     *
     * @return mixed
     */
    public function get($fileName)
    {
        $data = $this->getData();

        if (!isset($data[$fileName])) {
            $data[$fileName] = $this->load($fileName);
            $this->setData($data);
        }

        return $data[$fileName];
    }

    /**
     * Return value for the key in the file content.
     *
     * @param $fileName
     * @param $key
     * @param array $replacements
     * @return mixed
     * @throws \Exception
     */
    public function getValueByKey($fileName, $key, $replacements = [])
    {
        $fileContent = $this->get($fileName);

        if (!array_key_exists($key, $fileContent)) {
            throw new \Exception("Key: '{$key}' does not exist in file: {$fileName}");
        }

        $found = $fileContent[$key];

        if (empty($replacements)) {
            return $found;
        }

        foreach ($replacements as $key => $value) {
            $found = str_replace('{'.$key.'}', $value, $found);
        }

        return $found;
    }
}

Add a new function to get value by key in a file content


<?php
class Kwc_FulltextSearch_Search_ViewAjax_SearchForm_FrontendForm extends Kwf_Form
{
    protected function _initFields()
    {
        parent::_initFields();
        $this->_model = new Kwf_Model_FnF();
        $this->fields->add(new Kwf_Form_Field_TextField('query', 'Query'))
            ->setAutoComplete(false)
            ->setHideLabel(true)
            ->setEmptyText(trlStatic('Suchbegriff'));
    }
}

<?php
class Kwc_FulltextSearch_Search_ViewAjax_SearchForm_FrontendForm extends Kwf_Form
{
    protected function _initFields()
    {
        parent::_initFields();
        $this->_model = new Kwf_Model_FnF();
        $this->fields->add(new Kwf_Form_Field_TextField('query', 'Query'))
            ->setAutoComplete(false)
            ->setHideLabel(true)
            ->setEmptyText(trlKwfStatic('Search'));
    }
}

Use trlKwfStatic and english translation

Fix for
e8f5b04611dce93131967f8e6902155896f71d3c


<?php

namespace CalendarReminder;

use PHPUnit\Framework\TestCase;

class ReminderFileRepositoryTest extends TestCase
{
    /** @var ReminderFileRepository */
    public $reminderRepository;

    protected function setUp()
    {
        $this->reminderRepository = new ReminderFileRepository();
    }

    public function itShouldCreateReminderAndSave()
    {

    }
}

<?php

namespace CalendarReminder;

use PHPUnit\Framework\TestCase;

class ReminderFileRepositoryTest extends TestCase
{
    const REMINDERS_ROOT_PATH = 'tests/reminders';

    /** @var ReminderFileRepository */
    public $reminderRepository;

    protected function setUp()
    {
        $this->reminderRepository = new ReminderFileRepository(self::REMINDERS_ROOT_PATH);
    }

    protected function tearDown()
    {
        $this->deleteRecursive(self::REMINDERS_ROOT_PATH);
    }

    /**
     * @test
     */
    public function itShouldHaveRepositoryRootPath()
    {
        $this->assertEquals(self::REMINDERS_ROOT_PATH, $this->reminderRepository->remindersPath());
    }

    public function itShouldCreateReminderAndSave()
    {

    }
}

Add ensure Repository Root Path test

Add ensure Repository Root Path test


<?php
class ForumSpamPostExtension extends DataExtension {

	public function augmentSQL(SQLSelect $query) {
		if (Config::inst()->forClass('Post')->allow_reading_spam) return;

		$member = Member::currentUser();
		$forum = $this->owner->Forum();

		// Do Status filtering

		if($member && is_numeric($forum->ID) && $member->ID == $forum->Moderator()->ID) {
			$filter = "\"Post\".\"Status\" IN ('Moderated', 'Awaiting')";
		} else {
			$filter = "\"Post\".\"Status\" = 'Moderated'";
		}

		$query->addWhere($filter);

		// Filter out posts where the author is in some sort of banned / suspended status

		$query->addInnerJoin("Member", "\"AuthorStatusCheck\".\"ID\" = \"Post\".\"AuthorID\"", "AuthorStatusCheck");

		$authorStatusFilter = array(
			array('"AuthorStatusCheck"."ForumStatus"' => 'Normal')
		);
		if ($member && $member->ForumStatus === 'Ghost') {
			$authorStatusFilter[] =  array('"Post"."AuthorID" = ?', $member->ID);
		}

		$query->addWhereAny($authorStatusFilter);
		$query->setDistinct(false);
	}

}

<?php
class ForumSpamPostExtension extends DataExtension {

	public function augmentSQL(SQLQuery &$query) {
		if (Config::inst()->forClass('Post')->allow_reading_spam) return;

		$member = Member::currentUser();
		$forum = $this->owner->Forum();

		// Do Status filtering

		if($member && is_numeric($forum->ID) && $member->ID == $forum->Moderator()->ID) {
			$filter = "\"Post\".\"Status\" IN ('Moderated', 'Awaiting')";
		} else {
			$filter = "\"Post\".\"Status\" = 'Moderated'";
		}

		$query->addWhere($filter);

		// Filter out posts where the author is in some sort of banned / suspended status

		$query->addInnerJoin("Member", "\"AuthorStatusCheck\".\"ID\" = \"Post\".\"AuthorID\"", "AuthorStatusCheck");

		$authorStatusFilter = array(
			array('"AuthorStatusCheck"."ForumStatus"' => 'Normal')
		);
		if ($member && $member->ForumStatus === 'Ghost') {
			$authorStatusFilter[] =  array('"Post"."AuthorID" = ?', $member->ID);
		}

		$query->addWhereAny($authorStatusFilter);
		$query->setDistinct(false);
	}

}

FIX augmentSQL func to be compatible with 3.2 method signature


<?php

namespace Nwidart\Modules\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;

class GenerateResource extends Command
{
    /**
     * The command name.
     *
     * @var string
     */
    protected $name = 'module:make:resource';

    /**
     * The command description.
     *
     * @var string
     */
    protected $description = 'Generate all assets for a new resource.';

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['resource', InputArgument::REQUIRED, 'The singular name of the resource.'],
            ['module', InputArgument::REQUIRED, 'The name of the module to create the controller in.'],
        ];
    }

    /**
     * Execute the console command.
     */
    public function fire()
    {
        // TODO: create resource, repo, … based on migration

        $this->call('module:make:resource-controller', [
            'resource' => $this->argument('resource'),
            'module' => $this->argument('module'),
        ]);

        $this->call('module:make:resource-router', [
            'resource' => $this->argument('resource'),
            'module' => $this->argument('module'),
        ]);

        $this->call('module:make:views:resource', [
            'resource' => $this->argument('resource'),
            'module' => $this->argument('module'),
        ]);

        $this->info('Now register your resource router in the <mapRoutes> method of your module service provider.');
    }
}

<?php

namespace Nwidart\Modules\Commands;

use Illuminate\Console\Command;

class GenerateResource extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'module:make:resource
                            {resource : The singular name of the resource}
                            {module? : The name of the module to create the controller in}';

    /**
     * The command description.
     *
     * @var string
     */
    protected $description = 'Generate all assets for a new resource.';

    /**
     * Execute the console command.
     */
    public function fire()
    {
        // TODO: create resource, repo, … based on migration

        $this->call('module:make:controller', [
            'resource' => $this->argument('resource'),
            'module' => $this->argument('module'),
        ]);

        $this->call('module:make:router', [
            'resource' => $this->argument('resource'),
            'module' => $this->argument('module'),
        ]);

        $this->call('module:make:views:resource', [
            'resource' => $this->argument('resource'),
            'module' => $this->argument('module'),
        ]);

        $this->info('Now register your resource router in the "mapRoutes" method of your module service provider.');
    }
}

Update generate resource command signature


<?php

use yii\db\Migration;

class m130524_201442_init extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%user}}', [
            'id' => $this->primaryKey(),
            'username' => $this->string()->notNull()->unique(),
            'auth_key' => $this->string(32)->notNull(),
            'password_hash' => $this->string()->notNull(),
            'password_reset_token' => $this->string()->unique(),
            'email' => $this->string()->notNull()->unique(),

            'status' => $this->smallInteger()->notNull()->defaultValue(10),
            'created_at' => $this->integer()->notNull(),
            'updated_at' => $this->integer()->notNull(),
        ], $tableOptions);
    }

    public function down()
    {
        $this->dropTable('{{%user}}');
    }
}

<?php

use yii\db\Migration;

class m130524_201442_init extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%user}}', [
            'id' => $this->primaryKey(),
            'full_name' => $this->string()->notNull()->unique(),
            'email' => $this->string()->notNull()->unique(),
            'auth_key' => $this->string(32)->notNull(),
            'password_hash' => $this->string()->notNull(),
            'password_reset_token' => $this->string()->unique(),
            'status' => $this->smallInteger()->notNull()->defaultValue(10),
            'role' => $this->smallInteger()->notNull()->defaultValue(10),
            'created_at' => $this->integer()->notNull(),
            'updated_at' => $this->integer()->notNull(),
        ], $tableOptions);
    }

    public function down()
    {
        $this->dropTable('{{%user}}');
    }
}

Add fields in the user table migration class


<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * FennecDbxrefRepository
 *
 * This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom
 * repository methods below.
 */
class FennecDbxrefRepository extends EntityRepository
{
}

<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * FennecDbxrefRepository
 *
 * This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom
 * repository methods below.
 */
class FennecDbxrefRepository extends EntityRepository
{
    public function getIds($ids, $dbname){
        $dbId = $this->getDbId($dbname);
        $qb = $this->getEntityManager()->createQueryBuilder();
        $qb->select('IDENTITY(dbxref.fennec) AS fennecId', 'dbxref.identifier')
            ->from('AppBundle:FennecDbxref', 'dbxref')
            ->where('dbxref.db = :dbId')
            ->andWhere('dbxref.identifier IN (:ids)')
            ->setParameter('dbId', $dbId)
            ->setParameter('ids', $ids);
        $query = $qb->getQuery();
        $result = $query->getResult();
        $data = array_fill_keys($ids, null);

        for($i=0;$i<sizeof($result);$i++){
            $id = $result[$i]['identifier'];
            if($data[$id] === null){
                $data[$id] = $result[$i]['fennecId'];
            } else {
                if(!is_array($data[$id]) ){
                    $data[$id] = [$data[$id]];
                }
                $data[$id][] = $result[$i]['fennecId'];
            }
        }
        return $data;
    }

    private function getDbId($dbname){
        $qb = $this->getEntityManager()->createQueryBuilder();
        $qb->select('db.dbId')
            ->from('AppBundle:Db', 'db')
            ->where('db.name = :dbname')
            ->setParameter('dbname', $dbname);
        $query = $qb->getQuery();
        $result = $query->getResult();
        return $result;
    }
}

Implement function for getting correct ids from dbxref repo


<?php namespace ZackKitzmiller\Laravel5;

use ZackKitzmiller\Tiny;
use Illuminate\Support\ServiceProvider;

class TinyServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app['tiny.generate'] = $this->app->share(function ($app) {
            return new TinyGenerateCommand();
        });

        $this->commands('tiny.generate');
    }

    public function register()
    {
        $this->app['tiny'] = $this->app->share(function ($app) {
            $key = getenv('LEAGUE_TINY_KEY');

            return new Tiny($key);
        });
    }

    public function provides()
    {
        return array('tiny');
    }
}

<?php namespace ZackKitzmiller\Laravel5;

use ZackKitzmiller\Tiny;
use Illuminate\Support\ServiceProvider;

class TinyServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app->singleton('tiny.generate', function () {
            return new TinyGenerateCommand();
        });

        $this->commands('tiny.generate');
    }

    public function register()
    {
        $this->app->singleton('tiny', function () {
            $key = getenv('LEAGUE_TINY_KEY');

            return new Tiny($key);
        });
    }

    public function provides()
    {
        return array('tiny');
    }
}

Remove use of depracated share method in Laravel 5 service provider


<?php

/*
 * This file is part of the Elcodi package.
 *
 * Copyright (c) 2014-2015 Elcodi.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Feel free to edit as you please, and have fun.
 *
 * @author Marc Morera <yuhu@mmoreram.com>
 * @author Aldo Chiecchia <zimage@tiscali.it>
 * @author Elcodi Team <tech@elcodi.com>
 */

namespace Elcodi\Plugin\TwitterBundle;

use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Elcodi\Component\Plugin\Interfaces\PluginInterface;
use Elcodi\Plugin\TwitterBundle\DependencyInjection\ElcodiTwitterExtension;

/**
 * Class ElcodiTwitterBundle
 */
class ElcodiTwitterBundle extends Bundle implements PluginInterface
{
    /**
     * Returns the bundle's container extension.
     *
     * @return ExtensionInterface The container extension
     */
    public function getContainerExtension()
    {
        return new ElcodiTwitterExtension();
    }

    /**
     * Register Commands.
     *
     * Disabled as commands are registered as services.
     *
     * @param Application $application An Application instance
     */
    public function registerCommands(Application $application)
    {
        return null;
    }
}

<?php

/*
 * This file is part of the Elcodi package.
 *
 * Copyright (c) 2014-2015 Elcodi.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Feel free to edit as you please, and have fun.
 *
 * @author Marc Morera <yuhu@mmoreram.com>
 * @author Aldo Chiecchia <zimage@tiscali.it>
 * @author Elcodi Team <tech@elcodi.com>
 */

namespace Elcodi\Plugin\TwitterBundle;

use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Elcodi\Component\Plugin\Interfaces\PluginInterface;
use Elcodi\Plugin\TwitterBundle\DependencyInjection\ElcodiTwitterExtension;

/**
 * Class ElcodiTwitterBundle
 */
class ElcodiTwitterBundle extends Bundle implements PluginInterface
{
    /**
     * Returns the bundle's container extension.
     *
     * @return ExtensionInterface The container extension
     */
    public function getContainerExtension()
    {
        return new ElcodiTwitterExtension();
    }

    /**
     * Register Commands.
     *
     * Disabled as commands are registered as services.
     *
     * @param Application $application An Application instance
     *
     * @return null
     */
    public function registerCommands(Application $application)
    {
        return null;
    }
}

Store + Shipping + Menus

Store + Shipping + Menus

* Using new Store feature from Elcodi
* Added Store management in Admin
* Changed all definitions that was depending on such implementation
* Removed under construction logic and tests

* Removed menu fixtures
* Defined them as dynamic content. Some of them are generated dinamically, and
  some of them statically.
* Added neede menu builders in every Admin bundle
* Changed the way menu is loaded in Admin

* Removed dependency with Configuration and Configuration annotation, in order to use
  new implementation.
* Removed configuration elements
* Removed all `elcodi_config` twig extension usage

* Moved custom shipping logic from elcodi/elcodi to elcodi-plugins/*
* Added full repo inside Plugin folder
* Using new Shipping engine

* Updated some code in order to be compatible with Sf2.7 deprecations

Ready for Elcodi Beta! Auu! Auu!


<?php

function env_is_cli() {
    return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
}

// ----- only run from command line -----
if (!env_is_cli())
    die;

// ----- params -----
set_time_limit(0);
error_reporting(E_ALL);

define('CAPTURE', 'onepercent');

// ----- includes -----
include __DIR__ . '/../../config.php';                  // load base config file
include __DIR__ . '/../../common/functions.php';        // load base functions file
include __DIR__ . '/../common/functions.php";           // load capture function file

require __DIR__ . '/../common/tmhOAuth/tmhOAuth.php';

$thislockfp = script_lock(CAPTURE);
if (!is_resource($thislockfp)) {
    logit(CAPTURE . ".error.log", "script invoked but will not continue because a process is already holding the lock file.");
    die;          // avoid double execution of script
}

if (dbserver_has_utf8mb4_support() == false) {
    logit(CAPTURE . ".error.log", "DMI-TCAT requires at least MySQL version 5.5.3 - please upgrade your server");
    exit();
}

// ----- connection -----
dbconnect();      // connect to database @todo, rewrite mysql calls with pdo

tracker_run();

<?php

function env_is_cli() {
    return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
}

// ----- only run from command line -----
if (!env_is_cli())
    die;

// ----- params -----
set_time_limit(0);
error_reporting(E_ALL);

define('CAPTURE', 'onepercent');

// ----- includes -----
include __DIR__ . '/../../config.php';                  // load base config file
include __DIR__ . '/../../common/functions.php';        // load base functions file
include __DIR__ . '/../common/functions.php';           // load capture function file

require __DIR__ . '/../common/tmhOAuth/tmhOAuth.php';

$thislockfp = script_lock(CAPTURE);
if (!is_resource($thislockfp)) {
    logit(CAPTURE . ".error.log", "script invoked but will not continue because a process is already holding the lock file.");
    die;          // avoid double execution of script
}

if (dbserver_has_utf8mb4_support() == false) {
    logit(CAPTURE . ".error.log", "DMI-TCAT requires at least MySQL version 5.5.3 - please upgrade your server");
    exit();
}

// ----- connection -----
dbconnect();      // connect to database @todo, rewrite mysql calls with pdo

tracker_run();

Fix syntax error from wrong quotation mark.


<?php

return array(
    'client_tabs' => array(
        'smart_stats-tab' => array('view' => 'smart_stats_tab', 'i18n' => 'smart_stats.clienttabtitle', 'badge' => 'smart_stats-cnt'),
    ),
    'listings' => array(
        'smart_stats' => array('view' => 'smart_stats_listing', 'i18n' => 'smart_stats.clienttabtitle'),
    ),
    'widgets' => array(
        'smart_overall_health_test' => array('view' => 'smart_overall_health_test_widget'),
    ),
    'reports' => array(
        'smart_report' => array('view' => 'smart_report', 'i18n' => 'smart_stats.report'),
    ),
);

<?php

return array(
    'client_tabs' => array(
        'smart_stats-tab' => array('view' => 'smart_stats_tab', 'i18n' => 'smart_stats.clienttabtitle', 'badge' => 'smart_stats-cnt'),
    ),
    'listings' => array(
        'smart_stats' => array('view' => 'smart_stats_listing', 'i18n' => 'smart_stats.clienttabtitle'),
    ),
    'widgets' => array(
        'smart_overall_health_test' => array('view' => 'smart_overall_health_test_widget'),
    ),
    'reports' => array(
        'smart_report' => array('view' => 'smart_report', 'i18n' => 'smart_stats.reporttitle'),
    ),
);

Fix SMART stats report title

Fix SMART stats report title


<?php
/**
 * MSCR Utilities
 */
class MSCRUtilsTest extends WP_UnitTestCase {
	public $plugin_slug = 'mute-screamer';

	public function setUP() {
		parent::setUp();
	}

	public function testIntrusionsPerPage()	{
		delete_option('mscr_intrusions_per_page');
		$this->assertEquals(20, MSCR_Utils::mscr_intrusions_per_page(), '->mscr_intrusions_per_page default is 20');
	}
}

<?php
/**
 * MSCR Utilities
 */
class MSCRUtilsTest extends WP_UnitTestCase {
	public $plugin_slug = 'mute-screamer';

	public function setUP() {
		parent::setUp();
	}

	public function testIntrusionsPerPage()	{
		$this->assertEquals(20, MSCR_Utils::mscr_intrusions_per_page(), '->mscr_intrusions_per_page default is 20');
	}
}

Remove delete from mscr_intrusions_per_page tests


<?php

namespace Spark\Test\Util;

use PHPUnit_Framework_TestCase,
    Spark\Util;

class ClassLoaderTest extends PHPUnit_Framework_TestCase
{
    function setUp()
    {
        $this->classLoader = Util\ClassLoader();
    }

    function testClassLoaderActsAsSingleton()
    {
        $instance1 = Util\ClassLoader();
        $instance2 = Util\ClassLoader();
        $this->assertEquals($instance1, $instance2);
    }

    function testClassLoaderRegistersOnSplAutoloadStack()
    {
        $classLoader = $this->classLoader;
        $this->assertTrue(in_array($classLoader, spl_autoload_functions(), true));
    }

    function testClassLoaderCanBeUnregisteredFromSplAutoloadStack()
    {
        $classLoader = $this->classLoader;
        $classLoader->unregister();
        $this->assertFalse(in_array($classLoader, spl_autoload_functions(), true));

        $classLoader->register();
    }

    function testAutoloadFunction()
    {
        autoload("Spark\Test\SampleClass", TESTS . "/Spark/_data/SampleClass.php");
        $this->assertTrue(class_exists("Spark\Test\SampleClass"), "Sample Class is not loadable");
    }
}

<?php

namespace Spark\Test\Util;

use PHPUnit_Framework_TestCase,
    Spark\Util;

class ClassLoaderTest extends PHPUnit_Framework_TestCase
{
    function setUp()
    {
        $this->classLoader = Util\ClassLoader();
    }

    function testClassLoaderActsAsSingleton()
    {
        $instance1 = Util\ClassLoader();
        $instance2 = Util\ClassLoader();
        $this->assertSame($instance1, $instance2);
    }

    function testClassLoaderRegistersOnSplAutoloadStack()
    {
        $classLoader = $this->classLoader;
        $this->assertTrue(in_array($classLoader, spl_autoload_functions(), true));
    }

    function testClassLoaderCanBeUnregisteredFromSplAutoloadStack()
    {
        $classLoader = $this->classLoader;
        $classLoader->unregister();
        $this->assertFalse(in_array($classLoader, spl_autoload_functions(), true));

        $classLoader->register();
    }

    function testAutoloadFunction()
    {
        autoload("Spark\Test\SampleClass", TESTS . "/Spark/_data/SampleClass.php");
        $this->assertTrue(class_exists("Spark\Test\SampleClass"), "Sample Class is not loadable");
    }
}

Use PHPUnit_Framework_Assert::assertSame() to check if the variables refer to the same ClassLoader instances


<?php
/**
 * Remove or comment the following lines to enable/disable features.
 * You can register the YouTube feature to other shortcodes, but I prefer shorter bb-code.
 *
 * To enable, just add a / directly after the star below this line
 *
// It seems an array bugs out :(
// Can this be done via a yml file?
ShortcodeParser::get()->register('tweet',array('NewsHolderPage','TweetHandler'));
ShortcodeParser::get()->register('code',array('NewsHolderPage','GeshiParser'));
ShortcodeParser::get()->register('YT',array('NewsHolderPage','YouTubeHandler'));
ShortcodeParser::get()->register('slideshow', array('NewsHolderPage','createSlideshow'));
/*This comment is here to save you from WTF HAPPENED!*/

<?php
/**
 * Remove or comment the following lines to enable/disable features.
 * You can register the YouTube feature to other shortcodes, but I prefer shorter bb-code.
 *
 * To enable, just add a / directly after the star below this line. To disable, remove the /
 */
// It seems an array bugs out :(
// Can this be done via a yml file?
ShortcodeParser::get()->register('tweet',array('NewsHolderPage','TweetHandler'));
ShortcodeParser::get()->register('code',array('NewsHolderPage','GeshiParser'));
ShortcodeParser::get()->register('YT',array('NewsHolderPage','YouTubeHandler'));
ShortcodeParser::get()->register('slideshow', array('NewsHolderPage','createSlideshow'));
/*This comment is here to save you from WTF HAPPENED!*/

Revert "Revert "Enabled shortcodeparser by default.""

This reverts commit 46e6565887bbc9cfab8996d0b5ea0a8631e98ceb.


<?php

namespace League\Glide\Requests;

use Symfony\Component\HttpFoundation\Request;

class RequestFactory
{
    /**
     * Create a request instance.
     * @param  max     $args                 The request object or path/params combination.
     * @param  array   $defaultManipulations The default image manipulations.
     * @return Request The request object.
     */
    public static function create($args, $defaultManipulations = [])
    {
        if (isset($args[0]) and $args[0] instanceof Request) {
            $request = $args[0];
        }

        if (isset($args[0]) and is_string($args[0])) {
            $params = [];

            if (isset($args[1]) and is_array($args[1])) {
                $params = $args[1];
            }

            $request = new Request($params, [], [], [], [], array_merge($_SERVER, ['REQUEST_URI' => $args[0]]));
        }

        if (!isset($request)) {
            throw new InvalidArgumentException('Not a valid path or Request object.');
        }

        foreach ($defaultManipulations as $key => $value) {
            if (!$request->get($key)) {
                $request->query->set($key, $value);
            }
        }

        return $request;
    }
}

<?php

namespace League\Glide\Requests;

use Symfony\Component\HttpFoundation\Request;

class RequestFactory
{
    /**
     * Create a request instance.
     * @param  max     $args                 The request object or path/params combination.
     * @param  array   $defaultManipulations The default image manipulations.
     * @return Request The request object.
     */
    public static function create($args, $defaultManipulations = [])
    {
        if (isset($args[0]) and $args[0] instanceof Request) {
            $request = $args[0];
        }

        if (isset($args[0]) and is_string($args[0])) {
            $params = [];

            if (isset($args[1]) and is_array($args[1])) {
                $params = $args[1];
            }

            $request = new Request($params, [], [], [], [], array_merge($_SERVER, ['REQUEST_URI' => $args[0]]));
        }

        if (!isset($request)) {
            throw new InvalidArgumentException('Not a valid path/params combination or Request object.');
        }

        foreach ($defaultManipulations as $key => $value) {
            if (!$request->get($key)) {
                $request->query->set($key, $value);
            }
        }

        return $request;
    }
}

Improve invalid request exception message.


@extends('layouts.admin')

@section('title') Pitch #{{ $pitch->id }} @endsection

@section('content')

{{ Form::model($pitch, ['route' => ['sysop.pitches.update', $pitch->id], 'method' => 'put']) }}

{{ Form::label('name', 'From') }}
{{ Form::text('name') }}

{{ Form::label('email', 'Email') }}
{{ Form::email('email') }}

{{ Form::label('status', 'Submission Status') }}
{{ Form::select('status', $menu) }}

{{ Form::label('blurb', 'The Pitch') }}
{{ Form::textarea('blurb', null, ['class'=>'input-block-level', 'rows'=>15]) }}

{{ Form::label('notes', 'Editorial Notes') }}
{{ Form::textarea('notes', null, ['class'=>'input-block-level', 'rows'=>10]) }}

To Do: link author_id and story_id up here

  {{ Form::submit('Update', ['class'=>'btn btn-primary']) }}
  {{ Html::linkRoute('sysop.pitches.index', 'Back', null, ['class'=>'btn'])}}

{{ Form::close() }}
@endsection

@extends('layouts.admin')

@section('title') Pitch #{{ $pitch->id }} @endsection

@section('content')

{{ Form::model($pitch, ['route' => ['sysop.pitches.update', $pitch->id], 'method' => 'put']) }}

{{ Form::label('name', 'From') }}
{{ Form::text('name') }}

{{ Form::label('email', 'Email') }}
{{ Form::email('email') }}

{{ Form::label('status', 'Submission Status') }}
{{ Form::select('status', $menu) }}

{{ Form::label('blurb', 'The Pitch') }}
{{ Form::textarea('blurb', null, ['class'=>'input-block-level', 'rows'=>15]) }}

{{ Form::label('notes', 'Editorial Notes') }}
{{ Form::textarea('notes', null, ['class'=>'input-block-level', 'rows'=>10]) }}

<p>
  {{ Form::submit('Update', ['class'=>'btn btn-primary']) }}
  {{ Html::linkRoute('sysop.pitches.index', 'Back', null, ['class'=>'btn'])}}
</p>

{{ Form::close() }}
@endsection

{{-- TODO way to link stories and pitches --}}

Move a comment to a real comment field

Move a comment to a real comment field


Hey {{ $user->username }}!

{{ $blueprint->reply->user->username }} replied to your post (#{{ $blueprint->post->number }}) in {{ $blueprint->post->discussion->title }}.

{{ \Flarum\Core::url() }}/d/{{ $blueprint->reply->discussion_id }}/{{ $blueprint->reply->number }}

---

{{ strip_tags($blueprint->post->contentHtml) }}

Hey {{ $user->username }}!

{{ $blueprint->reply->user->username }} replied to your post (#{{ $blueprint->post->number }}) in {{ $blueprint->post->discussion->title }}.

{{ \Flarum\Core::url() }}/d/{{ $blueprint->reply->discussion_id }}/{{ $blueprint->reply->number }}

---

{{ strip_tags($blueprint->reply->contentHtml) }}

Fix issue-email notifications quoting wrong reply

This commit fix this bug https://github.com/flarum/core/issues/304.Problem not in newPost.blade.php but in this file.


<?php

trait Trait_currentMember
{
	protected $_current_member	=	null;

	protected function _checkCurrentMember()
	{
		if(isset($_SESSION['connected_user_id']))
		{
			$this->_current_member = Model_Users::getById($_SESSION['connected_user_id']);
			$this->_current_member->prop('last_login', date('Y-m-d H:i:s'));
            Model_Users::update($this->_current_member);

			if($this->_current_member->prop('is_banned'))
				$this->_current_member = new Model_Users();
		}
		else
			$this->_current_member = new Model_Users();

		Library_i18n::defineLocale($this->_current_member);

		\Eliya\Tpl::set(['current_member' => $this->_current_member]);

		if(!isset($_SESSION['token_logout']))
			$_SESSION['token_logout'] = uniqid(rand(), true); //Protection contre les failles CSRF
	}

	protected function _redirectToCurrentMemberProfile()
	{
		$this->response->redirect($this->request->getBaseUrl().'profile/'.$this->_current_member->getId());
		exit;
	}
}

<?php

trait Trait_currentMember
{
	protected $_current_member	=	null;

	protected function _checkCurrentMember()
	{
		if(isset($_SESSION['connected_user_id']))
		{
			$this->_current_member = Model_Users::getById($_SESSION['connected_user_id']);
			$this->_current_member->prop('last_login', date('Y-m-d H:i:s'));

            $this->_current_member->load('user_group');
            $this->_current_member->load('locale_website');
            $this->_current_member->load('locales_comics');
			$this->_current_member->load('follows');

            Model_Users::update($this->_current_member);

			if($this->_current_member->prop('is_banned'))
				$this->_current_member = new Model_Users();
		}
		else
			$this->_current_member = new Model_Users();

		Library_i18n::defineLocale($this->_current_member);

		\Eliya\Tpl::set(['current_member' => $this->_current_member]);

		if(!isset($_SESSION['token_logout']))
			$_SESSION['token_logout'] = uniqid(rand(), true); //Protection contre les failles CSRF
	}

	protected function _redirectToCurrentMemberProfile()
	{
		$this->response->redirect($this->request->getBaseUrl().'profile/'.$this->_current_member->getId());
		exit;
	}
}

Fix bug when following an user

Fix bug when following an user


<?php

namespace Niif\ShibAuthBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('niif_shib_auth');
        $rootNode
            ->children()
                ->scalarNode('baseURL')
                    ->isRequired()
                    ->cannotBeEmpty()
                ->end()
                ->scalarNode('sessionInitiator')
                    ->defaultValue('Shibbholeth.sso/DSS')
                ->end()
                ->scalarNode('logoutPath')
                    ->defaultValue('Shibboleth.sso/Logout')
                ->end()
                ->scalarNode('usernameAttribute')
                    ->isRequired()
                    ->cannotBeEmpty()
                ->end()
                ->scalarNode('mailAttribute')
                    ->isRequired()
                    ->cannotBeEmpty()
                ->end()
                ->scalarNode('affiliationAttribute')
                    ->isRequired()
                    ->cannotBeEmpty()
                ->end()
                ->scalarNode('entitlementAttribute')
                    ->isRequired()
                    ->cannotBeEmpty()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

<?php

namespace Niif\ShibAuthBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files.
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('niif_shib_auth');
        $rootNode
            ->children()
                ->scalarNode('baseURL')
                    ->isRequired()
                    ->cannotBeEmpty()
                ->end()
                ->scalarNode('sessionInitiator')
                    ->defaultValue('Shibbholeth.sso/DSS')
                ->end()
                ->scalarNode('logoutPath')
                    ->defaultValue('Shibboleth.sso/Logout')
                ->end()
                ->scalarNode('usernameAttribute')
                    ->isRequired()
                    ->cannotBeEmpty()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

Move config parameters to user provider

Move config parameters to user provider


<?php declare(strict_types=1);
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2019, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\ImageBundle\Entity\Image;

use Darvin\ContentBundle\Traits\TranslationTrait;
use Doctrine\ORM\Mapping as ORM;

/**
 * Image translation
 *
 * @ORM\Entity
 * @ORM\InheritanceType("SINGLE_TABLE")
 */
class ImageTranslation
{
    use TranslationTrait;

    /**
     * {@inheritDoc}
     */
    public static function getTranslatableEntityClass(): string
    {
        return AbstractImage::class;
    }
}

<?php declare(strict_types=1);
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2019, Darvin Studio
 * @link      https://www.darvin-studio.ru
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Darvin\ImageBundle\Entity\Image;

use Darvin\ContentBundle\Traits\TranslationTrait;
use Doctrine\ORM\Mapping as ORM;

/**
 * Image translation
 *
 * @ORM\Entity
 * @ORM\InheritanceType("SINGLE_TABLE")
 */
class ImageTranslation
{
    use TranslationTrait;

    /**
     * @var string|null
     *
     * @ORM\Column(nullable=true)
     */
    private $alt;

    /**
     * @var string|null
     *
     * @ORM\Column(nullable=true)
     */
    private $title;

    /**
     * {@inheritDoc}
     */
    public static function getTranslatableEntityClass(): string
    {
        return AbstractImage::class;
    }

    /**
     * @return string|null
     */
    public function getAlt(): ?string
    {
        return $this->alt;
    }

    /**
     * @param string|null $alt alt
     *
     * @return ImageTranslation
     */
    public function setAlt(?string $alt): ImageTranslation
    {
        $this->alt = $alt;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getTitle(): ?string
    {
        return $this->title;
    }

    /**
     * @param string|null $title title
     *
     * @return ImageTranslation
     */
    public function setTitle(?string $title): ImageTranslation
    {
        $this->title = $title;

        return $this;
    }
}

Add properties to image translation entity.


<?php

namespace InMockBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class DefaultController
 * @package InMockBundle\Controller
 */
class DefaultController extends Controller
{
    /**
     * @Route("/")
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function indexAction(Request $request): JsonResponse
    {
        return new JsonResponse(array('hello' => 'world'));
    }
}

<?php

namespace InMockBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class DefaultController
 * @package InMockBundle\Controller
 */
class DefaultController extends Controller
{
    /**
     * @Route("/")
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function indexAction(Request $request): JsonResponse
    {
        return new JsonResponse(['hello' => 'world']);
    }
}

Change array to new style

Change array to new style


  protected function doSave()
  {
    $this->object->save();
    return sfView::NONE;
  }

  protected function doSave()
  {
    $this->object->save();

    // Set a Location header with the path to the new / updated object
    $this->getResponse()->setHttpHeader('Location', $this->getController()->genUrl(
      array_merge(array(
        'sf_route' => '<?php echo $this->getModuleName(); ?>_show',
        'sf_format' => $this->getFormat(),
      ), $this->object->identifier())
    ));

    return sfView::NONE;
  }

Add the Location header on Response when an entity is saved.


<?php

namespace OldSound\RabbitMqBundle\RabbitMq;

use OldSound\RabbitMqBundle\RabbitMq\BaseConsumer;
use PhpAmqpLib\Message\AMQPMessage;

class Consumer extends BaseConsumer
{
    public function consume($msgAmount)
    {
        $this->target = $msgAmount;

        $this->setUpConsumer();

        while (count($this->ch->callbacks))
        {
            $this->ch->wait();
        }
    }

    public function processMessage(AMQPMessage $msg)
    {
        if (false === call_user_func($this->callback, $msg)) {
            // Reject and requeue message to RabbitMQ
            $msg->delivery_info['channel']->basic_reject($msg->delivery_info['delivery_tag'], true);
        }
        else {
            // Remove message from queue only if callback return not false
            $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
        }

        $this->consumed++;
        $this->maybeStopConsumer();
    }
}

<?php

namespace OldSound\RabbitMqBundle\RabbitMq;

use OldSound\RabbitMqBundle\RabbitMq\BaseConsumer;
use PhpAmqpLib\Message\AMQPMessage;

class Consumer extends BaseConsumer
{
    public function consume($msgAmount)
    {
        $this->target = $msgAmount;

        $this->setUpConsumer();

        while (count($this->ch->callbacks))
        {
            $this->maybeStopConsumer();
            $this->ch->wait();
        }
    }

    public function processMessage(AMQPMessage $msg)
    {
        if (false === call_user_func($this->callback, $msg)) {
            // Reject and requeue message to RabbitMQ
            $msg->delivery_info['channel']->basic_reject($msg->delivery_info['delivery_tag'], true);
        }
        else {
            // Remove message from queue only if callback return not false
            $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
        }

        $this->consumed++;
        $this->maybeStopConsumer();
    }
}

Fix consumer killing on empty queue

Fix consumer killing on empty queue


<?php

namespace OParl\Server\Commands;

use Illuminate\Console\Command;
use OParl\Server\Model\Body;
use OParl\Server\Model\Consultation;
use OParl\Server\Model\File;
use OParl\Server\Model\Keyword;
use OParl\Server\Model\LegislativeTerm;
use OParl\Server\Model\Location;
use OParl\Server\Model\Meeting;
use OParl\Server\Model\Membership;
use OParl\Server\Model\Organization;
use OParl\Server\Model\Paper;
use OParl\Server\Model\Person;
use OParl\Server\Model\System;

/**
 * Clear the server data
 *
 * @package OParl\Server\Commands
 */
class ResetCommand extends Command
{
    protected $name = 'server:reset';
    protected $description = "Reset the server's database";

    public function handle()
    {
        $this->info('Removing all existing server data...');

        System::truncate();
        Body::truncate();
        LegislativeTerm::truncate();
        Person::truncate();
        Organization::truncate();
        Membership::truncate();
        Meeting::truncate();
        Consultation::truncate();
        Paper::truncate();
        Location::truncate();
        File::truncate();
        Keyword::truncate();
    }
}

<?php

namespace OParl\Server\Commands;

use Illuminate\Console\Command;
use OParl\Server\Model\Body;
use OParl\Server\Model\Consultation;
use OParl\Server\Model\File;
use OParl\Server\Model\Keyword;
use OParl\Server\Model\LegislativeTerm;
use OParl\Server\Model\Location;
use OParl\Server\Model\Meeting;
use OParl\Server\Model\Membership;
use OParl\Server\Model\Organization;
use OParl\Server\Model\Paper;
use OParl\Server\Model\Person;
use OParl\Server\Model\System;

/**
 * Clear the server data
 *
 * @package OParl\Server\Commands
 */
class ResetCommand extends Command
{
    protected $name = 'server:reset';
    protected $description = "Reset the server's database";

    public function handle()
    {
        $this->info('Reset demoserver database...');
        unlink(config('database.connections.sqlite_demo.database'));
        touch(config('database.connections.sqlite_demo.database'));
        $this->call('migrate', ['--database' => 'sqlite_demo']);
    }
}

Reset now deletes and recreates the demo db


<?php

namespace Tightenco\Ziggy;

use Illuminate\Routing\Router;

class BladeRouteGenerator
{
    private $router;
    public $routes;

    public function __construct(Router $router)
    {
        $this->router = $router;
    }

    public function generate()
    {
        $json = (string) $this->nameKeyedRoutes();

        return <<<EOT
<script type="text/javascript">
    var namedRoutes = JSON.parse('$json');

    function route (name, params) {
        return namedRoutes[name].uri.replace(
            /\{([^}]+)\}/,
            function (tag) {
                return params[tag.replace(/\{|\}/gi, '')];
            }
        );
    }
</script>
EOT;
    }

    public function nameKeyedRoutes()
    {
        return collect($this->router->getRoutes()->getRoutesByName())
            ->map(function ($route) {
                return collect($route)->only(['uri', 'methods']);
            });
    }
}

<?php

namespace Tightenco\Ziggy;

use Illuminate\Routing\Router;

class BladeRouteGenerator
{
    private $router;
    public $routes;

    public function __construct(Router $router)
    {
        $this->router = $router;
    }

    public function generate()
    {
        $json = (string) $this->nameKeyedRoutes();
        $appUrl = rtrim(config('app.url'), '/') . '/';

        return <<<EOT
<script type="text/javascript">
    var namedRoutes = JSON.parse('$json'),
        baseUrl = '$appUrl';

    function route (name, params, absolute = true) {
        return (absolute ? baseUrl : '') + namedRoutes[name].uri.replace(
            /\{([^}]+)\}/,
            function (tag) {
                return params[tag.replace(/\{|\}/gi, '')];
            }
        );
    }
</script>
EOT;
    }

    public function nameKeyedRoutes()
    {
        return collect($this->router->getRoutes()->getRoutesByName())
            ->map(function ($route) {
                return collect($route)->only(['uri', 'methods']);
            });
    }
}

Add absolute URL generation without consideration of subdomains or params in domains


<?php
declare(strict_types=1);

namespace WyriHaximus\Travis\Resource\Async;

use GuzzleHttp\Psr7\Request;
use React\Promise\PromiseInterface;
use WyriHaximus\Travis\Resource\User as BaseUser;

class User extends BaseUser
{
    public function refresh() : User
    {
        return $this->wait($this->callAsync('refresh'));
    }

    public function sync(): PromiseInterface
    {
        return $this->getTransport()->requestPsr7(
            new Request(
                'POST',
                $this->getTransport()->getBaseURL() . 'users/sync',
                $this->getTransport()->getHeaders()
            )
        )->then(function () {
            return $this->refresh();
        });
    }
}

<?php
declare(strict_types=1);

namespace WyriHaximus\Travis\Resource\Async;

use GuzzleHttp\Psr7\Request;
use React\Promise\PromiseInterface;
use WyriHaximus\Travis\Resource\User as BaseUser;
use function React\Promise\resolve;

class User extends BaseUser
{
    public function refresh() : PromiseInterface
    {
        return $this->getTransport()->request('users/' . $this->id())->then(function ($json) {
            return resolve($this->getTransport()->getHydrator()->hydrate('User', $json['user']));
        });
    }

    public function sync(): PromiseInterface
    {
        return $this->getTransport()->requestPsr7(
            new Request(
                'POST',
                $this->getTransport()->getBaseURL() . 'users/sync',
                $this->getTransport()->getHeaders()
            )
        )->then(function () {
            return $this->refresh();
        });
    }
}

Refresh a user from travis

Refresh a user from travis


<?php defined('SYSPATH') OR die('No direct script access.');
/**
 * Performs install/uninstall methods for the FrontlineCloud Plugin
 *
 * @package    Ushahidi
 * @author     Ushahidi Team
 * @copyright  (c) 2008 Ushahidi Team
 * @license    http://www.ushahidi.com/license.html
 */
class Frontlinecloud_Install {

	/**
	 * Constructor to load the shared database library
	 */
	public function __construct()
	{
		$this->db =  new Database;
	}

	/**
	 * Creates the required columns for the frontlinecloud Plugin
	 */
	public function run_install()
	{

		// ****************************************
		// DATABASE STUFF
		$this->db->query("
			CREATE TABLE IF NOT EXISTS `".Kohana::config('database.default.table_prefix')."frontlinecloud`
			(
				id int(11) unsigned NOT NULL AUTO_INCREMENT,
				frontlinecloud_key varchar(100) DEFAULT NULL,
				PRIMARY KEY (`id`)
			);
		");

	/**
	 * Drops the frontlinecloud Tables
	 */
	public function uninstall()
	{
		$this->db->query("DROP TABLE ".Kohana::config('database.default.table_prefix')."frontlinecloud;");
	}
}

<?php defined('SYSPATH') OR die('No direct script access.');
/**
 * Performs install/uninstall methods for the FrontlineCloud Plugin
 *
 * @package    Ushahidi
 * @author     Ushahidi Team
 * @copyright  (c) 2008 Ushahidi Team
 * @license    http://www.ushahidi.com/license.html
 */
class Frontlinecloud_Install {

	/**
	 * Constructor to load the shared database library
	 */
	public function __construct()
	{
		$this->db =  new Database;
	}

	/**
	 * Creates the required columns for the frontlinecloud Plugin
	 */
	public function run_install()
	{

		// ****************************************
		// DATABASE STUFF
		$this->db->query("
			CREATE TABLE IF NOT EXISTS `".Kohana::config('database.default.table_prefix')."frontlinecloud`
			(
				id int(11) unsigned NOT NULL AUTO_INCREMENT,
				frontlinecloud_key varchar(100) DEFAULT NULL,
				frontlinecloud_api_url varchar(255) DEFAULT NULL,
				PRIMARY KEY (`id`)
			);
		");
	}

	/**
	 * Drops the frontlinecloud Tables
	 */
	public function uninstall()
	{
		$this->db->query("DROP TABLE ".Kohana::config('database.default.table_prefix')."frontlinecloud;");
	}
}

Add entry in the settings table for api url


<?php

namespace Fig\Cache;

/**
 * Generic method implementations common to most/all pool implementations.
 */
trait BasicPoolTrait
{
    use CachePoolDeferTrait;

    /**
     * {@inheritdoc}
     */
    public function deleteItem($key)
    {
        return $this->deleteItems([$key]);
    }

    /**
     * {@inheritdoc}
     */
    abstract public function deleteItems(array $items);
}

<?php

namespace Fig\Cache;

/**
 * Generic method implementations common to most/all pool implementations.
 */
trait BasicPoolTrait
{
    use CachePoolDeferTrait;

    /**
     * Characters which cannot be used in cache key.
     *
     * The following characters are reserved for future extensions and MUST NOT be
     * supported by implementing libraries
     */
    const RESERVED_KEY_CHARACTERS = '{}()/\@:';

    /**
     * {@inheritdoc}
     */
    public function deleteItem($key)
    {
        return $this->deleteItems([$key]);
    }

    /**
     * {@inheritdoc}
     */
    abstract public function deleteItems(array $items);
}

Add constant with reserved key characters


<?php
namespace Criterion\Model;

class User extends \Criterion\Model
{
    public $collection = 'users';

}

<?php
namespace Criterion\Model;

class User extends \Criterion\Model
{
    public $collection = 'users';

    public function isAdmin()
    {
        return isset($this->role) && $this->role === 'admin';
    }

}

Add a isAdmin() to user model

Add a isAdmin() to user model


<?php

/*
 * This file is part of CSBill package.
 *
 * (c) 2013-2015 Pierre du Plessis <info@customscripts.co.za>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

class Version042 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

        $this->addSql('ALTER TABLE security_token CHANGE payment_name gateway_name VARCHAR(255) NOT NULL;');
    }

    public function down(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");
    }
}

<?php

/*
 * This file is part of CSBill package.
 *
 * (c) 2013-2015 Pierre du Plessis <info@customscripts.co.za>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

class Version042 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

        $this->addSql('ALTER TABLE security_token CHANGE payment_name gateway_name VARCHAR(255) NOT NULL');
        $this->addSql('UPDATE app_config set setting_value = "info@csbill.org" WHERE setting_key  = "from_address"');
        $this->addSql('UPDATE app_config set setting_value = "CSBill" WHERE setting_key  = "from_name"');
    }

    public function down(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

        $this->addSql('ALTER TABLE security_token CHANGE gateway_name payment_name VARCHAR(255) NOT NULL');
        $this->addSql('UPDATE app_config set setting_value = "" WHERE setting_key  = "from_address"');
        $this->addSql('UPDATE app_config set setting_value = "" WHERE setting_key  = "from_name"');
    }
}

Set default email from name and address

Set default email from name and address


<?php

/**
 * Factory functions loader
 *
 * @author Petr Pliska
 */
foreach (glob(__DIR__ . '/Factory/*.php') as $file) {
    require_once $file;
}

<?php

/**
 * @author Petr Pliska <petr.pliska@post.cz>
 */

/**
 * Factory functions loader
 *
 * @author Petr Pliska
 */
foreach (glob(__DIR__ . '/Factory/*.php') as $file) {
    require_once $file;
}

Add author to phpdoc comment

Add author to phpdoc comment


<?php

namespace soap\LanguageSwitcher\bundles;

use yii\web\AssetBundle;

/**
 * LanguageLargeIcons asset bundle
 * @author Lajos Molnár <lajax.m@gmail.com>
 * @since 1.0
 */
class LanguageLargeIconsAsset extends AssetBundle {

    /**
     * @inheritdoc
     */
    public $sourcePath = '@vendor/soap/yii2-language-picker/src/assets';

    /**
     * @inheritdoc
     */
    public $css = [
        'stylesheets/language-switcher.min.css',
        'stylesheets/flags-large.min.css',
    ];

}

<?php

namespace soap\LanguageSwitcher\bundles;

use yii\web\AssetBundle;

/**
 * LanguageLargeIcons asset bundle
 * @author Lajos Molnár <lajax.m@gmail.com>
 * @since 1.0
 */
class LanguageLargeIconsAsset extends AssetBundle {

    /**
     * @inheritdoc
     */
    public $sourcePath = '@vendor/soap/yii2-language-switcher/src/assets';

    /**
     * @inheritdoc
     */
    public $css = [
        'stylesheets/language-switcher.min.css',
        'stylesheets/flags-large.min.css',
    ];

}

Fix error cannot load large icon set.

Fix error cannot load large icon set.


<?php
declare(strict_types=1);

if (!getenv('HEROKU')) {
    return [];
}

return [
    'debug' => false,
    'config_cache_enabled' => false,
    'doctrine' => [
        'connection' => [
            'orm_default' => [
                'params' => [
                    'url' => \getenv('DATABASE_URL'),
                ],
            ],
        ],
    ],
    'phph-site' => [
        's3' => [
            'credentials' => [
                'key' => \getenv('AWS_S3_KEY'),
                'secret' => \getenv('AWS_S3_SECRET'),
            ],
            'region' => \getenv('AWS_S3_REGION'),
            'version' => 'latest',
            'bucket' => \getenv('AWS_S3_BUCKET'),
        ],
        'google-recaptcha' => [
            'site-key' => \getenv('GOOGLE_RECAPTCHA_SITE_KEY'),
            'secret-key' => \getenv('GOOGLE_RECAPTCHA_SECRET_KEY'),
        ],
        'twitter' => [
            'identifier' => \getenv('TWITTER_IDENTIFIER'),
            'secret' => \getenv('TWITTER_SECRET'),
            'callback_uri' => \getenv('TWITTER_CALLBACK_URL'),
        ],
        'github' => [
            'clientId' => \getenv('GITHUB_CLIENT_ID'),
            'clientSecret' => \getenv('GITHUB_CLIENT_SECRET'),
            'redirectUri' => \getenv('GITHUB_REDIRECT_URI'),
        ],
    ],
];

<?php
declare(strict_types=1);

if (!getenv('HEROKU')) {
    return [];
}

return [
    'debug' => (bool)\getenv('DEBUG'),
    'config_cache_enabled' => true,
    'doctrine' => [
        'connection' => [
            'orm_default' => [
                'params' => [
                    'url' => \getenv('DATABASE_URL'),
                ],
            ],
        ],
    ],
    'phph-site' => [
        's3' => [
            'credentials' => [
                'key' => \getenv('AWS_S3_KEY'),
                'secret' => \getenv('AWS_S3_SECRET'),
            ],
            'region' => \getenv('AWS_S3_REGION'),
            'version' => 'latest',
            'bucket' => \getenv('AWS_S3_BUCKET'),
        ],
        'google-recaptcha' => [
            'site-key' => \getenv('GOOGLE_RECAPTCHA_SITE_KEY'),
            'secret-key' => \getenv('GOOGLE_RECAPTCHA_SECRET_KEY'),
        ],
        'twitter' => [
            'identifier' => \getenv('TWITTER_IDENTIFIER'),
            'secret' => \getenv('TWITTER_SECRET'),
            'callback_uri' => \getenv('TWITTER_CALLBACK_URL'),
        ],
        'github' => [
            'clientId' => \getenv('GITHUB_CLIENT_ID'),
            'clientSecret' => \getenv('GITHUB_CLIENT_SECRET'),
            'redirectUri' => \getenv('GITHUB_REDIRECT_URI'),
        ],
    ],
];

Allow configuration of debug on prod lol


<?php
/*
 * The configuration of SURFconext Service Registry package
 */

$config = array (
    'meta_refresh_cron_tags'      => array('hourly'),
    'validate_entity_certificate_cron_tags' => array('daily'),
    'validate_entity_endpoints_cron_tags' => array('daily'),
    'ca_bundle_file' => '/etc/pki/tls/certs/ca-bundle.crt',
);

$localConfig = '/etc/surfconext/serviceregistry.module_serviceregistry.php';
if (file_exists($localConfig)) {
    require $localConfig;
}

<?php
/*
 * The configuration of SURFconext Service Registry package
 */

$config = array (
    'metadata_refresh_cron_tags'      => array('hourly'),
    'validate_entity_certificate_cron_tags' => array('daily'),
    'validate_entity_endpoints_cron_tags' => array('daily'),
    'ca_bundle_file' => '/etc/pki/tls/certs/ca-bundle.crt',
);

$localConfig = '/etc/surfconext/serviceregistry.module_serviceregistry.php';
if (file_exists($localConfig)) {
    require $localConfig;
}

Use proper tag for metadata refresh rate

git-svn-id: fac53d8b196e0ef1c2775236b39a8c3227ab71b5@1191 528793b8-127e-4309-9901-b74759c7208d


<?php

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

class CreateUsersTable extends Migration {

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

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

}

<?php

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

class CreateUsersTable extends Migration {

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

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

}

Add role to user table

Add role to user table


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

DNS server communication failure

The DNS server is not responding.

<?php if(!is_null($active_user) && $active_user->admin) { ?>

Make sure that the following PowerDNS parameters are set correctly in pdns.conf:

webserver=yes
webserver=yes
webserver-address=...
webserver-allow-from=...
webserver-port=...
api=yes
api-key=...

Reload PowerDNS after making changes to this file.

Also check the values set in the [powerdns] section of the DNS UI configuration file (config/config.ini).

<?php } ?>

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

DNS server communication failure

The DNS server is not responding.

<?php if(!is_null($active_user) && $active_user->admin) { ?>

Make sure that the following PowerDNS parameters are set correctly in pdns.conf:

webserver=yes
webserver-address=...
webserver-allow-from=...
webserver-port=...
api=yes
api-key=...

Reload PowerDNS after making changes to this file.

Also check the values set in the [powerdns] section of the DNS UI configuration file (config/config.ini).

<?php } ?>

Remove duplicate line from suggested PowerDNS config


<?php

namespace Deployer;

use SourceBroker\DeployerExtended\Utility\FileUtility;

task('file:rm2steps:1', function () {
    $removeRecursiveAtomicItems = get('file_remove2steps_items');
    $random = get('random');
    // Set active_path so the task can be used before or after "symlink" task or standalone.
    $activePath = get('deploy_path') . '/' . (test('[ -L {{deploy_path}}/release ]') ? 'release' : 'current');
    foreach ($removeRecursiveAtomicItems as $removeRecursiveAtomicItem) {
        $removeRecursiveAtomicItem = FileUtility::normalizeFolder(trim($removeRecursiveAtomicItem));
        if(strlen($removeRecursiveAtomicItem)) {
            $itemToRename = escapeshellarg("$activePath/$removeRecursiveAtomicItem");
            $itemToRenameNewName = escapeshellarg("$activePath/$removeRecursiveAtomicItem$random");
            run("if [ -e $itemToRename ]; then mv -f $itemToRename $itemToRenameNewName; fi");
        }

    }
})->desc('Remove files and directories in two steps. First step: rename. Second step: remove.');

Fix bug and refactor 2 step remove.

[BUGFIX] Fix bug and refactor 2 step remove.