<?php

namespace Rudolf\Modules\Pages\Roll\Admin;

use Rudolf\Component\Helpers\Pagination\Calc as Pagination;
use Rudolf\Framework\Controller\AdminController;
use Rudolf\Modules\Pages\One\Model as PageOne;
use Rudolf\Modules\Pages\Roll\Admin\Model as PagesList;
use Rudolf\Modules\Pages\Roll\Model as PagesFullList;

class Controller extends AdminController
{
    public function getList($page)
    {
        $page = $this->firstPageRedirect($page, 301, $location = '../../list');

        $list = new PagesList();
        $total = $list->getTotalNumber('1');

        $pagination = new Pagination($total, $page, 10);
        $limit = $pagination->getLimit();
        $onPage = $pagination->getOnPage();

        $results = $list->getList($limit, $onPage);

        $page = new PageOne();
        $pagesList = new PagesFullList();
        foreach ($results as $key => $value) {
            $results[$key] = $page->addToPageUrl(
                $value,
                $pagesList->getPagesList()
            );
        }

        $view = new View();
        $view->setData($results, $pagination);
        $view->render('admin');
    }
}

<?php

namespace Rudolf\Modules\Pages\Roll\Admin;

use Rudolf\Component\Helpers\Pagination\Calc as Pagination;
use Rudolf\Framework\Controller\AdminController;
use Rudolf\Modules\Pages\One\Model as PageOne;
use Rudolf\Modules\Pages\Roll\Admin\Model as PagesList;
use Rudolf\Modules\Pages\Roll\Model as PagesFullList;

class Controller extends AdminController
{
    public function getList($page)
    {
        $page = $this->firstPageRedirect($page, 301, $location = '../../list');

        $list = new PagesList();
        $total = $list->getTotalNumber('1');

        $pagination = new Pagination($total, $page, 10);
        $limit = $pagination->getLimit();
        $onPage = $pagination->getOnPage();

        $results = $list->getList($limit, $onPage);

        $page = new PageOne();
        $pagesList = new PagesFullList();

        if (!empty($resutls)) {
        foreach ($results as $key => $value) {
                $results[$key] = $page->addToPageUrl(
                    $value,
                    $pagesList->getPagesList()
                );
            }
        }

        $view = new View();
        $view->setData($results, $pagination);
        $view->render('admin');
    }
}

Fix invalid argument for foreach, when pages table is empty


<?php

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

namespace Symfony\Bridge\Twig\Extension;

use Symfony\Component\Yaml\Dumper as YamlDumper;

/**
 * Provides integration of the Yaml component with Twig.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class YamlExtension extends \Twig_Extension
{
    /**
     * {@inheritdoc}
     */
    public function getFilters()
    {
        return array(
            'yaml_encode' => new \Twig_Filter_Method($this, 'encode'),
            'yaml_dump'   => new \Twig_Filter_Method($this, 'dump'),
        );
    }

    public function encode($input, $inline = 0)
    {
        static $dumper;

        if (null === $dumper) {
            $dumper = new YamlDumper();
        }

        return $dumper->dump($input, $inline);
    }

    public function dump($value)
    {
        if (is_resource($value)) {
            return '%Resource%';
        }

        if (is_array($value) || is_object($value)) {
            return '%'.gettype($value).'% '.$this->encode($value);
        }

        return $value;
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'yaml';
    }
}

<?php

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

namespace Symfony\Bridge\Twig\Extension;

use Symfony\Component\Yaml\Dumper as YamlDumper;

/**
 * Provides integration of the Yaml component with Twig.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class YamlExtension extends \Twig_Extension
{
    /**
     * {@inheritdoc}
     */
    public function getFilters()
    {
        return array(
            'yaml_encode' => new \Twig_Filter_Method($this, 'encode'),
            'yaml_dump'   => new \Twig_Filter_Method($this, 'dump'),
        );
    }

    public function encode($input, $inline = 0)
    {
        static $dumper;

        if (null === $dumper) {
            $dumper = new YamlDumper();
        }

        return $dumper->dump($input, $inline);
    }

    public function dump($value)
    {
        if (is_resource($value)) {
            return '%Resource%';
        }

        if (is_array($value) || is_object($value)) {
            return '%'.gettype($value).'% '.$this->encode($value);
        }

        return $this->encode($value);
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'yaml';
    }
}

Add Support for boolean as to string into yaml extension


@extends('layout.app', [
    'title' => 'Design Stories',
    'body_id' => 'designer-index-page',
    'body_class' => 'designer-index index',
    'active_nav' => 'designer',
])

@section('main')

        @foreach ($designers as $designer)

id }}" class="story grid-item col-xs-12 col-sm-6 col-md-4 col-lg-3"
                data-id="{{ $designer->id }}">
                url }}">
                    @if ($image = $designer->image)
                        file_urls['thumb'] }}" />
                    @else

                    @endif

                        {{ $designer->text('name') }}: {{ $designer->text('tagline') }}

        @endforeach

    {!! $designers->links() !!}

@endsection

@extends('layout.app', [
    'title' => 'Designers',
    'body_id' => 'designer-index-page',
    'body_class' => 'designer-index index',
    'active_nav' => 'designer',
])

@section('main')

        @foreach ($designers as $designer)

id }}" class="story grid-item col-xs-12 col-sm-6 col-md-4 col-lg-3"
                data-id="{{ $designer->id }}">
                url }}">
                    @if ($image = $designer->image)
                        file_urls['thumb'] }}" />
                    @else

                    @endif

                        {{ $designer->text('name') }}: {{ $designer->text('tagline') }}

        @endforeach

    {!! $designers->links() !!}

@endsection

Change title of designer index page.

Change title of designer index page.


<?php
require('/www/auth/webkit-blog-config.php');

define('WP_CACHE', true); //Added by WP-Cache Manager
define('ABSPATH', dirname(__FILE__).'/');
require_once(ABSPATH.'wp-settings.php');
?>

<?php
require('/var/www/config/webkit-blog-config.php');

define('WP_CACHE', true); //Added by WP-Cache Manager
define('ABSPATH', dirname(__FILE__).'/');
require_once(ABSPATH.'wp-settings.php');
?>

Update website for new hardware.

Update website for new hardware.

git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@123400 bbb929c8-8fbe-4397-9dbb-9b2b20218538


<?php
/**
 * Test runner bootstrap.
 *
 * Add additional configuration/setup your application needs when running
 * unit tests in this file.
 */
require dirname(__DIR__) . '/config/bootstrap.php';

<?php
/**
 * Test runner bootstrap.
 *
 * Add additional configuration/setup your application needs when running
 * unit tests in this file.
 */
require dirname(__DIR__) . '/vendor/autoload.php';

require dirname(__DIR__) . '/config/bootstrap.php';

Include composer's autoloader in tests/boostrap.php


<?php

namespace App\Providers;

use Timegridio\Concierge\Models\Appointment;
use Timegridio\Concierge\Models\Business;
use Timegridio\Concierge\Models\Contact;
use Timegridio\Concierge\Models\Service;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Routing\Router;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to the controller routes in your routes file.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @param \Illuminate\Routing\Router $router
     *
     * @return void
     */
    public function boot(Router $router)
    {
        //

        parent::boot($router);

        $router->model('contact', Contact::class);
        $router->model('service', Service::class);
        $router->model('appointment', Appointment::class);
        $router->bind('business', function ($businessSlug) {
            return Business::where('slug', $businessSlug)->first();
        });
    }

    /**
     * Define the routes for the application.
     *
     * @param \Illuminate\Routing\Router $router
     *
     * @return void
     */
    public function map(Router $router)
    {
        $router->group(['namespace' => $this->namespace], function ($router) {
            require app_path('Http/routes.php');
        });
    }
}

<?php

namespace App\Providers;

use Timegridio\Concierge\Models\Appointment;
use Timegridio\Concierge\Models\Business;
use Timegridio\Concierge\Models\Contact;
use Timegridio\Concierge\Models\Service;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Routing\Router;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to the controller routes in your routes file.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @param \Illuminate\Routing\Router $router
     *
     * @return void
     */
    public function boot(Router $router)
    {
        parent::boot($router);

        $router->model('contact', Contact::class);
        $router->model('service', Service::class);
        $router->model('appointment', Appointment::class);
    }

    /**
     * Define the routes for the application.
     *
     * @param \Illuminate\Routing\Router $router
     *
     * @return void
     */
    public function map(Router $router)
    {
        $router->group(['namespace' => $this->namespace], function ($router) {
            require app_path('Http/routes.php');
        });
    }
}

Remove binding as got moved to concierge package


<?php

// This file is necessary to run the unit tests and profiling
// scripts.

// Is PEAR available on your system? If it isn't, set to false. If PEAR
// is not part of the default include_path, add it.
$GLOBALS['HTMLPurifierTest']['PEAR'] = true;

// How many times should profiling scripts iterate over the function? More runs
// means more accurate results, but they'll take longer to perform.
$GLOBALS['HTMLPurifierTest']['Runs'] = 2;

// Where is SimpleTest located?
$simpletest_location = '/path/to/simpletest/';

<?php

// This file is necessary to run the unit tests and profiling scripts.
// Please copy it to 'test-settings.php' and make the necessary edits.

// It's recommended that you turn off PHP's time limit for the unit tests.
set_time_limit(0);

// Turning off output buffering will prevent mysterious errors from core dumps
@ob_end_flush();

// Is PEAR available on your system? If it isn't, set to false. If PEAR
// is not part of the default include_path, add it.
$GLOBALS['HTMLPurifierTest']['PEAR'] = false;
// set_include_path('/path/to/pear' . PATH_SEPARATOR . get_include_path());

// How many times should profiling scripts iterate over the function? More runs
// means more accurate results, but they'll take longer to perform.
$GLOBALS['HTMLPurifierTest']['Runs'] = 2;

// Where is SimpleTest located?
$simpletest_location = '/path/to/simpletest/';

Update test settings file with more options.

git-svn-id: 25f448894bd6eb0cddf10ded73b4f5a7ea3203f3@1302 48356398-32a2-884e-a903-53898d9a118a


<?php

namespace Civi\Api4\Service\Spec\Provider;

use Civi\Api4\Service\Spec\RequestSpec;

class EntityTagCreationSpecProvider implements Generic\SpecProviderInterface {

  /**
   * @param RequestSpec $spec
   */
  public function modifySpec(RequestSpec $spec) {
    $spec->getFieldByName('entity_table')->setRequired(TRUE);
  }

  /**
   * @param string $entity
   * @param string $action
   *
   * @return bool
   */
  public function applies($entity, $action) {
    return $entity === 'EntityTag' && $action === 'create';
  }

}

<?php

namespace Civi\Api4\Service\Spec\Provider;

use Civi\Api4\Service\Spec\RequestSpec;

class EntityTagCreationSpecProvider implements Generic\SpecProviderInterface {

  /**
   * @param RequestSpec $spec
   */
  public function modifySpec(RequestSpec $spec) {
    $spec->getFieldByName('entity_table')->setRequired(FALSE)->setDefaultValue('civicrm_contact');
  }

  /**
   * @param string $entity
   * @param string $action
   *
   * @return bool
   */
  public function applies($entity, $action) {
    return $entity === 'EntityTag' && $action === 'create';
  }

}

Add default value for entity_table

Add default value for entity_table


<?php namespace Flarum\Subscriptions\Gambits;

use Flarum\Core\Search\Search;
use Flarum\Core\Search\RegexGambit;

class SubscriptionGambit extends RegexGambit
{
    protected $pattern = 'is:(follow|ignor)(?:ing|ed)';

    protected function conditions(Search $search, array $matches, $negate)
    {
        $actor = $search->getActor();

        // might be better as `id IN (subquery)`?
        $method = $negate ? 'whereNotExists' : 'whereExists';
        $search->getQuery()->$method(function ($query) use ($actor, $matches) {
            $query->select(app('flarum.db')->raw(1))
                  ->from('users_discussions')
                  ->whereRaw('discussion_id = discussions.id')
                  ->where('user_id', $actor->id)
                  ->where('subscription', $matches[1] === 'follow' ? 'follow' : 'ignore');
        });
    }
}

<?php namespace Flarum\Subscriptions\Gambits;

use Flarum\Core\Search\Search;
use Flarum\Core\Search\RegexGambit;
use Illuminate\Database\Query\Expression;

class SubscriptionGambit extends RegexGambit
{
    protected $pattern = 'is:(follow|ignor)(?:ing|ed)';

    protected function conditions(Search $search, array $matches, $negate)
    {
        $actor = $search->getActor();

        // might be better as `id IN (subquery)`?
        $method = $negate ? 'whereNotExists' : 'whereExists';
        $search->getQuery()->$method(function ($query) use ($actor, $matches) {
            $query->select(app('flarum.db')->raw(1))
                  ->from('users_discussions')
                  ->where('discussions.id', new Expression('discussion_id'))
                  ->where('user_id', $actor->id)
                  ->where('subscription', $matches[1] === 'follow' ? 'follow' : 'ignore');
        });
    }
}

Make sure query filter works with database prefix

Related to flarum/core#269.


<?php
defined('BASEPATH') or exit('No direct script access allowed');

/**
 * Description of Logout
 *
 * @author Amir <amirsanni@gmail.com>
 * Date: 30th Dec, 2016
 */

class Logout extends CI_Controller
{

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

  public function index()
  {
    $this->session->sess_destroy();

    /*
    * unset all cookies
    * Thanks to http://stackoverflow.com/questions/2310558/how-to-delete-all-cookies-of-my-website-in-php
    */
    if (isset($_SERVER['HTTP_COOKIE'])) {
      $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
      foreach ($cookies as $cookie) {
        $parts = explode('=', $cookie);
        $name = trim($parts[0]);
        setcookie($name, '', time() - 1000);
        setcookie($name, '', time() - 1000, '/');
      }
    }

    session_write_close();

    redirect(base_url());
  }
}

<?php
defined('BASEPATH') or exit('No direct script access allowed');

/**
 * Description of Logout
 *
 * @author Amir <amirsanni@gmail.com>
 * Date: 30th Dec, 2016
 */

class Logout extends CI_Controller
{

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

  public function index()
  {
    session_destroy();

    redirect(base_url());
  }
}

Use php inbuilt function for destroying session


<?php

class Apply_model extends CI_Model {
    /**
     * table_name: apply
     */
    const TABLE_NAME = 'apply';

    //public $id; -- Ignore PK
    public $exhibition_id;
    public $artwork_id;
    public $status;
    public $registered_at;

    public function insert($exhibition_id, $artwork_id, $status) {
        $data = [
            'exhibition_id' => $exhibition_id,
            'artwork_id' => $artwork_id,
            'status' => $status
        ];

        if (!$this->db->insert(self::TABLE_NAME, $data)) {
            return false;
        }

        return $this->db->insert_id();
    }

    public function get_by_exhibition_id_and_artwork_id($exhibition_id, $artwork_id) {
        return $this->db
            ->from(self::TABLE_NAME)
            ->where('exhibition_id', $exhibition_id)
            ->where('artwork_id', $artwork_id)
            ->get()->row();
    }
}

<?php

class Apply_model extends CI_Model {
    /**
     * table_name: apply
     */
    const TABLE_NAME = 'apply';

    //public $id; -- Ignore PK
    public $exhibition_id;
    public $artwork_id;
    public $status;
    public $registered_at;

    public function insert($exhibition_id, $artwork_id, $status) {
        $data = [
            'exhibition_id' => $exhibition_id,
            'artwork_id' => $artwork_id,
            'status' => $status
        ];

        if (!$this->db->insert(self::TABLE_NAME, $data)) {
            return false;
        }

        return $this->db->insert_id();
    }

    public function get_by_exhibition_id_and_artwork_id($exhibition_id, $artwork_id) {
        return $this->db
            ->from(self::TABLE_NAME)
            ->where('exhibition_id', $exhibition_id)
            ->where('artwork_id', $artwork_id)
            ->get()->row();
    }

    public function update_status($exhibition_id, $artwork_id) {
        $this->db->update(self::TABLE_NAME, ['status' => APPLY_STATUS_ACCEPTED], ['exhibition_id' => $exhibition_id, 'artwork_id' => $artwork_id]);
        if ($this->db->affected_rows() > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
}

Add apply model update status function

Add apply model update status function


<?php

class Default_Model_MovieMapper extends Default_Model_AbstractMapper
{
    public function find($id)
    {

        $result = $this->getDbTable()->find($id);

        return $result->current();
    }

    public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();

        return $resultSet;
    }

    public function getFilteredQuery($idUser, $status)
    {
		$select = $this->getDbTable()->select()
			->from('movie')
			->joinLeft('status', 'movie.id = status.idMovie AND status.idUser = ' . $idUser , array())
			->where('status.idUser = ?', $idUser);

		if ($status >= 0 && $status <= 5)
		{
			$select->where('status.rating = ?', $status);
		}
		elseif ($status == -1)
		{
			$select->where('status.rating <> ?', 0);
		}

		if ($status == 0 || $status == -2)
		{
			$select->orWhere('status.rating IS NULL');
		}

    	return $select;
    }
}

?>

<?php

class Default_Model_MovieMapper extends Default_Model_AbstractMapper
{
    public function find($id)
    {

        $result = $this->getDbTable()->find($id);

        return $result->current();
    }

    public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();

        return $resultSet;
    }

    public function getFilteredQuery($idUser, $status)
    {
		$select = $this->getDbTable()->select()
			->from('movie')
			->joinLeft('status', 'movie.id = status.idMovie AND status.idUser = ' . $idUser , array())
			->where('status.idUser = ?', $idUser)
			->order('title');

		if ($status >= 0 && $status <= 5)
		{
			$select->where('status.rating = ?', $status);
		}
		elseif ($status == -1)
		{
			$select->where('status.rating <> ?', 0);
		}

		if ($status == 0 || $status == -2)
		{
			$select->orWhere('status.rating IS NULL');
		}

    	return $select;
    }
}

?>

FIX order movies by title

FIX order movies by title


<?php

namespace Solidifier;

use Solidifier\Analyzers\FakeAnalyzer;

class ConfigurationHandlerTest extends \PHPUnit_Framework_TestCase
{
    private
        $analyzer;

    protected function setUp()
    {
        $this->analyzer = new FakeAnalyzer();
    }

    private function getVisitorTypes()
    {
        $types = array();

        foreach($this->analyzer->getVisitors() as $traverse => $traverseVisitors)
        {
             foreach($traverseVisitors as $visitor)
             {
                 $types[] = get_class($visitor);
             }
        }

        return $types;
    }

    private function assertHasVisitor($visitorClass)
    {
        return $this->assertContains($visitorClass, $this->getVisitorTypes());
    }

    private function assertNotHasVisitor($visitorClass)
    {
        return $this->assertNotContains($visitorClass, $this->getVisitorTypes());
    }

    public function testPassThru()
    {
        $handler = new ConfigurationHandler(array());
        $handler->configure($this->analyzer);

        $this->assertHasVisitor('Solidifier\Visitors\Property\PublicAttributes');
    }

    public function testEnable()
    {
        $values = array(
            'property.public' => array('enabled' => false),
            'dependency.strongCoupling' => array('enabled' => true),
        );

        $handler = new ConfigurationHandler($values);
        $handler->configure($this->analyzer);

        $this->assertNotHasVisitor('Solidifier\Visitors\Property\PublicAttributes');
        $this->assertHasVisitor('Solidifier\Visitors\DependencyInjection\StrongCoupling');
    }
}

<?php

namespace Solidifier;

use Solidifier\Analyzers\FakeAnalyzer;

class ConfigurationHandlerTest extends \PHPUnit_Framework_TestCase
{
    private
        $analyzer;

    protected function setUp()
    {
        $this->analyzer = new FakeAnalyzer();
    }

    private function getVisitorTypes()
    {
        $types = array();

        foreach($this->analyzer->getVisitors() as $traverse => $traverseVisitors)
        {
             foreach($traverseVisitors as $visitor)
             {
                 $types[] = get_class($visitor);
             }
        }

        return $types;
    }

    private function assertHasVisitor($visitorClass)
    {
        return $this->assertContains($visitorClass, $this->getVisitorTypes());
    }

    private function assertNotHasVisitor($visitorClass)
    {
        return $this->assertNotContains($visitorClass, $this->getVisitorTypes());
    }

    public function testPassThru()
    {
        $handler = new ConfigurationHandler(array());
        $handler->configure($this->analyzer);

        $this->assertHasVisitor('Solidifier\Visitors\Property\PublicAttributes');
    }

    public function testEnable()
    {
        $values = array(
            'property.public' => array('enabled' => false),
            'dependency.strongCoupling' => array('enabled' => true, 'excludePatterns' => array('foo')),
        );

        $handler = new ConfigurationHandler($values);
        $handler->configure($this->analyzer);

        $this->assertNotHasVisitor('Solidifier\Visitors\Property\PublicAttributes');
        $this->assertHasVisitor('Solidifier\Visitors\DependencyInjection\StrongCoupling');
    }
}

Update visitor strongCoupling unit test

Update visitor strongCoupling unit test


<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

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

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

<?php

namespace App;

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', 'email', 'password',
    ];

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

Add notifiable trait to default user.

Add notifiable trait to default user.


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | OAI-PMH harvests
    |--------------------------------------------------------------------------
    |
    | Each harvest is configured using the OAI-PMH url, set, and a local
    | collection name stored in the local database.
    |
    */

    'harvests' => [
        'samling42' => [
            // 'url'         => 'https://sandbox-eu.alma.exlibrisgroup.com/view/oai/47BIBSYS_UBO/request',
            'url'         => 'https://bibsys-k.alma.exlibrisgroup.com/view/oai/47BIBSYS_UBO/request',
            'set'         => 'ureal_samling42',
            'schema'      => 'marc21',
            'max-retries' => 10,
        ],
        's-litt' => [
            'url'         => 'https://bibsys-k.alma.exlibrisgroup.com/view/oai/47BIBSYS_UBO/request',
            'set'         => 'S-Litt_Colligator',
            'schema'      => 'marc21',
            'max-retries' => 10,
        ],
    ],

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | OAI-PMH harvests
    |--------------------------------------------------------------------------
    |
    | Each harvest is configured using the OAI-PMH url, set, and a local
    | collection name stored in the local database.
    |
    */

    'harvests' => [
        'samling42' => [
            // 'url'         => 'https://sandbox-eu.alma.exlibrisgroup.com/view/oai/47BIBSYS_UBO/request',
            'url'         => 'https://bibsys.alma.exlibrisgroup.com/view/oai/47BIBSYS_UBO/request',
            'set'         => 'ureal_samling42',
            'schema'      => 'marc21',
            'max-retries' => 10,
        ],
        's-litt' => [
            'url'         => 'https://bibsys.alma.exlibrisgroup.com/view/oai/47BIBSYS_UBO/request',
            'set'         => 'S-Litt_Colligator',
            'schema'      => 'marc21',
            'max-retries' => 10,
        ],
    ],

];

Switch to bibsys.alma.exlibrisgroup.com for OAI


<?php

namespace NUSWhispers\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $urlFragments = parse_url(url()->current());

        $scheme = empty($urlFragments['scheme']) ? 'https' : $urlFragments['scheme'];
        $port = ! empty($urlFragments['port']) ? ':' . $urlFragments['port'] : '';

        return $next($request)
            ->header('Access-Control-Allow-Origin', $scheme . '://' . $urlFragments['host'] . $port)
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

<?php

namespace NUSWhispers\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

Use wildcard instead for allowed origins


<?php namespace Lio\Bin;

use Hashids\Hashids;
use Request;

class PasteCreator
{
    protected $pastes;
    protected $hashids;

    public function __construct(PasteRepository $pastes, Hashids $hashids)
    {
        $this->pastes = $pastes;
        $this->hashids = $hashids;
    }

    public function create($observer, $code, $user, $validator = null)
    {
        if ($validator && ! $validator->isValid()) {
            return $observer->pasteValidationError($validator->getErrors());
        }

        $paste = $this->createPaste($code, $user);
        if ( ! $this->pastes->save($paste)) {
            return $observer->pasteValidationError($paste->getErrors());
        }
        $this->addHash($paste);
        return $observer->pasteCreated($paste);
    }

    protected function createPaste($code, $user)
    {
        return $this->pastes->getNew(['code' => $code, 'author' => $user, 'ip' => Request::getClientIp()]);
    }

    protected function addHash($paste)
    {
        $paste->hash = $this->hashids->encrypt($paste->id);
        $this->pastes->save($paste);
    }
}

<?php namespace Lio\Bin;

use Hashids\Hashids;
use Request;

class PasteCreator
{
    protected $pastes;
    protected $hashids;

    public function __construct(PasteRepository $pastes, Hashids $hashids)
    {
        $this->pastes = $pastes;
        $this->hashids = $hashids;
    }

    public function create($observer, $code, $user, $validator = null)
    {
        if ($validator && ! $validator->isValid()) {
            return $observer->pasteValidationError($validator->getErrors());
        }

        $paste = $this->createPaste($code, $user);
        if ( ! $this->pastes->save($paste)) {
            return $observer->pasteValidationError($paste->getErrors());
        }
        $this->addHash($paste);
        return $observer->pasteCreated($paste);
    }

    protected function createPaste($code, $user)
    {
        return $this->pastes->getNew(['code' => $code, 'author' => $user, 'ip' => Request::getClientIp()]);
    }

    protected function addHash($paste)
    {
        $paste->hash = $this->hashids->encode($paste->id);
        $this->pastes->save($paste);
    }
}

Fix error with hashids function

Fix error with hashids function

This function seems to have been removed in 1.0.0


<?php
namespace Backend\Modules\MiniBlog\Installer;

use Backend\Core\Installer\ModuleInstaller;

/**
 * This action will install the mini blog module.
 *
 * @author Lander Vanderstraeten <lander.vanderstraeten@wijs.be>
 */
class Installer extends ModuleInstaller
{
    /**
     * Install the module
     */
    public function install()
    {
        $this->importSQL(dirname(__FILE__) . '/Data/install.sql');

        $this->addModule('MiniBlog');

        $this->importLocale(dirname(__FILE__) . '/Data/locale.xml');

        $this->makeSearchable('MiniBlog');
        $this->setModuleRights(1, 'MiniBlog');

        $this->setActionRights(1, 'MiniBlog', 'Index');
        $this->setActionRights(1, 'MiniBlog', 'Add');
        $this->setActionRights(1, 'MiniBlog', 'Edit');
        $this->setActionRights(1, 'MiniBlog', 'Delete');

        $this->insertExtra('MiniBlog', 'block', 'MiniBlog');
        $this->insertExtra('MiniBlog', 'widget', 'RecentPosts', 'recent_posts');

        $navigationModulesId = $this->setNavigation(null, 'Modules');
        $this->setNavigation($navigationModulesId, 'MiniBlog', 'MiniBlog/Index', array('MiniBlog/Add', 'MiniBlog/Edit'));
    }
}

<?php
namespace Backend\Modules\MiniBlog\Installer;

use Backend\Core\Installer\ModuleInstaller;

/**
 * This action will install the mini blog module.
 *
 * @author Lander Vanderstraeten <lander.vanderstraeten@wijs.be>
 */
class Installer extends ModuleInstaller
{
    /**
     * Install the module
     */
    public function install()
    {
        $this->importSQL(dirname(__FILE__) . '/Data/install.sql');

        $this->addModule('MiniBlog');

        $this->importLocale(dirname(__FILE__) . '/Data/locale.xml');

        $this->makeSearchable('MiniBlog');
        $this->setModuleRights(1, 'MiniBlog');

        $this->setActionRights(1, 'MiniBlog', 'Index');
        $this->setActionRights(1, 'MiniBlog', 'Add');
        $this->setActionRights(1, 'MiniBlog', 'Edit');
        $this->setActionRights(1, 'MiniBlog', 'Delete');

        $this->insertExtra('MiniBlog', 'block', 'MiniBlog');
        $this->insertExtra('MiniBlog', 'widget', 'RecentPosts', 'recentposts');

        $navigationModulesId = $this->setNavigation(null, 'Modules');
        $this->setNavigation($navigationModulesId, 'MiniBlog', 'MiniBlog/Index', array('MiniBlog/Add', 'MiniBlog/Edit'));
    }
}

Fix modules_extra action for widget recent posts


<?php

declare(strict_types=1);

namespace Cortex\Fort\Http\Controllers\Backend;

use Carbon\Carbon;
use Cortex\Fort\Models\Role;
use Cortex\Fort\Models\User;
use Cortex\Fort\Models\Ability;
use Rinvex\Fort\Models\Session;
use Illuminate\Support\Facades\DB;
use Cortex\Foundation\Http\Controllers\AuthorizedController;

class DashboardController extends AuthorizedController
{
    /**
     * {@inheritdoc}
     */
    protected $resource = 'dashboard';

    /**
     * {@inheritdoc}
     */
    protected $resourceAbilityMap = ['home' => 'access'];

    /**
     * Show the dashboard home.
     *
     * @return \Illuminate\Http\Response
     */
    public function home()
    {
        // Get statistics
        $stats = [
            'abilities' => ['route' => route('backend.abilities.index'), 'count' => Ability::count()],
            'roles' => ['route' => route('backend.roles.index'), 'count' => Role::count()],
            'users' => ['route' => route('backend.users.index'), 'count' => User::count()],
        ];

        // Get online users
        $onlineInterval = Carbon::now()->subMinutes(config('rinvex.fort.online_interval'));
        $sessions = Session::users($onlineInterval)->groupBy(['user_id'])->with(['user'])->get(['user_id', DB::raw('MAX(last_activity) as last_activity')]);

        return view('cortex/fort::backend.pages.home', compact('sessions', 'stats'));
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Fort\Http\Controllers\Backend;

use Carbon\Carbon;
use Cortex\Fort\Models\Role;
use Cortex\Fort\Models\User;
use Cortex\Fort\Models\Ability;
use Rinvex\Fort\Models\Session;
use Illuminate\Support\Facades\DB;
use Cortex\Foundation\Http\Controllers\AuthorizedController;

class DashboardController extends AuthorizedController
{
    /**
     * {@inheritdoc}
     */
    protected $resource = 'dashboard';

    /**
     * {@inheritdoc}
     */
    protected $resourceAbilityMap = ['home' => 'access'];

    /**
     * Show the dashboard home.
     *
     * @return \Illuminate\Http\Response
     */
    public function home()
    {
        // Get statistics
        $stats = [
            'abilities' => ['route' => route('backend.abilities.index'), 'count' => Ability::count()],
            'roles' => ['route' => route('backend.roles.index'), 'count' => Role::count()],
            'users' => ['route' => route('backend.users.index'), 'count' => User::count()],
        ];

        // Get online users
        $sessions = Session::users(config('rinvex.fort.online_interval'))->groupBy(['user_id'])->with(['user'])->get(['user_id', DB::raw('MAX(last_activity) as last_activity')]);

        return view('cortex/fort::backend.pages.home', compact('sessions', 'stats'));
    }
}

Fix wrong sessions time interval parameter datatype


<?php

require_once 'Zend/Log/Writer/Abstract.php';

/**
 * Publish SilverStripe errors and warnings to Sentry using the Raven client.
 */
class SentryLogger extends Zend_Log_Writer_Abstract {

    private $sentry;

    private $logLevels = array(
        'NOTICE'    => Raven_Client::INFO,
        'WARN'      => Raven_Client::WARNING,
        'ERR'       => Raven_Client::ERROR
    );

    /**
     * @config
     */
    private static $sentry_dsn;

    public static function factory($config) {
        return new SentryLogger();
    }

    public function __construct()
    {
        $DSN = Config::inst()->get('SentryLogger', 'sentry_dsn');
        $this->sentry = new Raven_Client($DSN);
        $this->sentry->setEnvironment(Director::get_environment_type());
    }

    /**
     * Send the error.
     *
     * @param array $event
     * @return void
    */
    public function _write($event) {
        $data['level'] = $this->logLevels[$event['priorityName']];
        $data['timestamp'] = strtotime($event['timestamp']);
        $backtrace = SS_Backtrace::filter_backtrace(debug_backtrace(), array("SentryLogger->_write"));
        $this->sentry->captureMessage($event['message']['errstr'], array(), $data, $backtrace);
    }

}

<?php

require_once 'Zend/Log/Writer/Abstract.php';

/**
 * Publish SilverStripe errors and warnings to Sentry using the Raven client.
 */
class SentryLogger extends Zend_Log_Writer_Abstract {

    private $sentry;

    private $logLevels = array(
        'NOTICE'    => Raven_Client::INFO,
        'WARN'      => Raven_Client::WARNING,
        'ERR'       => Raven_Client::ERROR
    );

    /**
     * @config
     */
    private static $sentry_dsn;

    public static function factory($config) {
        return new SentryLogger();
    }

    public function __construct()
    {
        $DSN = Config::inst()->get('SentryLogger', 'sentry_dsn');
        $this->sentry = new Raven_Client($DSN);
        $this->sentry->setEnvironment(Director::get_environment_type());

        if(Member::currentUserID()) {
            $this->sentry->user_context(array(
                'email' => Member::curentUser()->Email,
                'id' => Member::currentUserID()
            ));
        }
    }

    /**
     * Send the error.
     *
     * @param array $event
     * @return void
    */
    public function _write($event) {
        $data['level'] = $this->logLevels[$event['priorityName']];
        $data['timestamp'] = strtotime($event['timestamp']);
        $backtrace = SS_Backtrace::filter_backtrace(debug_backtrace(), array("SentryLogger->_write"));
        $this->sentry->captureMessage($event['message']['errstr'], array(), $data, $backtrace);
    }

}

Add user context to Raven client, if the user is logged in


<?php

$path_extra = dirname(dirname(__FILE__)) . '/lib';

$path = ini_get('include_path');
$path = $path_extra . PATH_SEPARATOR . $path;
ini_set('include_path', $path);

require_once('SimpleSAML/Configuration.php');

SimpleSAML_Configuration::init(dirname(dirname(__FILE__)) . '/config');

?>

<?php

/* Remove magic quotes. */
if(get_magic_quotes_gpc()) {
	foreach(array('_GET', '_POST', '_COOKIE', '_REQUEST') as $a) {
		foreach($$a as &$v) {

			/* We don't use array-parameters anywhere.
			 * Ignore any that may appear.
			 */
			if(is_array($v)) {
				continue;
			}

			/* Unescape the string. */
			$v = stripslashes($v);
		}
	}
}

$path_extra = dirname(dirname(__FILE__)) . '/lib';

$path = ini_get('include_path');
$path = $path_extra . PATH_SEPARATOR . $path;
ini_set('include_path', $path);

require_once('SimpleSAML/Configuration.php');

SimpleSAML_Configuration::init(dirname(dirname(__FILE__)) . '/config');

?>

Remove magic quotes as a part of the initialization of simpleSAMLphp.


<?php

namespace Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor;

use Symfony\Component\HttpFoundation\Request;

/**
 * AuthorizationHeaderTokenExtractor.
 *
 * @author Nicolas Cabot <n.cabot@lexik.fr>
 */
class AuthorizationHeaderTokenExtractor implements TokenExtractorInterface
{
    /**
     * @var string
     */
    protected $prefix;

    /**
     * @var string
     */
    protected $name;

    /**
     * @param string $prefix
     * @param string $name
     */
    public function __construct($prefix, $name)
    {
        $this->prefix = $prefix;
        $this->name   = $name;
    }

    /**
     * {@inheritdoc}
     */
    public function extract(Request $request)
    {
        if (!$request->headers->has($this->name)) {
            return false;
        }

        $headerParts = explode(' ', $request->headers->get($this->name));

        if (!(count($headerParts) === 2 && $headerParts[0] === $this->prefix)) {
            return false;
        }

        return $headerParts[1];
    }
}

<?php

namespace Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor;

use Symfony\Component\HttpFoundation\Request;

/**
 * AuthorizationHeaderTokenExtractor.
 *
 * @author Nicolas Cabot <n.cabot@lexik.fr>
 */
class AuthorizationHeaderTokenExtractor implements TokenExtractorInterface
{
    /**
     * @var string
     */
    protected $prefix;

    /**
     * @var string
     */
    protected $name;

    /**
     * @param string|null $prefix
     * @param string      $name
     */
    public function __construct($prefix, $name)
    {
        $this->prefix = $prefix;
        $this->name   = $name;
    }

    /**
     * {@inheritdoc}
     */
    public function extract(Request $request)
    {
        if (!$request->headers->has($this->name)) {
            return false;
        }

        $authorizationHeader = $request->headers->get($this->name);

        if (empty($this->prefix)) {
            return $authorizationHeader;
        }

        $headerParts = explode(' ', $authorizationHeader);

        if (!(count($headerParts) === 2 && $headerParts[0] === $this->prefix)) {
            return false;
        }

        return $headerParts[1];
    }
}

Handle empty or null authorization header prefix


<?php

namespace AppBundle\API\Mapping;

use AppBundle\API\Webservice;
use AppBundle\User\FennecUser;
use Symfony\Component\HttpFoundation\ParameterBag;

class ByOrganismName extends Webservice
{
    private $db;

    /**
     * @inheritdoc
     */
    public function execute(ParameterBag $query, FennecUser $user = null)
    {
        $this->db = $this->getManagerFromQuery($query)->getConnection();
        if(!$query->has('ids') || !is_array($query->get('ids')) || count($query->get('ids')) === 0){
            return array();
        }
        $ids = $query->get('ids');
        $result = array_fill_keys($ids, null);
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $query_get_mapping = <<<EOF
SELECT fennec_id, scientific_name
    FROM organism
        WHERE scientific_name IN ({$placeholders})
EOF;
        $stm_get_mapping = $this->db->prepare($query_get_mapping);
        $stm_get_mapping->execute($ids);

        while($row = $stm_get_mapping->fetch(\PDO::FETCH_ASSOC)){
            $result[$row['scientific_name']] = $row['fennec_id'];
        }

        return $result;
    }
}

<?php

namespace AppBundle\API\Mapping;

use AppBundle\API\Webservice;
use AppBundle\User\FennecUser;
use Symfony\Component\HttpFoundation\ParameterBag;

class ByOrganismName extends Webservice
{
    private $db;

    /**
     * @inheritdoc
     */
    public function execute(ParameterBag $query, FennecUser $user = null)
    {
        $this->db = $this->getManagerFromQuery($query)->getConnection();
        if(!$query->has('ids') || !is_array($query->get('ids')) || count($query->get('ids')) === 0){
            return array();
        }
        $ids = $query->get('ids');
        $result = array_fill_keys($ids, null);
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $query_get_mapping = <<<EOF
SELECT fennec_id, scientific_name
    FROM organism
        WHERE scientific_name IN ({$placeholders})
EOF;
        $stm_get_mapping = $this->db->prepare($query_get_mapping);
        $stm_get_mapping->execute($ids);

        while($row = $stm_get_mapping->fetch(\PDO::FETCH_ASSOC)){
            $name = $row['scientific_name'];
            if($result[$name] === null){
                $result[$row['scientific_name']] = $row['fennec_id'];
            } else {
                if(! is_array($result[$name]) ){
                    $result[$name] = [$result[$name]];
                }
                $result[$name][] = $row['fennec_id'];
            }
        }

        return $result;
    }
}

Add multi mappings to mapping by scientific name


<?php
use Migrations\AbstractMigration;

class PrefixMenuItems extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $this->table('menu_items')
            ->rename('qobo_menu_items');
    }
}

<?php
use Migrations\AbstractMigration;

class PrefixMenuItems extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $this->table('menu_items')
            ->rename('qobo_menu_items')
            ->update();
    }
}

Fix compatibility isssues with Phinx 0.11


<?php
namespace Scheb\TwoFactorBundle\Tests;

abstract class TestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * Returns a test double for the specified class.
     * Compatibility layer for PHPUnit < 5.3
     *
     * @param string $originalClassName
     *
     * @return \PHPUnit_Framework_MockObject_MockObject
     * @throws \PHPUnit_Framework_Exception
     */
    protected function createMock($originalClassName)
    {
        return $this->getMockBuilder($originalClassName)
            ->disableOriginalConstructor()
            ->disableOriginalClone()
            ->disableArgumentCloning()
            ->getMock();
    }
}

<?php
namespace Scheb\TwoFactorBundle\Tests;

use PHPUnit\Framework\TestCase as PHPUnitTestCase;

abstract class TestCase extends PHPUnitTestCase
{

}

Migrate tests to new PHPUnit version

Migrate tests to new PHPUnit version


<?php
/**
 * Part of CI PHPUnit Test
 *
 * @author     Kenji Suzuki <https://github.com/kenjis>
 * @license    MIT License
 * @copyright  2015 Kenji Suzuki
 * @link       https://github.com/kenjis/ci-phpunit-test
 */

class Welcome_test extends TestCase
{
	public function test_index()
	{
		$output = $this->request('GET', ['welcome', 'index']);
		$this->assertContains('<title>Welcome to CodeIgniter</title>', $output);
	}

	public function test_APPPATH()
	{
		$actual = realpath(APPPATH);
		$expected = realpath(__DIR__ . '/../..');
		$this->assertEquals(
			$expected,
			$actual,
			'Your APPPATH seems to be wrong. Check your $application_folder in tests/Bootstrap.php'
		);
	}
}

<?php
/**
 * Part of CI PHPUnit Test
 *
 * @author     Kenji Suzuki <https://github.com/kenjis>
 * @license    MIT License
 * @copyright  2015 Kenji Suzuki
 * @link       https://github.com/kenjis/ci-phpunit-test
 */

class Welcome_test extends TestCase
{
	public function test_index()
	{
		$output = $this->request('GET', ['welcome', 'index']);
		$this->assertContains('<title>Welcome to CodeIgniter</title>', $output);
	}

	/**
	 * @expectedException		PHPUnit_Framework_Exception
	 * @expectedExceptionCode	404
	 */
	public function test_method_404()
	{
		$output = $this->request('GET', ['welcome', 'method_not_exist']);
	}

	public function test_APPPATH()
	{
		$actual = realpath(APPPATH);
		$expected = realpath(__DIR__ . '/../..');
		$this->assertEquals(
			$expected,
			$actual,
			'Your APPPATH seems to be wrong. Check your $application_folder in tests/Bootstrap.php'
		);
	}
}

Add test sample of 404 method

Add test sample of 404 method


<?php namespace Weidner\Goutte;

use Weidner\Goutte\Goutte;
use Illuminate\Support\ServiceProvider;

class GoutteServiceProvider extends ServiceProvider {

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

  /**
   * Bootstrap the application events.
   *
   * @return void
   */
  public function boot()
  {
    $this->package('weidner/goutte');
  }

  /**
   * Register the service provider.
   *
   * @return void
   */
  public function register()
  {
    $this->registerGoutte();

    $this->app->alias('goutte', 'Goutte\Client');
  }

  /**
   * Register the Goutte instance.
   *
   * @return void
   */
  protected function registerGoutte()
  {
    $this->app->bindShared('goutte', function($app)
    {
      return new \Goutte\Client();
    });
  }

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

}

<?php namespace Weidner\Goutte;

use Weidner\Goutte\Goutte;
use Illuminate\Support\ServiceProvider;

class GoutteServiceProvider extends ServiceProvider {

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

  /**
   * Register the service provider.
   *
   * @return void
   */
  public function register()
  {
    $this->registerGoutte();

    $this->app->alias('goutte', 'Goutte\Client');
  }

  /**
   * Register the Goutte instance.
   *
   * @return void
   */
  protected function registerGoutte()
  {
    $this->app->bindShared('goutte', function($app)
    {
      return new \Goutte\Client();
    });
  }

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

}

Remove call to undefined method from service provider


<?php

/**
* @author fabriceb
* @since Sep 29, 2009
*/

/**
 * Add the facebook app url in front
 *
 * @param string $internal_uri
 * @return string
 * @author fabriceb
 * @since 2009-06-03
 */
function fb_url_for($internal_uri)
{
  $host = '';
  if (sfFacebook::inCanvas())
  {
    $host = sfConfig::get('app_facebook_app_url');
  }

  return $host.url_for($internal_uri, false);
}

<?php

/**
* @author fabriceb
* @since Sep 29, 2009
*/

/**
 * Add the facebook app url in front
 *
 * @param string $internal_uri
 * @return string
 * @author fabriceb
 * @since 2009-06-03
 */
function fb_url_for()
{
  $arguments = func_get_args();

  $host = '';
  if (sfFacebook::inCanvas())
  {
    $host = sfConfig::get('app_facebook_app_url');
  }

  return $host.call_user_func_array('url_for', $arguments);
}

[sfFacebookConnectPlugin] Use the fb_url_for function to easily reference urls in a canvas application

git-svn-id: 8bf30244cac7f210af08ef653903b56a8ef0c1af@22608 ee427ae8-e902-0410-961c-c3ed070cd9f9


<?php
namespace Craft;

class SyncCommand extends BaseCommand
{

    public function actionPlugin()
    {
        echo "Synchronizing plugins\n";
        $requiredPlugins = array_merge(['Console'], craft()->config->get('activePlugins', 'plugins'));
        $currentPlugins = craft()->plugins->getPlugins(false);

        foreach ($currentPlugins as $plugin) {

            $pluginClassHandle = $plugin->getClassHandle();

            if (in_array($pluginClassHandle, $requiredPlugins)) {

                // This plugin should be activated
                if (!$plugin->isInstalled) {
                    echo "Installing $pluginClassHandle plugin.\n";
                    craft()->plugins->installPlugin($pluginClassHandle);
                } elseif (!$plugin->isEnabled) {
                    echo "Enabling $pluginClassHandle plugin.\n";
                    craft()->plugins->enablePlugin($pluginClassHandle);
                } else {
                    echo "Plugin $pluginClassHandle is already active.\n";
                }

            } else {

                // This plugin should be deactivated
                if ($plugin->isEnabled) {
                    echo "Disabling $pluginClassHandle plugin.\n";
                    craft()->plugins->disablePlugin($pluginClassHandle);
                }

            }
        }
    }

}

<?php
namespace Craft;

class SyncCommand extends BaseCommand
{

    public function actionPlugin()
    {
        echo "Synchronizing plugins\n";
        if (!craft()->config->exists('activePlugins', 'plugins')) {
            echo "You need to specify plugins in craft/config/plugins.php before using this functionality.\n";
        }
        $requiredPlugins = array_merge(['Console'], craft()->config->get('activePlugins', 'plugins'));
        $currentPlugins = craft()->plugins->getPlugins(false);

        foreach ($currentPlugins as $plugin) {

            $pluginClassHandle = $plugin->getClassHandle();

            if (in_array($pluginClassHandle, $requiredPlugins)) {

                // This plugin should be activated
                if (!$plugin->isInstalled) {
                    echo "Installing $pluginClassHandle plugin.\n";
                    craft()->plugins->installPlugin($pluginClassHandle);
                } elseif (!$plugin->isEnabled) {
                    echo "Enabling $pluginClassHandle plugin.\n";
                    craft()->plugins->enablePlugin($pluginClassHandle);
                } else {
                    echo "Plugin $pluginClassHandle is already active.\n";
                }

            } else {

                // This plugin should be deactivated
                if ($plugin->isEnabled) {
                    echo "Disabling $pluginClassHandle plugin.\n";
                    craft()->plugins->disablePlugin($pluginClassHandle);
                }

            }
        }
    }

}

Verify the config file before use

Verify the config file before use


<?php

namespace UCD\Infrastructure\Repository\CharacterRepository\FileRepository\RangeFile;

use IntervalTree\IntervalTree as BaseIntervalTree;
use UCD\Infrastructure\Repository\CharacterRepository\FileRepository\Range;

class IntervalTree extends BaseIntervalTree
{
    /**
     * @var Range[]
     */
    protected $ranges = [];

    /**
     * @param Range[] $ranges
     * @param callable|null $comparator
     */
    public function __construct(array $ranges, callable $comparator = null)
    {
        $this->ranges = $ranges;

        BaseIntervalTree::__construct($ranges, $comparator);
    }

    /**
     * @param Range $range
     */
    public function add(Range $range)
    {
        $this->ranges[] = $range;
        $this->top_node = $this->divide_intervals($this->ranges);
    }
}

<?php

namespace UCD\Infrastructure\Repository\CharacterRepository\FileRepository\RangeFile;

use IntervalTree\IntervalTree as BaseIntervalTree;
use UCD\Infrastructure\Repository\CharacterRepository\FileRepository\Range;

class IntervalTree extends BaseIntervalTree
{
    /**
     * @var Range[]
     */
    protected $ranges = [];

    /**
     * @param Range[] $ranges
     * @param callable|null $comparator
     */
    public function __construct(array $ranges, callable $comparator = null)
    {
        $this->ranges = $ranges;

        parent::__construct($ranges, $comparator);
    }

    /**
     * @param Range $range
     */
    public function add(Range $range)
    {
        $this->ranges[] = $range;
        $this->top_node = $this->divide_intervals($this->ranges);
    }
}

Call to parent does not need to use classname


<?php

class Base_Controller extends Controller {

	/**
	 * Add the general styles and scripts.
	 *
	 */
	public function __construct() {
		Asset::container('header')->add('bootstrap_css', "/maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css");
		Asset::container('header')->add('open_sans', "/fonts.googleapis.com/css?family=Open+Sans:400,800,700,600,600italic,400italic");
		Asset::container('header')->add('global', "css/global.css");

		Asset::container('footer')->add('jquery', '/code.jquery.com/jquery-1.11.1.min.js');
		Asset::container('footer')->add('bootstrap_js', "/maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js");
	}

	/**
	 * Catch-all method for requests that can't be matched.
	 *
	 * @param  string    $method
	 * @param  array     $parameters
	 * @return Response
	 */
	public function __call($method, $parameters)
	{
		return Response::error('404');
	}

}

<?php

class Base_Controller extends Controller {

	/**
	 * Add the general styles and scripts.
	 *
	 */
	public function __construct() {
		Asset::container('header')->add('bootstrap_css', "/maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css");
		Asset::container('header')->style('open_sans', "/fonts.googleapis.com/css?family=Open+Sans:400,800,700,600,600italic,400italic");
		Asset::container('header')->add('global', "css/global.css");

		Asset::container('footer')->add('jquery', '/code.jquery.com/jquery-1.11.1.min.js');
		Asset::container('footer')->add('bootstrap_js', "/maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js");
	}

	/**
	 * Catch-all method for requests that can't be matched.
	 *
	 * @param  string    $method
	 * @param  array     $parameters
	 * @return Response
	 */
	public function __call($method, $parameters)
	{
		return Response::error('404');
	}

}

Add properly open sans font.

Add properly open sans font.


<?php

use yii\db\Migration;
use yii\db\mysql\Schema;

class m160107_221900_add_wallet_table extends Migration
{
    public function up()
    {
        $this->createTable('{{%wallet}}', [
            'id' => Schema::TYPE_PK,
            'user_id' => Schema::TYPE_INTEGER . ' NOT NULL',
            'name' => Schema::TYPE_STRING . ' NOT NULL',
            'created_at' => Schema::TYPE_DATETIME . ' NOT NULL',
            'updated_at' => Schema::TYPE_DATETIME
        ]);
        $this->addForeignKey('fk_wallet_user', 'wallet', 'user_id', 'user', 'id', 'CASCADE', 'CASCADE');
    }

    public function down()
    {
        $this->dropForeignKey('fk_wallet_user', 'wallet');
        $this->dropTable('{{%wallet}}');
    }
}

<?php

use yii\db\Migration;
use yii\db\mysql\Schema;

class m160107_221900_add_wallet_table extends Migration
{
    public function up()
    {
        $this->createTable('{{%wallet}}', [
            'id' => Schema::TYPE_PK,
            'user_id' => Schema::TYPE_INTEGER . ' NOT NULL',
            'name' => Schema::TYPE_STRING . ' NOT NULL',
            'currency' => 'CHAR(3)',
            'created_at' => Schema::TYPE_DATETIME . ' NOT NULL',
            'updated_at' => Schema::TYPE_DATETIME
        ]);
        $this->addForeignKey('fk_wallet_user', 'wallet', 'user_id', 'user', 'id', 'CASCADE', 'CASCADE');
    }

    public function down()
    {
        $this->dropForeignKey('fk_wallet_user', 'wallet');
        $this->dropTable('{{%wallet}}');
    }
}

Master: Update migration, add currency column to wallet table


<?php
class testRuleDoesApplyToCompoundVariableInString
{
    public function testRuleDoesApplyToCompoundVariableInString()
    {
        $bar = 'foo';
        return "${bar}_me";
    }
}

<?php
/**
 * This file is part of PHP Mess Detector.
 *
 * Copyright (c) Manuel Pichler <mapi@phpmd.org>.
 * All rights reserved.
 *
 * Licensed under BSD License
 * For full copyright and license information, please see the LICENSE file.
 * Redistributions of files must retain the above copyright notice.
 *
 * @author Manuel Pichler <mapi@phpmd.org>
 * @copyright Manuel Pichler. All rights reserved.
 * @license https://opensource.org/licenses/bsd-license.php BSD License
 * @link http://phpmd.org/
 */

class testRuleDoesApplyToCompoundVariableInString
{
    public function testRuleDoesApplyToCompoundVariableInString()
    {
        $bar = 'foo';
        return "${bar}_me";
    }
}

Add new file doc block

Add new file doc block


<?php

namespace Codenexus\Honeypot;

use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;

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

    public function boot()
    {
    	$this->loadTranslationsFrom(__DIR__ . '/../lang', 'honeypot');

    	Validator::extend('honeypot', 'honeypot@validateHoneypot', trans('validation.honeypot'));
    	Validator::extend('honeytime', 'honeypot@validateHoneytime', trans('validation.honeytime'));
    }

    public function register()
    {
        $this->app->singleton('honeypot', function () {
            return new Honeypot;
        });
    }

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

<?php

namespace Codenexus\Honeypot;

use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;

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

    public function boot()
    {
    	$this->loadTranslationsFrom(__DIR__ . '/../lang', 'honeypot');

    	Validator::extend('honeypot', 'honeypot@validateHoneypot', trans('honeypot::validation.honeypot'));
    	Validator::extend('honeytime', 'honeypot@validateHoneytime', trans('honeypot::validation.honeytime'));
    }

    public function register()
    {
        $this->app->singleton('honeypot', function () {
            return new Honeypot;
        });
    }

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

Fix localization for validation error messages.


        <?php if ($mode == 'issue'): ?>
            <?= __('Attach one or more file(s) to this issue'); ?>
        <?php elseif ($mode == 'article'): ?>
            <?= __('Attach one or more file(s) to this article'); ?>
        <?php endif; ?>
        <?= fa_image_tag('times'); ?>

    <?php include_component('main/'.$uploader.'uploader', compact('mode', 'issue', 'article')); ?>

        <?php if ($mode == 'issue'): ?>
            <?= __('Attach one or more file(s) to this issue'); ?>
        <?php elseif ($mode == 'article'): ?>
            <?= __('Attach one or more file(s) to this article'); ?>
        <?php endif; ?>
        <?= fa_image_tag('times'); ?>

    <?php
        if (isset($article))
        {
            include_component('main/'.$uploader.'uploader', compact('mode', 'issue', 'article'));
        }
        else
        {
            include_component('main/'.$uploader.'uploader', compact('mode', 'issue'));
        }
    ?>

Check if $article is set

Check if $article is set


<?php

// test disconnection from skeleton.mics.me
if (Site::$hostname == 'skeleton.emr.ge') {
    Site::$autoPull = false;
}

Site::$debug = true; // set to true for extended query logging
//Site::$production = true; // set to true for heavy file caching

// these resolved paths will skip initializing a user session
Site::$skipSessionPaths[] = 'thumbnail.php';

// uncomment or set to an array of specific hostnames to enable CORS
//Site::$permittedOrigins = '*';

// Custom routing called if a page isn't found in site-root
/*Site::$onNotFound = function($message) {
    switch($action = Site::$requestPath[0])
    {
        default:
            if($Page = Page::getByHandle($action))
            {
                return Page::renderPage();
            }
            else
            {
                header('HTTP/1.0 404 Not Found');
                die($message);
            }
    }
};*/

<?php

// test disconnection from skeleton.mics.me
if (Site::$hostname == 'skeleton.emr.ge') {
    Site::$autoPull = false;
}

Site::$debug = true; // set to true for extended query logging
//Site::$production = true; // set to true for heavy file caching

// these resolved paths will skip initializing a user session
Site::$skipSessionPaths[] = 'thumbnail.php';
Site::$skipSessionPaths[] = 'min.php';

// uncomment or set to an array of specific hostnames to enable CORS
//Site::$permittedOrigins = '*';

// Custom routing called if a page isn't found in site-root
/*Site::$onNotFound = function($message) {
    switch($action = Site::$requestPath[0])
    {
        default:
            if($Page = Page::getByHandle($action))
            {
                return Page::renderPage();
            }
            else
            {
                header('HTTP/1.0 404 Not Found');
                die($message);
            }
    }
};*/

Add min.php to skip session list

Add min.php to skip session list


<?php

abstract class SQLayerTable
{

    /** @property *str* table name **/
    protected $tableName;

    /** @property *obj* SQLayerDbo **/
    protected $dbo;

    /** @method get record from key
      * @param  *int* integer key
      * @return *arr* assoc (or false) **/
    public function recFromKey($key)
    {
        /** compose sql **/
        $sql = 'SELECT * FROM "'.$this->tableName.'" WHERE "key" = '.$key.';';

        /** return the first record (or false) **/
        if ($recs = $this->dbo->fetchRecs($sql)) {
            foreach ($recs as $rec) {
                return $rec;
            }
        } else {
            return false;
        }

    }

    /** @method get record from key
      * @param  *int* integer key
      * @return *arr* array of assocs (or false) **/
    public function allRecs()
    {
        /** compose sql **/
        $sql = 'SELECT * FROM "'.$this->tableName.'";';

        /** return the array of recs (or false) **/
        if ($recs = $this->dbo->fetchRecs($sql)) {
            return $recs;
        } else {
            return false;
        }

    }

}

<?php

abstract class SQLayerTable
{

    /** @property *str* table name **/
    protected $tableName;

    /** @property *obj* SQLayerDbo **/
    protected $dbo;

    /** @method get record from key
      * @param  *int* integer key
      * @return *arr* assoc (or false) **/
    public function recFromKey($key)
    {
        /** compose sql **/
        $sql = 'SELECT * FROM "'.$this->tableName.'" WHERE "key" = '.$key.';';

        /** return the first record (or false) **/
        if ($recs = $this->dbo->fetchRecs($sql)) {
            foreach ($recs as $rec) {
                return $rec;
            }
        } else {
            return false;
        }

    }

    /** @method get record from key
      * @param  void
      * @return *arr* array of assocs (or false) **/
    public function allRecs()
    {
        /** compose sql **/
        $sql = 'SELECT * FROM "'.$this->tableName.'";';

        /** return the array of recs (or false) **/
        if ($recs = $this->dbo->fetchRecs($sql)) {
            return $recs;
        } else {
            return false;
        }

    }

}

Fix comment incorrectly indicating an unexpected method parameter.


<?php

namespace Rogue\Services;

use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;

class GraphQL
{
    /**
     * Build a new GraphQL client.
     */
    public function __construct()
    {
        $this->client = ClientBuilder::build(config('services.graphql.url'));
    }

    /**
     * Run a GraphQL query using the client and return the data result.
     *
     * @param  $query     String
     * @param  $variables Array
     * @return array
     */
    public function query($query, $variables)
    {
        $response = $this->client->query($query, $variables);

        return $response ? $response->getData() : [];
    }

    /**
     * Query for a CampaignWebsite by campaignId field.
     *
     * @param  $campaignId String
     * @return array
     */
    public function getCampaignWebsiteByCampaignId($campaignId)
    {
        $query = '
        query GetCampaignWebsiteByCampaignId($campaignId: String!) {
          campaignWebsiteByCampaignId(campaignId: $campaignId) {
            title
            slug
          }
        }';

        $variables = [
            'campaignId' => $campaignId,
        ];

        return $this->query($query, $variables);
    }
}

<?php

namespace Rogue\Services;

use Softonic\GraphQL\ClientBuilder;

class GraphQL
{
    /**
     * Build a new GraphQL client.
     */
    public function __construct()
    {
        $this->client = ClientBuilder::build(config('services.graphql.url'));
    }

    /**
     * Run a GraphQL query using the client and return the data result.
     *
     * @param  $query     String
     * @param  $variables Array
     * @return array
     */
    public function query($query, $variables)
    {
        $response = $this->client->query($query, $variables);

        return $response ? $response->getData() : [];
    }

    /**
     * Query for a CampaignWebsite by campaignId field.
     *
     * @param  $campaignId String
     * @return array
     */
    public function getCampaignWebsiteByCampaignId($campaignId)
    {
        $query = '
        query GetCampaignWebsiteByCampaignId($campaignId: String!) {
          campaignWebsiteByCampaignId(campaignId: $campaignId) {
            title
            slug
          }
        }';

        $variables = [
            'campaignId' => $campaignId,
        ];

        return $this->query($query, $variables);
    }
}

Remove the now unused Log import

Remove the now unused Log import


<?php
/**
 * Changes made by Pierre-Henry Soria.
 */

// JavaScript file is located in the directory ~static/js/str.js which is included in the file ~templates/themes/base/tpl/layout.tpl
namespace PFBC\Element;

class Textarea extends \PFBC\Element
{
    /** @var array */
    protected $attributes = array('class' => 'pfbc-textarea');

    public function jQueryDocumentReady()
    {
        echo 'jQuery("#', $this->attributes['id'], '").outerWidth(jQuery("#', $this->attributes['id'], '").width());';
    }

    public function render()
    {
        $iLength = !empty($this->attributes['value']) ? (new \PH7\Framework\Str\Str)->length($this->attributes['value']) : 0;

        echo '<textarea onkeyup="textCounter(\'', $this->attributes['id'], '\',\'', $this->attributes['id'], '_rem_len\')"', $this->getAttributes('value'), $this->getHtmlRequiredIfApplicable(), '>';

        if (!empty($this->attributes['value'])) {
            echo $this->filter($this->attributes['value']);
        }

        echo '</textarea>
attributes['id'], '_rem_len">' . $iLength . ' ', t('character(s).'), '
';
    }
}

<?php
/**
 * Changes made by Pierre-Henry Soria.
 */

// JavaScript file is located in the directory ~static/js/str.js which is included in the file ~templates/themes/base/tpl/layout.tpl
namespace PFBC\Element;

class Textarea extends \PFBC\Element
{
    /** @var array */
    protected $attributes = array('class' => 'pfbc-textarea');

    public function render()
    {
        $iLength = !empty($this->attributes['value']) ? (new \PH7\Framework\Str\Str)->length($this->attributes['value']) : 0;

        echo '<textarea onkeyup="textCounter(\'', $this->attributes['id'], '\',\'', $this->attributes['id'], '_rem_len\')"', $this->getAttributes('value'), $this->getHtmlRequiredIfApplicable(), '>';

        if (!empty($this->attributes['value'])) {
            echo $this->filter($this->attributes['value']);
        }

        echo '</textarea>
attributes['id'], '_rem_len">' . $iLength . ' ', t('character(s).'), '
';
    }
}

Remove unused jQuery width size code

Remove unused jQuery width size code

Now, the textarea size is managed with CSS (no jQuery code anymore for that!)


<?php

class Reimbursement extends CActiveRecord{
	public $user_id,$type,$username,$name,$item, $price, $content, $approve_time, $create_time, $status;
	public static function model($className = __CLASS__){
		return parent::model($className);
	}
	public function tableName(){
		return 'reimbursement';
	}
    public function relations(){
        return array(
          'item' => array(self::HAS_MANY, 'reimbursement_item', 'reimbursement_id')

        );
    }
    public function rules(){
    	return array(
    		array('username, price', 'safe')
    		);
    }
}
?>

<?php

class Reimbursement extends CActiveRecord{
	public $user_id,$type,$username,$name,$item, $price, $content, $approve_time, $create_time, $status;
	public static function model($className = __CLASS__){
		return parent::model($className);
	}
	public function tableName(){
		return 'reimbursement';
	}
    public function relations(){
        return array(
          'item' => array(self::HAS_MANY, 'reimbursement_item', 'reimbursement_id')

        );
    }
    public function rules(){
    	return array(
    		array('username, price, content, approve_time, type', 'safe')
    		);
    }
    /**
     * Add new attributes
     * @param array $data
     * @param array $items
     * @return bool
     **/
    public static function add(array $data, array $items){
        $model = new Reimbursement;
        $model->attributes = $data;
        if($model->save()){
            foreach($items as $item){
                $itemModel = new ReimbursementItem;
                $itemModel->attributes = $item;
                $itemModel->reimbursement_id = $model->id;
                $itemModel->save();
            }
            return true;
        }
        return false;
    }
    /**
     * Update reimbusement record
     * @param array $data
     * @param array $items
     * @return bool
     **/
    public static function update(array $data, array $items){
        if(isset($data['id']))
            $model = self::model()->findByPk($data['id']);
        unset($data['id']);
        $model->attributes = $data;
        if($model->save()){
            if(Reimbursement::model()->deleteAllByAttributes(array('reimbursement_id'=>$model->id))){
                foreach($items as $item){
                    $itemModel = new ReimbursementItem;
                    $itemModel->attributes = $item;
                    $itemModel->reimbursement_id = $model->id;
                    $itemModel->save();
                }
            }
            return true;
        }
        return false;
    }
}
?>

Add useful functions to model

Add useful functions to model


<?php

/**
* @package   s9e\mediaembed
* @copyright Copyright (c) 2015-2016 The s9e Authors
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace s9e\Flarum\MediaEmbed;

use Flarum\Event\ConfigureFormatter;
use Illuminate\Events\Dispatcher;
use s9e\TextFormatter\Configurator\Bundles\MediaPack;

function subscribe(Dispatcher $events)
{
	$events->listen(
		ConfigureFormatter::class,
		function (ConfigureFormatter $event)
		{
			(new MediaPack)->configure($event->configurator);
		}
	);
};

return __NAMESPACE__ . '\\subscribe';

<?php

/**
* @package   s9e\mediaembed
* @copyright Copyright (c) 2015-2016 The s9e Authors
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace s9e\Flarum\MediaEmbed;

use Flarum\Formatter\Event\Configuring;
use Illuminate\Events\Dispatcher;
use s9e\TextFormatter\Configurator\Bundles\MediaPack;

function subscribe(Dispatcher $events)
{
	$events->listen(
		Configuring::class,
		function (Configuring $event)
		{
			(new MediaPack)->configure($event->configurator);
		}
	);
};

return __NAMESPACE__ . '\\subscribe';

Update namespaces for beta 8

Update namespaces for beta 8


<?php

//Revert all features
echo "Reverting all features...";
passthru('drush fra -y');
echo "Reverting complete...";

//Clear all cache
echo "Clearing cache...";
passthru('drush cc all');
echo "Clearing cache complete...";

<?php

//Revert all features
echo "Reverting all features...\n";
passthru('drush fra -y');
echo "Reverting complete.\n";

//Clear all cache
echo "Clearing cache.\n";
passthru('drush cc all');
echo "Clearing cache complete.\n";

Adjust status messages in 'drush revert features' example.


<?php
// (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

class Search_Formatter_ValueFormatter_Datetime extends Search_Formatter_ValueFormatter_Abstract
{
	protected $format;

	function __construct()
	{
		$tikilib = TikiLib::lib('tiki');
		$this->format = $tikilib->get_short_datetime_format();
	}

	function render($name, $value, array $entry)
	{
		if (preg_match('/^\d{14}$/', $value)) {
			// Facing a date formated as YYYYMMDDHHIISS as indexed in lucene
			// Always stored as UTC
			$value = date_create_from_format('YmdHise', $value . 'UTC')->getTimestamp();
		}

		if (is_numeric($value)) {	// expects a unix timestamp but might be getting the default value
			$tikilib = TikiLib::lib('tiki');
			return $tikilib->date_format($this->format, $value);
		} else {
			return $value;
		}
	}
}

<?php
// (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

class Search_Formatter_ValueFormatter_Datetime extends Search_Formatter_ValueFormatter_Abstract
{
	protected $format;

	function __construct()
	{
		$tikilib = TikiLib::lib('tiki');
		$this->format = $tikilib->get_short_datetime_format();
	}

	function render($name, $value, array $entry)
	{
		if (preg_match('/^\d{14}$/', $value)) {
			// Facing a date formated as YYYYMMDDHHIISS as indexed in lucene
			// Always stored as UTC
			$value = date_create_from_format('YmdHise', $value . 'UTC')->getTimestamp();
		}

		$tikilib = TikiLib::lib('tiki');
		if (is_numeric($value)) {	// expects a unix timestamp but might be getting the default value
			return $tikilib->date_format($this->format, $value);
		} elseif (false !== $time = strtotime($value)) {
			return $tikilib->date_format($this->format, $time);
		} else {
			return $value;
		}
	}
}

[FIX] Handle other date formats that may come out of MySQL/ElasticSearch

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@47066 b456876b-0849-0410-b77d-98878d47e9d5


<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'j.naranjojr@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

Add email address to accept emails

Add email address to accept emails


@extends('layouts.admin')

@section('title'){{ $title }}@endsection

@section('content')

{{ Form::model($page, ['url' => $url, 'method' => $method]) }}

<label class="checkbox pull-right">
  {{ Form::checkbox('is_visible') }} Visible (Published)
</label>

{{ Form::label('title', 'Page Title') }}
{{ Form::text('title', null, ['class'=>'input-xxlarge', 'style'=>'font-size:150%']) }}

{{ Form::label('slug', 'URL (slug)') }}
{{ Form::text('slug', null, ['class'=>'input-xxlarge']) }}

{{ Form::label('body', 'Body (Markdown)') }}
{{ Form::textarea('body', null, ['class'=>'input-block-level', 'rows'=>20]) }}

{{ Form::label('head', 'Extra HTML for <head>') }}
{{ Form::textarea('head', null, ['class'=>'input-block-level']) }}

<p>
  {{ Form::submit('Submit', ['class'=>'btn']) }}
  {{ Html::linkRoute('sysop.pages.index', 'Cancel', null, ['class'=>'btn btn-danger'])}}
</p>

@endsection

@extends('layouts.admin')

@section('title'){{ $title }}@endsection

@section('content')

{{ Form::model($page, ['url' => $url, 'method' => $method]) }}

<label class="checkbox pull-right">
  {{ Form::checkbox('is_visible') }} Visible (Published)
</label>

{{ Form::label('title', 'Page Title') }}
{{ Form::text('title', null, ['class'=>'input-xxlarge', 'style'=>'font-size:150%']) }}

{{ Form::label('slug', 'URL (slug)') }}
{{ Form::text('slug', null, ['class'=>'input-xxlarge']) }}

{{ Form::label('body', 'Body (Markdown)') }}
{{ Form::textarea('body', null, ['class'=>'input-block-level', 'rows'=>20]) }}

{{ Form::label('head', 'Extra HTML for <head>') }}
{{ Form::textarea('head', null, ['class'=>'input-block-level']) }}

<p>
  {{ Form::submit('Submit', ['class'=>'btn']) }}
  {{ Html::linkRoute('sysop.pages.index', 'Cancel', null, ['class'=>'btn btn-danger'])}}
</p>

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

Add a missing Form::close() method

Add a missing Form::close() method


<?php

namespace PhpSchool\PhpWorkshop\Exception;

/**
 * Class InvalidArgumentException
 * @package PhpSchool\PhpWorkshop\Exception
 * @author Aydin Hassan <aydin@hotmail.co.uk>
 */
class InvalidArgumentException extends \InvalidArgumentException
{
    /**
     * @param string $expected
     * @param mixed $actual
     * @return static
     */
    public static function typeMisMatch($expected, $actual)
    {
        return new static(
            sprintf(
                'Expected: "%s" Received: "%s"',
                $expected,
                is_object($actual) ? get_class($actual) : gettype($actual)
            )
        );
    }
}

<?php

namespace PhpSchool\PhpWorkshop\Exception;

/**
 * Class InvalidArgumentException
 * @package PhpSchool\PhpWorkshop\Exception
 * @author Aydin Hassan <aydin@hotmail.co.uk>
 */
class InvalidArgumentException extends \InvalidArgumentException
{
    /**
     * @param string $expected
     * @param mixed $actual
     * @return static
     */
    public static function typeMisMatch($expected, $actual)
    {
        return new static(
            sprintf(
                'Expected: "%s" Received: "%s"',
                $expected,
                is_object($actual) ? get_class($actual) : gettype($actual)
            )
        );
    }

    /**
     * @param string $parameterName
     * @param mixed[] $allowedValues
     * @param mixed $actualValue
     * @return static
     */
    public static function notValidParameter($parameterName, array $allowedValues, $actualValue)
    {
        return new static(
            sprintf(
                'Parameter: "%s" can only be one of: "%s" Received: "%s"',
                $parameterName,
                static::stringify($allowedValues),
                static::stringify($actualValue)
            )
        );
    }

    /**
     * @param $value
     * @return string
     */
    public static function stringify($value)
    {
        if (is_object($value)) {
            return get_class($value);
        }

        if (is_array($value)) {
            return implode('", "', array_map([static::class, 'stringify'], $value));
        }

        if (is_scalar($value)) {
            return (string) $value;
        }

        if (is_bool($value)) {
            return ($value) ? 'true' : 'false';
        }

        return 'unknown';
    }
}

Add new static constructor for invalid parameters


<?php
/**
* phpCan - http://idc.anavallasuiza.com/
*
* phpCan is released under the GNU Affero GPL version 3
*
* More information at license.txt
*/

defined('ANS') or die();
?>

        <?php echo $info['title']; ?>

        <?php $Templates->render($template_content, array('info' => $info)); ?>

<?php
/**
* phpCan - http://idc.anavallasuiza.com/
*
* phpCan is released under the GNU Affero GPL version 3
*
* More information at license.txt
*/

defined('ANS') or die();
?>

        <?php echo $Content->info($Vars->get('connection'), 'name', $info['table']); ?>

        <?php $Templates->render($template_content, array('info' => $info)); ?>

Change relation template to get localized table names

Use the content info method to get table name instead os using the
title so it can use translations.


<?php

/**
 * Defines the SiteSprocketProductGroup data type, representing a holder for
 * {@link SiteSprocketProductOption}
 *
 * @package SiteSprocket
 * @author Aaron Carlino
 */

class SiteSprocketProductGroup extends DataObject
{
	static $db = array (
		'Title' => 'Varchar'
	);

	static $has_many = array (
		'Options' => 'SiteSprocketProductOption'
	);

	static $has_one = array (
		'SiteSprocket' => 'SiteSprocket'
	);

	static $summary_fields = array (
		'Title' => 'Title'
	);

	public function canCreate() {
		return true;
	}

	public function canDelete() {
		return true;
	}

	public function canEdit() {
		return true;
	}

	public function getCMSFields() {
		return new FieldSet (
			new TextField('Title', _t('SSP.GROUPNAME','Name'))
		);
	}

}

<?php

/**
 * Defines the SiteSprocketProductGroup data type, representing a holder for
 * {@link SiteSprocketProductOption}
 *
 * @package SiteSprocket
 * @author Aaron Carlino
 */

class SiteSprocketProductGroup extends DataObject
{
	static $db = array (
		'Title' => 'Varchar',
		'LimitOne' => 'Boolean'
	);

	static $has_many = array (
		'Options' => 'SiteSprocketProductOption'
	);

	static $has_one = array (
		'SiteSprocket' => 'SiteSprocket'
	);

	static $summary_fields = array (
		'Title' => 'Title'
	);

	public function canCreate() {
		return true;
	}

	public function canDelete() {
		return true;
	}

	public function canEdit() {
		return true;
	}

	public function getCMSFields() {
		return new FieldSet (
			new TextField('Title', _t('SSP.GROUPNAME','Name')),
			new CheckboxField('LimitOne', _t('SSP.GROUPLIMIT', 'Allow only one option?'))
		);
	}

	public function LimitOne() {
		if($this->LimitOne) {
			return " limit-one";
		}

		return false;
	}

}

ADD - Limit one functionality

ADD - Limit one functionality


<?php

namespace App\Storage;

use Amp\Mysql\Pool;
use Kelunik\Chat\Storage\int;
use Kelunik\Chat\Storage\RoomPermissionStorage;
use Kelunik\Chat\Storage\RoomStorage;

class MysqlRoomPermissionStorage implements RoomPermissionStorage {
    private $mysql;
    private $roomStorage;

    public function __construct(Pool $mysql, RoomStorage $roomStorage) {
        $this->mysql = $mysql;
    }

    public function getPermissions(int $user, int $room) {
        $query = yield $this->mysql->prepare("SELECT `permissions` FROM `room_user` WHERE `user_id` = ? && `room_id` = ?", [
            $user, $room,
        ]);

        $result = yield $query->fetch();

        if ($result) {
            $permissions = json_decode($result["permissions"]);

            return array_flip($permissions);
        }

        $room = yield $this->roomStorage->get($room);

        if (!$room) {
            return [];
        }

        if ($room->public) {
            return array_flip(["read"]);
        }

        return [];
    }
}

<?php

namespace App\Storage;

use Amp\Mysql\Pool;
use Kelunik\Chat\Storage\RoomPermissionStorage;
use Kelunik\Chat\Storage\RoomStorage;

class MysqlRoomPermissionStorage implements RoomPermissionStorage {
    private $mysql;
    private $roomStorage;

    public function __construct(Pool $mysql, RoomStorage $roomStorage) {
        $this->mysql = $mysql;
    }

    public function getPermissions(int $user, int $room) {
        $query = yield $this->mysql->prepare("SELECT `permissions` FROM `room_user` WHERE `user_id` = ? && `room_id` = ?", [
            $user, $room,
        ]);

        $result = yield $query->fetch();

        if ($result) {
            $permissions = json_decode($result["permissions"]);

            return array_flip($permissions);
        }

        $room = yield $this->roomStorage->get($room);

        if (!$room) {
            return [];
        }

        if ($room->public) {
            return array_flip(["read"]);
        }

        return [];
    }
}

Remove dumb int use statement

Remove dumb int use statement


<?php

namespace Overblog\GraphQLBundle\Event;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\Kernel;

/**
 * @internal
 * TODO(mcg-web): delete hack after migrating Symfony >= 4.3
 */
final class EventDispatcherVersionHelper
{
    private static $isForLegacy;

    /**
     * @return bool
     */
    public static function isForLegacy()
    {
        if (null === self::$isForLegacy) {
            self::$isForLegacy = \version_compare(Kernel::VERSION, '4.3.0', '<');
        }

        return self::$isForLegacy;
    }

    /**
     * @param EventDispatcherInterface $dispatcher
     * @param object                   $event
     * @param string|null              $eventName
     *
     * @return object the event
     */
    public static function dispatch(EventDispatcherInterface $dispatcher, $event, $eventName)
    {
        if (self::isForLegacy()) {
            return $dispatcher->dispatch($eventName, $event);
        } else {
            return $dispatcher->dispatch($event, $eventName);
        }
    }
}

<?php

namespace Overblog\GraphQLBundle\Event;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\Kernel;

/**
 * @internal
 * TODO(mcg-web): delete hack after migrating Symfony >= 4.3
 */
final class EventDispatcherVersionHelper
{
    /**
     * @return bool
     */
    public static function isForLegacy()
    {
        return Kernel::VERSION_ID < 403000;
    }

    /**
     * @param EventDispatcherInterface $dispatcher
     * @param object                   $event
     * @param string|null              $eventName
     *
     * @return object the event
     */
    public static function dispatch(EventDispatcherInterface $dispatcher, $event, $eventName)
    {
        if (self::isForLegacy()) {
            return $dispatcher->dispatch($eventName, $event);
        } else {
            return $dispatcher->dispatch($event, $eventName);
        }
    }
}

Fix eventDispatcher version helper to work with symfony 5 dev


<?php
namespace Purethink\CMSBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class Language extends Admin
{
    protected $translationDomain = 'PurethinkCMSBundle';

    protected $datagridValues = [
        '_sort_by' => 'name'
    ];

    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->with('General')
                ->add('name')
                ->add('alias')
                ->add('enabled', null, ['required' => false])
            ->end();
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('id')
            ->add('name')
            ->add('alias')
            ->add('enabled');
    }

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('id')
            ->addIdentifier('name')
            ->add("alias")
            ->add('enabled', null, ['editable' => true]);
    }

}

<?php
namespace Purethink\CMSBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class Language extends Admin
{
    protected $translationDomain = 'PurethinkCMSBundle';

    protected $datagridValues = [
        '_sort_by' => 'name'
    ];

    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->with('General', ['class' => 'col-md-8'])
                ->add('name')
                ->add('alias')
            ->end()
            ->with('Options', ['class' => 'col-md-4'])
                ->add('enabled', null, ['required' => false])
            ->end();
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('id')
            ->add('name')
            ->add('alias')
            ->add('enabled');
    }

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('id')
            ->addIdentifier('name')
            ->add("alias")
            ->add('enabled', null, ['editable' => true]);
    }

}

Change style for admin language panel

Change style for admin language panel


<?php
	/*
	Copyight: Deux Huit Huit 2013
	License: MIT, see the LICENCE file
	*/

	if(!defined("__IN_SYMPHONY__")) die("
Error

You cannot directly access this file
");

	/**
	 *
	 * @author Deux Huit Huit
	 * http://www.deuxhuithuit.com
	 *
	 */
	class extension_system_log_link extends Extension {

		/**
		 * Name of the extension
		 * @var string
		 */
		const EXT_NAME = 'System Log Link';

		/**
		 * Add the System logs to the naviguation
		 */
		public function fetchNavigation() {
			return array(
					array (
						'location' =>  __('System'),
						'name' => __('Log'),
						'limit' => 'developer',
						'link' => 'system/log/',
						'relative' => false,
						'target' => '_blank'
					)
				);
		}

		/* ********* INSTALL/UPDATE/UNISTALL ******* */

		/**
		 * Creates the table needed for the settings of the field
		 */
		public function install() {
			return true;

		}

		/**
		 * Creates the table needed for the settings of the field
		 */
		public function update($previousVersion) {
			return true;
		}

		/**
		 *
		 * Drops the table needed for the settings of the field
		 */
		public function uninstall() {
			return true;
		}

	}

<?php
	/*
	Copyight: Deux Huit Huit 2013
	License: MIT, see the LICENCE file
	*/

	if(!defined("__IN_SYMPHONY__")) die("
Error

You cannot directly access this file
");

	/**
	 *
	 * @author Deux Huit Huit
	 * http://www.deuxhuithuit.com
	 *
	 */
	class extension_system_log_link extends Extension {

		/**
		 * Name of the extension
		 * @var string
		 */
		const EXT_NAME = 'System Log Link';

		/**
		 * Add the System logs to the naviguation
		 */
		public function fetchNavigation() {
			return array(
					array (
						'location' =>  __('System'),
						'name' => __('Log'),
						'limit' => 'developer',
						'link' => 'system/log/',
						'relative' => false,
						'target' => '_blank'
					)
				);
		}

		/* ********* INSTALL/UPDATE/UNISTALL ******* */

		/**
		 * Creates the table needed for the settings of the field
		 */
		public function install() {
			return true;

		}

		/**
		 * Creates the table needed for the settings of the field
		 */
		public function update($previousVersion = false) {
			return true;
		}

		/**
		 *
		 * Drops the table needed for the settings of the field
		 */
		public function uninstall() {
			return true;
		}

	}

Fix compatibility php 7 strict mode

Fix compatibility php 7 strict mode

Picked from 1a289a49a8c346f19535dec55be02906797e6acd


<?php

namespace Yajra\CMS\Themes;

use Illuminate\View\FileViewFinder;

class ThemeViewFinder extends FileViewFinder
{
    /**
     * Base path to look for blade files.
     *
     * @var string
     */
    protected $basePath;

    /**
     * Set file view finder base path.
     *
     * @param $path
     */
    public function setBasePath($path)
    {
        $this->basePath = $path;

        array_unshift($this->paths, $this->basePath);
    }
}

<?php

namespace Yajra\CMS\Themes;

use Illuminate\View\FileViewFinder;

class ThemeViewFinder extends FileViewFinder
{
    /**
     * Base path to look for blade files.
     *
     * @var string
     */
    protected $basePath;

    /**
     * Set file view finder base path.
     *
     * @param $path
     */
    public function setBasePath($path)
    {
        $this->basePath = $path;

        array_unshift($this->paths, $this->basePath);
    }

    /**
     * Remove base path.
     */
    public function removeBasePath()
    {
        unset($this->paths[0]);
    }
}

Add method to remove base path.

Add method to remove base path.


<?php
$query = Query("SELECT name FROM {$dbpref}users");
$names = array();
while ($name = FetchRow($query))
{
	$name = strtolower(preg_replace('/[^a-zA-Z]/', '', $name[0]));
	// Name might not use any letters. Skip those.
	if ($name) {
		$names[] = $name;
	}
}
?>

Warning

You should be more original with your user names.

<?php
require 'pages/register.php';
?>

<?php
$query = Query("SELECT name FROM {$dbpref}users");
$names = array();
while ($name = FetchRow($query))
{
	$name = strtolower(preg_replace('/[^a-zA-Z]/', '', $name[0]));
	// Name might not use any letters. Skip those.
	if ($name)
		$names[] = $name;
}
?>

Warning

You should be more original with your user names.

<?php
require 'pages/register.php';
?>

Fix style of unoriginal names plugin

Fix style of unoriginal names plugin


<?php declare(strict_types = 1);

namespace Room11\StackChat\Auth;

use Room11\StackChat\Room\Identifier;

class ActiveSessionTracker implements SessionTracker
{
    /**
     * @var Session[]
     */
    private $sessions = [];

    public function setSessionForRoom(Identifier $room, Session $session): void
    {
        $this->sessions[$room->getIdentString()] = $session;
    }

    public function getSessionForRoom(Identifier $room): Session
    {
        //todo: throw on non-existent key?
        return $this->sessions[$room->getIdentString()];
    }
}

<?php declare(strict_types = 1);

namespace Room11\StackChat\Auth;

use Room11\StackChat\KeyNotFoundException;
use Room11\StackChat\Room\Identifier;

class ActiveSessionTracker implements SessionTracker
{
    /**
     * @var Session[]
     */
    private $sessions = [];

    public function setSessionForRoom(Identifier $room, Session $session): void
    {
        $this->sessions[$room->getIdentString()] = $session;
    }

    public function getSessionForRoom(Identifier $room): Session
    {
        if (!isset($this->sessions[$room->getIdentString()])) {
            throw new KeyNotFoundException("Key {$room->getIdentString()} not found in session tracker");
        }

        return $this->sessions[$room->getIdentString()];
    }

    public function hasSessionForRoom(Identifier $room): bool
    {
        return isset($this->sessions[$room->getIdentString()]);
    }
}

Throw on accessing non-existent session

Throw on accessing non-existent session