<?php

namespace BestIt\Mage\Tasks\Release;

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

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

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

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

<?php

namespace BestIt\Mage\Tasks\Release;

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

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

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

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

Make sure to sync all files (including hidden files).


<?php

namespace SKE\Composer;

class Script
{
    public static function install()
    {
        $dirs = array(
            'resources/cache',
            'resources/log',
        );

        foreach($dirs as $dir) {
            if (!file_exists($dir))
                mkdir($dir, 0755, true);
            else
                chmod($dir, 0755);
        }

        $console = 'console';

        $code = <<<HEREDOC
#!/usr/bin/env php
<?php

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

\$app = new Silex\Application();

\$app['environment'] = 'dev';
require __DIR__.'/src/app.php';
\$app->boot();

\$console = require __DIR__.'/src/console.php';
\$console->run();
HEREDOC;

        if (!file_exists($console)){
            $fileinfo = new \SplFileInfo($console);
            $f = $fileinfo->openFile('w');
            $f->fwrite($code);
            $fileinfo = null;
            $f= null;
        }

        if (file_exists($console)){
            chmod($console, 0500);
        }
    }
}

<?php

namespace SKE\Composer;

class Script
{
    public static function install()
    {
        $dirs = array(
            'resources/cache',
            'resources/log',
            'tmp',
        );

        foreach($dirs as $dir) {
            if (!file_exists($dir))
                mkdir($dir, 0755, true);
            else
                chmod($dir, 0755);
        }

        $console = 'console';

        $code = <<<HEREDOC
#!/usr/bin/env php
<?php

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

\$app = new Silex\Application();

\$app['environment'] = 'dev';
require __DIR__.'/src/app.php';
\$app->boot();

\$console = require __DIR__.'/src/console.php';
\$console->run();
HEREDOC;

        if (!file_exists($console)){
            $fileinfo = new \SplFileInfo($console);
            $f = $fileinfo->openFile('w');
            $f->fwrite($code);
            $fileinfo = null;
            $f= null;
        }

        if (file_exists($console)){
            chmod($console, 0500);
        }
    }
}

Update now creates tmp git ignored dir

Update now creates tmp git ignored dir


<?php namespace Pingpong\Themes;

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

class Finder {

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

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

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

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

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

        return $themes;
    }

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

}

<?php namespace Pingpong\Themes;

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

class Finder {

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

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

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

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

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

        return $themes;
    }

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

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

        return $attributes;
    }

}

Add path to theme attributes

Add path to theme attributes


<?php
namespace GMO\Common\Web\Twig;

use Silex\Application;
use Silex\ServiceProviderInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class TwigResponseServiceProvider implements ServiceProviderInterface, EventSubscriberInterface {

	public function onResponse(FilterResponseEvent $event) {
		$response = $event->getResponse();
		if (!$response instanceof TwigResponse) {
			return;
		}
		/** @var \Twig_Environment $twig */
		$twig = $this->app['twig'];
		$content = $twig->render($response->getTemplate(), $response->getVariables()->toArray());
		$newResponse = new Response($content, $response->getStatusCode(), $response->headers->all());
		$event->setResponse($newResponse);
	}

	public function register(Application $app) {
		$this->app = $app;
	}

	public function boot(Application $app) {
		$app['dispatcher']->addSubscriber($this);
	}

	/** @inheritdoc */
	public static function getSubscribedEvents() {
		return array(
			KernelEvents::RESPONSE => array('onResponse', -100),
		);
	}

	/** @var Application */
	protected $app;
}

<?php
namespace GMO\Common\Web\Twig;

use Silex\Application;
use Silex\ServiceProviderInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class TwigResponseServiceProvider implements ServiceProviderInterface, EventSubscriberInterface {

	public function onResponse(FilterResponseEvent $event) {
		$response = $event->getResponse();
		if (!$response instanceof TwigResponse) {
			return;
		}
		/** @var \Twig_Environment $twig */
		$twig = $this->app['twig'];
		$content = $twig->render($response->getTemplate(), $response->getVariables()->toArray());
		$newResponse = new Response($content, $response->getStatusCode());
		$newResponse->headers = $response->headers;
		$event->setResponse($newResponse);
	}

	public function register(Application $app) {
		$this->app = $app;
	}

	public function boot(Application $app) {
		$app['dispatcher']->addSubscriber($this);
	}

	/** @inheritdoc */
	public static function getSubscribedEvents() {
		return array(
			KernelEvents::RESPONSE => array('onResponse', -100),
		);
	}

	/** @var Application */
	protected $app;
}

Fix headers when creating new response from twig response


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Autoload Files.
    |--------------------------------------------------------------------------
    |
    | You may add files which you want pine annotations to autoload. Annotations
    | in these files will be valid for the Reader to parse. Feel free
    | to add as many files as you need.
    |
    */

    'autoload_files' => [
        // app_path('Annotations/FooAnnotation.php')
    ],

    /*
    |--------------------------------------------------------------------------
    | Autoload Namespaces
    |--------------------------------------------------------------------------
    |
    | You may add namespaces here which you want pine annotations to autoload.
    | Annotations in these namespaces will be valid for the Reader to
    | parse. Feel free to add as many files as you need.
    |
    */

    'autoload_namespaces' => [
        'App\Annotations' => app_path('Annotations'),
    ],
];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Autoload Files.
    |--------------------------------------------------------------------------
    |
    | You may add files which you want pine annotations to autoload. Annotations
    | in these files will be valid for the Reader to parse. Feel free
    | to add as many files as you need.
    |
    */

    'autoload_files' => [
        // app_path('Annotations/FooAnnotation.php')
    ],

    /*
    |--------------------------------------------------------------------------
    | Autoload Namespaces
    |--------------------------------------------------------------------------
    |
    | You may add namespaces here which you want pine annotations to autoload.
    | Annotations in these namespaces will be valid for the Reader to
    | parse. Feel free to add as many files as you need.
    |
    */

    'autoload_namespaces' => [
        // 'App\Annotations' => app_path('Annotations'),
    ],
];

Fix finder does not exist directory

Fix finder does not exist directory


<?php

namespace Purethink\CMSBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Purethink\CoreBundle\Entity\Media;

/**
 * @ORM\Table()
 * @ORM\Entity
 */
class ComponentHasFile extends ComponentHasValue
{
    /**
     * @var Media
     *
     * @ORM\ManyToOne(targetEntity="Purethink\CoreBundle\Entity\Media", cascade={"persist"}, fetch="EAGER")
     * @ORM\JoinColumn(nullable=true)
     */
    private $file;

    public function setContent($content)
    {
        $this->setFile($content);

        return $this;
    }

    public function getContent()
    {
        return $this->getFile();
    }

    public function getStringContent()
    {
        if ($this->getContent()) {
            return $this->getContent();
        } else {
            return '';
        }
    }

    /**
     * Set file
     *
     * @param Media $file
     * @return ComponentHasFile
     */
    public function setFile(Media $file = null)
    {
        $this->file = $file;

        return $this;
    }

    /**
     * Get file
     *
     * @return Media
     */
    public function getFile()
    {
        return $this->file;
    }
}

<?php

namespace Purethink\CMSBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Purethink\CoreBundle\Entity\Media;

/**
 * @ORM\Table()
 * @ORM\Entity
 */
class ComponentHasFile extends ComponentHasValue
{
    /**
     * @var Media
     *
     * @ORM\ManyToOne(targetEntity="Purethink\CoreBundle\Entity\Media", cascade={"persist"}, fetch="EAGER")
     * @ORM\JoinColumn(nullable=true, onDelete="SET NULL")
     */
    private $file;

    public function setContent($content)
    {
        $this->setFile($content);

        return $this;
    }

    public function getContent()
    {
        return $this->getFile();
    }

    public function getStringContent()
    {
        if ($this->getContent()) {
            return $this->getContent();
        } else {
            return '';
        }
    }

    /**
     * Set file
     *
     * @param Media $file
     * @return ComponentHasFile
     */
    public function setFile(Media $file = null)
    {
        $this->file = $file;

        return $this;
    }

    /**
     * Get file
     *
     * @return Media
     */
    public function getFile()
    {
        return $this->file;
    }
}

Fix event after remove file

Fix event after remove file


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Auth;
use DB;

class DashboardController extends Controller {
    public function __invoke() {
        $user = Auth::user();

        $totalSpendings = $user
            ->spendings()
            ->whereRaw('MONTH(happened_on) = ?', [date('m')])
            ->sum('amount');

        $recentSpendings = $user
            ->spendings()
            ->orderBy('created_at', 'DESC')
            ->limit(3)
            ->get();

        $mostExpensiveTags = DB::select('
            SELECT
                tags.name AS name,
                SUM(spendings.amount) AS amount
            FROM
                tags
            LEFT OUTER JOIN
                spendings ON tags.id = spendings.tag_id
            WHERE
                tags.user_id = ?
                AND MONTH(happened_on) = ?
            GROUP BY
                tags.id
            HAVING
                SUM(spendings.amount) > 0
            ORDER BY
                SUM(spendings.amount) DESC
            LIMIT 3;
        ', [$user->id, date('m')]);

        return view('dashboard', [
            'currency' => $user->currency,

            'month' => date('n'),

            'totalSpendings' => $totalSpendings,

            'recentSpendings' => $recentSpendings,
            'mostExpensiveTags' => $mostExpensiveTags,

            'earningsCount' => $user->earnings->count(),
            'spendingsCount' => $user->spendings->count()
        ]);
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Auth;
use DB;

class DashboardController extends Controller {
    public function __invoke() {
        $user = Auth::user();

        $space_id = session('space')->id;

        $totalSpendings = $user
            ->spendings()
            ->whereRaw('MONTH(happened_on) = ?', [date('m')])
            ->sum('amount');

        $recentSpendings = $user
            ->spendings()
            ->orderBy('created_at', 'DESC')
            ->limit(3)
            ->get();

        $mostExpensiveTags = DB::select('
            SELECT
                tags.name AS name,
                SUM(spendings.amount) AS amount
            FROM
                tags
            LEFT OUTER JOIN
                spendings ON tags.id = spendings.tag_id
            WHERE
                tags.space_id = ?
                AND MONTH(happened_on) = ?
            GROUP BY
                tags.id
            HAVING
                SUM(spendings.amount) > 0
            ORDER BY
                SUM(spendings.amount) DESC
            LIMIT 3;
        ', [$space_id, date('m')]);

        return view('dashboard', [
            'currency' => $user->currency,

            'month' => date('n'),

            'totalSpendings' => $totalSpendings,

            'recentSpendings' => $recentSpendings,
            'mostExpensiveTags' => $mostExpensiveTags,

            'earningsCount' => $user->earnings->count(),
            'spendingsCount' => $user->spendings->count()
        ]);
    }
}

Update query for selecting most-expensive tags on dashboard to query by space_id instead of user_id


<?php
namespace Phortress;

class EnvironmentTest extends \PHPUnit_Framework_TestCase {
	public function testCanFindFunction() {

	}
}

<?php
namespace Phortress;

class EnvironmentTest extends \PHPUnit_Framework_TestCase {
	public function testCanFindFunction() {
		$file = realpath(__DIR__ . '/Fixture/environment_test.php');
		$program = loadGlassBoxProgram($file);

		$this->assertTrue($program->environment->resolveFunction('a')
			->environment->getParent() instanceof GlobalEnvironment);
	}
}

Test defining functions in the global scope.


<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2017, 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\Imagine\Cache\Resolver;

use Liip\ImagineBundle\Imagine\Cache\Resolver\WebPathResolver;

/**
 * Imagine cache resolver
 */
class Resolver extends WebPathResolver
{
    /**
     * {@inheritdoc}
     */
    protected function getFileUrl($path, $filter)
    {
        return implode(DIRECTORY_SEPARATOR, [$this->cachePrefix, $filter, preg_replace('/.*\//', '', $path)]);
    }
}

<?php
/**
 * @author    Igor Nikolaev <igor.sv.n@gmail.com>
 * @copyright Copyright (c) 2017, 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\Imagine\Cache\Resolver;

use Liip\ImagineBundle\Imagine\Cache\Resolver\WebPathResolver;

/**
 * Imagine cache resolver
 */
class Resolver extends WebPathResolver
{
    /**
     * {@inheritdoc}
     */
    protected function getFileUrl($path, $filter)
    {
        return implode(DIRECTORY_SEPARATOR, [$this->cachePrefix, str_replace('_', '/', $filter), preg_replace('/.*\//', '', $path)]);
    }
}

Implement custom Imagine cache resolver.


<?php

class ClientTest extends PHPUnit_Framework_TestCase
{

    public function testIsThereAnySyntaxError()
    {
        $var = new Rentlio\Api\Client("some api key");
        $this->assertTrue(is_object($var));
        unset($var);
    }

    public function testSetBaseUrl()
    {
        $client = new Rentlio\Api\Client("some api key");
        $this->assertTrue(is_object($client->setBaseUrl("https://api.rentl.io/v2")));
        unset($var);
    }
}

<?php

class ClientTest extends PHPUnit_Framework_TestCase
{

    public function testIsThereAnySyntaxError()
    {
        $var = new Rentlio\Api\Client("some api key");
        $this->assertTrue(is_object($var));
        unset($var);
    }

    public function testSetBaseUrl()
    {
        $client = new Rentlio\Api\Client("some api key");
        $this->assertTrue(is_object($client->setBaseUrl("https://api.rentl.io/v2")));
        unset($client);
    }

    public function testGetMyData() {
        $client = new Rentlio\Api\Client("04b028b0ac3b4e5882a0085cba36415f");
        $request = new Rentlio\Api\Request\GetMyDataRequest();
        $response = $client->send($request);
        var_dump(json_decode($response->getBody()->getContents()));
    }
}

Add testGetMyData for testing GetMyData request


<?php
namespace Nubs\Vectorix;

use PHPUnit_Framework_TestCase;

/**
 * @coversDefaultClass \Nubs\Vectorix\Vector
 */
class VectorTest extends PHPUnit_Framework_TestCase
{
    /**
     * Verify that getComponents returns the same components the vector was constructed with.
     *
     * In particular, this makes sure that the keys are left alone.
     *
     * @test
     * @covers ::__construct
     * @covers ::components
     */
    public function componentsMaintainStructure()
    {
        $components = array(5, 2.4, 'z' => 1.773);
        $vector = new Vector($components);

        $this->assertSame($components, $vector->components());
    }

    /**
     * Verify that the dimension of the vector is correct.
     *
     * @test
     * @covers ::dimension
     */
    public function dimensionIsCorrect()
    {
        $vector = new Vector(array(1, 0, 0));
        $this->assertSame(3, $vector->dimension());
    }

    /**
     * Verify that the length of the vector is correct.
     *
     * @test
     * @covers ::length
     */
    public function lengthIsCorrect()
    {
        $vector = new Vector(array(3, 4));
        $this->assertEquals(5.0, $vector->length(), '', 1e-10);
    }
}

<?php
namespace Nubs\Vectorix;

use PHPUnit_Framework_TestCase;

/**
 * @coversDefaultClass \Nubs\Vectorix\Vector
 */
class VectorTest extends PHPUnit_Framework_TestCase
{
    /**
     * Verify that getComponents returns the same components the vector was constructed with.
     *
     * In particular, this makes sure that the keys are left alone.
     *
     * @test
     * @covers ::__construct
     * @covers ::components
     */
    public function componentsMaintainStructure()
    {
        $components = array(5, 2.4, 'z' => 1.773);
        $vector = new Vector($components);

        $this->assertSame($components, $vector->components());
    }

    /**
     * Verify that the dimension of the vector is correct.
     *
     * @test
     * @uses \Nubs\Vectorix\Vector::__construct
     * @covers ::dimension
     */
    public function dimensionIsCorrect()
    {
        $vector = new Vector(array(1, 0, 0));
        $this->assertSame(3, $vector->dimension());
    }

    /**
     * Verify that the length of the vector is correct.
     *
     * @test
     * @uses \Nubs\Vectorix\Vector::__construct
     * @uses \Nubs\Vectorix\Vector::components
     * @covers ::length
     */
    public function lengthIsCorrect()
    {
        $vector = new Vector(array(3, 4));
        $this->assertEquals(5.0, $vector->length(), '', 1e-10);
    }
}

Add @uses tags for --strict mode.

Add @uses tags for --strict mode.

Whoops missed these!

Unfortunately, I had to specify the full class name in these uses tags.


<?php

namespace WhichBrowser\Data;

Manufacturers::$GENERIC = [
    'LG Electronics'                            => 'LG',
    'LGE'                                       => 'LG',
    'TOSHIBA'                                   => 'Toshiba',
    'SAMSUNG'                                   => 'Samsung',
    'SHARP'                                     => 'Sharp',
    'SONY'                                      => 'Sony',
];

Manufacturers::$TELEVISION = [
    'BANGOLUFSEN'                               => 'Bang & Olufsen',
    'CHANGHONG'                                 => 'Changhong',
    'HYUNDAI'                                   => 'Hyundai',
    'inverto'                                   => 'Inverto',
    'LOEWE'                                     => 'Loewe',
    'MEDION'                                    => 'Medion',
    'Sagemcom_Broadband_SAS'                    => 'Sagemcom',
    'SERAPHIC'                                  => 'Seraphic',
    'selevision'                                => 'Selevision',
    'smart'                                     => 'Smart',
    'Sky_worth'                                 => 'Skyworth',
    'TELEFUNKEN'                                => 'Telefunken',
    'THOM'                                      => 'Thomson',
    'THOMSON'                                   => 'Thomson',
    'tv2n'                                      => 'TV2N',
    'VESTEL'                                    => 'Vestel'
];

<?php

namespace WhichBrowser\Data;

Manufacturers::$GENERIC = [
    'LG Electronics'                            => 'LG',
    'LGE'                                       => 'LG',
    'TOSHIBA'                                   => 'Toshiba',
    'SAMSUNG'                                   => 'Samsung',
    'SHARP'                                     => 'Sharp',
    'SONY'                                      => 'Sony',
];

Manufacturers::$TELEVISION = [
    'BANGOLUFSEN'                               => 'Bang & Olufsen',
    'CHANGHONG'                                 => 'Changhong',
    'changhong'                                 => 'Changhong',
    'HYUNDAI'                                   => 'Hyundai',
    'inverto'                                   => 'Inverto',
    'LOEWE'                                     => 'Loewe',
    'MEDION'                                    => 'Medion',
    'Sagemcom_Broadband_SAS'                    => 'Sagemcom',
    'SERAPHIC'                                  => 'Seraphic',
    'selevision'                                => 'Selevision',
    'smart'                                     => 'Smart',
    'Sky_worth'                                 => 'Skyworth',
    'TELEFUNKEN'                                => 'Telefunken',
    'THOM'                                      => 'Thomson',
    'THOMSON'                                   => 'Thomson',
    'tv2n'                                      => 'TV2N',
    'VESTEL'                                    => 'Vestel'
];

Add Changhong to list of manufacturers

Add Changhong to list of manufacturers


<?php

include_once 'header.php';
include_once 'database.php';

$_POST[ 'speaker' ] =  $_SESSION[ 'user' ];

$res = insertIntoTable( 'aws_requests'
        , array( 'speaker', 'title', 'abstract', 'supervisor_1', 'supervisor_2'
        , 'tcm_member_1', 'tcm_member_2', 'tcm_member_3', 'tcm_member_4'
        , 'date', 'time'
    ) , $_POST
    );

if( $res )
{
    echo printInfo( 'Successfully created a request to edit AWS details ' );
    goToPage( 'user_aws.php', 1 );
    exit;
}
else
{
    echo minionEmbarrassed( 'I could not create a request to edit your AWS' );
}

echo goBackToPageLink( 'user_aws.php', 'Go back' );

?>

<?php

include_once 'header.php';
include_once 'database.php';

$_POST[ 'speaker' ] =  $_SESSION[ 'user' ];

$res = insertIntoTable( 'aws_requests'
        , array( 'speaker', 'title', 'abstract', 'supervisor_1', 'supervisor_2'
        , 'tcm_member_1', 'tcm_member_2', 'tcm_member_3', 'tcm_member_4'
        , 'date', 'time' , 'is_presynopsis_seminar'
    ) , $_POST
    );

if( $res )
{
    echo printInfo( 'Successfully created a request to edit AWS details ' );
    goToPage( 'user_aws.php', 1 );
    exit;
}
else
{
    echo minionEmbarrassed( 'I could not create a request to edit your AWS' );
}

echo goBackToPageLink( 'user_aws.php', 'Go back' );

?>

Make sure user can also change is_presynopsis_seminar.


<?php

namespace Acd;

/**
* Http class
* @author Acidvertigo MIT Licence
*/
class Http
{

    /**
     * Check HTTP version
     * @return string
     */
    public function protocol()
    {
    return $_SERVER['SERVER_PROTOCOL'];
    }

    /**
     * Check if communication is on SSL or not
     * @return bool true on HTTPS
     */
    public function isSsl()
    {
    return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? true : false;
    }

    /**
     * @param string $method HTTP method
     * @return bool true if the mothod is safe
     */
    public function isSafeMethod($method)
    {
        $safeMethods = ['HEAD', 'GET', 'OPTIONS', 'TRACE'];
        return isset($safeMethods[$method]);
    }

    /**
     * @param string $method HTTP method
     * @return bool true if the method is idempotent
     */
    public function isIdempotentMethod($method)
    {
        // Though it is possible to be idempotent, POST
        // is not guarunteed to be, and more often than
        // not, it is not.
        $idempotentMethods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'PUT', 'TRACE'];
        return isset($idempotentMethods[$method]);
    }
}

<?php

namespace Acd;

/**
* Http class
* @author Acidvertigo MIT Licence
*/
class Http
{

    /**
     * Check HTTP version
     * @return string
     */
    public function protocol()
    {
      return filter_input(INPUT_SERVER,'SERVER_PROTOCOL');
    }

    /**
     * Check if communication is on SSL or not
     * @return bool true on HTTPS
     */
    public function isSsl()
    {
    return (!empty(filter_input(INPUT_SERVER,'HTTPS')) && filter_input(INPUT_SERVER,'HTTPS') !== 'off' || filter_input(INPUT_SERVER,'SERVER_PORT') == 443) ? TRUE : FALSE;
    }

    /**
     * @param string $method HTTP method
     * @return bool true if the mothod is safe
     */
    public function isSafeMethod($method)
    {
        $safeMethods = ['HEAD', 'GET', 'OPTIONS', 'TRACE'];
        return isset($safeMethods[$method]);
    }

    /**
     * @param string $method HTTP method
     * @return bool true if the method is idempotent
     */
    public function isIdempotentMethod($method)
    {
        // Though it is possible to be idempotent, POST
        // is not guarunteed to be, and more often than
        // not, it is not.
        $idempotentMethods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'PUT', 'TRACE'];
        return isset($idempotentMethods[$method]);
    }
}

Add filter input on server var

Add filter input on server var


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Password Reminder Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines are the default lines which match reasons
    | that are given by the password broker for a password update attempt
    | has failed, such as for an invalid token or invalid new password.
    |
    */

    'password' => 'Las contraseñas deben coincidir y contener al menos 6 caracteres',
    'reset'    => '¡Tu contraseña ha sido restablecida!',
    'sent'     => '¡Recordatorio de contraseña enviado!',
    'token'    => 'El token de recuperación de contraseña es inválido.',
    'user'     => 'No podemos encontrar ningún usuario con ese correo electrónico.',

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Password Reminder Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines are the default lines which match reasons
    | that are given by the password broker for a password update attempt
    | has failed, such as for an invalid token or invalid new password.
    |
    */

    'password' => 'Las contraseñas deben coincidir y contener al menos 6 caracteres',
    'reset'    => '¡Tu contraseña ha sido restablecida!',
    'sent'     => '¡Te hemos enviado por correo el enlace para restablecer tu contraseña!',
    'token'    => 'El token de recuperación de contraseña es inválido.',
    'user'     => 'No podemos encontrar ningún usuario con ese correo electrónico.',

];

Change the spanish password reminder sent language line for a more readable one.


<?php

require_once __DIR__.'/../vendor/.composer/autoload.php';
$app = require __DIR__.'/../src/app.php';
require __DIR__.'/../src/controllers.php';
$app->run();

<?php

require_once __DIR__.'/../vendor/autoload.php';
$app = require __DIR__.'/../src/app.php';
require __DIR__.'/../src/controllers.php';
$app->run();

Use the new autoload.php path

Use the new autoload.php path


<?php
require 'init.php';

ComPHPartment\ComPHPartment::$redirectURI = 'http://comphpartment/dashboard.php';

$comPHPartment->authenticate();
$_SESSION['token'] = $comPHPartment->token;

require 'auth.php';

<?php
require 'init.php';

ComPHPartment\ComPHPartment::$redirectURI = 'http://' . $_SERVER['SERVER_NAME'] . '/dashboard.php';

$comPHPartment->authenticate();
$_SESSION['token'] = $comPHPartment->token;

require 'auth.php';

Change hostname for servername variable

Change hostname for servername variable


<?php
/*
 * This file is part of the CLIFramework package.
 *
 * (c) Yo-An Lin <cornelius.howl@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */
namespace CLIFramework;
use ReflectionClass;

class Utils
{

    /**
     * translate command name to class name
     *
     * so something like:   to-list will be ToListCommand
     *
     * */
    public static function translateCommandClassName($command)
    {
        $args = explode('-',$command);
        foreach($args as & $a)
            $a = ucfirst($a);
        $subclass = join('',$args) . 'Command';

        return $subclass;
    }

    public static function getClassPath($class, $baseDir)
    {
        $refclass = new ReflectionClass($class);
        if ($path = $refclass->getFilename()) {
            return str_replace(
                rtrim(realpath($baseDir),DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR,
                '',
                $path);
        }
        return null;
    }

}

<?php
/*
 * This file is part of the CLIFramework package.
 *
 * (c) Yo-An Lin <cornelius.howl@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */
namespace CLIFramework;
use ReflectionClass;

class Utils
{

    /**
     * translate command name to class name
     *
     * so something like:   to-list will be ToListCommand
     *
     * */
    public static function translateCommandClassName($command)
    {
        $args = explode('-',$command);
        foreach($args as & $a)
            $a = ucfirst($a);
        $subclass = join('',$args) . 'Command';

        return $subclass;
    }

    public static function getClassPath($class, $baseDir = null)
    {
        $refclass = new ReflectionClass($class);
        $path = $refclass->getFilename();
        if ($path && $baseDir) {
            return str_replace(
                rtrim(realpath($baseDir),DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR,
                '',
                $path);
        }
        return $path;
    }

}

Allow empty baseDir for getClassPath

Allow empty baseDir for getClassPath


<?php

namespace Platformsh\Cli\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class WebCommand extends UrlCommandBase
{

    protected function configure()
    {
        parent::configure();
        $this
            ->setName('web')
            ->setDescription('Open the Web UI');
        $this->addProjectOption()
             ->addEnvironmentOption();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Attempt to select the appropriate project and environment.
        try {
            $this->validateInput($input);
        } catch (\Exception $e) {
            // Ignore errors.
        }

        if ($this->hasSelectedEnvironment()) {
            $url = $this->getSelectedEnvironment()->getUri();
        } elseif ($this->hasSelectedProject()) {
            $url = $this->getSelectedProject()->getLink('#ui');
        } else {
            $url = self::$config->get('service.accounts_url');
        }

        $this->openUrl($url, $input, $output);
    }
}

<?php

namespace Platformsh\Cli\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class WebCommand extends UrlCommandBase
{

    protected function configure()
    {
        parent::configure();
        $this
            ->setName('web')
            ->setDescription('Open the Web UI');
        $this->addProjectOption()
             ->addEnvironmentOption();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Attempt to select the appropriate project and environment.
        try {
            $this->validateInput($input);
        } catch (\Exception $e) {
            // Ignore errors.
        }

        $url = self::$config->get('service.accounts_url');
        if ($this->hasSelectedProject()) {
            $url = $this->getSelectedProject()->getLink('#ui');
            if ($this->hasSelectedEnvironment()) {
                $url .= '/environments/' . rawurlencode($this->getSelectedEnvironment()->id);
            }
        }

        $this->openUrl($url, $input, $output);
    }
}

Fix (again) environment URL in `web` command


<?php

namespace App\Transformers\Inbound\Library;

use App\Transformers\Datum;
use App\Transformers\Inbound\AbstractTransformer;

class Material extends AbstractTransformer
{

    protected function attachFrom( Datum $datum )
    {

        return [
            'creators' => collect( $datum->creators )->pluck('id'),
            'subjects' => collect( $datum->subjects )->pluck('id'),
        ];

    }

}

<?php

namespace App\Transformers\Inbound\Library;

use App\Transformers\Datum;
use App\Transformers\Inbound\AbstractTransformer;

class Material extends AbstractTransformer
{

    protected function getSync( Datum $datum )
    {

        return [
            'creators' => collect( $datum->creators )->pluck('id'),
            'subjects' => collect( $datum->subjects )->pluck('id'),
        ];

    }

}

Fix relation sync for library materials

Fix relation sync for library materials


<?php

use yii\helpers\Html;
use yii\bootstrap\Carousel;

/* @var $this yii\web\View */
/* @var $ticket common\models\Ticket */
/* @var $showTagMax int/boolean maximum number of tags to display*/

//Ticket Decoration Bar displays the Ticket decorations
if ($taglist = $ticket->tagNames) {

    echo Html::beginTag('div', ['class' => 'ticket-single-tags']);

    $tagArray = explode(',', $taglist);
    $tagCount = count($tagArray);
    $i = 1;
    foreach ($tagArray as $tag) {
        $carouselItems[] = [
            'content' => '',
            'caption' => "<small>$i/$tagCount</small> $tag",
        ];
        $i++;
    }

    echo Carousel::widget([
        'items' => $carouselItems,
        'controls' => false,
        'showIndicators' => false,
    ]);

    echo Html::endTag('div');

}

?>

<?php

use yii\helpers\Html;
use yii\bootstrap\Carousel;

/* @var $this yii\web\View */
/* @var $ticket common\models\Ticket */
/* @var $showTagMax int/boolean maximum number of tags to display*/

//Ticket Decoration Bar displays the Ticket decorations
if ($taglist = $ticket->tagNames) {

    echo Html::beginTag('div', ['class' => 'ticket-single-tags']);

    $tagArray = explode(',', $taglist);
    $tagCount = count($tagArray);
    $i = 1;
    foreach ($tagArray as $tag) {
        $carouselItems[] = [
            'content' => '',
            'caption' => "$tag - <small>($i/$tagCount)</small>",
        ];
        $i++;
    }

    echo Carousel::widget([
        'items' => $carouselItems,
        'controls' => false,
        'showIndicators' => false,
    ]);

    echo Html::endTag('div');

}

?>

Tag Display in single Ticket

Tag Display in single Ticket


<?php

function slack_get_user_by_email($email) {

    static $users;

    if (defined('SLACK_API_TOKEN')) {

        if (!$users) {
            // @todo cache users.list
            $slack      = new Slack(SLACK_API_TOKEN);
            $response   = $slack->call('users.list');

            if ($response['ok']) {
                $users = $response['members'];
            }
        }

        foreach ($users as $user) {
            if ($user['profile']['email'] == $email) {
                return $user;
            }
        }
    }
}

function slack_post_message($channel, $message) {
    $slack = new Slack(SLACK_API_TOKEN);

    $slack->call('chat.postMessage', array(
        'channel'       => $channel,
        'text'          => $message,
        'username'      => 'ActiveCollab',
        'as_user'       => FALSE,
        'icon_url'      => defined('ASSETS_URL') ? ASSETS_URL . '/images/system/default/application-branding/logo.40x40.png'  : '',
        'link_names'    => 1
    ));
}

<?php

function slack_get_user_by_email($email) {

    static $users;

    if (defined('SLACK_API_TOKEN')) {

        if (!$users) {
            // @todo cache users.list
            $slack      = new Slack(SLACK_API_TOKEN);
            $response   = $slack->call('users.list');

            if ($response['ok']) {
                $users = $response['members'];
            }
        }

        foreach ($users as $user) {
            if ($user['profile']['email'] == $email) {
                return $user;
            }
        }
    }
}

function slack_post_message($channel, $message) {
    $slack = new Slack(SLACK_API_TOKEN);

    $slack->call('chat.postMessage', array(
        'channel'       => $channel,
        'text'          => $message,
        'username'      => 'ActiveCollab',
        'as_user'       => FALSE,
        'icon_url'      => defined('ASSETS_URL') ? ASSETS_URL . '/images/system/default/application-branding/logo.80x80.png'  : '',
        'link_names'    => 1
    ));
}

Use bigger AC icon for mobile support

Use bigger AC icon for mobile support


<?php

namespace Luminary\Services\ApiQuery\Grouping;

use Illuminate\Database\Eloquent\Model;
use Luminary\Services\ApiQuery\Eloquent\BaseScope;

class Scope extends BaseScope
{
    /**
     * Apply to the Query Scope
     *
     * @param $builder
     * @param Model $model
     * @return void
     */
    public function apply($builder, Model $model) :void
    {
        $this->builder = $builder;
        $this->model = $model;
        $group = $this->grouping();

        if(!empty($group)) {
            $builder->groupBy($group);
        }
    }

    /**
     * Get the query fields
     *
     * @return array
     */
    protected function grouping() :array
    {
        $resource = str_replace('_', '-', $this->resource());
        return $this->query()->grouping($resource);
    }
}

<?php

namespace Luminary\Services\ApiQuery\Grouping;

use Illuminate\Database\Eloquent\Model;
use Luminary\Services\ApiQuery\Eloquent\BaseScope;

class Scope extends BaseScope
{
    /**
     * Apply to the Query Scope
     *
     * @param $builder
     * @param Model $model
     * @return void
     */
    public function apply($builder, Model $model) :void
    {
        $this->builder = $builder;
        $this->model = $model;
        $group = $this->grouping();

        if(!empty($group)) {
            $builder->groupBy($group);
        }
    }

    /**
     * Get the query fields
     *
     * @return array
     */
    protected function grouping() :array
    {
        $resource = $this->resource();
        return $this->query()->grouping($resource);
    }
}

Fix resource check for grouping scope

Fix resource check for grouping scope


<?php
// This is global bootstrap for autoloading
$autoloader = require __DIR__.'/../vendor/autoload.php';
$autoloader->addClassMap([
    'Functional\CestAbstract' => __DIR__ . '/Functional/CestAbstract.php',
]);

\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$autoloader, 'loadClass']);

$GLOBALS['autoloader'] = $autoloader;

if (!function_exists('__')) {
    $translator = new \Gettext\Translator();
    $translator->register();
}

// Clear output directory
function rrmdir($dir)
{
    if (is_dir($dir)) {
        $objects = array_diff(scandir($dir, SCANDIR_SORT_NONE) ?: [], ['.', '..', '.gitignore']);
        foreach ($objects as $object) {
            if (is_dir($dir . '/' . $object)) {
                rrmdir($dir . '/' . $object);
            } else {
                unlink($dir . '/' . $object);
            }
        }
        reset($objects);
        @rmdir($dir);
    }
}

rrmdir(__DIR__ . '/_output');

<?php
// This is global bootstrap for autoloading
$autoloader = require __DIR__.'/../vendor/autoload.php';
$autoloader->addClassMap([
    'Functional\CestAbstract' => __DIR__ . '/Functional/CestAbstract.php',
]);

\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$autoloader, 'loadClass']);

$GLOBALS['autoloader'] = $autoloader;

if (!function_exists('__')) {
    \Gettext\TranslatorFunctions::register(new \Gettext\Translator());
}

// Clear output directory
function rrmdir($dir)
{
    if (is_dir($dir)) {
        $objects = array_diff(scandir($dir, SCANDIR_SORT_NONE) ?: [], ['.', '..', '.gitignore']);
        foreach ($objects as $object) {
            if (is_dir($dir . '/' . $object)) {
                rrmdir($dir . '/' . $object);
            } else {
                unlink($dir . '/' . $object);
            }
        }
        reset($objects);
        @rmdir($dir);
    }
}

rrmdir(__DIR__ . '/_output');

Fix test suite gettext handler.

Fix test suite gettext handler.


<?php

// Make sure we are called from index.php
if (!defined('SECURITY')) die('Hacking attempt');

// Check if the API is activated
$api->isActive();

// Check user token
$user_id = $api->checkAccess($user->checkApiKey($_REQUEST['api_key']), @$_REQUEST['id']);

// Output JSON format
$data = array(
	// coin info
	'currency' 				=> $config[currency],
	'coinname'				=> $config[gettingstarted][coinname],
	// coin algorithm info
	'cointarget' 			=> $config[cointarget],
	'coindiffchangetarget' 	=> $config[coindiffchangetarget],
	'algorithm' 			=> $config[algorithm],
	// stratum
	'stratumport'			=> $config[gettingstarted][stratumport],
	// payments
	'payout_system' 		=> $config[payout_system],
	'min_ap_threshold' 		=> $config[ap_threshold][min],
	'max_ap_threshold' 		=> $config[ap_threshold][max],
	'txfee' 				=> $config[txfee],
	'fees'					=> $config[fees],
);

echo $api->get_json($data);

// Supress master template
$supress_master = 1;
?>

<?php

// Make sure we are called from index.php
if (!defined('SECURITY')) die('Hacking attempt');

// Check if the API is activated
$api->isActive();

// Check user token
$user_id = $api->checkAccess($user->checkApiKey($_REQUEST['api_key']), @$_REQUEST['id']);

// Output JSON format
$data = array(
	// coin info
	'currency' 				=> $config[currency],
	'coinname'				=> $config[gettingstarted][coinname],
	// coin algorithm info
	'cointarget' 			=> $config[cointarget],
	'coindiffchangetarget' 	=> $config[coindiffchangetarget],
	'algorithm' 			=> $config[algorithm],
	// stratum
	'stratumport'			=> $config[gettingstarted][stratumport],
	// payments
	'payout_system' 		=> $config[payout_system],
	'confirmations' => $config['confirmations'],
	'min_ap_threshold' 		=> $config[ap_threshold][min],
	'max_ap_threshold' 		=> $config[ap_threshold][max],
	// backwards compatibility for old API calls
	'txfee' => $config['txfee_manual'],
	'txfee_manual' => $config['txfee_manual'],
	'txfee_auto' => $config['txfee_auto'],
	'fees'					=> $config[fees]
);

echo $api->get_json($data);

// Supress master template
$supress_master = 1;
?>

[BUG] Fix txfee API call with added support for old API calls
[ADD] txfee_auto to API Calls
[ADD] txfee_manual to API Calls
[ADD] confirmations to API Calls


<?php

/*
 * This file is part of the qandidate/symfony-json-request-transformer package.
 *
 * (c) Qandidate.com <opensource@qandidate.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Qandidate\Common\Symfony\HttpKernel\EventListener;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

/**
 * Transforms the body of a json request to POST parameters.
 */
class JsonRequestTransformerListener
{
    /**
     * @param GetResponseEvent $event
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();

        if (! $this->isJsonRequest($request)) {
            return;
        }

        if (! $this->transformJsonBody($request)) {
            $response = Response::create('Unable to parse request.', Response::HTTP_BAD_REQUEST);
            $event->setResponse($response);
        }
    }

    private function isJsonRequest(Request $request)
    {
        return 'json' === $request->getContentType();
    }

    private function transformJsonBody(Request $request)
    {
        $data = json_decode($request->getContent(), true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            return false;
        }

        if ($data === null) {
            return true;
        }

        $request->request->replace($data);

        return true;
    }
}

<?php

/*
 * This file is part of the qandidate/symfony-json-request-transformer package.
 *
 * (c) Qandidate.com <opensource@qandidate.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Qandidate\Common\Symfony\HttpKernel\EventListener;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

/**
 * Transforms the body of a json request to POST parameters.
 */
class JsonRequestTransformerListener
{
    /**
     * @param GetResponseEvent $event
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();

        if (! $this->isJsonRequest($request)) {
            return;
        }

        if (! $this->transformJsonBody($request)) {
            $response = Response::create('Unable to parse request.', 400);
            $event->setResponse($response);
        }
    }

    private function isJsonRequest(Request $request)
    {
        return 'json' === $request->getContentType();
    }

    private function transformJsonBody(Request $request)
    {
        $data = json_decode($request->getContent(), true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            return false;
        }

        if ($data === null) {
            return true;
        }

        $request->request->replace($data);

        return true;
    }
}

Remove Response::HTTP_BAD_REQUEST for symfony 2.3 compatibility


{{-- Block Type: Call To Action --}}

{{ $block->block_title }}

    {{ $block->block_body_html }}

      @if (Auth::guest())
        {{ link_to_route('registration.create', 'Start Application', null, ['class' => 'button -default']) }}
        {{ link_to_route('status', 'or continue an application') }}
      @else
        {{ link_to_route('status', 'Continue Application', null, ['class' => 'button -default']) }}
      @endif

{{-- Block Type: Call To Action --}}

{{ $block->block_title }}

    {{ $block->block_body_html }}

    @if($url === 'home')

        @if (Auth::guest())
          {{ link_to_route('registration.create', 'Start Application', null, ['class' => 'button -default']) }}
          {{ link_to_route('status', 'or continue an application') }}
        @else
          {{ link_to_route('status', 'Continue Application', null, ['class' => 'button -default']) }}
        @endif

    @endif

Update to ensure button logic only happens on homepage.


<?php
/**
 * Created by PhpStorm.
 * User: daniel
 * Date: 08.09.14
 * Time: 16:14
 */

namespace Cundd\PersistentObjectStore\Configuration;

/**
 * Class to read the configuration from config files
 *
 * @package Cundd\PersistentObjectStore\Configuration
 */
class ConfigurationReader {
	/**
	 * Reads the configuration from the configuration files
	 *
	 * @return array
	 */
	public function readConfigurationFiles() {
		$configuration = array_merge_recursive(
			$this->readConfigurationFile('/etc/pos')
		);
		if (isset($_SERVER['HOME']) && $_SERVER['HOME']) {
			$configuration = array_merge_recursive($configuration, $this->readConfigurationFile($_SERVER['HOME'] . '/.pos/config.json'));
		}
		$configuration = array_merge_recursive($configuration, $this->readConfigurationFile('.pos-config.json'));
		return $configuration;
	}

	/**
	 * Tries to read the given configuration file
	 *
	 * @param string $file
	 * @return array
	 */
	public function readConfigurationFile($file) {
		$configuration = array();
		if (file_exists($file) && is_readable($file)) {
			$configuration = json_decode(file_get_contents($file), TRUE);
		}
		return $configuration ? $configuration : array();
	}
}

<?php
/**
 * Created by PhpStorm.
 * User: daniel
 * Date: 08.09.14
 * Time: 16:14
 */

namespace Cundd\PersistentObjectStore\Configuration;

/**
 * Class to read the configuration from config files
 *
 * @package Cundd\PersistentObjectStore\Configuration
 */
class ConfigurationReader {
	/**
	 * Reads the configuration from the configuration files
	 *
	 * @return array
	 */
	public function readConfigurationFiles() {
		$configuration = array_merge_recursive(
			$this->readConfigurationFile('/etc/pos')
		);
		if (isset($_ENV['HOME']) && $_ENV['HOME']) {
			$configuration = array_merge_recursive($configuration, $this->readConfigurationFile($_ENV['HOME'] . '/.pos/config.json'));
		}
		$configuration = array_merge_recursive($configuration, $this->readConfigurationFile('.pos-config.json'));
		return $configuration;
	}

	/**
	 * Tries to read the given configuration file
	 *
	 * @param string $file
	 * @return array
	 */
	public function readConfigurationFile($file) {
		$configuration = array();
		if (file_exists($file) && is_readable($file)) {
			$configuration = json_decode(file_get_contents($file), TRUE);
		}
		return $configuration ? $configuration : array();
	}
}

Use $_ENV instead of $_SERVER

Use $_ENV instead of $_SERVER


<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}

<?php
umask('0022');

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}

Set file permissions for app.

Set file permissions for app.


<?php

include_once($BASE_DIR . 'database/models.php');

function getComments($comments) {
    global $smarty;
    $smarty->assign("comments", $comments);
    $smarty->display('models/comments.tpl');
}

class CommentsHandler {
    function post($modelId) { // TODO: xhr
        global $BASE_DIR;
        global $smarty;

        $memberId = getLoggedId();
        if (!$memberId) {
            http_response_code(403);
            return;
        }

        if (isset($_POST['content']) && strlen($_POST['content']) > 0)
            insertComment($memberId, $modelId, htmlspecialchars($_POST['content']));

        header('Location: ' . $_SERVER['HTTP_REFERER'] . '#tab_comments');
    }

    function delete($modelId, $commentId) {
        global $BASE_DIR;
        global $smarty;

        $comment = getComment($commentId);
        if($comment == null) {
            http_response_code(404);
            return;
        }
        if (getLoggedId() != $comment['idmember']) {
            http_response_code(403);
            return;
        }

        deleteComment($modelId, $commentId);
    }
}

<?php

include_once($BASE_DIR . 'database/models.php');

function getComments($comments) {
    global $smarty;
    $smarty->assign("comments", $comments);
    $smarty->display('models/comments.tpl');
}

class CommentsHandler {
    function post($modelId) { // TODO: xhr
        global $BASE_DIR;
        global $smarty;

        $memberId = getLoggedId();
        if (!$memberId) {
            http_response_code(403);
            return;
        }

        if (isset($_POST['content']) && strlen($_POST['content']) > 0)
            insertComment($memberId, $modelId, htmlspecialchars(stripslashes($_POST['content'])));

        header('Location: ' . $_SERVER['HTTP_REFERER'] . '#tab_comments');
    }

    function delete($modelId, $commentId) {
        global $BASE_DIR;
        global $smarty;

        $comment = getComment($commentId);
        if($comment == null) {
            http_response_code(404);
            return;
        }
        if (getLoggedId() != $comment['idmember']) {
            http_response_code(403);
            return;
        }

        deleteComment($modelId, $commentId);
    }
}

Add stripslashes to comment content

Add stripslashes to comment content

Closes #24


<?php

namespace BoomCMS\Core\Http\Middleware;

use Closure;
use BoomCMS\Core\Auth\Auth;

class DisableHttpCacheIfLoggedIn
{
    /**
     *
     * @var Auth
     */
    protected $auth;

    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if ($this->auth->isLoggedIn()) {
            $response->setCache(['private' => true]);
        }

        return $response;
    }

}

<?php

namespace BoomCMS\Core\Http\Middleware;

use Closure;
use BoomCMS\Core\Auth\Auth;

class DisableHttpCacheIfLoggedIn
{
    /**
     *
     * @var Auth
     */
    protected $auth;

    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if ($this->auth->isLoggedIn()) {
            $response->header('Cache-Control', 'no-cache, max-age=0, must-revalidate, no-store');
        }

        return $response;
    }

}

Disable cache properly when logged in. Prevents browser using cache for back button which breaks CSRF protection


<?php
use OCA\PasswordPolicy\Service;
use OCA\PasswordPolicy\Service\PasswordPolicyService;

\OCP\Util::addScript('passwordpolicy', 'user');
$tpl = new OCP\Template('passwordpolicy', 'user');

$ocConfig = \OC::$server->getConfig();
$service = new PasswordPolicyService($ocConfig,'passwordpolicy');

$minlength = $service->getAppValue('minlength');
$hasmixedcase = $service->getAppValue('hasmixedcase');
$hasnumbers = $service->getAppValue('hasnumbers');
$hasspecialchars = $service->getAppValue('hasspecialchars');
$specialcharslist = $service->getAppValue('specialcharslist');

if($hasmixedcase == "true")
{
	$tpl->assign('mixedcase',"Must contain UPPER and lower case characters.");
}
if($hasnumbers == "true")
{
	$tpl->assign('numbers',"Must contain numbers.");
}
if($hasspecialchars == "true")
{
	$tpl->assign('specialcharslist',"Must contain special characters: ".$specialcharslist);
}

$tpl->assign('minlength', $minlength);

return $tpl->fetchPage();

<?php
use OCA\PasswordPolicy\Service;
use OCA\PasswordPolicy\Service\PasswordPolicyService;

\OCP\Util::addScript('passwordpolicy', 'user');
$tpl = new OCP\Template('passwordpolicy', 'user');

$ocConfig = \OC::$server->getConfig();
$service = new PasswordPolicyService($ocConfig,'passwordpolicy');

$minlength = $service->getAppValue('minlength');
$hasmixedcase = $service->getAppValue('hasmixedcase');
$hasnumbers = $service->getAppValue('hasnumbers');
$hasspecialchars = $service->getAppValue('hasspecialchars');
$specialcharslist = $service->getAppValue('specialcharslist');

$tpl->assign('mixedcase',$hasmixedcase);
$tpl->assign('numbers',$hasnumbers);
$tpl->assign('specialchars',$hasspecialchars);
$tpl->assign('specialcharslist',$specialcharslist);
$tpl->assign('minlength', $minlength);

return $tpl->fetchPage();

Move text parts to template

Move text parts to template


<?php

namespace BisonLab\SugarCrmBundle\Service;

/*
 * Just a service object for the sugar7crm-wrapper class.
 */

class SugarWrapper
{
    private $sugar;
    private $options;

    public function __construct($base_url, $username, $password, $platform = "sugar-wrapper")
    {
        if (!preg_match("/rest\/v\d\d/", $base_url)) {
            $base_url .= '/rest/v11_5/';
        }
        $this->options = [
            'base_url' => $base_url,
            'username' => $username,
            'password' => $password,
            'platform' => $platform
        ];
    }

    public function getSugar()
    {
        if (!$this->sugar)
            $this->connectSugar();
        return $this->sugar;
    }

    public function connectSugar()
    {
        $this->sugar = new \Spinegar\SugarRestClient\Rest();
        $this->sugar
            ->setUrl($this->options['base_url'])
            ->setUsername($this->options['username'])
            ->setPassword($this->options['password'])
            ->setPlatform($this->options['platform'])
            ;
    }
}

<?php

namespace BisonLab\SugarCrmBundle\Service;

/*
 * Just a service object for the sugar7crm-wrapper class.
 */

class SugarWrapper
{
    private $sugar;
    private $options;

    public function __construct($base_url, $username, $password, $platform = "sugar-wrapper")
    {
        if (!preg_match("/rest\/v[\d_]+/", $base_url)) {
            $base_url .= '/rest/v11_5/';
        }
        $this->options = [
            'base_url' => $base_url,
            'username' => $username,
            'password' => $password,
            'platform' => $platform
        ];
    }

    public function getSugar()
    {
        if (!$this->sugar)
            $this->connectSugar();
        return $this->sugar;
    }

    public function connectSugar()
    {
        $this->sugar = new \Spinegar\SugarRestClient\Rest();
        $this->sugar
            ->setUrl($this->options['base_url'])
            ->setUsername($this->options['username'])
            ->setPassword($this->options['password'])
            ->setPlatform($this->options['platform'])
            ;
    }
}

Handle sugar rest api version properly.

Handle sugar rest api version properly.


<?php

require_once("tokenstrategy.php");

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

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

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

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

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

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

}

<?php

require_once("tokenstrategy.php");

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

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

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

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

	public function setNextAuthToken($token)
	{
		$expiry = Configuration::getInstance()->getConfig("cookie_expiry_time");
		$secure = (bool)Configuration::getInstance()->getConfig("require_ssl");
		if ($expiry == null)
		{
			throw new Exception("no cookie expiry time found in config file", E_NO_EXPIRY_TIME);
		}
		setcookie(
		          self::COOKIENAME,
		          $token,
		          time() + (int)$expiry,
		          $this->path,
		          '',	// domain - don't set.
		          $secure,
		          true	// HTTPOnly
		         );
	}

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

}

Make the Cookie TokenStrategy more strict.

Require SSL if this is configured, and always set httponly.


<?php

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

require __DIR__.'/config.php';

$app = new Silex\Application();

// use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;

$app->register(new Silex\Provider\SessionServiceProvider());
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
$app->register(new Silex\Provider\TranslationServiceProvider());
$app->register(new Silex\Provider\FormServiceProvider());
$app->register(new Silex\Provider\ValidatorServiceProvider());

// register providers
$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path'       	=> __DIR__.'/../views',
    'twig.class_path' 	=> __DIR__.'/../vendor/twig/lib',
    'twig.cache'		=> (!DEBUG_APP),  // disble caching when debugging
));

$app['debug'] = DEBUG_APP;

return $app;

<?php

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

require __DIR__.'/config.php';

$app = new Silex\Application();

// use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;

$app->register(new Silex\Provider\SessionServiceProvider());
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
$app->register(new Silex\Provider\TranslationServiceProvider());
$app->register(new Silex\Provider\FormServiceProvider());
$app->register(new Silex\Provider\ValidatorServiceProvider());

// register providers
$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path'       	=> __DIR__.'/../src/views',
    'twig.class_path' 	=> __DIR__.'/../vendor/twig/lib',
    'twig.cache'		=> (!DEBUG_APP),  // disble caching when debugging
));

$app['debug'] = DEBUG_APP;

return $app;

Move views folder into src

Move views folder into src


<?php

namespace HGG\Pardot\ResponseHandler;

use HGG\Pardot\Exception\RuntimeException;
use HGG\Pardot\Exception\AuthenticationErrorException;

/**
 * JsonResponseHandler
 *
 * @author Henning Glatter-Götz <henning@glatter-gotz.com>
 */
class JsonResponseHandler extends AbstractResponseHandler
{
    /**
     * parse
     *
     * @param mixed $document
     * @param mixed $object
     *
     * @access protected
     * @return void
     */
    protected function parse($document, $object)
    {
        if ('ok' !== $document['@attributes']['stat']) {
            $errorCode = $document['@attributes']['err_code'];
            $errorMessage = $document['err'];

            if (15 == $errorCode) {
                throw new AuthenticationErrorException($errorMessage, $errorCode);
            } else {
                throw new RuntimeException($errorMessage, $errorCode);
            }
        } else {
            if (array_key_exists('result', $document)) {
                $this->resultCount = $document['result']['total_results'];
                $this->result = (0 === $this->resultCount) ? array() : $document['result'][$object];
            } elseif (array_key_exists($object, $document)) {
                $this->resultCount = 1;
                $this->result = $document[$object];
            } elseif (array_key_exists('api_key', $document)) {
                $this->resultCount = 0;
                $this->result = $document['api_key'];
            } else {
                throw new RuntimeException('Unknown response format '.json_encode($document));
            }
        }
    }
}

<?php

namespace HGG\Pardot\ResponseHandler;

use HGG\Pardot\Exception\RuntimeException;
use HGG\Pardot\Exception\AuthenticationErrorException;

/**
 * JsonResponseHandler
 *
 * @author Henning Glatter-Götz <henning@glatter-gotz.com>
 */
class JsonResponseHandler extends AbstractResponseHandler
{
    /**
     * parse
     *
     * @param mixed $document
     * @param mixed $object
     *
     * @access protected
     * @return void
     */
    protected function parse($document, $object)
    {
        if ('ok' !== $document['@attributes']['stat']) {
            $errorCode = $document['@attributes']['err_code'];
            $errorMessage = $document['err'];

            if (in_array($errorCode, array(1, 15))) {
                throw new AuthenticationErrorException($errorMessage, $errorCode);
            } else {
                throw new RuntimeException($errorMessage, $errorCode);
            }
        } else {
            if (array_key_exists('result', $document)) {
                $this->resultCount = $document['result']['total_results'];
                $this->result = (0 === $this->resultCount) ? array() : $document['result'][$object];
            } elseif (array_key_exists($object, $document)) {
                $this->resultCount = 1;
                $this->result = $document[$object];
            } elseif (array_key_exists('api_key', $document)) {
                $this->resultCount = 0;
                $this->result = $document['api_key'];
            } else {
                throw new RuntimeException('Unknown response format '.json_encode($document));
            }
        }
    }
}

Add error code 1 to handling of Auth errors


<?php
/*
 * This file is part of the Patternseek ComponentView library.
 *
 * (c) 2014 Tolan Blundell <tolan@patternseek.net>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PatternSeek\ComponentView;

/**
 * Class ViewComponentResponse
 */
class Response
{

    /**
     * Currently one of "redirect" or a valid MIME type.
     * @var string
     */
    public $type;
    /**
     * @var string
     */
    public $content;

    /**
     * @param $type
     * @param $content
     * @param null $responseCode
     */
    function __construct( $type, $content, $responseCode = null )
    {
        $this->type = $type;
        $this->content = $content;

        // Response code defaults
        if( null == $responseCode ){
            if( $type == "redirect" ){
                $responseCode = 301;
            }else{
                $responseCode = 200;
            }
        }
        $this->responseCode = $responseCode;
    }
}

<?php
/*
 * This file is part of the Patternseek ComponentView library.
 *
 * (c) 2014 Tolan Blundell <tolan@patternseek.net>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace PatternSeek\ComponentView;

/**
 * Class ViewComponentResponse
 */
class Response
{

    /**
     * Currently one of "redirect" or a valid MIME type.
     * @var string
     */
    public $type;
    /**
     * @var string
     */
    public $content;

    /**
     * @param $type
     * @param $content
     * @param null $responseCode
     */
    function __construct( $type, $content, $responseCode = null )
    {
        $this->type = $type;
        $this->content = $content;

        // Response code defaults
        if( null == $responseCode ){
            if( $type == "redirect" ){
                $responseCode = 302;
            }else{
                $responseCode = 200;
            }
        }
        $this->responseCode = $responseCode;
    }
}

Fix default redirect code (now 302)

Fix default redirect code (now 302)


  <a class="read-more" href="<?php the_permalink() ?>">Read more about this topic
  <?php if (get_comments_number() != 0) { ?>
      - <a href="<?php comments_link() ?>" class="view-comments"><?php printf(_n('1 comment', '%1$s comments', get_comments_number(), 'roots'), number_format_i18n(get_comments_number())) ?>
    <?php } ?>

  <a class="read-more" href="<?php the_permalink() ?>">Read more about this topic
  <?php if (get_comments_number() != 0) { ?>
      - <a href="<?php comments_link() ?>" class="govuk-link"><?php printf(_n('1 comment', '%1$s comments', get_comments_number(), 'roots'), number_format_i18n(get_comments_number())) ?>
    <?php } ?>

Add classes to footer for sizing

Add classes to footer for sizing


<?php

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

namespace Symfony\Component\Security\Http;

final class SecurityEvents
{
    /**
     * The INTERACTIVE_LOGIN event occurs after a user is logged in
     * interactively for authentication based on http, cookies or X509.
     *
     * The event listener method receives a
     * Symfony\Component\Security\Http\Event\InteractiveLoginEvent instance.
     *
     * @Event
     *
     * @var string
     */
    const INTERACTIVE_LOGIN = 'security.interactive_login';

    /**
     * The SWITCH_USER event occurs before switch to another user and
     * before exit from an already switched user.
     *
     * The event listener method receives a
     * Symfony\Component\Security\Http\Event\SwitchUserEvent instance.
     *
     * @Event
     *
     * @var string
     */
    const SWITCH_USER = 'security.switch_user';
}

<?php

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

namespace Symfony\Component\Security\Http;

final class SecurityEvents
{
    /**
     * The INTERACTIVE_LOGIN event occurs after a user has actively logged
     * into your website. It is important to distinguish this action from
     * non-interactive authentication methods, such as:
     *   - authentication based on your session.
     *   - authentication using a HTTP basic or HTTP digest header.
     *
     * The event listener method receives a
     * Symfony\Component\Security\Http\Event\InteractiveLoginEvent instance.
     *
     * @Event
     *
     * @var string
     */
    const INTERACTIVE_LOGIN = 'security.interactive_login';

    /**
     * The SWITCH_USER event occurs before switch to another user and
     * before exit from an already switched user.
     *
     * The event listener method receives a
     * Symfony\Component\Security\Http\Event\SwitchUserEvent instance.
     *
     * @Event
     *
     * @var string
     */
    const SWITCH_USER = 'security.switch_user';
}

[Security] Fix security.interactive_login event const doc block


<?
namespace Concrete\Controller\SinglePage\Dashboard\Files;
use \Concrete\Core\Page\Controller\DashboardPageController;
use \Concrete\Controller\Search\Files as SearchFilesController;
use View;
use Loader;
class Search extends DashboardPageController {

	public function view() {
		$cnt = new SearchFilesController();
		$cnt->search();
		$this->set('searchController', $cnt);
		$result = Loader::helper('json')->encode($cnt->getSearchResultObject()->getJSONObject());
		$v = View::getInstance();
		$v->requireAsset('core/file-manager');
		$this->addFooterItem("<script type=\"text/javascript\">$(function() { $('div[data-search=files]').concreteFileManager({result: " . $result . "}); });</script>");
	}

}

<?
namespace Concrete\Controller\SinglePage\Dashboard\Files;
use \Concrete\Core\Page\Controller\DashboardPageController;
use \Concrete\Controller\Search\Files as SearchFilesController;
use View;
use Loader;
class Search extends DashboardPageController {

	public function view() {
		$cnt = new SearchFilesController();
		$cnt->search();
		$this->set('searchController', $cnt);
		$result = Loader::helper('json')->encode($cnt->getSearchResultObject()->getJSONObject());
		$v = View::getInstance();
        $v->requireAsset('core/file-manager');
        $v->requireAsset('core/imageeditor');
		$this->addFooterItem("<script type=\"text/javascript\">$(function() { $('div[data-search=files]').concreteFileManager({result: " . $result . "}); });</script>");
	}

}

Add imageeditor js and css to filemanager controller

Former-commit-id: 2d15f51f47d689c350a424ade827917f0b9036ef


<?php namespace Illuminate\Workbench;

class Starter {

	/**
	 * Load the workbench vendor auto-load files.
	 *
	 * @param  string  $path
	 * @param  Illuminate\Filesystem  $files
	 * @return void
	 */
	public static function start($path, $finder = null, $files = null)
	{
		$finder = $finder ?: new \Symfony\Component\Finder\Finder;

		$files = $files ?: new \Illuminate\Filesystem\Filesystem;

		// We will use the finder to locate all "autoload.php" files in the workbench
		// directory, then we will include them each so that they are able to load
		// the appropriate classes and file used by the given workbench package.
		$autoloads = $finder->in($path)->files()->name('autoload.php');

		foreach ($autoloads as $file)
		{
			$files->requireOnce($file->getRealPath());
		}
	}

}

<?php namespace Illuminate\Workbench;

class Starter {

	/**
	 * Load the workbench vendor auto-load files.
	 *
	 * @param  string  $path
	 * @param  Illuminate\Filesystem  $files
	 * @return void
	 */
	public static function start($path, $finder = null, $files = null)
	{
		$finder = $finder ?: new \Symfony\Component\Finder\Finder;

		// We will use the finder to locate all "autoload.php" files in the workbench
		// directory, then we will include them each so that they are able to load
		// the appropriate classes and file used by the given workbench package.
		$files = $files ?: new \Illuminate\Filesystem\Filesystem;

		$autoloads = $finder->in($path)->files()->name('autoload.php');

		foreach ($autoloads as $file)
		{
			$files->requireOnce($file->getRealPath());
		}
	}

}

Fix bug in Eloquent model update routine.


<?php

final class PhutilMissingSymbolException extends Exception {

  public function __construct($symbol, $type, $reason) {
    parent::__construct(
      pht(
        "Failed to load %s '%s': %s ".
        "If this symbol was recently added or moved, your library map may ".
        "be out of date. You can rebuild the map by running '%s'. ".
        "For more information, see: %s",
        $type,
        $symbol,
        $reason,
        'arc liberate',
        'http://www.phabricator.com/docs/phabricator/article/'.
        'libphutil_Libraries_User_Guide.html'));
  }

}

<?php

final class PhutilMissingSymbolException extends Exception {

  public function __construct($symbol, $type, $reason) {
    parent::__construct(
      pht(
        "Failed to load %s '%s': %s.\n\n".
        "If you are not a developer, this almost always means that a library ".
        "is out of date. For example, you may have upgraded `phabricator` ".
        "without upgrading `libphutil`, or vice versa. It might also mean ".
        "that you need to restart Apache or PHP-FPM. Make sure all libraries ".
        "are up to date and all services have been restarted.\n\n".
        "If you are a developer and this symbol was recently added or moved, ".
        "your library map may need to be rebuilt. You can rebuild the map by ".
        "running '%s'. For more information, see:\n\n".
        "%s",
        $type,
        $symbol,
        $reason,
        'arc liberate',
        'https://secure.phabricator.com/book/phabcontrib/article/'.
          'adding_new_classes/'));
  }

}

Remove referneces to "www.phabricator.com" in libphutil

Summary: This host is out of service.

Test Plan: `git grep -i www.phabricator.com`, triggered exception, read text.

Reviewers: chad

Reviewed By: chad

Subscribers: epriestley

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


<?php

namespace Geocoder\Tests;

use Http\Client\HttpClient;
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7;

class CachedResponseClient implements HttpClient
{
    private $delegate;

    private $useCache;

    private $apiKey;

    private $cacheDir;

    public function __construct(HttpClient $delegate, $useCache = false, $apiKey = null, $cacheDir = '.cached_responses')
    {
        $this->delegate  = $delegate;
        $this->useCache = $useCache;
        $this->apiKey   = $apiKey;
        $this->cacheDir = $cacheDir;
    }

    /**
     * {@inheritDoc}
     */
    public function sendRequest(RequestInterface $request)
    {
        $url = (string) $request->getUri();
        if ($this->apiKey) {
            $url = str_replace($this->apiKey, '[apikey]', $url);
        }

        $file = sprintf('%s/%s/%s', realpath(__DIR__ . '/../../'), $this->cacheDir, sha1($url));

        if ($this->useCache && is_file($file) && is_readable($file)) {
            return new Response(200, [], Psr7\stream_for(unserialize(file_get_contents($file))));
        }

        $response = $this->delegate->sendRequest($request);

        if ($this->useCache) {
            file_put_contents($file, $response->getBody()->getContents());
        }

        return $response;
    }
}

<?php

namespace Geocoder\Tests;

use Http\Client\HttpClient;
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7;

class CachedResponseClient implements HttpClient
{
    private $delegate;

    private $useCache;

    private $apiKey;

    private $cacheDir;

    public function __construct(HttpClient $delegate, $useCache = false, $apiKey = null, $cacheDir = '.cached_responses')
    {
        $this->delegate  = $delegate;
        $this->useCache = $useCache;
        $this->apiKey   = $apiKey;
        $this->cacheDir = $cacheDir;
    }

    /**
     * {@inheritDoc}
     */
    public function sendRequest(RequestInterface $request)
    {
        $url = (string) $request->getUri();
        if ($this->apiKey) {
            $url = str_replace($this->apiKey, '[apikey]', $url);
        }

        $file = sprintf('%s/%s/%s', realpath(__DIR__ . '/../../'), $this->cacheDir, sha1($url));

        if ($this->useCache && is_file($file) && is_readable($file)) {
            return new Response(200, [], Psr7\stream_for(unserialize(file_get_contents($file))));
        }

        $response = $this->delegate->sendRequest($request);

        if ($this->useCache) {
            file_put_contents($file, serialize($response->getBody()->getContents()));
        }

        return $response;
    }
}

Fix bug where cached unit test responses aren't serialised


<?php
  get_header();

  if (have_posts()) {
    while (have_posts()) {
      the_post();
?>

      <?php the_content(); ?>

<?php
      if (is_page("tags")) {
?>

        <?php
          wp_list_categories(
            array(
              "hierarchical"      => 1,
              "title_li"          => __(""),
              "show_count"        => 1,
              "depth"             => 0,
              "exclude"           => "1,7"
            )
          );
        ?>

      <?php
        wp_get_archives(
          array(
            "type" => "yearly"
          )
        );
      ?>

      <?php
        wp_get_archives(
          array(
            "type" => "monthly"
          )
        );
      ?>

      <?php
        wp_get_archives(
          array(
            "type" => "daily"
          )
        );
      ?>

<?php
      }
?>

<?php
    }
  }

  get_footer();

?>

<?php
  get_header();

  if (have_posts()) {
    while (have_posts()) {
      the_post();
?>

      <?php the_content(); ?>

<?php
      if (is_page("tags")) {
?>

        <?php
          wp_list_categories(
            array(
              "hierarchical"      => 1,
              "title_li"          => __(""),
              "show_count"        => 1,
              "depth"             => 0,
              "exclude"           => "1,7,11,148"
            )
          );
        ?>

      <?php
        wp_get_archives(
          array(
            "type" => "yearly"
          )
        );
      ?>

      <?php
        wp_get_archives(
          array(
            "type" => "monthly"
          )
        );
      ?>

      <?php
        wp_get_archives(
          array(
            "type" => "daily"
          )
        );
      ?>

<?php
      }
?>

<?php
    }
  }

  get_footer();

?>

Exclude more categories to make generating site faster


<?php
App::uses('AppController', 'Controller');

/**
 * Products controller
 *
 * Handles requests about products.
 */
class ProductsController extends AppController
{
	/**
	 * Controller name
	 *
	 * @var string
	 */
	public $name = 'Product';

	/**
	 * This controller does not use a model
	 *
	 * @var array
	 */
	public $uses = array();

	/**
	 * Searches for a product like the given string.
	 */
	public function search($description)
	{
		Semantics3::search($description);
	}
}

<?php
App::uses('AppController', 'Controller');

/**
 * Products controller
 *
 * Handles requests about products.
 */
class ProductsController extends AppController
{
	/**
	 * Controller name
	 *
	 * @var string
	 */
	public $name = 'Product';

	/**
	 * This controller does not use a model
	 *
	 * @var array
	 */
	public $uses = array();

	/**
	 * Searches for a product like the given string.
	 */
	public function search($description, $start = 0)
	{
		$result = Semantics3::search($description, $start);
		$display = (object)array(
			'total_results_count' => $result->total_results_count,
			'results' => array_map(function($item) {
				$item->id = $item->sem3_id;
				unset($item->sem3_id);
				return $item;
			}, $result->results)
		);

		$this->set(array('result' => &$display));
		$this->set('_serialize', array('result'));
	}
}

Implement fully working product search.

Implement fully working product search.


<?php

namespace AydinHassan\CliMdRendererTest\Renderer;

use AydinHassan\CliMdRenderer\CliRenderer;
use AydinHassan\CliMdRenderer\Renderer\HorizontalRuleRenderer;
use AydinHassan\CliMdRendererTest\RendererTestInterface;
use Colors\Color;
use League\CommonMark\Block\Element\HorizontalRule;

/**
 * Class HorizontalRuleRendererTest
 * @package AydinHassan\CliMdRendererTest\Renderer
 * @author Aydin Hassan <aydin@hotmail.co.uk>
 */
class HorizontalRuleRendererTest extends AbstractRendererTest implements RendererTestInterface
{

    /**
     * @return string
     */
    public function getRendererClass()
    {
        return HorizontalRuleRenderer::class;
    }

    public function testRender()
    {
        $class          = $this->getRendererClass();
        $renderer       = new $class;
        $rule           = new HorizontalRule();

        $color          = new Color;
        $color->setForceStyle(true);
        $cliRenderer    = new CliRenderer([], [], $color);

        $this->assertEquals(
            "------------------------------",
            $renderer->render($rule, $cliRenderer)
        );
    }
}

<?php

namespace AydinHassan\CliMdRendererTest\Renderer;

use AydinHassan\CliMdRenderer\CliRenderer;
use AydinHassan\CliMdRenderer\Renderer\HorizontalRuleRenderer;
use AydinHassan\CliMdRendererTest\RendererTestInterface;
use Colors\Color;
use InvalidArgumentException;
use League\CommonMark\Block\Element\HorizontalRule;

/**
 * Class HorizontalRuleRendererTest
 * @package AydinHassan\CliMdRendererTest\Renderer
 * @author Aydin Hassan <aydin@hotmail.co.uk>
 */
class HorizontalRuleRendererTest extends AbstractRendererTest implements RendererTestInterface
{

    /**
     * @return string
     */
    public function getRendererClass()
    {
        return HorizontalRuleRenderer::class;
    }

    public function testExceptionIsThrownIfWidthNotInterger()
    {
        $this->setExpectedException(
            InvalidArgumentException::class,
            'Width should be an integer. Got: "stdClass"'
        );

        $class          = $this->getRendererClass();
        $renderer       = new $class(new \stdClass);
    }

    public function testRender()
    {
        $class          = $this->getRendererClass();
        $renderer       = new $class;
        $rule           = new HorizontalRule();

        $color          = new Color;
        $color->setForceStyle(true);
        $cliRenderer    = new CliRenderer([], [], $color);

        $this->assertEquals(
            "------------------------------",
            $renderer->render($rule, $cliRenderer)
        );
    }
}

Add test for invalid width

Add test for invalid width


<?php

namespace Backend\Core\Cronjobs;

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

use Backend\Core\Engine\Base\Cronjob;
use Backend\Core\Engine\Mailer;

/**
 * This is the cronjob to send the queued emails.
 *
 * @author Tijs Verkoyen <tijs@sumocoders.be>
 * @author Davy Hellemans <davy@spoon-library.com>
 */
class BackendCoreCronjobSendQueuedEmails extends Cronjob
{
    /**
     * Execute the action
     */
    public function execute()
    {
        // set busy file
        $this->setBusyFile();

        // send all queued e-mails
        foreach (Mailer::getQueuedMailIds() as $id) {
            Mailer::send($id);
        }

        // remove busy file
        $this->clearBusyFile();
    }
}

<?php

namespace Backend\Core\Cronjobs;

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

use Backend\Core\Engine\Base\Cronjob;
use Common\Mailer;

/**
 * This is the cronjob to send the queued emails.
 *
 * @author Tijs Verkoyen <tijs@sumocoders.be>
 * @author Davy Hellemans <davy@spoon-library.com>
 */
class BackendCoreCronjobSendQueuedEmails extends Cronjob
{
    /**
     * Execute the action
     */
    public function execute()
    {
        // set busy file
        $this->setBusyFile();

        // send all queued e-mails
        $mailer = $this->get('mailer');
        foreach ($mailer->getQueuedMailIds() as $id) {
            $mailer->send($id);
        }

        // remove busy file
        $this->clearBusyFile();
    }
}

Use the common mailer in the sendQueuedEmails cronjob


<?php

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

use Symfony\Component\VarDumper\VarDumper;

if (!function_exists('dump')) {
    /**
     * @author Nicolas Grekas <p@tchwork.com>
     */
    function dump($var, ...$moreVars)
    {
        VarDumper::dump($var);

        foreach ($moreVars as $v) {
            VarDumper::dump($v);
        }

        if (1 < func_num_args()) {
            return func_get_args();
        }

        return $var;
    }
}

if (!function_exists('dd')) {
    function dd($var, ...$moreVars)
    {
        VarDumper::dump($var);

        foreach ($moreVars as $v) {
            VarDumper::dump($v);
        }

        exit(1);
    }
}

<?php

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

use Symfony\Component\VarDumper\VarDumper;

if (!function_exists('dump')) {
    /**
     * @author Nicolas Grekas <p@tchwork.com>
     */
    function dump($var, ...$moreVars)
    {
        VarDumper::dump($var);

        foreach ($moreVars as $v) {
            VarDumper::dump($v);
        }

        if (1 < func_num_args()) {
            return func_get_args();
        }

        return $var;
    }
}

if (!function_exists('dd')) {
    function dd(...$vars)
    {
        foreach ($vars as $v) {
            VarDumper::dump($v);
        }

        die(1);
    }
}

[VarDumper] Allow dd() to be called without arguments


<?php

namespace Ojs\ImportBundle\Helper;

class FileHelper {
    public static $mimeToExtMap = [
        'application/pdf'    => 'pdf',
        'image/jpeg'         => 'jpg',
        'application/msword' => 'doc',
        'application/zip'    => 'zip',
        'application/text-plain:formatted' => 'txt',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx'
    ];
}

<?php

namespace Ojs\ImportBundle\Helper;

class FileHelper {
    public static $mimeToExtMap = [
        'application/pdf'    => 'pdf',
        'image/jpeg'         => 'jpg',
        'application/msword' => 'doc',
        'application/zip'    => 'zip',
        'application/octet-stream' => 'bin',
        'application/text-plain:formatted' => 'txt',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx'
    ];
}

Add a mime type for binary files

Add a mime type for binary files


<?php

declare(strict_types=1);

namespace test\Primitive;

use Widmogrod\Helpful\SetoidLaws;
use Widmogrod\Primitive\Num;

class NumTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @dataProvider provideSetoidLaws
     */
    public function test_it_should_obay_setoid_laws(
        $a,
        $b,
        $c
    ) {
        SetoidLaws::test(
            [$this, 'assertEquals'],
            $a,
            $b,
            $c
        );
    }

    private function randomize()
    {
        return Num::of(random_int(-100000000, 100000000));
    }

    public function provideSetoidLaws()
    {
        return array_map(function () {
            return [
                $this->randomize(),
                $this->randomize(),
                $this->randomize(),
            ];
        }, array_fill(0, 50, null));
    }
}

<?php

declare(strict_types=1);

namespace test\Primitive;

use Eris\TestTrait;
use Eris\Generator;
use Widmogrod\Helpful\SetoidLaws;
use Widmogrod\Primitive\Num;

class NumTest extends \PHPUnit\Framework\TestCase
{
    use TestTrait;

    public function test_it_should_obay_setoid_laws()
    {
        $this->forAll(
            Generator\choose(0, 1000),
            Generator\choose(1000, 4000),
            Generator\choose(4000, 100000)
        )->then(function (int $x, int $y, int $z) {
            SetoidLaws::test(
                [$this, 'assertEquals'],
                Num::of($x),
                Num::of($y),
                Num::of($z)
            );
        });
    }
}

Make Primitive\Num tests much more nicer


<div class="update" data-productname="<?php p($_['productName']) ?>" data-version="<?php p($_['version']) ?>">

<?php p($l->t('Update needed')) ?>

			<?php if ($_['tooBig']) {
				p($l->t('Please use the command line updater because you have a big instance.'));
			} else {
				p($l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
			} ?>

			<?php
			print_unescaped($l->t('For help, see the  documentation.', [link_to_docs('admin-cli-upgrade')])); ?>

<div class="update" data-productname="<?php p($_['productName']) ?>" data-version="<?php p($_['version']) ?>">

<?php p($l->t('Update needed')) ?>

			<?php if ($_['tooBig']) {
				p($l->t('Your instance possibly hosts many users and files. To ensure a smooth upgrade process, please use the command line updater (occ upgrade).'));
			} else {
				p($l->t('Automatic updating was disabled in config.php. To upgrade your instance, please use the command line updater (occ upgrade).'));
			} ?>

			<?php
			print_unescaped($l->t('For help, see the  documentation.', [link_to_docs('admin-cli-upgrade')])); ?>

Make admin feedback easier understandable