<?php
function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

$c = new Memcached();
$c->addServer("localhost", 11211);
foreach($c->getAllKeys() as $key) {
	if(startsWith($key, "qreport_")) {
		echo substr($key, strlen("qreport_")) . "\n";
	}

}
// var_dump( $c->getAllKeys() );
?>

<?php
function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

$c = new Memcached();
$c->addServer("localhost", 11211);
foreach($c->getAllKeys() as $key) {
	if(startsWith($key, "qreport_")) {
		$time_start = microtime(true);
		$query = substr($key, strlen("qreport_")) ;
		echo "====== QUERY  $query ======\n";

		echo file_get_contents("http://builder.osmand.net/reports/query_report?".$query."&force=true";
		$time_end = microtime(true);
		$time = $time_end - $time_start;

		echo "\n====== DONE $time seconds ======\n";
	}

}
// var_dump( $c->getAllKeys() );
?>

Update server site for osmlive reports

Update server site for osmlive reports


<?php

namespace eien;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'username', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

<?php

namespace eien;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'username', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token', 'api_token',
    ];
}

Add api_token to hidden fields

Add api_token to hidden fields


<?php

function create_callable($type, $mode)
{
    switch ($type) {
        case 'method':
            return [new TestClass(), 'method'.camelize($mode)];

        case 'static_method':
            return ['TestClass', 'staticMethod'.camelize($mode)];

        case 'invoked_method':
            return (new ReflectionClass('Invoke'.camelize($mode).'Class'))->newInstance();

        case 'closure':
            return (new ReflectionFunction('function_'.$mode))->getClosure();

        case 'function':
            return 'function_'.$mode;
    }
}

function camelize($string)
{
    return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
}

<?php

function create_callable($type, $mode)
{
    switch ($type) {
        case 'method':
            return [new TestClass(), 'method'.camelize($mode)];

        case 'static_method':
            return ['TestClass', 'staticMethod'.camelize($mode)];

        case 'invoked_method':
            return (new ReflectionClass('Invoke'.camelize($mode).'Class'))->newInstance();

        case 'closure':
            return (new ReflectionFunction('function_'.$mode))->getClosure();

        case 'function':
            return 'function_'.$mode;
    }

    throw new \InvalidArgumentException(sprintf('Unsupported callable type "%s".', $type));
}

function camelize($string)
{
    return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
}

Throw an exception on an unsupported callable type


<?php

// Autofind the first available app environment
$sf_root_dir = realpath(dirname(__FILE__).'/../../../');
$apps_dir = glob($sf_root_dir.'/apps/*', GLOB_ONLYDIR);
$app = substr($apps_dir[0],
              strrpos($apps_dir[0], DIRECTORY_SEPARATOR) + 1,
              strlen($apps_dir[0]));
if (!$app)
{
  throw new Exception('No app has been detected in this project');
}

// -- path to the symfony project where the plugin resides
$sf_path = dirname(__FILE__).'/../../..';

// bootstrap
include($sf_path . '/test/bootstrap/functional.php');

// create a new test browser
$browser = new sfTestBrowser();
$browser->initialize();

// initialize database manager
$databaseManager = new sfDatabaseManager();
$databaseManager->initialize();

<?php

// Autofind the first available app environment
$sf_root_dir = realpath(dirname(__FILE__).'/../../../');
$apps_dir = glob($sf_root_dir.'/apps/*', GLOB_ONLYDIR);
$app = substr($apps_dir[0],
              strrpos($apps_dir[0], DIRECTORY_SEPARATOR) + 1,
              strlen($apps_dir[0]));
if (!$app)
{
  throw new Exception('No app has been detected in this project');
}

// -- path to the symfony project where the plugin resides
$sf_path = dirname(__FILE__).'/../../..';

// bootstrap
include($sf_path . '/test/bootstrap/functional.php');

// create a new test browser
$browser = new sfTestBrowser();
$browser->initialize();

// initialize database manager
if(method_exists('sfDatabaseManager', 'loadConfiguration'))
{
  // symfony 1.1 style
  new sfDatabaseManager($configuration);
}
else
{
  // symfony 1.0 style
  $databaseManager = new sfDatabaseManager();
  $databaseManager->initialize();
}

Allow for easier testing with sf 1.1

[wiki:DbFinderPlugin] Allow for easier testing with sf 1.1

git-svn-id: 1cdbda4e123179f2e1e2c55188bc07ae93e59a0a@13191 ee427ae8-e902-0410-961c-c3ed070cd9f9


<?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\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Doctrine\Bundle\PHPCRBundle\DoctrinePHPCRBundle(),
            new Acme\BasicCmsBundle\AcmeBasicCmsBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $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

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\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Doctrine\Bundle\PHPCRBundle\DoctrinePHPCRBundle(),
            new Acme\BasicCmsBundle\AcmeBasicCmsBundle(),
            new Symfony\Cmf\Bundle\RoutingBundle\CmfRoutingBundle(),
            new Symfony\Cmf\Bundle\RoutingAutoBundle\CmfRoutingAutoBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $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');
    }
}

Installation: Enable the routing bundles to your kernel


@extends('fluxbb::layout.main')

@section('main')

{{ $category->name }}

        @if ($categories)
            @include('fluxbb::categories.list')
        @endif

        @include('fluxbb::conversations.list')

         $category->slug]) }}">New topic

@stop

@extends('fluxbb::layout.main')

@section('main')

{{ $category->name }}

        @if ($categories)
            @include('fluxbb::categories.list')
        @endif

Pages:

1

2

3

…

5

Next

                    Subscribe
                    Mark as read
                     $category->slug]) }}">{{ trans('fluxbb::forum.post_topic') }}

        @include('fluxbb::conversations.list')

@stop

Add pagination stub and buttons to category conversation list.


<?php

class GroupedProduct extends Product {

    /**
     * @config
     */
    private static $description = "A product containing other products";

    private static $has_many = array(
        "ChildProducts" => "Product"
    );

    public function getCMSFields() {
        $fields = parent::getCMSFields();

        $fields->addFieldToTab(
            "Root.Settings",
            $grid = DropdownField::create(
                "ShowChildrenAs",
                null,
                $this->dbobject("ShowChildrenAs")->enumValues()
            )
        );

        $fields->addFieldToTab(
            "Root.Children",
            $grid = GridField::create(
                "Products",
                null,
                $this->ChildProducts()
            )
        );

        $config = GridfieldConfig_RelationEditor::create();
        $grid->setConfig($config);

        $config
            ->getComponentByType("GridFieldDataColumns")
            ->setDisplayFields(array(
                "CMSThumbnail"  => "Thumbnail",
                "ClassName" => "Product",
                "Title" => "Title",
                "StockID" => "StockID",
                "Price" => "Price",
                "Disabled" => "Disabled"
            ));

        return $fields;
    }

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

        // Loop through our children and save (incase we need to set prices)
        foreach($this->ChildProducts() as $product) {
            $write = false;

            if(!$product->BasePrice && $this->BasePrice) {
                $product->BasePrice = $this->BasePrice;
                $write = true;
            }

            if($this->isChanged("BasePrice")) {
                $product->BasePrice = $this->BasePrice;
                $write = true;
            }

            if($write) $product->write();
        }
    }

}

<?php

class GroupedProduct extends Product {

    /**
     * @config
     */
    private static $description = "A product containing other products";

    private static $has_many = array(
        "ChildProducts" => "Product"
    );

    public function getCMSFields() {
        $fields = parent::getCMSFields();

        $fields->addFieldToTab(
            "Root.Children",
            $grid = GridField::create(
                "Products",
                null,
                $this->ChildProducts()
            )
        );

        $config = GridfieldConfig_RelationEditor::create();
        $grid->setConfig($config);

        $config
            ->getComponentByType("GridFieldDataColumns")
            ->setDisplayFields(array(
                "CMSThumbnail"  => "Thumbnail",
                "ClassName" => "Product",
                "Title" => "Title",
                "StockID" => "StockID",
                "Price" => "Price",
                "Disabled" => "Disabled"
            ));

        return $fields;
    }

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

        // Loop through our children and save (incase we need to set prices)
        foreach($this->ChildProducts() as $product) {
            $write = false;

            if(!$product->BasePrice && $this->BasePrice) {
                $product->BasePrice = $this->BasePrice;
                $write = true;
            }

            if($this->isChanged("BasePrice")) {
                $product->BasePrice = $this->BasePrice;
                $write = true;
            }

            if($write) $product->write();
        }
    }

}

Remove showshildren as field from CMS

Remove showshildren as field from CMS


<?php function HookPdf_exportAllRender_actions_add_collection_option($top_actions,$options){
	global $lang,$pagename,$pdf_output,$pdf_output_only_annotated,$baseurl_short,$collection,$count_result;
	$selectedcoll = '';
	foreach ($options as $theoption){
		if (isset($theoption['extra_tag_attributes'])){
			if (preg_match("/\/pages\/collection_log\.php\?ref=(\\d+)/",$theoption['extra_tag_attributes'],$thiscoll)){
				$selectedcoll = $thiscoll[1];
			}
		}
	}

	$c=count($options);

	if ($pdf_output || $count_result!=0){
		$data_attribute['url'] = sprintf('%splugins/pdf_export/pages/pdf_export_config.php?col=%s',
            $baseurl_short,
            urlencode($selectedcoll)
        );
        $options[$c]['value']='pdf_export';
		$options[$c]['label']=$lang['pdfexportwithnotes'];
		$options[$c]['data_attr']=$data_attribute;

		return $options;
	}
}

?>

<?php function HookPdf_exportAllRender_actions_add_collection_option($top_actions,$options){
	// global $lang,$pagename,$pdf_output,$pdf_output_only_annotated,$baseurl_short,$collection,$count_result;
// 	$selectedcoll = '';
// 	foreach ($options as $theoption){
// 		if (isset($theoption['extra_tag_attributes'])){
// 			if (preg_match("/\/pages\/collection_log\.php\?collection=(\\d+)/",$theoption['extra_tag_attributes'],$thiscoll)){
// 				$selectedcoll = $thiscoll[1];
// 			}
// 		}
// 	}
	$c=count($options);
	$colreff = $collection;
	if ($pdf_output || $count_result!=0){
		$data_attribute['url'] = sprintf('%splugins/pdf_export/pages/pdf_export_config.php?col=%s',
            $baseurl_short,
            urlencode($colreff)
        );
        $options[$c]['value']='pdf_export';
		$options[$c]['label']=$lang['pdfexportwithnotes'];
		$options[$c]['data_attr']=$data_attribute;

		return $options;
	}
}

?>

Fix for collection id not sending

Fix for collection id not sending


<?php

use Faker\Factory as FakerFactory;

/**
 * Class Collection Test Case
 *
 * Base test case class for most collection tests
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package unit\collection
 */
abstract class CollectionTestCase extends \Codeception\TestCase\Test
{
    /**
     * @var \UnitTester
     */
    protected $tester;

    /**
     * Instance of faker
     *
     * @var \Faker\Generator
     */
    protected $faker = null;

    protected function _before()
    {
        $this->faker = FakerFactory::create();
    }

    protected function _after()
    {
    }

    /*********************************************************************************
     * Helpers
     ********************************************************************************/

    /**
     * Returns a list of key => value pairs, where the keys are
     * unique
     *
     * @return array
     */
    protected function getListOfKeyValuePairs(){
        return [
            $this->faker->unique()->word => $this->faker->boolean(),
            $this->faker->unique()->word => $this->faker->sentence(),
            $this->faker->unique()->word => $this->faker->randomNumber(),
        ];
    }

    /*********************************************************************************
     * Actual tests
     ********************************************************************************/

}

<?php

use Faker\Factory as FakerFactory;

/**
 * Class Collection Test Case
 *
 * Base test case class for most collection tests
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package unit\collection
 */
abstract class CollectionTestCase extends UnitTestCase
{
    /*********************************************************************************
     * Helpers
     ********************************************************************************/

    /**
     * Returns a list of key => value pairs, where the keys are
     * unique
     *
     * @return array
     */
    protected function getListOfKeyValuePairs(){
        return [
            $this->faker->unique()->word => $this->faker->boolean(),
            $this->faker->unique()->word => $this->faker->sentence(),
            $this->faker->unique()->word => $this->faker->randomNumber(),
        ];
    }

    /*********************************************************************************
     * Actual tests
     ********************************************************************************/

}

Test now extends new base unit-test-case


<?php
	include '../util.php.inc';

	$dir = $_GET['dir'];
	$path = bespin_get_file_name($dir);

	// Open a known directory, and proceed to read its contents
	if (is_dir($path)) {
	    if ($dh = opendir($path)) {
	        echo '
';
	        while (($file = readdir($dh)) !== false) {
	            if (substr($file, 0, 1) == '.') { continue; }
                $class_name = is_dir("$path/$file") ? 'directory' : 'file ext_css';
	            $postfix = is_dir("$path/$file") ? '/' : '';
	            echo "
$file
";
	        }
	        closedir($dh);
	    }
	}
?>

<?php
	include '../util.php.inc';

	$dir = $_GET['dir'];
	$path = bespin_get_file_name($dir);

    $folder_array = array();
    $file_array = array();

	if (is_dir($path)) {
	    if ($dh = opendir($path)) {
	        while (($entry = readdir($dh)) !== false) {
	            if (substr($entry, 0, 1) == '.') { continue; }
                if (is_dir("$path/$entry")) {
                    $folder_array[] = $entry;
                } else {
                    $file_array[] = $entry;
                }
            }
            closedir($dh);
        }
    }

    sort($folder_array);
    sort($file_array);

    echo '
';
    foreach ($folder_array as $folder) {
        echo "
$folder
";
    }
    foreach ($file_array as $file) {
        echo "
$file
";
    }
    echo '
'
?>

Sort the results from ls

Sort the results from ls


<?php
	class ArchiveLink {
		private $dba;

		function __construct() {
			global $dba;
			global $db;

			$this->db = $db;

			$dbaname = ARCHIVE_DATABASE;

			$dba = new ezSQL_mysqli();
			$dba->quick_connect(
				$this->db->dbuser,
				$this->db->dbpassword,
				$dbaname,
				$this->db->dbhost,
				3306,
				'utf8'
			);
			$this->safesql = new SafeSQL_MySQLi($dba->dbh);
			$dba->cache_timeout = 24; // Note: this is hours
			$dba->use_disk_cache = true;
			$dba->cache_dir = 'inc/ezsql_cache'; // Specify a cache dir. Path is taken from calling script
			$dba->show_errors();

			$this->dba = $dba;
		}

		public function getLatestForPublication($pubid) {
			try {
				$issue_manager = new \FelixOnline\Core\IssueManager();

				$issues = $issue_manager->getAllPublicationIssues($pubid);

				$issue = end($issues);
				return $issue;
			} catch(Exception $e) {
				return false;
			}
		}
	}

<?php
	class ArchiveLink {
		private $dba;

		function __construct() {
			global $dba;
			global $db;

			$this->db = $db;

			$dbaname = ARCHIVE_DATABASE;

			$dba = new ezSQL_mysqli();
			$dba->quick_connect(
				$this->db->dbuser,
				$this->db->dbpassword,
				$dbaname,
				$this->db->dbhost,
				3306,
				'utf8'
			);
			$this->safesql = new SafeSQL_MySQLi($dba->dbh);
			$dba->cache_timeout = 24; // Note: this is hours
			$dba->use_disk_cache = true;
			$dba->cache_dir = 'inc/ezsql_cache'; // Specify a cache dir. Path is taken from calling script
			$dba->show_errors();

			$this->dba = $dba;
		}

		public function getLatestForPublication($pubid) {
			try {
				$issue_manager = new \FelixOnline\Core\IssueManager();

				$issues = $issue_manager->getLatestPublicationIssue($pubid);

				$issue = end($issues);
				return $issue;
			} catch(Exception $e) {
				return false;
			}
		}
	}

Speed up latest issue block

Speed up latest issue block


<?php
if(!empty($_COOKIE['lang']))$lang=$_COOKIE['lang'];
if(!empty($_GET['lang']))$lang=$_GET['lang'];
if(!empty($lang) && ($lang=='en' || $lang=='fr' || $lang=='es'
        || $lang=='nl'|| $lang=='fi' || $lang=='it' || $lang=='de' || $lang=='pt' || $lang=='gr')){
  include('lang_'.$lang.'.php');
  setcookie('lang',$lang,time()+3600*25*365,'/');
}else include('lang_en.php'); //Eng by default
// echo "webui_welcome = $webui_welcome";
?>

<?php
if(!empty($_COOKIE['lang']))$lang=$_COOKIE['lang'];
if(!empty($_GET['lang']))$lang=$_GET['lang'];
if(!empty($lang) && array_key_exists($lang, $languages))
{
    include('lang_'.$lang.'.php');
    setcookie('lang',$lang,time()+3600*25*365,'/');
}
else
    include('lang_en.php'); //Eng by default
// echo "webui_welcome = $webui_welcome";
?>

Remove very messy old language code and replace it with something that doesn't require changing every time a language is added.


<?php

namespace Sven\FlexEnv;

use Sven\FlexEnv\Contracts\Parser;

class EnvParser implements Parser
{
    public function parse(string $env): EnvFile
    {
        $lines = $this->removeEmptyLines(
            $this->splitIntoLines($env)
        );

        $parser = new LineParser();

        return array_reduce($lines, function (EnvFile $carry, $line) use ($parser) {
            [$key, $value] = $parser->parse($line);

            $carry[$key] = $value;

            return $carry;
        }, new EnvFile);
    }

    protected function splitIntoLines(string $env): array
    {
        return explode(PHP_EOL, $env);
    }

    protected function removeEmptyLines(array $lines): array
    {
        return array_filter($lines);
    }
}

<?php

namespace Sven\FlexEnv;

use Sven\FlexEnv\Contracts\Parser;

class EnvParser implements Parser
{
    public function parse(string $env): EnvFile
    {
        $lines = $this->removeEmptyLines(
            $this->splitIntoLines($env)
        );

        $parser = new LineParser();

        return array_reduce($lines, function (EnvFile $file, $line) use ($parser) {
            [$key, $value] = $parser->parse($line);

            $file->set($key, $value);

            return $file;
        }, new EnvFile);
    }

    protected function splitIntoLines(string $env): array
    {
        return explode(PHP_EOL, $env);
    }

    protected function removeEmptyLines(array $lines): array
    {
        return array_filter($lines);
    }
}

Use set method on EnvFile object

Use set method on EnvFile object


<?php
/**
 * Loads test fixtures into S3
 */

date_default_timezone_set('Europe/Prague');
ini_set('display_errors', true);
error_reporting(E_ALL);

$basedir = dirname(__DIR__);

require_once $basedir . '/vendor/autoload.php';

$client =  new \Aws\S3\S3Client([
    'region' => 'us-east-1',
    'version' => '2006-03-01',
    'credentials' => [
        'key' => getenv('AWS_ACCESS_KEY'),
        'secret' => getenv('AWS_SECRET_KEY'),
    ],
]);

$client->getObject([
    'Bucket' => 'keboola-configs',
    'Key' => 'drivers/snowflake/snowflake_linux_x8664_odbc.2.12.76.tgz',
    'SaveAs' => './snowflake_linux_x8664_odbc.tgz'
]);

<?php
/**
 * Loads test fixtures into S3
 */

date_default_timezone_set('Europe/Prague');
ini_set('display_errors', true);
error_reporting(E_ALL);

$basedir = dirname(__DIR__);

require_once $basedir . '/vendor/autoload.php';

$client =  new \Aws\S3\S3Client([
    'region' => 'us-east-1',
    'version' => '2006-03-01',
    'credentials' => [
        'key' => getenv('AWS_ACCESS_KEY'),
        'secret' => getenv('AWS_SECRET_KEY'),
    ],
]);

$client->getObject([
    'Bucket' => 'keboola-configs',
    'Key' => 'drivers/snowflake/snowflake_linux_x8664_odbc.2.12.75.tgz',
    'SaveAs' => './snowflake_linux_x8664_odbc.tgz'
]);

Revert "snowflake - odbc drivers update"

This reverts commit 4532642aba3a1e691d4ca1d8636d9b185d50dcf9.


<?php
/**
 * mbc-transactional-digest
 *
 * Collect transactional campaign sign up message requests in a certain time period and
 * compose a single digest message request.
 */

date_default_timezone_set('America/New_York');
define('CONFIG_PATH',  __DIR__ . '/messagebroker-config');

// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\ MBC_TransactionalDigest\MBC_TransactionalDigest_Consumer;

// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-transactional-digest.config.inc';

// Kick off
echo '------- mbc-transactional-digest START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

$mb = $mbConfig->getProperty('messageBroker_transactionalDigest');
$mb->consumeMessage(array(new MBC_TransactionalDigest_Consumer('messageBroker_transactionalDigest'), 'consumeQueue'));

echo '------- mbc-transactional-digest END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

<?php
/**
 * mbc-transactional-digest
 *
 * Collect transactional campaign sign up message requests in a certain time period and
 * compose a single digest message request.
 */

date_default_timezone_set('America/New_York');
define('CONFIG_PATH',  __DIR__ . '/messagebroker-config');
define('QOS_SIZE', 1);

// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\ MBC_TransactionalDigest\MBC_TransactionalDigest_Consumer;

// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-transactional-digest.config.inc';

// Kick off
echo '------- mbc-transactional-digest START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

$mb = $mbConfig->getProperty('messageBroker_transactionalDigest');
$mb->consumeMessage([new MBC_TransactionalDigest_Consumer('messageBroker_transactionalDigest'), 'consumeQueue'], QOS_SIZE);

echo '------- mbc-transactional-digest END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

Add QOS_SIZE setting to allow ack messages being removed from queue as fatch size is set to 1


<?php
/**
 * Fiber: String
 * Copyright (c) 2013 Eirik Refsdal <eirikref@gmail.com>
 */

namespace Fiber;

/**
 * Fiber: String
 *
 * Class for generating string test data
 *
 * Things: - strings of various length (min, max, exact)
 *         - different charsets
 *         - empty strings (just length 0)
 *         - really long strings (1M, 5M, 10M, etc.)
 *         - single string, words, sentences, lorem ipsum, special chars
 *           (!?;:, etc.), password (fix of small, caps, numbers,
 *           etc.)
 *
 * @package Fiber
 * @version 2013-06-27
 * @author  Eirik Refsdal <eirikref@gmail.com>
 */
class String extends DataType
{

    /**
     * Get object
     *
     * @author Eirik Refsdal <eirikref@gmail.com>
     * @since  2013-06-27
     * @access private
     * @return object
     */
    private function generateString($length, $charset, $mode)
    {
    }

    /**
     * Get object
     *
     * @author Eirik Refsdal <eirikref@gmail.com>
     * @since  2013-07-18
     * @access public
     * @return object
     */
    public function getEmpty()
    {
        return "";
    }
}

<?php
/**
 * Fiber: String
 * Copyright (c) 2013 Eirik Refsdal <eirikref@gmail.com>
 */

namespace Fiber;

/**
 * Fiber: String
 *
 * Class for generating string test data
 *
 * Things: - strings of various length (min, max, exact)
 *         - different charsets
 *         - empty strings (just length 0)
 *         - really long strings (1M, 5M, 10M, etc.)
 *         - single string, words, sentences, lorem ipsum, special chars
 *           (!?;:, etc.), password (fix of small, caps, numbers,
 *           etc.)
 *
 * @package Fiber
 * @version 2013-06-27
 * @author  Eirik Refsdal <eirikref@gmail.com>
 */
class String extends DataType
{

    /**
     * Get object
     *
     * @author Eirik Refsdal <eirikref@gmail.com>
     * @since  2013-06-27
     * @access private
     * @return string
     */
    private function generateString($length, $charset, $mode)
    {
    }

    /**
     * Get object
     *
     * @author Eirik Refsdal <eirikref@gmail.com>
     * @since  2013-07-18
     * @access public
     * @return string
     */
    public function getEmpty()
    {
        return "";
    }
}

Fix return values in doc

Fix return values in doc


<?php namespace Kshabazz\BattleNet\D3\Models;
/**
 *
 */

/**
 * Class Skill
 *
 * @package Kshabazz\BattleNet\D3\Models
 */
interface Skill
{
	/**
	 * Constructor
	 *
	 * @param string $pType
	 * @param array $pSkill
	 */
	public function __construct( $pType, array $pSkill );

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

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

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

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

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

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

	/**
	 * @return string
	 */
	public function getType();
}
?>

<?php namespace Kshabazz\BattleNet\D3\Skills;
/**
 * Interface Skill
 *
 * @package Kshabazz\BattleNet\D3\Skills
 */
interface Skill
{
	/**
	 * Constructor
	 *
	 * @param string $pType
	 * @param array $pSkill
	 */
	public function __construct( $pType, array $pSkill );

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

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

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

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

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

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

	/**
	 * @return string
	 */
	public function getType();
}
?>

Fix skills interface name-space and docblock.


<?php
ob_start();
?>

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Example</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

Hello world!

        <SparkVersion></SparkVersion>

<?php
$ob = ob_get_clean();

require_once("../../vendor/autoload.php");
$spark = new Spark\Core\Spark();
$spark->render($ob);
?>

<?php
ob_start();
?>

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Example</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

Hello world!

        <SparkVersion></SparkVersion>

Nested boolean test result:
            <SparkTest>
                <SparkTest>
                    True
                </SparkTest>
            </SparkTest>

<?php
$ob = ob_get_clean();

require_once("../../vendor/autoload.php");
$spark = new Spark\Core\Spark();

// This is a Boolean switch
$spark->addTag("Test", function($html) {
    if ($html == "True") return "False";
    if ($html == "False") return "True";
    return "Error: " . htmlentities($html);
});

// Render out
$spark->render($ob);
?>

Update test to prepare for nested parsing development


<?php

namespace LaravelTrailingSlash;

use Illuminate\Routing\UrlGenerator as BaseUrlGenerator;

class UrlGenerator extends BaseUrlGenerator
{
	/**
     * Format the given URL segments into a single URL.
     *
     * @param  string  $root
     * @param  string  $path
     * @param  string  $tail
     * @return string
     */
	protected function trimUrl($root, $path, $tail = '')
	{
		return parent::trimUrl($root, $path, $tail).'/';
	}
}

<?php

namespace LaravelTrailingSlash;

use Illuminate\Routing\UrlGenerator as BaseUrlGenerator;

class UrlGenerator extends BaseUrlGenerator
{
	/**
     * Format the given URL segments into a single URL.
     *
     * @param  string  $root
     * @param  string  $path
     * @param  string  $tail
     * @return string
     */
	protected function trimUrl($root, $path, $tail = '')
	{
		return parent::trimUrl($root, $path, $tail).'/';
	}

	/**
     * Format the given URL segments into a single URL.
     *
     * @param  string  $root
     * @param  string  $path
     * @return string
     */
    public function format($root, $path)
	{
		return parent::format($root, $path).'/';
	}
}

Create format() method to match old trimUrl() for Laravel 5.4 version


<?php
/**
 * The template used for displaying page content
 *
 */
?>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

		<?php the_title( '
', '
' ); ?>

		<?php the_content(); ?>
		<?php
			wp_link_pages( array(
				'before'      => '
' . __( 'Pages:', 'twentyfifteen' ) . '',
				'after'       => '
',
				'link_before' => '',
				'link_after'  => '',
				'pagelink'    => '' . __( 'Page', 'twentyfifteen' ) . ' %',
				'separator'   => ', ',
			) );
		?>

Add container div for two-column layout

Add container div for two-column layout


<?php

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

class OrchestraAuthCreatePasswordRemindersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create($this->tableNameForPasswordReset(), static function (Blueprint $table) {
            $table->string('email')->index();
            $table->string('token')->index();
            $table->timestamp('created_at')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists($this->tableNameForPasswordReset());
    }

    /**
     * Resolve table name.
     */
    protected function tableNameForPasswordReset(): string
    {
        return config(
            'auth.passwords.'.config('auth.defaults.passwords').'.table', 'password_resets'
        );
    }
}

<?php

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

class OrchestraAuthCreatePasswordRemindersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create($this->tableNameForPasswordReset(), static function (Blueprint $table) {
            $table->string('email')->index();
            $table->string('token')->index();
            $table->timestamp('created_at')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists($this->tableNameForPasswordReset());
    }

    /**
     * Resolve table name.
     */
    protected function tableNameForPasswordReset(): string
    {
        return Config::get(
            'auth.passwords.'.Config::get('auth.defaults.passwords').'.table', 'password_resets'
        );
    }
}

Use facade because config() helper may cause some issue on teardown
process during testing.

Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php namespace MODX\Shell\Command\User;

use MODX\Shell\Command\ListProcessor;

/**
 * List all users for the current modX instance
 */
class GetList extends ListProcessor
{
    protected $processor = 'security/user/getlist';
    protected $headers = array(
        'id', 'username', 'active', 'sudo'
    );

    protected $name = 'user:list';
    protected $description = 'List users';

    protected function configure()
    {
        $version = $this->modx->getVersionData();
        if (version_compare($version['full_version'], '2.2.0-pl', '<')) {
            $this->headers = array(
                'id', 'username', 'active'
            );
        }
    }

    /**
     * Format the "modUer.active" field as boolean
     *
     * @param bool $value
     *
     * @return string
     */
    protected function formatActive($value)
    {
        return $this->renderBoolean($value);
    }

    /**
     * Format the "modUser.sudo" field as boolean
     *
     * @param bool $value
     *
     * @return string
     */
    protected function formatSudo($value)
    {
        return $this->renderBoolean($value);
    }
}

<?php namespace MODX\Shell\Command\User;

use MODX\Shell\Command\ListProcessor;

/**
 * List all users for the current modX instance
 */
class GetList extends ListProcessor
{
    protected $processor = 'security/user/getlist';
    protected $headers = array(
        'id', 'username', 'active', 'sudo'
    );

    protected $name = 'user:list';
    protected $description = 'List users';

    protected function configure()
    {
        $this->getMODX();
        $version = $this->modx->getVersionData();
        if (version_compare($version['full_version'], '2.2.0-pl', '<')) {
            $this->headers = array(
                'id', 'username', 'active'
            );
        }
    }

    /**
     * Format the "modUer.active" field as boolean
     *
     * @param bool $value
     *
     * @return string
     */
    protected function formatActive($value)
    {
        return $this->renderBoolean($value);
    }

    /**
     * Format the "modUser.sudo" field as boolean
     *
     * @param bool $value
     *
     * @return string
     */
    protected function formatSudo($value)
    {
        return $this->renderBoolean($value);
    }
}

Fix issue where modX was not yet available


<?php

namespace TitusPiJean\Flarum\Auth\SSOwat\Listeners;

use Flarum\Core\User;
use Flarum\Event\UserLoggedOut;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Contracts\Events\Dispatcher;

class LogOutUser {
    protected $settings;
    public function __construct(SettingsRepositoryInterface $settings)
    {
        $this->settings = $settings;
        //$this->user = $user;
    }
    public function subscribe(Dispatcher $events)
    {
        $events->listen(UserLoggedOut::class, [$this, 'addLogoutRedirect']);
    }
    public function addLogoutRedirect(UserLoggedOut $event)
    {
      $ssowat = $this->settings->get('flarum-ext-auth-ssowat.address');
      $ssowat_user = $_SERVER['PHP_AUTH_USER'];
      $flarum_user = $event->user->username;
      if ( $ssowat_user == $flarum_user ) {
        $r           = base64_encode( "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
        $urlredirect = "https://" . $ssowat . "/yunohost/sso/?action=logout&r=" . $r;
        header("Location: " . $urlredirect . $r); /* Redirect browser */
  		  die();
      } else {
        die();
      }
    }
}

<?php

namespace TitusPiJean\Flarum\Auth\SSOwat\Listeners;

use Flarum\Core\User;
use Flarum\Event\UserLoggedOut;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Contracts\Events\Dispatcher;

class LogOutUser {
    protected $settings;
    public function __construct(SettingsRepositoryInterface $settings)
    {
        $this->settings = $settings;
    }
    public function subscribe(Dispatcher $events)
    {
        $events->listen(UserLoggedOut::class, [$this, 'addLogoutRedirect']);
    }
    public function addLogoutRedirect(UserLoggedOut $event)
    {
      if isset($_SERVER['PHP_AUTH_USER']) {
      $ssowat = $this->settings->get('flarum-ext-auth-ssowat.address');
      $ssowat_user = $_SERVER['PHP_AUTH_USER'];
      $flarum_user = $event->user->username;
        if ( $ssowat_user == $flarum_user ) {
          $r           = base64_encode( "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
          $urlredirect = "https://" . $ssowat . "/yunohost/sso/?action=logout&r=" . $r;
          header("Location: " . $urlredirect . $r); /* Redirect browser */
          exit; // Stop at SSO login
        } else {
          // Nothing
        }
      } else {
      // Nothing
      }
    }
}

Fix logging out for non-SSO users

Fix logging out for non-SSO users


<?php
namespace Muffin\Slug\Test\Fixture;

use Cake\TestSuite\Fixture\TestFixture;

class TagsFixture extends TestFixture
{
    public $table = 'slug_tags';

    public $fields = [
        'id' => ['type' => 'integer'],
        'namespace' => ['type' => 'string', 'length' => 255, 'null' => true],
        'slug' => ['type' => 'string', 'length' => 255],
        'name' => ['type' => 'string', 'length' => 255],
        'counter' => ['type' => 'integer', 'unsigned' => true, 'default' => 0, 'null' => true],
        'created' => ['type' => 'datetime', 'null' => true],
        'modified' => ['type' => 'datetime', 'null' => true],
        '_constraints' => [
            'primary' => ['type' => 'primary', 'columns' => ['id']],
        ],
    ];

    public $records = [
        [
            'namespace' => null,
            'slug' => 'color',
            'name' => 'Color',
            'counter' => 2,
        ],
        [
            'namespace' => null,
            'slug' => 'dark-color',
            'name' => 'Dark Color',
            'counter' => 1,
        ],
    ];

    public function init()
    {
        $created = $modified = date('Y-m-d H:i:s');
        array_walk($this->records, function (&$record) use ($created, $modified) {
            $record += compact('created', 'modified');
        });
        parent::init();
    }
}

<?php
namespace Muffin\Slug\Test\Fixture;

use Cake\TestSuite\Fixture\TestFixture;

class TagsFixture extends TestFixture
{
    public $table = 'slug_tags';

    public $fields = [
        'id' => ['type' => 'integer'],
        'namespace' => ['type' => 'string', 'length' => 255, 'null' => true],
        'slug' => ['type' => 'string', 'length' => 255],
        'name' => ['type' => 'string', 'length' => 320],
        'counter' => ['type' => 'integer', 'unsigned' => true, 'default' => 0, 'null' => true],
        'created' => ['type' => 'datetime', 'null' => true],
        'modified' => ['type' => 'datetime', 'null' => true],
        '_constraints' => [
            'primary' => ['type' => 'primary', 'columns' => ['id']],
        ],
    ];

    public $records = [
        [
            'namespace' => null,
            'slug' => 'color',
            'name' => 'Color',
            'counter' => 2,
        ],
        [
            'namespace' => null,
            'slug' => 'dark-color',
            'name' => 'Dark Color',
            'counter' => 1,
        ],
    ];

    public function init()
    {
        $created = $modified = date('Y-m-d H:i:s');
        array_walk($this->records, function (&$record) use ($created, $modified) {
            $record += compact('created', 'modified');
        });
        parent::init();
    }
}

Update Tags name length to 320 characters;

per https://github.com/UseMuffin/Slug/pull/25#issuecomment-225242866;


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Config options for the Slack bot
    |--------------------------------------------------------------------------
    |
    |
    |
    */

    'api-url'   => 'https://provibloc.slack.com/api/',
    'api-token' => env('SLACK_API_TOKEN'),
    'admin-token' => env('SLACK_ADMIN_TOKEN'),
    'register-token' => env('SLACK_REGISTER_TOKEN'),

    'post-url' => env('SLACK_POST_URL'),

    'token-expression' => '/api_token: \'([a-zA-Z0-9-]*)\'/',

    'auto-join-channels' => ['C04G7GNLT', 'C050GQPC0'],

    'command-tokens' => [
        '/portrait' => env('SLACK_PORTRAIT_TOKEN'),
        '/punk'     => env('SLACK_PUNK_TOKEN'),
    ],

    'cache-time' => 5,

    'jamyl-id' => 'U04JN1L0C',

    'channels-to-manage' => [
        'G04FM566L',    // api_test
        'G04V6HSHC',    // group_test
        'G04G7KMFM',    // p_fc_chat
        'G04G7KRUD',    // p_fc_pings
        'G04GC8QMX',    // titan_pings
        'G04HPDE74',    // cap_fcs
        'G04QGUA5H',    // p_scouts
    ],

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Config options for the Slack bot
    |--------------------------------------------------------------------------
    |
    |
    |
    */

    'api-url'   => 'https://provibloc.slack.com/api/',
    'api-token' => env('SLACK_API_TOKEN'),
    'admin-token' => env('SLACK_ADMIN_TOKEN'),
    'register-token' => env('SLACK_REGISTER_TOKEN'),

    'post-url' => env('SLACK_POST_URL'),

    'token-expression' => '/api_token: \'([a-zA-Z0-9-]*)\'/',

    'auto-join-channels' => ['C04G7GNLT', 'C050GQPC0'],

    'command-tokens' => [
        '/portrait' => env('SLACK_PORTRAIT_TOKEN'),
        '/punk'     => env('SLACK_PUNK_TOKEN'),
    ],

    'cache-time' => 5,

    'jamyl-id' => 'U04JN1L0C',

    'channels-to-manage' => [
        'G04FM566L',    // api_test
        'G04V6HSHC',    // group_test
        'G04G7KMFM',    // p_fc_chat
        'G04G7KRUD',    // p_fc_pings
        'G04GC8QMX',    // titan_pings
        'G04HPDE74',    // cap_fcs
        'G04QGUA5H',    // p_scouts
        'G04N41BB8',    // profidence
    ],

];

Add profidence to managed channels

Add profidence to managed channels


<?php

if(!function_exists('wp_bootstrap_the_content')) {

  function wp_bootstrap_the_content($content) {
    $html = new DOMDocument();
    @$html->loadHTML('<?xml encoding="utf-8" ?>' . $content );
    $image_nodes = $html->getElementsByTagName( 'img' );

    foreach ($image_nodes as $image_node) {
      $class = $image_node->getAttribute('class');
      if (strpos($class, 'alignleft') !== false) {
        $class.= " pull-left";
      }
      if (strpos($class, 'alignright') !== false) {
        $class.= " pull-right";
      }
      if (strpos($class, 'aligncenter') !== false) {
        $class.= " center-block";
      }
      $image_node->setAttribute('class', $class);
    }

    return preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('', '', '', ''), array('', '', '', ''), $html->saveHTML()));
  }

}

?>

<?php

if(!function_exists('wp_bootstrap_the_content')) {

  function wp_bootstrap_the_content($content) {
    $html = new DOMDocument();
    @$html->loadHTML('<?xml encoding="utf-8" ?>' . $content );
    $image_nodes = $html->getElementsByTagName( 'img' );

    foreach ($image_nodes as $image_node) {
      $class = $image_node->getAttribute('class');
      if (strpos($class, 'alignleft') !== false) {
        $class.= " pull-left";
      }
      if (strpos($class, 'alignright') !== false) {
        $class.= " pull-right";
      }
      if (strpos($class, 'aligncenter') !== false) {
        $class.= " center-block";
      }
      $image_node->setAttribute('class', $class);
    }

    return preg_replace('~(?:<\?[^>]*>|<(?:!DOCTYPE|/?(?:html|head|body))[^>]*>)\s*~i', '', $html->saveHTML());

  }

}

?>

Fix xml declaration not parsed

Fix xml declaration not parsed


<?php
require __DIR__ . '/../vendor/autoload.php';

$app = new \Slim\Slim();

$app->get('/hello', function() {
    echo json_encode(array("message" => "Hello"));
});

$app->get('/hello/:name', function($name) {
    echo json_encode(array("message" => "Hello " . ucfirst($name)));
});

$app->run();

<?php
require __DIR__ . '/../vendor/autoload.php';

$app = new \Slim\Slim();

$app->get('/hello', function() use ($app) {
    $app->response->write(json_encode(array("message" => "Hello")));
});

$app->get('/hello/:name', function($name) use ($app) {
    $app->response->write(json_encode(array(
        "message" => "Hello " . ucfirst($name)
    )));
});

$app->run();

Switch slim api example to use response object


<?php

namespace Laravel\Cashier;

class Cashier
{
    /**
     * The custom currency formatter.
     *
     * @var callable
     */
    protected static $formatCurrencyUsing;

    /**
     * Set the custom currency formatter.
     *
     * @param  callable  $callback
     * @return void
     */
    public static function formatCurrencyUsing(callable $callback)
    {
        static::$formatCurrencyUsing = $callback;
    }

    /**
     * Format the given amount into a displayable currency.
     *
     * @param  int  $amount
     * @return string
     */
    public static function formatAmount($amount)
    {
        if (static::$formatCurrencyUsing) {
            return call_user_func(static::$formatCurrencyUsing, $amount);
        }

        $amount = number_format($amount / 100, 2);

        if (starts_with($amount, '-')) {
            return '-$'.ltrim($amount, '-');
        } else {
            return '$'.$amount;
        }
    }
}

<?php

namespace Laravel\Cashier;

class Cashier
{
    /**
     * The custom currency formatter.
     *
     * @var callable
     */
    protected static $formatCurrencyUsing;

    /**
     * Set the custom currency formatter.
     *
     * @param  callable  $callback
     * @return void
     */
    public static function formatCurrencyUsing(callable $callback)
    {
        static::$formatCurrencyUsing = $callback;
    }

    /**
     * Format the given amount into a displayable currency.
     *
     * @param  int  $amount
     * @return string
     */
    public static function formatAmount($amount)
    {
        if (static::$formatCurrencyUsing) {
            return call_user_func(static::$formatCurrencyUsing, $amount);
        }

        $amount = number_format($amount / 100, 2);

        if (starts_with($amount, '-')) {
            return '-$'.ltrim($amount, '-');
        }

        return '$'.$amount;
    }
}

Remove unnecessary else from formatAmount() method.


<?php

namespace Kurt\Repoist;

use Illuminate\Support\ServiceProvider;
use Kurt\Repoist\Commands\MakeCriterionCommand;
use Kurt\Repoist\Commands\MakeRepositoryCommand;

class RepoistServiceProvider extends ServiceProvider
{
    /**
     * Commands to be registered.
     * @var array
     */
    private $repoistCommands = [
        MakeCriterionCommand::class,
        MakeRepositoryCommand::class,
    ];

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
    	$this->mergeConfigFrom(__DIR__.'/config/repoist.php', 'repoist');

    	$this->publishes([
	        __DIR__.'/config/package.php' => config_path('repoist.php')
	    ], 'repoist-config');

        $this->registerCommands();
    }

    /**
     * Registers repoist commands.
     */
    public function registerCommands()
    {
    	$this->commands($this->repoistCommands);
    }
}

<?php

namespace Kurt\Repoist;

use Illuminate\Support\ServiceProvider;
use Kurt\Repoist\Commands\MakeCriterionCommand;
use Kurt\Repoist\Commands\MakeRepositoryCommand;

class RepoistServiceProvider extends ServiceProvider
{
    /**
     * Commands to be registered.
     * @var array
     */
    private $repoistCommands = [
        MakeCriterionCommand::class,
        MakeRepositoryCommand::class,
    ];

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
    	$this->mergeConfigFrom(__DIR__.'/config/repoist.php', 'repoist');

    	$this->publishes([
	        __DIR__.'/config/repoist.php' => config_path('repoist.php')
	    ], 'repoist-config');

        $this->registerCommands();
    }

    /**
     * Registers repoist commands.
     */
    public function registerCommands()
    {
    	$this->commands($this->repoistCommands);
    }
}

Fix invalid path when publishing vendor config.


<?php

/*
 * This file is part of the SensioLabsConnectBundle package.
 *
 * (c) SensioLabs <contact@sensiolabs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SensioLabs\Bundle\ConnectBundle\DependencyInjection;

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

/**
 * Configuration.
 *
 * @author Marc Weistroff <marc.weistroff@sensiolabs.com>
 */
class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('sensiolabs_connect');

        $rootNode
            ->children()
                ->scalarNode('app_id')->isRequired()->end()
                ->scalarNode('app_secret')->isRequired()->end()
                ->scalarNode('scope')->isRequired()->end()
                ->scalarNode('oauth_callback_path')->defaultValue('/session/callback')->end()
                ->scalarNode('oauth_endpoint')->defaultValue('https://connect.sensiolabs.com')->end()
                ->scalarNode('api_endpoint')->defaultValue('https://connect.sensiolabs.com/api')->end()
                ->scalarNode('timeout')->defaultValue(5)->end()
                ->booleanNode('strict_checks')->defaultValue(true)->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

<?php

/*
 * This file is part of the SensioLabsConnectBundle package.
 *
 * (c) SensioLabs <contact@sensiolabs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace SensioLabs\Bundle\ConnectBundle\DependencyInjection;

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

/**
 * Configuration.
 *
 * @author Marc Weistroff <marc.weistroff@sensiolabs.com>
 */
class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        if (method_exists(TreeBuilder::class, 'getRootNode')) {
            $treeBuilder = new TreeBuilder('sensiolabs_connect');
            $rootNode = $treeBuilder->getRootNode();
        } else {
            $treeBuilder = new TreeBuilder();
            $rootNode = $treeBuilder->root('sensiolabs_connect');
        }

        $rootNode
            ->children()
                ->scalarNode('app_id')->isRequired()->end()
                ->scalarNode('app_secret')->isRequired()->end()
                ->scalarNode('scope')->isRequired()->end()
                ->scalarNode('oauth_callback_path')->defaultValue('/session/callback')->end()
                ->scalarNode('oauth_endpoint')->defaultValue('https://connect.sensiolabs.com')->end()
                ->scalarNode('api_endpoint')->defaultValue('https://connect.sensiolabs.com/api')->end()
                ->scalarNode('timeout')->defaultValue(5)->end()
                ->booleanNode('strict_checks')->defaultValue(true)->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

Fix depreciation notices with Symfony >= 4.2


<?php

namespace Meot\FormBundle\Controller;

use Meot\FormBundle\Entity\Question,
    Meot\FormBundle\Entity\Response,
    Meot\FormBundle\Form\ResponseType;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     * @Template(engine="twig")
     */
    public function indexAction()
    {
        return array();
    }

    /**
     * @Route("/builder")
     * @Template(engine="twig")
     */
    public function builderAction()
    {
        return array();
    }
}

<?php

namespace Meot\FormBundle\Controller;

use Meot\FormBundle\Entity\Question,
    Meot\FormBundle\Entity\Response,
    Meot\FormBundle\Form\ResponseType;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     * @Template(engine="twig")
     */
    public function indexAction()
    {
        return array();
    }

    /**
     * @Route("/builder")
     * @Template(engine="twig")
     */
    public function builderAction()
    {
        // force browser not to cache the builder page so that when user logout
        // and click back button, he/she will not see the previous page
        header("Cache-Control: no-store, no-cache, must-revalidate");
        return array();
    }
}

Disable browser cache for builder page

Disable browser cache for builder page

This is to avoid user uses back button after logout


<?php

namespace App\PostProcessor;

use cebe\markdown\GithubMarkdown;

class FilterMarkdown implements Filter
{
    public function getName()
    {
        return 'Markdown';
    }

    public function preProcess($post)
    {
        //
    }

    public function postProcess($post)
    {
        $parser = new GithubMarkdown();
        $parser->html5 = true;
        $parser->enableNewlines = true;

        return $parser->parse($post);
    }
}

<?php

namespace App\PostProcessor;

use cebe\markdown\GithubMarkdown;

class FilterMarkdown implements Filter
{
    public function getName()
    {
        return 'Markdown';
    }

    public function preProcess($post)
    {
        //
    }

    public function postProcess($post)
    {
        $parser = new GithubMarkdown();
        $parser->html5 = true;
        $parser->enableNewlines = true;
        $parser->keepListStartNumber = true;

        return $parser->parse($post);
    }
}

Set flag keepListStartNumber for the markdown parser. Means lists will start at whatever number is writen, rather than 1.


<?php namespace Flarum\Support\Extensions;

use Flarum\Core;
use Illuminate\Support\ServiceProvider;

class ExtensionsServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        // Extensions will not be registered if Flarum is not installed yet
        if (!Core::isInstalled()) {
            return;
        }

        $extensions = json_decode(Core::config('extensions_enabled'), true);
        $providers = [];

        foreach ($extensions as $extension) {
            if (file_exists($file = public_path().'/extensions/'.$extension.'/bootstrap.php') ||
                file_exists($file = base_path().'/extensions/'.$extension.'/bootstrap.php')) {
                $providers[$extension] = require $file;
            }
        }

        // @todo store $providers somewhere (in Core?) so that extensions can talk to each other
    }
}

<?php namespace Flarum\Support\Extensions;

use Flarum\Core;
use Illuminate\Support\ServiceProvider;

class ExtensionsServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
    }

    /**
     * Boot the service provider.
     *
     * @return void
     */
    public function boot()
    {
        // Extensions will not be registered if Flarum is not installed yet
        if (!Core::isInstalled()) {
            return;
        }

        $config = $this->app->make('Flarum\Core\Settings\SettingsRepository')->get('extensions_enabled');
        $extensions = json_decode($config, true);
        $providers = [];

        foreach ($extensions as $extension) {
            if (file_exists($file = public_path().'/extensions/'.$extension.'/bootstrap.php') ||
                file_exists($file = base_path().'/extensions/'.$extension.'/bootstrap.php')) {
                $providers[$extension] = require $file;
            }
        }

        // @todo store $providers somewhere (in Core?) so that extensions can talk to each other
    }
}

Move extension loading to boot method

Move extension loading to boot method

This will likely have to be reverted, to make things like $this->app->extend() work
reasonably well in extensions' service providers.

For now, since we fetch the enabled extensions from the config, there is no other way
for us to guarantee that the config is already available.


<?php

class IncludeSteepGadgets {
    static function HookParser($parser) {
        $parser->setHook("process-model", "IncludeSteepGadgets::ProcessModelRender");
        $parser->setHook("data-map", "IncludeSteepGadgets::MapRender");
        return true;
    }

    static function ProcessModelRender($input, $args, $parser, $frame) {
        return IncludeSteepGadgets::Render($args, "/process-model", "process-model");
    }

    static function MapRender($input, $args, $parser, $frame) {
        return IncludeSteepGadgets::Render($args, "/energy-efficiency-planner", "data-map");
    }

    static function Render($args, $location, $tag) {
        if (isset($args['name'])) {

            if (isset($args['width'])) {
                $width = $args['width'];
            } else {
                $width = "100%";
            }

            if (isset($args['height'])) {
                $height = $args['height'];
            } else {
                $height = "600px";
            }

            $iframeAttrs = array(
                "src" => $location . "/?name=" . $args['name'],
                "style" => "width:" . $width . "; height:" . $height . "; float:left;"
            );

            // This automatically escapes attribute values for us.
            return Html::rawElement(
                "iframe",
                $iframeAttrs
            );

        } else {
            return "Attempt to include " . $tag . " without setting name attribute.";
        }
    }
}

?>

<?php

class IncludeSteepGadgets {
    static function HookParser($parser) {
        $parser->setHook("process-model", "IncludeSteepGadgets::ProcessModelRender");
        $parser->setHook("data-map", "IncludeSteepGadgets::MapRender");
        return true;
    }

    static function ProcessModelRender($input, $args, $parser, $frame) {
        return IncludeSteepGadgets::Render($args, "/process-model", "process-model");
    }

    static function MapRender($input, $args, $parser, $frame) {
        return IncludeSteepGadgets::Render($args, "/energy-efficiency-planner", "data-map");
    }

    static function Render($args, $location, $tag) {
        if (isset($args['name'])) {

            if (isset($args['width'])) {
                $width = $args['width'];
            } else {
                $width = "100%";
            }

            if (isset($args['height'])) {
                $height = $args['height'];
            } else {
                $height = "600px";
            }

            $iframeAttrs = array(
                "src" => $location . "/?name=" . $args['name'],
                "style" => "width:" . $width . "; height:" . $height . "; display:inline-block;"
            );

            // This automatically escapes attribute values for us.
            return Html::rawElement(
                "iframe",
                $iframeAttrs
            );

        } else {
            return "Attempt to include " . $tag . " without setting name attribute.";
        }
    }
}

?>

Use inline-block instead of float for iframes to prevent text from wrapping around them.


<?php

namespace uran1980\yii\assets\jQueryEssential;

class JqueryScrollToAsset extends \yii\web\AssetBundle
{
    public $sourcePath = '@bower/jquery.scrollTo';
    public $js = [
        'jquery.scrollTo.min.js',
    ];
    public $depends = [
        'uran1980\yii\assets\jQueryEssential\JqueryEasingAsset',
    ];
}

<?php

namespace uran1980\yii\assets\jQueryEssential;

class JqueryScrollToAsset extends \yii\web\AssetBundle
{
    public $sourcePath = '@bower/jquery.scrollto';
    public $js = [
        'jquery.scrollTo.min.js',
    ];
    public $depends = [
        'uran1980\yii\assets\jQueryEssential\JqueryEasingAsset',
    ];
}

Change jQuery.scrollTo asset folder case


<?php
	// Include of configurations
	require_once("include/config.inc.php");

	// Include of required libs
	require_once("include/functions.inc.php");
	require_once("include/class.inc.php");

	// Include valids users
	require_once("include/access.inc.php");

	session_start();
    // TODO: Remove the second condition when the website is finished
    if (!isset($_SESSION['logon']) || !isValidUser($_SESSION['logon']))
        header('Location: http://www.polytech.univ-montp2.fr/intra/');
	if (!isset($_SESSION['lang']))
		$_SESSION['lang'] = "fr";
	require_once("lang/" . $_SESSION['lang'] .".php");

	// Include valids pages
	require_once("include/pages.inc.php");

    // Header and menu
	require_once("views/header.php");
	require_once("views/menu.php");
?>

	<div id="Body">
		<?php
            $pageName = $configurations['default_page'];

			if (isset($_GET['page']) && !empty($_GET['page']))
			{
				$pageName = secureInputData($_GET['page']);

                if(!isValidPage($pageName))
                    $pageName = $configurations['default_page'];
			}
            $_SESSION['page'] = $pageName;

			include("controllers/" . $pageName . ".php");
		?>
	</div>

<?php
    // Footer
	require_once("views/footer.php");
?>

<?php
	// Include of configurations
	require_once("include/config.inc.php");

	// Include of required libs
	require_once("include/functions.inc.php");

	// Include valids users
	require_once("include/access.inc.php");

	session_start();
    // TODO: Remove the second condition when the website is finished
    if (!isset($_SESSION['logon']) || !isValidUser($_SESSION['logon']))
        header('Location: http://www.polytech.univ-montp2.fr/intra/');
	if (!isset($_SESSION['lang']))
		$_SESSION['lang'] = "fr";
	require_once("lang/" . $_SESSION['lang'] .".php");

	// Include valids pages
	require_once("include/pages.inc.php");

    // Header and menu
	require_once("views/header.php");
	require_once("views/menu.php");
?>

	<div id="Body">
		<?php
            $pageName = $configurations['default_page'];

			if (isset($_GET['page']) && !empty($_GET['page']))
			{
				$pageName = secureInputData($_GET['page']);

                if(!isValidPage($pageName))
                    $pageName = $configurations['default_page'];
			}
            $_SESSION['page'] = $pageName;

			include("controllers/" . $pageName . ".php");
		?>
	</div>

<?php
    // Footer
	require_once("views/footer.php");
?>

Fix bug dans les includes

Fix bug dans les includes


<?php
// Auto load composer components
require '../vendor/autoload.php';

// Require config
include('../config.php');

// Initalize Slim instance
$app = new \Slim\Slim();
$app->view(new \JsonApiView());
$app->add(new \JsonApiMiddleware());

// Check for necessarry credential/configuration constants
if (!defined('DB_HOSTNAME') || !defined('DB_NAME') | !defined('DB_USERNAME') | !defined('DB_PASSWORD')) {
  die('{"msg":"Invalid database connection","error":true,"status":500}');
}

// Initalize database connection
$database = new medoo([
  'database_type' => 'mysql',
  'database_name' => constant('DB_NAME'),
  'server' => constant('DB_HOSTNAME'),
  'username' => constant('DB_USERNAME'),
  'password' => constant('DB_PASSWORD'),
  'charset' => 'utf8',
  // 'prefix' => 'crt_',
]);

// GET "/" route
$app->get('/', function() use ($app) {
  $app->render(200,array(
    'msg' => 'Welcome to my json API!',
  ));
});

$app->run();

<?php
// Auto load composer components
require '../vendor/autoload.php';

// Require config
include('../config.php');

// Initalize Slim instance
$app = new \Slim\Slim();
$app->view(new \JsonApiView());
$app->add(new \JsonApiMiddleware());

// Check for necessarry credential/configuration constants
if (!defined('DB_HOSTNAME') || !defined('DB_NAME') | !defined('DB_USERNAME') | !defined('DB_PASSWORD')) {
  die('{"msg":"Invalid database connection","error":true,"status":500}');
}

// Initalize database connection
$database = new medoo([
  'database_type' => 'mysql',
  'database_name' => constant('DB_NAME'),
  'server' => constant('DB_HOSTNAME'),
  'username' => constant('DB_USERNAME'),
  'password' => constant('DB_PASSWORD'),
  'charset' => 'utf8',
  // 'prefix' => 'crt_',
]);

// GET "/" route
$app->get('/', function() use ($app, $database) {
  // Create array with available routes
  $routes = array(
    'GET /' => 'This API overview, right here',
    'GET /certificates' => 'Get all available certificates'
  );

  // Render as JSON resulta
  $app->render(200,array(
    'msg' => array('routes'=>$routes)
  ));
});

// GET "/certificates" route
$app->get('/certificates', function() use ($app, $database) {
  // Run SQL select
  $data = $database->select("certificates", "*");

  // Render result
  $app->render(200,array(
    'msg' => $data
  ));
});

$app->run();

Adjust GET / and GET /certificates

Adjust  GET / and GET /certificates


<?php
    $page_title = 'Home';
    $site_title = 'Computer Society';
    $site_index = '/csociety';
    include '../header.php';
?>
    <link href="/assets/bootstrap.csociety.css" rel="stylesheet">

Computer Society

The Computer Society does fun projects with computers! Contact Sid Shah for more details.

<?php include '../footer.php';?>

<?php
    $page_title = 'Home';
    $site_title = 'Computer Society';
    $site_index = '/csociety';
    include '../header.php';
?>
    <link href="/assets/bootstrap.csociety.css" rel="stylesheet">

Computer Society

We are a group of highly curious people with quirks in the science of computation. We do cool stuff with computers and try to spread the enlightenment with who-so-ever matches the level of curiosity of the group. 3D printing, web developing, cyber security, high performance computing, machine learning, graphics and everything you've heard of as tech-y is discussed, talked and made here, feel free to drop by. Contact Sid Shah for more details.

<?php include '../footer.php';?>

Update CSociety Webpage to include more info


<?php

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

declare(strict_types=1);

namespace spec\Sylius\Bundle\CoreBundle\Listener;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Sylius\Bundle\CoreBundle\Processor\CatalogPromotionClearerInterface;
use Sylius\Bundle\CoreBundle\Processor\CatalogPromotionProcessorInterface;
use Sylius\Component\Core\Model\CatalogPromotionInterface;
use Sylius\Component\Promotion\Event\CatalogPromotionConfigurationRemoved;
use Sylius\Component\Promotion\Event\CatalogPromotionUpdated;
use Sylius\Component\Resource\Repository\RepositoryInterface;

final class CatalogPromotionConfigurationRemovedListenerSpec extends ObjectBehavior
{
    function let(
        CatalogPromotionClearerInterface $catalogPromotionClearer,
        CatalogPromotionProcessorInterface $catalogPromotionProcessor,
        RepositoryInterface $catalogPromotionRepository
    ): void {
        $this->beConstructedWith($catalogPromotionClearer, $catalogPromotionProcessor, $catalogPromotionRepository);
    }

    function it_processes_catalog_promotion_after_configuration_removal(
        CatalogPromotionClearerInterface $catalogPromotionClearer,
        CatalogPromotionProcessorInterface $catalogPromotionProcessor,
        RepositoryInterface $catalogPromotionRepository,
        CatalogPromotionInterface $firstCatalogPromotion,
        CatalogPromotionInterface $secondCatalogPromotion
    ): void {
        $catalogPromotionClearer->clear()->shouldBeCalled();

        $catalogPromotionRepository->findAll()->willReturn([$firstCatalogPromotion, $secondCatalogPromotion]);

        $catalogPromotionProcessor->process($firstCatalogPromotion)->shouldBeCalled();
        $catalogPromotionProcessor->process($secondCatalogPromotion)->shouldBeCalled();

        $this->__invoke(new CatalogPromotionConfigurationRemoved());
    }
}

<?php

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

declare(strict_types=1);

namespace spec\Sylius\Bundle\CoreBundle\Listener;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Sylius\Bundle\CoreBundle\Processor\CatalogPromotionClearerInterface;
use Sylius\Bundle\CoreBundle\Processor\CatalogPromotionProcessorInterface;
use Sylius\Component\Core\Model\CatalogPromotionInterface;
use Sylius\Component\Promotion\Event\CatalogPromotionConfigurationRemoved;
use Sylius\Component\Promotion\Event\CatalogPromotionUpdated;
use Sylius\Component\Resource\Repository\RepositoryInterface;

final class CatalogPromotionConfigurationRemovedListenerSpec extends ObjectBehavior
{
    function let(
        CatalogPromotionClearerInterface $catalogPromotionClearer,
        CatalogPromotionProcessorInterface $catalogPromotionProcessor,
        RepositoryInterface $catalogPromotionRepository
    ): void {
        $this->beConstructedWith($catalogPromotionClearer, $catalogPromotionProcessor, $catalogPromotionRepository);
    }

    function it_removes_promotions(
        CatalogPromotionClearerInterface $catalogPromotionClearer
    ): void {
        $catalogPromotionClearer->clear()->shouldBeCalled();

        $this->__invoke(new CatalogPromotionConfigurationRemoved());
    }
}

Remove apply from removing listener

Remove apply from removing listener


<?php

include 'mysqlConfig.php';

header('Content-type: text/plain; charset=us-ascii');
header("Access-Control-Allow-Origin: *");

@mysql_select_db($dsn) or die( "Unable to select database");

$min_bw = intval($_GET["min_bw"]);
$min_bw > 0 or $_GET["min_bw"] === "0" or die("Bad minimum bandwidth");
$max_bw = intval($_GET["max_bw"]);
$max_bw !== 0 or die("Bad maximum bandwidth");
$min_bw <= $max_bw or die("min bw > max bw");

$min_ts = intval($_GET["min_ts"]);
$min_ts !== 0 or die("Bad minimum timestamp");
$max_ts = intval($_GET["max_ts"]);
$max_ts !== 0 or die("Bad maximum timestamp");
$min_ts <= $max_ts or die("min ts > max ts");

$query="select ip from bw_max where bps < " . $max_bw . " and bps > " . $min_bw . " and ts < " . $max_ts . " and ts > " . $min_ts;
$result = mysql_query($query);

if(mysql_num_rows($result)) {
  while($value = mysql_fetch_assoc($result)) {
          echo $value["ip"] . "\n";
      }
}

mysql_close();

?>

<?php

include 'mysqlConfig.php';

header('Content-type: text/plain; charset=us-ascii');
header("Access-Control-Allow-Origin: *");

@mysql_select_db($dsn) or die( "Unable to select database");

$min_bw = intval($_GET["min_bw"]);
$min_bw > 0 or $_GET["min_bw"] === "0" or die("Bad minimum bandwidth");
$max_bw = intval($_GET["max_bw"]);
$max_bw !== 0 or die("Bad maximum bandwidth");
$min_bw <= $max_bw or die("min bw > max bw");

$min_ts = intval($_GET["min_ts"]);
$min_ts !== 0 or die("Bad minimum timestamp");
$max_ts = intval($_GET["max_ts"]);
$max_ts !== 0 or die("Bad maximum timestamp");
$min_ts <= $max_ts or die("min ts > max ts");

$query="select ip from bw_max where bps < " . $max_bw . " and bps > " . $min_bw . " and ts < " . $max_ts . " and ts > " . $min_ts;
$result = mysql_query($query);

$first_iter = true;

if(mysql_num_rows($result)) {
  while($value = mysql_fetch_assoc($result)) {
          if (! $first_iter){
              echo "\n";
          }
          $first_iter = false;
          echo $value["ip"];
      }
}

mysql_close();

?>

Fix off by 1 error

Fix off by 1 error


<?php
if ('cli' === php_sapi_name() && basename(__FILE__) === $argv[0] && isset($argv[1])) {
    switch ($argv[1]) {
        case 'update':
            $remoteFilename = 'http://silex-project.org/get/tunnel_http.php';
            $localFilename = __DIR__.'/tunnel_http.php';

            file_put_contents($localFilename, file_get_contents($remoteFilename));
            break;

        case 'check':
            $latest = trim(file_get_contents('http://silex-project.org/get/version'));

            if ($latest != Silex\Application::VERSION) {
                printf("A newer Silex version is available (%s).\n", $latest);
            } else {
                print("You are using the latest Silex version.\n");
            }
            break;

        case 'version':
            printf("Silex version %s\n", Silex\Application::VERSION);
            break;

        default:
            printf("Unknown command '%s' (available commands: version, check, and update).\n", $argv[1]);
    }

    exit(0);
}

header("Content-Type: application/octet-stream");

error_reporting(0);
set_time_limit(0);
set_magic_quotes_runtime(0);

function phpversion_int()
{
    list($maVer, $miVer, $edVer) = split("[/.-]", phpversion());
    return $maVer*10000 + $miVer*100 + $edVer;
}

function CheckFunctions()
{
    if (!function_exists("exec"))
        return "exec";
    return "";
}

Add futur http tunnel script for Asker Extension


<?php
/**
 *
 *
 * @package silverstripe
 * @subpackage sections
 */
class PeopleSection extends Section
{
    private static $title = "List of people";

    private static $description = "";

    /**
     * Database fields
     * @var array
     */
    private static $db = array(
        'Title' => 'Varchar(40)',
        'Content' => 'HTMLText'
    );

    /**
    * Many_many relationship
    * @var array
    */
    private static $many_many = array(
        'People' => 'SectionsPerson'
    );

    /**
     * {@inheritdoc }
     * @var array
     */
    private static $many_many_extraFields = array(
        'People' => array(
            'Sort' => 'Int'
        )
    );

    /**
     * CMS Fields
     * @return array
     */
    public function getCMSFields()
    {
        $fields = parent::getCMSFields();

        $PeopleConfig = GridFieldConfig_RecordEditor::create();
        if ($this->People()->Count() > 0) {
            $PeopleConfig->addComponent(new GridFieldOrderableRows());
        }

        $fields->addFieldsToTab(
            'Root.Main',
            array(
                TextareaField::create(
                    'Title'
                )->setRows(1),
                HTMLEditorField::create(
                    'Content'
                ),
                GridField::create(
                    'People',
                    'Current People(s)',
                    $this->People(),
                    $PeopleConfig
                )
            )
        );

        $this->extend('updateCMSFields', $fields);

        return $fields;
    }
}

<?php
/**
 *
 *
 * @package silverstripe
 * @subpackage sections
 */
class PeopleSection extends Section
{
    private static $title = "List of people";

    private static $description = "";

    /**
     * Database fields
     * @var array
     */
    private static $db = array(
        'Title' => 'Varchar(40)',
        'Content' => 'HTMLText'
    );

    /**
    * Many_many relationship
    * @var array
    */
    private static $many_many = array(
        'People' => 'SectionsPerson'
    );

    /**
     * {@inheritdoc }
     * @var array
     */
    private static $many_many_extraFields = array(
        'People' => array(
            'Sort' => 'Int'
        )
    );

    /**
     * CMS Fields
     * @return array
     */
    public function getCMSFields()
    {
        $fields = parent::getCMSFields();

        $PeopleConfig = GridFieldConfig_RecordEditor::create(100);
        if ($this->People()->Count() > 0) {
            $PeopleConfig->addComponent(new GridFieldOrderableRows());
        }

        $fields->addFieldsToTab(
            'Root.Main',
            array(
                TextareaField::create(
                    'Title'
                )->setRows(1),
                HTMLEditorField::create(
                    'Content'
                ),
                GridField::create(
                    'People',
                    'Current People(s)',
                    $this->People(),
                    $PeopleConfig
                )
            )
        );

        $this->extend('updateCMSFields', $fields);

        return $fields;
    }
}

Update grid field count view able on each page for staff


<?php

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

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

# github hook
Route::post("/git/pull", "GitController@pull");

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

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

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

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

<?php

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

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

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

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

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

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

# github hook
Route::post("/git/pull", "GitController@pull");

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

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

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

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

Add stream link route redirects

Add stream link route redirects


<?php
namespace Vresh\TwilioBundle\Service;

/**
 * This file is part of the VreshTwilioBundle.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Fridolin Koch <info@fridokoch.de>
 */
class TwilioWrapper extends \Services_Twilio
{
    /**
     * @param string $sid
     * @param string $token
     * @param null   $version
     * @param int    $retryAttempts
     */
    public function __construct($sid, $token, $version = null, $retryAttempts = 1)
    {
        parent::__construct($sid, $token, $version, null, $retryAttempts);
    }

    /**
     * Returns a new \Services_Twilio instance from the given parameters
     *
     * @param      $sid
     * @param      $token
     * @param null $version
     * @param int  $retryAttempts
     *
     * @return \Services_Twilio
     */
    public function createInstance($sid ,$token, $version = null, $retryAttempts = 1)
    {
        return new \Services_Twilio($sid, $token, null, $version, $retryAttempts);
    }

}

<?php
namespace Vresh\TwilioBundle\Service;

/**
 * This file is part of the VreshTwilioBundle.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Fridolin Koch <info@fridokoch.de>
 */
class TwilioWrapper extends \Services_Twilio
{
    /**
     * @param string $sid
     * @param string $token
     * @param null   $version
     * @param int    $retryAttempts
     */
    public function __construct($sid, $token, $version = null, $retryAttempts = 1)
    {
        parent::__construct($sid, $token, $version, null, $retryAttempts);
    }

    /**
     * Returns a new \Services_Twilio instance from the given parameters
     *
     * @param      $sid
     * @param      $token
     * @param null $version
     * @param int  $retryAttempts
     *
     * @return \Services_Twilio
     */
    public function createInstance($sid ,$token, $version = null, $retryAttempts = 1)
    {
        return new \Services_Twilio($sid, $token, $version, null, $retryAttempts);
    }

}

Fix "version" and "_http" swapped in argument list


<?php

// Jetpack bits.

add_action( 'pre_amp_render_post', 'amp_jetpack_mods' );

/**
 * Disable Jetpack features that are not compatible with AMP.
 *
 **/
function amp_jetpack_mods() {
	amp_jetpack_disable_related_posts();
}

/**
 * Remove the Related Posts placeholder and headline that gets hooked into the_content
 *
 * That placeholder is useless since we can't ouput, and don't want to output Related Posts in AMP.
 *
 **/
function amp_jetpack_disable_related_posts() {
	if ( class_exists( 'Jetpack_RelatedPosts' ) ) {
		$jprp = Jetpack_RelatedPosts::init();
		remove_filter( 'the_content', array( $jprp, 'filter_add_target_to_dom' ), 40 );
	}
}

<?php

// Jetpack bits.

add_action( 'pre_amp_render_post', 'amp_jetpack_mods' );

/**
 * Disable Jetpack features that are not compatible with AMP.
 *
 **/
function amp_jetpack_mods() {
	amp_jetpack_disable_sharing();
	amp_jetpack_disable_related_posts();
}

function amp_jetpack_disable_sharing() {
	add_filter( 'sharing_show', '__return_false', 100 );
}

/**
 * Remove the Related Posts placeholder and headline that gets hooked into the_content
 *
 * That placeholder is useless since we can't ouput, and don't want to output Related Posts in AMP.
 *
 **/
function amp_jetpack_disable_related_posts() {
	if ( class_exists( 'Jetpack_RelatedPosts' ) ) {
		$jprp = Jetpack_RelatedPosts::init();
		remove_filter( 'the_content', array( $jprp, 'filter_add_target_to_dom' ), 40 );
	}
}

Disable Jetpack Sharing and Likes

Disable Jetpack Sharing and Likes

Likes don't work without Javascript and we should wait until Sharing
lands (https://github.com/ampproject/amphtml/pull/1856)


<?php
declare(strict_types=1);

/**
 * This file is part of TwigView.
 *
 ** (c) 2014 Cees-Jan Kiewiet
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace WyriHaximus\TwigView;

use Cake\Core\BasePlugin;
use Cake\Core\Configure;
use Cake\Core\Plugin as CorePlugin;
use Cake\Core\PluginApplicationInterface;
use Cake\Event\EventManager;

/**
 * Plugin class for WyriHaximus\TwigView.
 */
class Plugin extends BasePlugin
{
    /**
     * Load all the plugin configuration and bootstrap logic.
     *
     * @param \Cake\Core\PluginApplicationInterface $app The host application
     * @return void
     */
    public function bootstrap(PluginApplicationInterface $app): void
    {
        EventManager::instance()->on(new Event\ExtensionsListener());
        EventManager::instance()->on(new Event\TokenParsersListener());

        if (Configure::read('debug') && CorePlugin::isLoaded('DebugKit')) {
            Configure::write('DebugKit.panels', array_merge(
                (array)Configure::read('DebugKit.panels'),
                [
                    'WyriHaximus/TwigView.Twig',
                ]
            ));
            EventManager::instance()->on(new Event\ProfilerListener());
        }
    }
}

<?php
declare(strict_types=1);

/**
 * This file is part of TwigView.
 *
 ** (c) 2014 Cees-Jan Kiewiet
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace WyriHaximus\TwigView;

use Cake\Core\BasePlugin;
use Cake\Core\Configure;
use Cake\Core\Plugin as CorePlugin;
use Cake\Core\PluginApplicationInterface;
use Cake\Event\EventManager;
use WyriHaximus\TwigView\View\TwigView;

/**
 * Plugin class for WyriHaximus\TwigView.
 */
class Plugin extends BasePlugin
{
    /**
     * Load all the plugin configuration and bootstrap logic.
     *
     * @param \Cake\Core\PluginApplicationInterface $app The host application
     * @return void
     */
    public function bootstrap(PluginApplicationInterface $app): void
    {
        EventManager::instance()->on(new Event\ExtensionsListener());
        EventManager::instance()->on(new Event\TokenParsersListener());

        if (Configure::read('debug') && CorePlugin::isLoaded('DebugKit')) {
            Configure::write('DebugKit.panels', array_merge(
                (array)Configure::read('DebugKit.panels'),
                [
                    'WyriHaximus/TwigView.Twig',
                ]
            ));
            EventManager::instance()->on(new Event\ProfilerListener());
        }

        if (Configure::read('debug')) {
            Configure::write(sprintf('%s.cache', TwigView::ENV_CONFIG), false);
        }
    }
}

Disable Twig cache in debug mode

Disable Twig cache in debug mode


<?php
	/**
	 * Url.php
	 * Contains the Thinker\Http\Url class
	 *
	 * @author Cory Gehr
	 */

namespace Thinker\Http;

class Url {

	/**
	 * __construct()
	 * Constructor for the Thinker\Http\Url class
	 * This is intentionally private, so that it cannot be
	 * 	instantiated
	 *
	 * @author Cory Gehr
	 * @access private
	 */
	private function __construct() {}

	/**
	 * create()
	 * Creates an internal site URL
	 *
	 * @author Cory Gehr
	 * @access public
	 * @static
	 * @param string $section Section Name
	 * @param string $subsection Subsection Name (default: null)
	 * @param string[] $params URL Parameters (default: empty array)
	 * @return string Full URL to Item
	 */
	public static function create($section, $subsection = null, $params = array())
	{
		$url =	BASE_URL . 'index.php?s=' . urlencode($section);

		if($subsection)
		{
			$url .= "&su=" . urlencode($subsection);
		}

		// Add URL Parameters
		if(count($params) > 0)
		{
			foreach($params as $key => $value)
			{
				$url .= ("&$key=" . urlencode($value));
			}
		}

		return $url;
	}
}
?>

Fix & W3 Validation Fail in a Links

Fix & W3 Validation Fail in a Links


<?php

namespace Beskhue\CookieTokenAuth\Controller;

use App\Controller\AppController;
use Cake\Event\Event;

class CookieTokenAuthController extends AppController
{
    public $autoRender = false;

    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
        $this->Auth->allow(['index']);
    }

    public function index()
    {
    }
}

Add newline at end of file.

Add newline at end of file.


<?php

namespace Milax\Mconsole\Traits;

use Milax\Mconsole\Exceptions\ModelPropertyException;
use Milax\Mconsole\Processors\TableProcessor;

use View;

trait HasQueryTraits
{
	/**
	 * Run queries with Paginatable and Redirectable traits
	 *
	 * @return
	 */
	public function run($view, $cb, $query = null)
	{
		// Check if $model property exists
		if (!property_exists($this, 'model')) {
			throw new ModelPropertyException('Controller must have protected $model property.');
		}

		// Check if $query property exists
		if (!property_exists($this, 'query')) {
			if ($query === null) {
				$model = $this->model;
				$this->query = $model::getQuery();
			} else {
				$this->query = $query;
			}
		}

		// Filterable Trait
		if (method_exists($this, 'filtrate'))
			$this->query = $this->filtrate($this->query);

		if (method_exists($this, 'paginate')) {
			$this->items = $this->query->paginate($this->perPage);
			View::share('paging', $this->items);
		} else {
			$this->items = $this->query->get();
		}

		return view($view, [
			'items' => TableProcessor::processItems($cb, $this->items),
		]);

	}

}

<?php

namespace Milax\Mconsole\Traits;

use Milax\Mconsole\Exceptions\ModelPropertyException;
use Milax\Mconsole\Processors\TableProcessor;

use View;

trait HasQueryTraits
{
	/**
	 * Run queries with Paginatable and Redirectable traits
	 *
	 * @return
	 */
	public function run($view, $cb, $query = null)
	{
		// Check if $model property exists
		if (!property_exists($this, 'model')) {
			throw new ModelPropertyException('Controller must have protected $model property.');
		}

		// Check if $query property exists
		if (!property_exists($this, 'query')) {
			if ($query === null) {
				$model = $this->model;
				$this->query = $model::query();
			} else {
				$this->query = $query;
			}
		}

		// Filterable Trait
		if (method_exists($this, 'filtrate'))
			$this->query = $this->filtrate($this->query);

		if (method_exists($this, 'paginate')) {
			$this->items = $this->query->paginate($this->perPage);
			View::share('paging', $this->items);
		} else {
			$this->items = $this->query->get();
		}

		return view($view, [
			'items' => TableProcessor::processItems($cb, $this->items),
		]);

	}

}

Fix HasQueryTrait, return model objects collection


<?php
/**
 * Database configuration
 *
 * @author David Carr - dave@daveismyname.com
 * @author Edwin Hoksberg - info@edwinhoksberg.nl
 * @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
 * @version 3.0
 */

use Core\Config;

/**
 * Setup the Database configuration.
 */
Config::set('database', array(
    'default' => array(
        'driver'    => DB_TYPE,
        'hostname'  => DB_HOST,
        'database'  => DB_NAME,
        'username'  => DB_USER,
        'password'  => DB_PASS,
        'prefix'    => PREFIX,
        'charset'   => 'utf8',
        'collation' => 'utf8_general_ci',
    ),
));

<?php
/**
 * Database configuration
 *
 * @author David Carr - dave@daveismyname.com
 * @author Edwin Hoksberg - info@edwinhoksberg.nl
 * @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
 * @version 3.0
 */

use Core\Config;

/**
 * Setup the Database configuration.
 */
Config::set('database', array(
    'default' => array(
        'driver'    => DB_TYPE,
        'hostname'  => DB_HOST,
        'database'  => DB_NAME,
        'username'  => DB_USER,
        'password'  => DB_PASS,
        'prefix'    => PREFIX,
        'charset'   => 'utf8',
        'collation' => 'utf8_general_ci',
    ),
    'custom' => array(
        'driver'    => 'sqlite',
        'database'  => APPDIR .'Storage' .DS .'database.sqlite',
        'prefix'    => PREFIX,
        'charset'   => 'utf8',
        'collation' => 'utf8_general_ci',
    ),
));

Add the SQLite configuration entry example


<?php

namespace Forecast;

class Forecast
{
    const API_ENDPOINT = 'https://api.forecast.io/forecast/';
    private $api_key;

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

    private function request($latitude, $longitude, $time = null, $options = array())
    {
        $request_url = self::API_ENDPOINT
            . $this->api_key
            . '/'
            . $latitude
            . ','
            . $longitude
            . ((is_null($time)) ? '' : ','. $time);

        if (!empty($options)) {
            $request_url .= '?'. http_build_query($options);
        }

        return json_decode(file_get_contents($request_url));
    }

    public function get($latitude, $longitude, $time = null, $options = array())
    {
        return $this->request($latitude, $longitude, $time, $options);
    }
}

<?php

namespace Forecast;

class Forecast
{
    const API_ENDPOINT = 'https://api.forecast.io/forecast/';
    private $api_key;

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

    private function request($latitude, $longitude, $time = null, $options = array())
    {
        $request_url = self::API_ENDPOINT
            . $this->api_key
            . '/'
            . $latitude
            . ','
            . $longitude
            . ((is_null($time)) ? '' : ','. $time);

        if (!empty($options)) {
            $request_url .= '?'. http_build_query($options);
        }

        $response = json_decode(file_get_contents($request_url));
        $response->headers = $http_response_header;
        return $response;
    }

    public function get($latitude, $longitude, $time = null, $options = array())
    {
        return $this->request($latitude, $longitude, $time, $options);
    }
}

Add the headers to the response

Add the headers to the response

https://developer.forecast.io/docs/v2#response-headers


<?php namespace Propaganistas\LaravelFakeId;

use Illuminate\Support\Facades\App;
use Exception;

trait RoutesWithFakeIds
{
    /**
     * Get the value of the model's route key.
     *
     * @return mixed
     */
    public function getRouteKey()
    {
        return App::make('fakeid')->encode($this->getKey());
    }

    /**
     * Retrieve model for route model binding
     *
     * @param  mixed  $routeKey
     * @return null|\Illuminate\Database\Eloquent\Model
     */
    public function resolveRouteBinding($routeKey)
    {
        try {
            $key = App::make('fakeid')->decode($routeKey);
        } catch (Exception $e) {
            return null;
        }

        return $this->where($this->getRouteKeyName(), $key)->first();
    }
}

<?php namespace Propaganistas\LaravelFakeId;

use Illuminate\Support\Facades\App;
use Exception;

trait RoutesWithFakeIds
{
    /**
     * Get the value of the model's route key.
     *
     * @return mixed
     */
    public function getRouteKey()
    {
        return App::make('fakeid')->encode($this->getKey());
    }

    /**
     * Retrieve model for route model binding
     *
     * @param  mixed  $value
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function resolveRouteBinding($value)
    {
        try {
            $value = App::make('fakeid')->decode($value);
        } catch (Exception $e) {
            return null;
        }

        return $this->where($this->getRouteKeyName(), $value)->first();
    }
}

Align method arguments with laravel/framework


<?php sleep(2); ?>

Usage

Battery

Play Time

    <fieldset>

            Years
            <input type="text" value="2"/>

            Months
            <input type="text" value="8"/>

            Days
            <input type="text" value="27"/>

    </fieldset>

Better recharge soon!

<?php sleep(2); ?>

Usage

Battery

Play Time

    <fieldset>

            Years
            2

            Months
            8

            Days
            27

    </fieldset>

Better recharge soon!

Update to use <span> instead of <input> for non-modifiable text.


<?
require_once('php/classes/member.php');

$profileEdited = $currentUser;
// TODO: Allow administrators to edit other member's profile pictures
?>

Edit Profile Picture: <?=$profileEdited->rcsid()?>

This picture is displayed publicly on the "About Us" page:

    <img src="<?=$profileEdited->photoURL()?>" alt="<?=$profileEdited->fullName()?>">

The new image must be a JPEG (*.jpg) file smaller than 1 MB.

    <form enctype="multipart/form-data" action="post.php" method="post">
      <input type="hidden" name="rcsid" value="<?=$profileEdited->rcsid()?>">
      <input type="hidden" name="MAX_FILE_SIZE" value="1048576">

          <input name="new_profile_photo" type="file">
          <button type="submit" name="action"
            value="profile_photo_edit">Upload</button>

    </form>

Fix profile photo upload indentation

Fix profile photo upload indentation