<?php
namespace Scat\Model;

class Config extends \Scat\Model {
  static protected $cache= [];

  static public function getValue($name) {
    if (array_key_exists($name, self::$cache)) {
      return self::$cache[$name];
    }

    $row= self::factory('Config')->where('name', $name)->find_one();

    if ($row) {
      return (self::$cache[$name]= $row->value);
    }

    return null;
  }

  static public function setValue($name, $value, $type= null) {
    $row= self::factory('Config')->where('name', $name)->find_one();

    if (!$row) {
      $row= self::factory('Config')->create();
      $row->name= $name;
    }

    $row->value= $value;
    if ($type) {
      $row->type= $type;
    }

    $row->save();

    unset(@self::$cache[$name]);
  }

  static public function forgetValue($name) {
    $row= self::factory('Config')->where('name', $name)->find_one();
    if ($row) {
      $row->delete();
    }
    unset(@self::$cache[$name]);

    if ($row) {
      return (self::$cache[$name]= $row->value);
    }

    return null;
  }

}

<?php
namespace Scat\Model;

class Config extends \Scat\Model {
  static protected $cache= [];

  static public function getValue($name) {
    if (array_key_exists($name, self::$cache)) {
      return self::$cache[$name];
    }

    $row= self::factory('Config')->where('name', $name)->find_one();

    if ($row) {
      return (self::$cache[$name]= $row->value);
    }

    return null;
  }

  static public function setValue($name, $value, $type= null) {
    $row= self::factory('Config')->where('name', $name)->find_one();

    if (!$row) {
      $row= self::factory('Config')->create();
      $row->name= $name;
    }

    $row->value= $value;
    if ($type) {
      $row->type= $type;
    }

    $row->save();

    unset(self::$cache[$name]);
  }

  static public function forgetValue($name) {
    $row= self::factory('Config')->where('name', $name)->find_one();
    if ($row) {
      $row->delete();
    }
    unset(self::$cache[$name]);

    if ($row) {
      return (self::$cache[$name]= $row->value);
    }

    return null;
  }

}

Fix silencing errors on unset

Fix silencing errors on unset


<?php

/**
 * Copyright (c) 2006- Facebook
 * Distributed under the Thrift Software License
 *
 * See accompanying file LICENSE or visit the Thrift site at:
 * http://developers.facebook.com/thrift/
 *
 * @package thrift
 * @author Mark Slee <mcslee@facebook.com>
 */

/**
 * Include this file if you wish to use autoload with your PHP generated Thrift
 * code. The generated code will *not* include any defined Thrift classes by
 * default, except for the service interfaces. The generated code will populate
 * values into $GLOBALS['THRIFT_AUTOLOAD'] which can be used by the autoload
 * method below. If you have your own autoload system already in place, rename your
 * __autoload function to something else and then do:
 * $GLOBALS['AUTOLOAD_HOOKS'][] = 'my_autoload_func';
 *
 * Generate this code using the -phpa Thrift generator flag.
 */

$GLOBALS['THRIFT_AUTOLOAD'] = array();
$GLOBALS['AUTOLOAD_HOOKS'] = array();

if (!function_exists('__autoload')) {
  function __autoload($class) {
    global $THRIFT_AUTOLOAD;
    $classl = strtolower($classl);
    if (isset($THRIFT_AUTOLOAD[$classl])) {
      include_once $GLOBALS['THRIFT_ROOT'].'/packages/'.$THRIFT_AUTOLOAD[$classl];
    } else if (!empty($GLOBALS['AUTOLOAD_HOOKS'])) {
      foreach ($GLOBALS['AUTOLOAD_HOOKS'] as $hook) {
        $hook($class);
      }
    }
  }
}

<?php

/**
 * Copyright (c) 2006- Facebook
 * Distributed under the Thrift Software License
 *
 * See accompanying file LICENSE or visit the Thrift site at:
 * http://developers.facebook.com/thrift/
 *
 * @package thrift
 * @author Mark Slee <mcslee@facebook.com>
 */

/**
 * Include this file if you wish to use autoload with your PHP generated Thrift
 * code. The generated code will *not* include any defined Thrift classes by
 * default, except for the service interfaces. The generated code will populate
 * values into $GLOBALS['THRIFT_AUTOLOAD'] which can be used by the autoload
 * method below. If you have your own autoload system already in place, rename your
 * __autoload function to something else and then do:
 * $GLOBALS['AUTOLOAD_HOOKS'][] = 'my_autoload_func';
 *
 * Generate this code using the -phpa Thrift generator flag.
 */

$GLOBALS['THRIFT_AUTOLOAD'] = array();
$GLOBALS['AUTOLOAD_HOOKS'] = array();

if (!function_exists('__autoload')) {
  function __autoload($class) {
    global $THRIFT_AUTOLOAD;
    $classl = strtolower($class);
    if (isset($THRIFT_AUTOLOAD[$classl])) {
      include_once $GLOBALS['THRIFT_ROOT'].'/packages/'.$THRIFT_AUTOLOAD[$classl];
    } else if (!empty($GLOBALS['AUTOLOAD_HOOKS'])) {
      foreach ($GLOBALS['AUTOLOAD_HOOKS'] as $hook) {
        $hook($class);
      }
    }
  }
}

Fix typo in Thrift trunk

Fix typo in Thrift trunk

Summary: $classl => $class

git-svn-id: 8d8e29b1fb681c884914062b88f3633e3a187774@665376 13f79535-47bb-0310-9956-ffa450edef68


<?php
class OC_Migrate_Provider_Bookmarks extends OC_Migrate_Provider{

	// Create the xml for the user supplied
	function export( $uid ){
		OC_Log::write('migration','starting export for bookmarks',OC_Log::INFO);
		$options = array(
			'table'=>'bookmarks',
			'matchcol'=>'user_id',
			'matchval'=>$uid,
			'idcol'=>'id'
		);
		$ids = OC_Migrate::copyRows( $options );

		$options = array(
			'table'=>'bookmarks_tags',
			'matchcol'=>'bookmark_id',
			'matchval'=>$ids
		);

		// Export tags
		OC_Migrate::copyRows( $options );

	}

	// Import function for bookmarks
	function import( $data, $uid ){

		// new id mapping
		$newids = array();

		// Import bookmarks
		foreach($data['bookmarks'] as $bookmark){
			$bookmark['user_id'] = $uid;
			// import to the db now
			$newids[$bookmark['id']] = OC_DB::insertid();
		}

		// Import tags
		foreach($data['bookmarks_tags'] as $tag){
			// Map the new ids
			$tag['id'] = $newids[$tag['id']];
			// Import to the db now using OC_DB
		}
	}

}

new OC_Migrate_Provider_Bookmarks( 'bookmarks' );

<?php
class OC_Migrate_Provider_Bookmarks extends OC_Migrate_Provider{

	// Create the xml for the user supplied
	function export( $uid ){
		OC_Log::write('migration','starting export for bookmarks',OC_Log::INFO);
		$options = array(
			'table'=>'bookmarks',
			'matchcol'=>'user_id',
			'matchval'=>$uid,
			'idcol'=>'id'
		);
		$ids = OC_Migrate::copyRows( $options );

		$options = array(
			'table'=>'bookmarks_tags',
			'matchcol'=>'bookmark_id',
			'matchval'=>$ids
		);

		// Export tags
		$ids2 = OC_Migrate::copyRows( $options );

		// If both returned some ids then they worked
		if( is_array( $ids ) && is_array( $ids2 ) )
		{
			return true;
		} else {
			return false;
		}

	}

	// Import function for bookmarks
	function import( $data, $uid ){

		// new id mapping
		$newids = array();

		// Import bookmarks
		foreach($data['bookmarks'] as $bookmark){
			$bookmark['user_id'] = $uid;
			// import to the db now
			$newids[$bookmark['id']] = OC_DB::insertid();
		}

		// Import tags
		foreach($data['bookmarks_tags'] as $tag){
			// Map the new ids
			$tag['id'] = $newids[$tag['id']];
			// Import to the db now using OC_DB
		}
	}

}

new OC_Migrate_Provider_Bookmarks( 'bookmarks' );

Fix return value of export

Fix return value of export


<?php

namespace Illuminate\Database;

use Illuminate\Support\Str;
use Throwable;

trait DetectsLostConnections
{
    /**
     * Determine if the given exception was caused by a lost connection.
     *
     * @param  \Throwable  $e
     * @return bool
     */
    protected function causedByLostConnection(Throwable $e)
    {
        $message = $e->getMessage();

        return Str::contains($message, [
            'server has gone away',
            'no connection to the server',
            'Lost connection',
            'is dead or not enabled',
            'Error while sending',
            'decryption failed or bad record mac',
            'server closed the connection unexpectedly',
            'SSL connection has been closed unexpectedly',
            'Error writing data to the connection',
            'Resource deadlock avoided',
            'Transaction() on null',
            'child connection forced to terminate due to client_idle_limit',
            'query_wait_timeout',
            'reset by peer',
            'Physical connection is not usable',
            'TCP Provider: Error code 0x68',
            'ORA-03114',
            'Packets out of order. Expected',
            'Adaptive Server connection failed',
            'Communication link failure',
            'connection is no longer usable',
            'Login timeout expired',
            'Connection refused',
            'running with the --read-only option so it cannot execute this statement',
            'The connection is broken and recovery is not possible. The connection is marked by the client driver as unrecoverable. No attempt was made to restore the connection.',
        ]);
    }
}

<?php

namespace Illuminate\Database;

use Illuminate\Support\Str;
use Throwable;

trait DetectsLostConnections
{
    /**
     * Determine if the given exception was caused by a lost connection.
     *
     * @param  \Throwable  $e
     * @return bool
     */
    protected function causedByLostConnection(Throwable $e)
    {
        $message = $e->getMessage();

        return Str::contains($message, [
            'server has gone away',
            'no connection to the server',
            'Lost connection',
            'is dead or not enabled',
            'Error while sending',
            'decryption failed or bad record mac',
            'server closed the connection unexpectedly',
            'SSL connection has been closed unexpectedly',
            'Error writing data to the connection',
            'Resource deadlock avoided',
            'Transaction() on null',
            'child connection forced to terminate due to client_idle_limit',
            'query_wait_timeout',
            'reset by peer',
            'Physical connection is not usable',
            'TCP Provider: Error code 0x68',
            'ORA-03114',
            'Packets out of order. Expected',
            'Adaptive Server connection failed',
            'Communication link failure',
            'connection is no longer usable',
            'Login timeout expired',
            'Connection refused',
            'running with the --read-only option so it cannot execute this statement',
            'The connection is broken and recovery is not possible. The connection is marked by the client driver as unrecoverable. No attempt was made to restore the connection.',
            'SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Try again',
        ]);
    }
}

Add pdo try again as lost connection message


<?php
header('Content-type: text/plain');
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
$formID = isset($_POST['form_id']) ? $_POST['form_id'] : '';
$response = Jojo_Plugin_Jojo_contact::sendEnquiry($formID);
$res = json_encode($response);
echo $res;
exit;

<?php
header('Content-type: application/json');
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
$formID = isset($_POST['form_id']) ? $_POST['form_id'] : '';
$response = Jojo_Plugin_Jojo_contact::sendEnquiry($formID);
$res = json_encode($response);
echo $res;
exit;

Change header content type to json specific one


<?php
declare(strict_types = 1);
/**
 * /src/Serializer/CollectionNormalizer.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Serializer\Normalizer;

use Doctrine\Common\Collections\Collection;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use function is_object;

/**
 * Class CollectionNormalizer
 *
 * @package App\Serializer
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class CollectionNormalizer implements NormalizerInterface
{
    private ObjectNormalizer $normalizer;

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

    /**
     * {@inheritdoc}
     */
    public function normalize($object, ?string $format = null, array $context = []): array
    {
        $output = [];

        foreach ($object as $value) {
            $output[] = $this->normalizer->normalize($value, $format, $context);
        }

        return $output;
    }

    /**
     * {@inheritdoc}
     */
    public function supportsNormalization($data, ?string $format = null): bool
    {
        return $format === 'json' && is_object($data) && $data instanceof Collection && is_object($data->first());
    }
}

<?php
declare(strict_types = 1);
/**
 * /src/Serializer/CollectionNormalizer.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Serializer\Normalizer;

use Doctrine\Common\Collections\Collection;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use function is_object;

/**
 * Class CollectionNormalizer
 *
 * @package App\Serializer
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class CollectionNormalizer implements NormalizerInterface
{
    public function __construct(
        private ObjectNormalizer $normalizer,
    ) {
    }

    /**
     * {@inheritdoc}
     */
    public function normalize($object, ?string $format = null, array $context = []): array
    {
        $output = [];

        foreach ($object as $value) {
            $output[] = $this->normalizer->normalize($value, $format, $context);
        }

        return $output;
    }

    /**
     * {@inheritdoc}
     */
    public function supportsNormalization($data, ?string $format = null): bool
    {
        return $format === 'json' && is_object($data) && $data instanceof Collection && is_object($data->first());
    }
}

Use PHP 8 constructor property promotion


<?php

if (!function_exists('theme')) {
    /**
     * Return a specified view from current theme.
     *
     * @param string $view
     * @param array  $data
     * @param array  $mergeData
     *
     * @return \Illuminate\View\View
     */
    function theme($view, array $data = array(), array $mergeData = array())
    {
        return app('themes')->view($view, $data, $mergeData);
    }
}

<?php

if (!function_exists('theme')) {
    /**
     * Return a specified view from current theme.
     *
     * @param string|null $view
     * @param array  $data
     * @param array  $mergeData
     *
     * @return \Illuminate\View\View
     */
    function theme($view = null, array $data = array(), array $mergeData = array())
    {
        $theme = app('themes');

        if (is_null($view)) {
            return $theme;
        }

        return $theme->view($view, $data, $mergeData);
    }
}

Allow to get theme instance via 'theme' helper, added theme helper tests


<?php

namespace App\Http\Controllers;

use App\Job;
use App\Http\Controllers\Controller;

class JobController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show post page.
     *
     * @return \Illuminate\Http\Response
     */
    public function matchIndex()
    {
        return view('matches');
    }

    /**
     * Show job page.
     *
     * @return \Illuminate\Http\Response
     */
    public function jobIndex()
    {
        $id = $request['id'];
        $job = Job::findOfFail($id);
        $title = $job->title;
        $description = $job->description;
        $hours = $job->hous;
        $salary = $job->salary;
        $availablefrom = $job->availablefrom;
        $location = $job->location;
        $startdate = $job->startdate;

        return view("job",["title"=>$title, "description"=>$description, "hours"=>$hours, "salary"=>$salary, "availablefrom"=>$availablefrom, "location"=>$location, "startdate"=>$startdate]);
    }

     /**
     * Delete job.
     *
     * @return void
     */
    public function delete()
    {
        $job = $request['id'];
        Job::destroy($job);

        return redirect()->route('home');
    }

    public function getJobs($state){
        return "hello";
    }
}

<?php

namespace App\Http\Controllers;

use App\Job;
use App\Http\Controllers\Controller;

class JobController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show matches page.
     *
     * @return \Illuminate\Http\Response
     */
    public function matchIndex()
    {
        return view('matches');
    }

    /**
     * Show job page.
     *
     * @return \Illuminate\Http\Response
     */
    public function jobIndex()
    {
        $id = $request['id'];
        $job = Job::findOfFail($id);
        $title = $job->title;
        $description = $job->description;
        $hours = $job->hous;
        $salary = $job->salary;
        $availablefrom = $job->availablefrom;
        $location = $job->location;
        $startdate = $job->startdate;

        return view("job",["title"=>$title, "description"=>$description, "hours"=>$hours, "salary"=>$salary, "availablefrom"=>$availablefrom, "location"=>$location, "startdate"=>$startdate]);
    }

     /**
     * Delete job.
     *
     * @return void
     */
    public function delete()
    {
        $job = $request['id'];
        Job::destroy($job);

        return redirect()->route('home');
    }

    public function getJobs($state){
        $jobs = Job::where('state', $state)->get();

        return $jobs;
    }
}

Create function to return all jobs by state

I moved this for security reasons (so we can use Auth).


<?php

namespace App\Policies;

use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class PublishingGroupPolicy
{
    use HandlesAuthorization;

    public function before($user, $ability)
    {
        if($user->isAdmin()){
            return true;
        }
    }

    /**
     * Determine whether the user can index Site.
     *
     * @param  User  $user
     * @return boolean
     */
    public function index(User $user)
    {
        return false;
    }

}

<?php

namespace App\Policies;

use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class PublishingGroupPolicy
{
    use HandlesAuthorization;

    public function before($user, $ability)
    {
        if($user->isAdmin()){
            return true;
        }
        return true;
    }

    /**
     * Determine whether the user can index Site.
     *
     * @param  User  $user
     * @return boolean
     */
    public function index(User $user)
    {
        return false;
    }

}

Allow all users to read list of publishing groups.


<?php

require_once 'Swat/SwatPage.php';
require_once 'XML/RPC2/Server.php';

/**
 * Base class for an XML-RPC Server
 *
 * The XML-RPC server acts as a regular page in an application . This means
 * all the regular page security features work for XML-RPC servers.
 *
 * Swat XML-RPC server pages use the PEAR::XML_RPC2 package to service
 * requests.
 *
 * @package   Swat
 * @copyright 2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
abstract class SwatXMLRPCServer extends SwatPage
{
    protected function createLayout()
    {
        return new SwatLayout('Swat/layouts/xmlrpcserver.php');
    }

	/**
	 * Process the request
	 *
	 * This method is called by site code to process the page request. It creates
	 * an XML-RPC server and handles a request. The XML-RPC response from the
	 * server is output here as well.
	 *
	 * @xmlrpc.hidden
	 */
	public function process()
	{
		$server = XML_RPC2_Server::create($this);

		ob_start();
		$server->handleCall();
		// TODO: remove workaround when php-5.0.5 is commonplace
		$x = ob_get_clean();
		$this->layout->response = $x;
	}

	/*
	 * @xmlrpc.hidden
	 */
	public function build()
	{
	}
}

?>

<?php

require_once 'Swat/SwatPage.php';
require_once 'XML/RPC2/Server.php';

/**
 * Base class for an XML-RPC Server
 *
 * The XML-RPC server acts as a regular page in an application . This means
 * all the regular page security features work for XML-RPC servers.
 *
 * Swat XML-RPC server pages use the PEAR::XML_RPC2 package to service
 * requests.
 *
 * @package   Swat
 * @copyright 2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
abstract class SwatXMLRPCServer extends SwatPage
{
	/**
	 * Process the request
	 *
	 * This method is called by site code to process the page request. It creates
	 * an XML-RPC server and handles a request. The XML-RPC response from the
	 * server is output here as well.
	 *
	 * @xmlrpc.hidden
	 */
	public function process()
	{
		$server = XML_RPC2_Server::create($this);

		ob_start();
		$server->handleCall();
		// TODO: remove workaround when php-5.0.5 is commonplace
		$x = ob_get_clean();
		$this->layout->response = $x;
	}

	/*
	 * @xmlrpc.hidden
	 */
	public function build()
	{
	}

	protected function createLayout()
	{
		return new SwatLayout('Swat/layouts/xmlrpcserver.php');
	}
}

?>

Put protected method after public methods.

svn commit r1579


<?php

class QuestionnairesController extends Controller {

    function view($token) {

        $this->Questionnaire = new Database();
        $this->Questionnaire->query('SELECT * FROM questionnaires WHERE token = :token');
        $this->Questionnaire->bind(':token', $token);
        $questionnaire = $this->Questionnaire->single();
        $this->set('questionnaire', $questionnaire);

        $this->Questionnaire = new Database();
        $this->Questionnaire->query('SELECT * FROM surveys WHERE id = :survey_id');
        $this->Questionnaire->bind(':survey_id', $questionnaire['survey_id']);
        $survey = $this->Questionnaire->single();
        $this->set('survey', $survey);

        $this->Questionnaire = new Database();
        $this->Questionnaire->query('SELECT * FROM questions WHERE survey_id = :survey_id');
        $this->Questionnaire->bind(':survey_id', $questionnaire['survey_id']);
        $questions = $this->Questionnaire->resultSet();

        if ($this->Questionnaire->rowCount() >= 1) {
            $this->set('questions', $questions);
        } else {
            $this->set('error', __('missing-questions'));
        }

        $this->set('title', $survey['name']);
    }

}

<?php

class QuestionnairesController extends Controller {

    function view($token) {

        $this->Questionnaire = new Database();
        $this->Questionnaire->query('SELECT * FROM questionnaires WHERE token = :token');
        $this->Questionnaire->bind(':token', $token);
        $questionnaire = $this->Questionnaire->single();
        $this->set('questionnaire', $questionnaire);

        $this->Questionnaire = new Database();
        $this->Questionnaire->query('SELECT * FROM surveys WHERE id = :survey_id');
        $this->Questionnaire->bind(':survey_id', $questionnaire['survey_id']);
        $survey = $this->Questionnaire->single();
        $this->set('survey', $survey);

        $this->Questionnaire = new Database();
        $this->Questionnaire->query('SELECT * FROM questions WHERE survey_id = :survey_id');
        $this->Questionnaire->bind(':survey_id', $questionnaire['survey_id']);
        $questions = $this->Questionnaire->resultSet();

        if ($this->Questionnaire->rowCount() >= 1) {
            $this->set('questions', $questions);
        } else {
            $this->set('error', __('missing-questions'));
        }

        $this->set('title', $survey['title']);
        $this->set('subtitle', $survey['subtitle']);
    }

}

Add survey title and subtitle to questionnaires


<?php

namespace BNETDocs\Controllers;

use \BNETDocs\Libraries\Controller;
use \BNETDocs\Libraries\Exceptions\UnspecifiedViewException;
use \BNETDocs\Libraries\Router;
use \BNETDocs\Models\Maintenance as MaintenanceModel;
use \BNETDocs\Views\MaintenanceHtml as MaintenanceHtmlView;
use \BNETDocs\Views\MaintenanceJSON as MaintenanceJSONView;
use \BNETDocs\Views\MaintenancePlain as MaintenancePlainView;

class Maintenance extends Controller {

  protected $message;

  public function __construct($message) {
    parent::__construct();
    $this->message = $message;
  }

  public function run(Router &$router) {
    switch ($router->getRequestPathExtension()) {
      case "htm": case "html": case "":
        $view = new MaintenanceHtmlView();
      break;
      case "json":
        $view = new MaintenanceJSONView();
      break;
      case "txt":
        $view = new MaintenancePlainView();
      break;
      default:
        throw new UnspecifiedViewException();
    }
    $model = new MaintenanceModel();
    $model->message = $this->message;
    ob_start();
    $view->render($model);
    $router->setResponseCode(503);
    $router->setResponseTTL(0);
    $router->setResponseHeader("Content-Type", $view->getMimeType());
    $router->setResponseContent(ob_get_contents());
    ob_end_clean();
  }

}

<?php

namespace BNETDocs\Controllers;

use \BNETDocs\Libraries\Controller;
use \BNETDocs\Libraries\Exceptions\UnspecifiedViewException;
use \BNETDocs\Libraries\Router;
use \BNETDocs\Models\Maintenance as MaintenanceModel;
use \BNETDocs\Views\MaintenanceHtml as MaintenanceHtmlView;
use \BNETDocs\Views\MaintenanceJSON as MaintenanceJSONView;
use \BNETDocs\Views\MaintenancePlain as MaintenancePlainView;

class Maintenance extends Controller {

  protected $message;

  public function __construct($message) {
    parent::__construct();
    $this->message = $message;
  }

  public function run(Router &$router) {
    switch ($router->getRequestPathExtension()) {
      case "htm": case "html": case "":
        $view = new MaintenanceHtmlView();
      break;
      case "json":
        $view = new MaintenanceJSONView();
      break;
      case "txt":
        $view = new MaintenancePlainView();
      break;
      default:
        $view = new MaintenanceHtmlView();
    }
    $model = new MaintenanceModel();
    $model->message = $this->message;
    ob_start();
    $view->render($model);
    $router->setResponseCode(503);
    $router->setResponseTTL(0);
    $router->setResponseHeader("Content-Type", $view->getMimeType());
    $router->setResponseContent(ob_get_contents());
    ob_end_clean();
  }

}

Handle unknown extensions with the html frontend


<?php

namespace Casinelli\CampaignMonitor;

class CampaignMonitor
{
    protected $app;

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

    public function campaigns($campaignId = null)
    {
        return new \CS_REST_Campaigns($campaignId, $this->getAuthTokens());
    }

    public function clients($clientId = null)
    {
        return new \CS_REST_Clients($clientId, $this->getAuthTokens());
    }

    public function lists($listId = null)
    {
        return new \CS_REST_Lists($listId, $this->getAuthTokens());
    }

    public function segments($segmentId = null)
    {
        return new \CS_REST_Segments($segmentId, $this->getAuthTokens());
    }

    public function template($templateId = null)
    {
        return new \CS_REST_Templates($templateId, $this->getAuthTokens());
    }

    public function subscribers($listId = null)
    {
        return new \CS_REST_Subscribers($listId, $this->getAuthTokens());
    }

    protected function getAuthTokens()
    {
        return [
            'apy_key' => $this->app['config']['campaignmonitor.api_key'],
        ];
    }
}

<?php

namespace Casinelli\CampaignMonitor;

class CampaignMonitor
{
    protected $app;

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

    public function campaigns($campaignId = null)
    {
        return new \CS_REST_Campaigns($campaignId, $this->getAuthTokens());
    }

    public function clients($clientId = null)
    {
        return new \CS_REST_Clients($clientId, $this->getAuthTokens());
    }

    public function lists($listId = null)
    {
        return new \CS_REST_Lists($listId, $this->getAuthTokens());
    }

    public function segments($segmentId = null)
    {
        return new \CS_REST_Segments($segmentId, $this->getAuthTokens());
    }

    public function template($templateId = null)
    {
        return new \CS_REST_Templates($templateId, $this->getAuthTokens());
    }

    public function subscribers($listId = null)
    {
        return new \CS_REST_Subscribers($listId, $this->getAuthTokens());
    }

    protected function getAuthTokens()
    {
        return [
            'api_key' => $this->app['config']['campaignmonitor.api_key'],
        ];
    }
}

Fix the array key name

Fix the array key name


<?php
/**
 * Interface StyleSheetParser.
 *
 * @package hatemile\util\css
 * @author Carlson Santana Cruz
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @copyright (c) 2018, HaTeMiLe
 */

namespace hatemile\util\css;

/**
 * The StyleSheetParser interface contains the methods for access the CSS
 * parser.
 */
interface StyleSheetParser
{

    /**
     * Returns the rules of parser by properties.
     * @param string[] $properties The properties.
     * @return \hatemile\util\css\StyleSheetRule The rules.
     */
    public function getRules($properties);
}

<?php
/**
 * Interface StyleSheetParser.
 *
 * @package hatemile\util\css
 * @author Carlson Santana Cruz
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @copyright (c) 2018, HaTeMiLe
 */

namespace hatemile\util\css;

/**
 * The StyleSheetParser interface contains the methods for access the CSS
 * parser.
 */
interface StyleSheetParser
{

    /**
     * Returns the rules of parser by properties.
     * @param string[] $properties The properties.
     * @return \hatemile\util\css\StyleSheetRule[] The rules.
     */
    public function getRules($properties);
}

Set to returns a array of object

:memo: Set to returns a array of object


<?php

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

declare(strict_types=1);

namespace Sylius\Bundle\UserBundle;

use Sylius\Bundle\ResourceBundle\AbstractResourceBundle;
use Sylius\Bundle\ResourceBundle\SyliusResourceBundle;
use Sylius\Bundle\UserBundle\DependencyInjection\Compiler\RemoveUserPasswordEncoderPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;

final class SyliusUserBundle extends AbstractResourceBundle
{
    public function getSupportedDrivers(): array
    {
        return [
            SyliusResourceBundle::DRIVER_DOCTRINE_ORM,
        ];
    }

    public function build(ContainerBuilder $container): void
    {
        $container->addCompilerPass(new RemoveUserPasswordEncoderPass());
    }

    /**
     * @psalm-suppress MismatchingDocblockReturnType https://github.com/vimeo/psalm/issues/2345
     */
    protected function getModelNamespace(): string
    {
        return 'Sylius\Component\User\Model';
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Bundle\UserBundle;

use Sylius\Bundle\ResourceBundle\AbstractResourceBundle;
use Sylius\Bundle\ResourceBundle\SyliusResourceBundle;
use Sylius\Bundle\UserBundle\DependencyInjection\Compiler\RemoveUserPasswordEncoderPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;

final class SyliusUserBundle extends AbstractResourceBundle
{
    public function getSupportedDrivers(): array
    {
        return [
            SyliusResourceBundle::DRIVER_DOCTRINE_ORM,
        ];
    }

    public function build(ContainerBuilder $container): void
    {
        parent::build($container);

        $container->addCompilerPass(new RemoveUserPasswordEncoderPass());
    }

    /**
     * @psalm-suppress MismatchingDocblockReturnType https://github.com/vimeo/psalm/issues/2345
     */
    protected function getModelNamespace(): string
    {
        return 'Sylius\Component\User\Model';
    }
}

[Sf6] Add UserBundle mappings to Symfony6 support


<?php

namespace Kunstmaan\DashboardBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class KunstmaanDashboardExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.yml');
        $loader->load('commands.yml');
    }
}

<?php

namespace Kunstmaan\DashboardBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class KunstmaanDashboardExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.yml');
        $loader->load('commands.yml');
    }

    public function prepend(ContainerBuilder $container)
    {
        $container->prependExtensionConfig('framework', ['esi' => ['enabled' => true]]);
    }
}

[DashboardBundle] Enable esi by default for the dashboard bundle


<?
include '../scat.php';
include '../lib/txn.php';

$txn_id= (int)$_REQUEST['txn'];
if (!$txn_id)
  die_jsonp("no transaction specified.");

$txn= txn_load($db, $txn_id);
if ($txn['paid']) {
  die_jsonp("This order is already paid!");
}

$tax_rate= (float)$_REQUEST['tax_rate'];
if (!strcmp($_REQUEST['tax_rate'], 'def')) {
  $tax_rate= DEFAULT_TAX_RATE;
}

$q= "UPDATE txn SET tax_rate = $tax_rate WHERE id = $txn_id";
$r= $db->query($q)
  or die_jsonp($db->error);

$txn= txn_load($db, $txn);

echo jsonp(array("success" => "Updated tax rate.", "txn" => $txn));

<?
include '../scat.php';
include '../lib/txn.php';

$txn_id= (int)$_REQUEST['txn'];
if (!$txn_id)
  die_jsonp("no transaction specified.");

$txn= txn_load($db, $txn_id);
if ($txn['paid']) {
  die_jsonp("This order is already paid!");
}

$tax_rate= (float)$_REQUEST['tax_rate'];
if (!strcmp($_REQUEST['tax_rate'], 'def')) {
  $tax_rate= DEFAULT_TAX_RATE;
}

$q= "UPDATE txn SET tax_rate = $tax_rate WHERE id = $txn_id";
$r= $db->query($q)
  or die_jsonp($db->error);

$txn= txn_load($db, $txn_id);

echo jsonp(array("success" => "Updated tax rate.", "txn" => $txn));

Fix loading of update transaction after changing tax rate


<?php

$__database = AdvancedBan::getDatabase( );

$response = json_encode([
	"PunishmentHistory" => $__database->getData("PunishmentHistory"),
	"Punishments" => $__database->getData("Punishments")
]);

die($response);

<?php

$__database = AdvancedBan::getDatabase( );

$response = json_encode([
	"PunishmentHistory" => $__database->getData("PunishmentHistory"),
	"Punishments" => $__database->getData("Punishments")
]);

header("Content-Type: application/json");
die($response);

Add appropriate header for response data


<?php

namespace Roots\Sage\Extras;

use Roots\Sage\Setup;

/**
 * Add  classes
 */
function body_class($classes) {
  // Add page slug if it doesn't exist
  if (is_single() || is_page() && !is_front_page()) {
    if (!in_array(basename(get_permalink()), $classes)) {
      $classes[] = basename(get_permalink());
    }
  }

  // Add class if sidebar is active
  if (Setup\display_sidebar()) {
    $classes[] = 'sidebar-primary';
  }

  return $classes;
}
add_filter('body_class', __NAMESPACE__ . '\\body_class');

/**
 * Clean up the_excerpt()
 */
function excerpt_more() {
  return ' … ' . __('Continued', 'sage') . '';
}
add_filter('excerpt_more', __NAMESPACE__ . '\\excerpt_more');

/**
 * Show signup button
 */
function signup_button($attrs) {
  if(is_user_logged_in()) {
    global $user_ID;
    global $wpdb;
    $results = $wpdb->get_results($wpdb->prepare('SELECT * FROM '.$wpdb->prefix.'frm_items WHERE user_id = %d AND form_id = %d', $user_ID, $attrs['form_id']), ARRAY_A);
    if(!empty($results)) {
      return ''.$attrs['edit_text'].'';
    }

    return ''.$attrs['new_text'].'';
  }

  return 'Create an Account/Login';
}
add_shortcode('signup_button', __NAMESPACE__ . '\\signup_button');

Make dynamic signup button shortcode.

Make dynamic signup button shortcode.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;

use App\Models\Challenge;

use Session;

class HomeController extends AppController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $content = $this->levelup->get_content();

        return view('home.index',compact('content'));
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;

use App\Models\Challenge;

use Session;

class HomeController extends AppController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $content = $this->levelup->get_content();

        $dailys_complete = Challenge::completed_featured_challenges($this->levelup);
        Session::put('levelup_dailys_complete', $dailys_complete);

        return view('home.index',compact('content'));
    }
}

Check for new daily challenges on home page


<?php

final class PhabricatorFileTransactionComment
  extends PhabricatorApplicationTransactionComment {

  public function getApplicationTransactionObject() {
    return new PhabricatorFileTransaction();
  }

  public function shouldUseMarkupCache($field) {
    // Only cache submitted comments.
    return ($this->getTransactionPHID() != null);
  }

  protected function getConfiguration() {
    $config = parent::getConfiguration();
    $config[self::CONFIG_KEY_SCHEMA] = array(
      'key_draft' => array(
        'columns' => array('authorPHID', 'transactionPHID'),
        'unique' => true,
      ),
    ) + $config[self::CONFIG_KEY_SCHEMA];
    return $config;
  }

}

<?php

final class PhabricatorFileTransactionComment
  extends PhabricatorApplicationTransactionComment {

  public function getApplicationTransactionObject() {
    return new PhabricatorFileTransaction();
  }

}

Allow file comments to be edited

Allow file comments to be edited

Summary:
Fixes T10750. Files have some outdated cache/key code which prevents recording an edit history on file comments.

Remove this ancient cruft.

(Users must `bin/storage adjust` after upgrading to this patch to reap the benefits.)

Test Plan:
  - Ran `bin/storage adjust`.
  - Edited a comment in Files.

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T10750

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


<?php

namespace Screeenly\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;

class CreateScreenshotRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'key'    => ['required', 'exists:api_keys,key'],
            'url'    => ['required', 'url'], // Is 'active_url' reliable enough?
            'width'  => ['sometimes', 'required', 'integer', 'max:2000', 'min:10'],
            'height' => ['sometimes', 'required', 'integer', 'min:10'],
            'delay'  => ['sometimes', 'required', 'integer', 'max:10', 'min:0'],
        ];
    }
}

<?php

namespace Screeenly\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;

class CreateScreenshotRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'key'    => ['required', 'exists:api_keys,key'],
            'url'    => ['required', 'url', 'active_url'],
            'width'  => ['sometimes', 'required', 'integer', 'max:2000', 'min:10'],
            'height' => ['sometimes', 'required', 'integer', 'min:10'],
            'delay'  => ['sometimes', 'required', 'integer', 'max:10', 'min:0'],
        ];
    }
}

Add active_url to URL validation

Add active_url to URL validation


<?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\Bundle\SecurityBundle\Security;

use Symfony\Component\Security\Http\Firewall\ExceptionListener;

/**
 * This is a wrapper around the actual firewall configuration which allows us
 * to lazy load the context for one specific firewall only when we need it.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class FirewallContext
{
    private $listeners;
    private $exceptionListener;
    private $config;

    /**
     * @param \Traversable|array     $listeners
     * @param ExceptionListener|null $exceptionListener
     * @param FirewallConfig|null    $firewallConfig
     */
    public function __construct($listeners, ExceptionListener $exceptionListener = null, FirewallConfig $config = null)
    {
        $this->listeners = $listeners;
        $this->exceptionListener = $exceptionListener;
        $this->config = $config;
    }

    public function getConfig()
    {
        return $this->config;
    }

    /**
     * @return \Traversable|array
     */
    public function getListeners()
    {
        return $this->listeners;
    }

    public function getExceptionListener()
    {
        return $this->exceptionListener;
    }
}

<?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\Bundle\SecurityBundle\Security;

use Symfony\Component\Security\Http\Firewall\ExceptionListener;

/**
 * This is a wrapper around the actual firewall configuration which allows us
 * to lazy load the context for one specific firewall only when we need it.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class FirewallContext
{
    private $listeners;
    private $exceptionListener;
    private $config;

    public function __construct(iterable $listeners, ExceptionListener $exceptionListener = null, FirewallConfig $config = null)
    {
        $this->listeners = $listeners;
        $this->exceptionListener = $exceptionListener;
        $this->config = $config;
    }

    public function getConfig()
    {
        return $this->config;
    }

    public function getListeners(): iterable
    {
        return $this->listeners;
    }

    public function getExceptionListener()
    {
        return $this->exceptionListener;
    }
}

Fix merge (phpdoc => typehint)

Fix merge (phpdoc => typehint)


<?php

require_once 'Swat/SwatFormField.php';

/**
 * A container to use around control widgets in a form
 *
 * Adds a label and space to output messages.
 *
 * @package   Swat
 * @copyright 2004-2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatFormFooterField extends SwatFormField
{
	/**
	 * Constructor
	 *
	 * Sets the class to swat-form-field-footer
	 *
	 * @param string $id the id of this form footer field.
	 */
	public function __construct($id = null)
	{
		parent::__construct($id);

		$this->class = 'swat-form-field-footer';
	}
}

?>

<?php

require_once 'Swat/SwatFormField.php';

/**
 * A container to use around control widgets in a form
 *
 * Adds a label and space to output messages.
 *
 * @package   Swat
 * @copyright 2004-2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatFormFooterField extends SwatFormField
{
	/**
	 * Constructor
	 *
	 * Sets the class to swat-form-field-footer
	 *
	 * @param string $id the id of this form footer field.
	 */
	public function __construct($id = null)
	{
		parent::__construct($id);

		$this->class = 'swat-form-footer-field';
	}
}

?>

Rename this CSS class correctly.

Rename this CSS class correctly.

svn commit r1670


<?php
namespace Ayeo\Validator\Constraint;

use Ayeo\Validator\Exception\InvalidConstraintParameter;

class NumericMin extends AbstractConstraint //todo: rename to IntegerMin
{
	/**
	 * @var integer
	 */
	private $min;

    /**
     * @param int $min
     * @throws InvalidConstraintParameter
     */
	public function __construct($min = 0)
	{
        if (is_integer($min))
        {
            $this->min = $min;
        }
        else
        {
            throw new InvalidConstraintParameter;
        }

	}

	public function run($value)
	{
		if (is_numeric($value) === false)
		{
			$this->addError('must_be_numeric');
		}

		if ($value < $this->min)
		{
			$this->addError('must_be_greater_than', $this->min);
		}
	}
}

<?php
namespace Ayeo\Validator\Constraint;

use Ayeo\Validator\Exception\InvalidConstraintParameter;

class NumericMin extends AbstractConstraint
{
	private $min;

    /**
     * @throws InvalidConstraintParameter
     */
	public function __construct($min = 0)
	{
        if (is_numeric($min))
        {
            $this->min = $min;
        }
        else
        {
            throw new InvalidConstraintParameter;
        }

	}

	public function run($value)
	{
		if (is_numeric($value) === false)
		{
			$this->addError('must_be_numeric');
		}

		if ($value < $this->min)
		{
			$this->addError('must_be_greater_than', $this->min);
		}
	}
}

Support floats in numeric constraint

Support floats in numeric constraint


<?php
/**
 * Describes an available update to an installed Composer package
 *
 * Originally from https://github.com/XploreNet/silverstripe-composerupdates
 *
 * @author Matt Dwen
 * @license MIT
 */
class ComposerUpdate extends DataObject
{
    /**
     * @var array
     */
    private static $db = array(
        'Name' => 'Varchar(255)',
        'Installed' => 'Varchar(255)',
        'Available' => 'Varchar(255)',
    );

    /**
     * @var array
     */
    private static $summary_fields = array(
        'Name' => 'Package',
        'Installed',
        'Available',
    );

    /**
     * name of the related job
     *
     * @var string
     */
    public $jobName = 'CheckComposerUpdatesJob';

    /**
     * self update on dev/build
     */
    public function requireDefaultRecords()
    {
        parent::requireDefaultRecords();

        // add a queuedjob on dev/build
        singleton('QueuedJobService')->queueJob(new CheckComposerUpdatesJob());
    }
}

<?php
/**
 * Describes an available update to an installed Composer package
 *
 * Originally from https://github.com/XploreNet/silverstripe-composerupdates
 *
 * @author Matt Dwen
 * @license MIT
 */
class ComposerUpdate extends DataObject
{
    /**
     * @var array
     */
    private static $db = array(
        'Name' => 'Varchar(255)',
        'Installed' => 'Varchar(255)',
        'Available' => 'Varchar(255)',
    );

    /**
     * @var array
     */
    private static $summary_fields = array(
        'Name' => 'Package',
        'Installed' => 'Installed',
        'Available' => 'Available',
    );

    /**
     * name of the related job
     *
     * @var string
     */
    public $jobName = 'CheckComposerUpdatesJob';

    /**
     * self update on dev/build
     */
    public function requireDefaultRecords()
    {
        parent::requireDefaultRecords();

        // add a queuedjob on dev/build
        singleton('QueuedJobService')->queueJob(new CheckComposerUpdatesJob());
    }
}

FIX Name not showing in updates report

FIX Name not showing in updates report


<?php

namespace ATPCore\Controller;

class AbstractController extends \Zend\Mvc\Controller\AbstractActionController
{
	public function get($resource)
	{
		return $this->getServiceLocator()->get($resource);
	}
}

<?php

namespace ATPCore\Controller;

class AbstractController extends \Zend\Mvc\Controller\AbstractActionController
{
	protected function get($resource)
	{
		return $this->getServiceLocator()->get($resource);
	}

	protected function config($path = null)
	{
		$parts = explode(".", $path);
		$config = $this->get('Config');
		if(empty($path)) return $config;

		foreach($parts as $part)
		{
			if(!isset($config[$part])) return null;
			$config = $config[$part];
		}

		return $config;
	}
}

Add config retrieval convenience function.


<?php

namespace CultuurNet\UDB3\Offer\Events;
use \CultuurNet\UDB3\BookingInfo;

abstract class AbstractBookingInfoEvent extends AbstractEvent
{
    protected $bookingInfo;
    /**
     * @param string $id
     * @param Object $bookingInfo
     */
    public function __construct($id, bookingInfo $bookingInfo)
    {
        parent::__construct($id);
        $this->bookingInfo = $bookingInfo;
    }

    /**
     * @return mixed The object instance
     */
    public static function deserialize(array $data)
    {
        return new static($data['item_id'], BookingInfo::deserialize($data['bookingInfo']));
    }
}

<?php

namespace CultuurNet\UDB3\Offer\Events;
use \CultuurNet\UDB3\BookingInfo;

abstract class AbstractBookingInfoEvent extends AbstractEvent
{
    protected $bookingInfo;
    /**
     * @param string $id
     * @param BookingInfo $bookingInfo
     */
    public function __construct($id, BookingInfo $bookingInfo)
    {
        parent::__construct($id);
        $this->bookingInfo = $bookingInfo;
    }

    /**
     * @return mixed The object instance
     */
    public static function deserialize(array $data)
    {
        return new static($data['item_id'], BookingInfo::deserialize($data['bookingInfo']));
    }
}

III-877: Fix BookingInfo parameter casing and docblock


<?php

/**
 * Customers may only see approved reviews and any they posted themselves
 *
 * @author Daniel Deady <daniel@clockworkgeek.com>
 * @license MIT
 */
class Clockworkgeek_Extrarestful_Model_Api2_Review_Rest_Customer_V1
extends Clockworkgeek_Extrarestful_Model_Api2_Review
{

    /**
     * Hides ID and Status for customers other than the calling one
     *
     * @see Clockworkgeek_Extrarestful_Model_Api2_Review::_retrieveCollection()
     */
    protected function _loadCollection(Varien_Data_Collection_Db $reviews)
    {
        /** @var $review Mage_Review_Model_Review */
        foreach ($reviews as $review) {
            if ($review->getCustomerId() != $this->getApiUser()->getUserId()) {
                $review->unsCustomerId()->unsStatus();
            }
        }
    }

    /**
     * Customers do not get to see pending or rejected reviews.
     *
     * @see Clockworkgeek_Extrarestful_Model_Api2_Review::_getReviews()
     */
    protected function _getCollection()
    {
        $reviews = parent::_getCollection();
        $reviews->addActiveCustomer($this->getApiUser()->getUserId());
        return $reviews;
    }

    protected function _saveModel($data)
    {
        $data['customer_id'] = $this->getApiUser()->getUserId();
        return parent::_saveModel($data);
    }
}

<?php

/**
 * Customers may only see approved reviews and any they posted themselves
 *
 * @author Daniel Deady <daniel@clockworkgeek.com>
 * @license MIT
 */
class Clockworkgeek_Extrarestful_Model_Api2_Review_Rest_Customer_V1
extends Clockworkgeek_Extrarestful_Model_Api2_Review
{

    /**
     * Hides ID and Status for customers other than the calling one
     *
     * @see Clockworkgeek_Extrarestful_Model_Api2_Review::_retrieveCollection()
     */
    protected function _loadCollection(Varien_Data_Collection_Db $reviews)
    {
        parent::_loadCollection($reviews);

        /** @var $review Mage_Review_Model_Review */
        foreach ($reviews as $review) {
            if ($review->getCustomerId() != $this->getApiUser()->getUserId()) {
                $review->unsCustomerId()->unsStatus();
            }
        }
    }

    /**
     * Customers do not get to see pending or rejected reviews.
     *
     * @see Clockworkgeek_Extrarestful_Model_Api2_Review::_getReviews()
     */
    protected function _getCollection()
    {
        $reviews = parent::_getCollection();
        $reviews->addActiveCustomer($this->getApiUser()->getUserId());
        return $reviews;
    }

    protected function _saveModel($data)
    {
        $data['customer_id'] = $this->getApiUser()->getUserId();
        return parent::_saveModel($data);
    }
}

Load ratings in reviews for customer users


<?php
namespace Concrete\Core\Config;

use Concrete\Core\Foundation\Service\Provider;

class ConfigServiceProvider extends Provider
{
    /**
     * Configuration repositories
     * @return void
     */
    public function register()
    {
        $this->registerFileConfig();
        $this->registerDatabaseConfig();
    }

    public function registerFileConfig()
    {
        // Bind abstract type
        $this->app->singleton('config', function($app) {
            $loader = $app->make('Concrete\Core\Config\FileLoader');
            $saver = $app->make('Concrete\Core\Config\FileSaver');

            return $app->build('Concrete\Core\Config\Repository\Repository', array($loader, $saver, $app->environment()));
        });

        // Bind the concrete type
        $this->app->bind('Concrete\Core\Config\Repository\Repository', 'config');
        $this->app->bind('Illuminate\Config\Repository', 'Concrete\Core\Config\Repository\Repository');
    }

    public function registerDatabaseConfig()
    {
        $this->app->bindShared('config/database', function($app) {
            $loader = $app->make('Concrete\Core\Config\DatabaseLoader');
            $saver = $app->make('Concrete\Core\Config\DatabaseSaver');

            return $app->build('Concrete\Core\Config\Repository\Repository', array($loader, $saver, $app->environment()));
        });
    }

}

4<?php
namespace Concrete\Core\Config;

use Concrete\Core\Foundation\Service\Provider;

class ConfigServiceProvider extends Provider
{
    /**
     * Configuration repositories
     * @return void
     */
    public function register()
    {
        $this->registerFileConfig();
        $this->registerDatabaseConfig();
    }

    private function registerFileConfig()
    {
        // Bind abstract type
        $this->app->singleton('config', function($app) {
            $loader = $app->make('Concrete\Core\Config\FileLoader');
            $saver = $app->make('Concrete\Core\Config\FileSaver');

            return $app->build('Concrete\Core\Config\Repository\Repository', array($loader, $saver, $app->environment()));
        });

        // Bind the concrete type
        $this->app->bind('Concrete\Core\Config\Repository\Repository', 'config');
        $this->app->bind('Illuminate\Config\Repository', 'Concrete\Core\Config\Repository\Repository');
    }

    private function registerDatabaseConfig()
    {
        $this->app->bindShared('config/database', function($app) {
            $loader = $app->make('Concrete\Core\Config\DatabaseLoader');
            $saver = $app->make('Concrete\Core\Config\DatabaseSaver');

            return $app->build('Concrete\Core\Config\Repository\Repository', array($loader, $saver, $app->environment()));
        });
    }

}

Make service provider methods private

Make service provider methods private


<?php
require_once('../inc/config.php');
require_once(CONTROLLERS_PATH.'page_controller.php');

//routing
$path = array_key_exists('path', $_GET) ? $_GET['path'] : '';
if(preg_match('/^suggestions/', $path)){
	$page_controller = new AGED_Suggestions_Controller();
}
else if(preg_match('/^rated/', $path)){
	$page_controller = new AGED_Rated_Controller();
}
else{
	$page_controller = new AGED_Index_Controller();
}

$movie_genre_result = AGED_Page_Controller::get_movie_genre_result();

include(VIEWS_PATH.'layout.php');

<?php
require_once('../inc/config.php');
require_once(CONTROLLERS_PATH.'page_controller.php');

//routing
$path = array_key_exists('path', $_GET) ? $_GET['path'] : '';
if(preg_match('/^suggestions/', $path)){
	$page_controller = new AGED_Suggestions_Controller();
}
else if(preg_match('/^rated/', $path)){
	$page_controller = new AGED_Rated_Controller();
}
else{
	$page_controller = new AGED_Index_Controller();
}

//required for add movie modal
$movie_genre_result = AGED_Page_Controller::get_movie_genre_result();

include(VIEWS_PATH.'layout.php');

Add commit about purpose of movie genre result


<?php

/**
 * Welcome to the Mackstar.Spout Project
 *
 * This is where the main configuration is added.
 * You can override this per environment in
 * /conf/env/{env}.php
 *
 */
$appDir = dirname(__DIR__);

return [
    'tmp_dir' => dirname(__DIR__) . '/var/tmp',
    'upload_dir' => dirname(__DIR__) . '/var/www/uploads',
    'resource_dir' => dirname(__DIR__),
    'lib_dir' => $appDir . '/lib',
    'log_dir' => $appDir . '/var/log',
    'template_dir' => $appDir . '/lib/twig/template',
    'master_db' => [
        'driver' => 'pdo_mysql',
        'host' => 'localhost',
        'dbname' => 'spout',
        'user' => 'root',
        'password' => '',
        'port' => '3306',
        'charset' => 'UTF8'
    ],
    'slave_db' => [
        'driver' => 'pdo_mysql',
        'host' => 'localhost',
        'dbname' =>  'spout',
        'user' => 'root',
        'password' => '',
        'port' => '3306',
        'charset' => 'UTF8'
    ],

];

<?php

/**
 * Welcome to the Mackstar.Spout Project
 *
 * This is where the main configuration is added.
 * You can override this per environment in
 * /conf/env/{env}.php
 *
 */
$appDir = dirname(__DIR__);

return [
    'tmp_dir' => dirname(__DIR__) . '/var/tmp',
    'upload_dir' => dirname(__DIR__) . '/var/www/uploads',
    'resource_dir' => dirname(__DIR__),
    'lib_dir' => $appDir . '/lib',
    'log_dir' => $appDir . '/var/log',
    'template_dir' => $appDir . '/lib/twig/template',
    'master_db' => [
        'driver' => 'pdo_sqlite',
        'path' => __DIR__ . '/test_db.sqlite3',
        'charset' => 'UTF8'
    ],
    'slave_db' => [
        'driver' => 'pdo_sqlite',
        'path' => __DIR__ . '/test_db.sqlite3',
        'charset' => 'UTF8'
    ],

];

Set sqlite as standard install method

Set sqlite as standard install method


<?php

	//https://developers.facebook.com/apps/
	define("FB_APP_ID", "replace_me");
	define("FB_APP_SECRET", "replace_me");

	// Live Streams for testing
	// https://www.facebook.com/livemap/
	define("FB_PAGE", "replace_me");

<?php

	//https://developers.facebook.com/apps/
	define("FB_APP_ID", "replace_me");
	define("FB_APP_SECRET", "replace_me");

	// Formats that work

	// https://www.facebook.com/KIRO7Seattle/
	// https://www.facebook.com/112779115408517
	// KIRO7Seattle
	// 112779115408517

	// Live Streams for testing
	// https://www.facebook.com/livemap/
	define("FB_PAGE", "replace_me");

Add comments for acceptable page arguments


<?php

/**
 * Class Vcl4Test
 *
 * @covers Vcl4
 * @author Carey Sizer <careysizer@gmail.com>
 */
class Vcl4Test extends SapphireTest
{
    /**
     * @covers Vcl4::getPurgeRegex()
     */
    public function testGetPurgeRegex()
    {
        $vcl4 = Vcl4::create();
        $this->assertEquals(
            '^/about\-us(\/|)$',
            $vcl4->getPurgeRegex('about-us')
        );
    }
}

<?php

/**
 * Class Vcl4Test
 *
 * @covers Vcl4
 * @author Carey Sizer <careysizer@gmail.com>
 */
class Vcl4Test extends SapphireTest
{
    /**
     * @covers Vcl4::getPurgeRegex()
     */
    public function testGetPurgeRegex()
    {
        $vcl4 = Vcl4::create();
        $this->assertEquals(
            '^about\-us(\/|)$',
            $vcl4->getPurgeRegex('about-us')
        );
    }
}

Fix typo in unit test

Fix typo in unit test


<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title> Template </title>
        <link rel="shortcut icon" href="/includes/img/kp.ico">
        <link href="/includes/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
        <link href="/includes/css/flat-ui-pro.min.css" rel="stylesheet">
        <link href="/includes/css/style.css" rel="stylesheet">

        <?php include 'includes/php/header.php'; ?>

 Page content

 This be your page content...

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

<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title> Template </title>
        <link rel="shortcut icon" href="/includes/img/kp.ico">
        <link href="/includes/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
        <link href="/includes/css/flat-ui-pro.min.css" rel="stylesheet">
        <link href="/includes/css/style.css" rel="stylesheet">
        <link href="/includes/js/konami.js">

        <?php include 'includes/php/header.php'; ?>

 Page content

 This be your page content...

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

Move along, nothing to see here.

Move along, nothing to see here.


<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

use Doctrine\DBAL\LockMode;
use Doctrine\Tests\Models\Company\CompanyManager;
use Doctrine\Tests\OrmFunctionalTestCase;

class DDC933Test extends OrmFunctionalTestCase
{
    public function setUp()
    {
        $this->useModelSet('company');

        parent::setUp();
    }

    /**
     * @group DDC-933
     */
    public function testLockCTIClass()
    {
        $manager = new CompanyManager();
        $manager->setName('beberlei');
        $manager->setSalary(1234);
        $manager->setTitle('Vice President of This Test');
        $manager->setDepartment("Foo");

        $this->_em->persist($manager);
        $this->_em->flush();

        $this->_em->beginTransaction();
        $this->_em->lock($manager, LockMode::PESSIMISTIC_READ);
        $this->_em->rollback();
    }
}

<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

use Doctrine\DBAL\LockMode;
use Doctrine\Tests\Models\Company\CompanyManager;
use Doctrine\Tests\OrmFunctionalTestCase;
use Doctrine\Tests\TestUtil;

class DDC933Test extends OrmFunctionalTestCase
{
    public function setUp()
    {
        $this->useModelSet('company');

        parent::setUp();
    }

    /**
     * @group DDC-933
     */
    public function testLockCTIClass()
    {
        if ($this->_em->getConnection()->getDatabasePlatform()->getName() === 'sqlite') {
            self::markTestSkipped('It should not run on in-memory databases');
        }

        $manager = new CompanyManager();
        $manager->setName('beberlei');
        $manager->setSalary(1234);
        $manager->setTitle('Vice President of This Test');
        $manager->setDepartment("Foo");

        $this->_em->persist($manager);
        $this->_em->flush();

        $this->_em->beginTransaction();
        $this->_em->lock($manager, LockMode::PESSIMISTIC_READ);
        $this->_em->rollback();

        // if lock hasn't been released we'd have an exception here
        $this->assertManagerCanBeUpdatedOnAnotherConnection($manager->getId(), 'Master of This Test');
    }

    /**
     * @param int    $id
     * @param string $newName
     *
     * @return void
     *
     * @throws \Doctrine\Common\Persistence\Mapping\MappingException
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     * @throws \Doctrine\ORM\TransactionRequiredException
     */
    private function assertManagerCanBeUpdatedOnAnotherConnection(int $id, string $newName)
    {
        $em = $this->_getEntityManager(TestUtil::getConnection());

        /** @var CompanyManager $manager */
        $manager = $em->find(CompanyManager::class, $id);
        $manager->setName($newName);

        $em->flush();
        $em->clear();

        self::assertSame($newName, $em->find(CompanyManager::class, $id)->getName());
    }
}

Validate if optimistic locks are released properly

By trying to update an entry using a different connection.


<?php /*
Returns the site's configuration
*/

function print_config_values ($config, $prefix = '') {
	foreach ($config as $key => $value) {
		if (is_array($value)) {
			print_config_values($value, "$key.");
		} else {
			echo "$prefix$key=$value\n";
		}
	}
}

require_once 'include/config.php';
if (aftertime_init(false) === false) {
	echo Config::init_log();
	exit (-1);
}

print_config_values(Config::get());
exit (0);
?>

<?php /*
Returns the site's configuration
*/

function print_config_values ($config, $prefix = '') {
	foreach ($config as $key => $value) {
		if (is_array($value)) {
			print_config_values($value, "$prefix$key.");
		} else {
			echo "$prefix$key=$value\n";
		}
	}
}

require_once 'include/config.php';
if (aftertime_init(false) === false) {
	echo Config::init_log();
	exit (-1);
}

print_config_values(Config::get());
exit (0);
?>

Fix for keys with more than 2 levels

Fix for keys with more than 2 levels


<?php

namespace Algolia\AlgoliaSearch\Support;

class Debug
{
    private static $debug = false;

    private static $handler;

    public static function isEnabled()
    {
        return self::$debug;
    }

    public static function disable()
    {
        self::$debug = false;
    }

    public static function enable()
    {
        if (!is_callable(self::$handler)) {
            self::setHandler(function () {
                $args = func_get_args();
                foreach ($args as $arg) {
                    if (function_exists('dump')) {
                        dump($arg);
                    } else {
                        var_dump($arg);
                    }
                }
            });
        }

        self::$debug = true;
    }

    public static function handle()
    {
        if (!is_callable(self::$handler)) {
            return;
        }

        forward_static_call_array(self::$handler, func_get_args());
    }

    public static function setHandler(callable $handler)
    {
        self::$handler = $handler;
    }
}

<?php

namespace Algolia\AlgoliaSearch\Support;

class Debug
{
    private static $debug = false;

    private static $handler;

    public static function isEnabled()
    {
        return self::$debug;
    }

    public static function disable()
    {
        self::$debug = false;
    }

    public static function enable()
    {
        if (!is_callable(self::$handler)) {
            self::setHandler(function () {
                $args = func_get_args();
                foreach ($args as $arg) {
                    if (function_exists('dump')) {
                        dump($arg);
                    } else {
                        var_dump($arg);
                    }
                }
            });
        }

        self::$debug = true;
    }

    public static function handle()
    {
        if (!is_callable(self::$handler)) {
            return;
        }

        forward_static_call_array(self::$handler, func_get_args());
    }

    public static function setHandler(callable $handler)
    {
        self::$handler = $handler;
    }

    public static function getRecordSize(array $record)
    {
        $strlen = mb_strlen(json_encode($record));
        if ($strlen < 1024) {
            return 1;
        } else {
            return round($strlen / 1024, 2);
        }
    }
}

Add helper to get record size

Add helper to get record size


<?php
namespace Doctrineum;

class EnumTest extends \PHPUnit_Framework_TestCase
{
    /** @test */
    public function can_create_instance()
    {
        $instance = Enum::get('foo');
        $this->assertInstanceOf(Enum::class, $instance);
    }

    /** @test */
    public function same_instance_for_same_name_is_returned()
    {
        $firstInstance = Enum::get('foo');
        $secondInstance = Enum::get('bar');
        $thirdInstance = Enum::get('foo');
        $this->assertNotSame($firstInstance, $secondInstance);
        $this->assertSame($firstInstance, $thirdInstance);
    }

    /** @test */
    public function returns_same_value_as_created_with()
    {
        $enum = Enum::get('foo');
        $this->assertSame('foo', $enum->getValue());
    }

    /** @test */
    public function as_string_is_of_same_value_as_created_with()
    {
        $enum = Enum::get('foo');
        $this->assertSame('foo', (string)$enum);
    }

    /**
     * @test
     * @expectedException \Doctrineum\Exceptions\Logic
     */
    public function cant_not_be_cloned()
    {
        $enum = Enum::get('foo');
        clone $enum;
    }
}

<?php
namespace Doctrineum;

class EnumTest extends \PHPUnit_Framework_TestCase
{
    /** @test */
    public function can_create_instance()
    {
        $instance = Enum::get('foo');
        $this->assertInstanceOf(Enum::class, $instance);
    }

    /** @test */
    public function same_instance_for_same_name_is_returned()
    {
        $firstInstance = Enum::get('foo');
        $secondInstance = Enum::get('bar');
        $thirdInstance = Enum::get('foo');
        $this->assertNotSame($firstInstance, $secondInstance);
        $this->assertSame($firstInstance, $thirdInstance);
    }

    /** @test */
    public function returns_same_value_as_created_with()
    {
        $enum = Enum::get('foo');
        $this->assertSame('foo', $enum->getValue());
    }

    /** @test */
    public function as_string_is_of_same_value_as_created_with()
    {
        $enum = Enum::get('foo');
        $this->assertSame('foo', (string)$enum);
    }

    /**
     * @test
     * @expectedException \Doctrineum\Exceptions\Logic
     */
    public function can_not_be_cloned()
    {
        $enum = Enum::get('foo');
        clone $enum;
    }
}

Test case name grammar fix.

refactoring: Test case name grammar fix.


<?php

class CM_LockTest extends CMTest_TestCase {

	public function testLock() {
		$lock = new CM_Lock('lock-test');
		$this->assertFalse($lock->isLocked());
		$lock->lock(1);
		$this->assertTrue($lock->isLocked());
	}

	public function testUnlock() {
		$lock = new CM_Lock('unlock-test');
		$lock->lock();
		$this->assertTrue($lock->isLocked());
		$lock->unlock();
		$this->assertFalse($lock->isLocked());
	}

	public function testWaitUntilUnlocked() {
		$lock = new CM_Lock('wait-test');
		$lockedAt = time();
		$lock->lock(30);
		CMTest_TH::timeForward(30);
		$lock->waitUntilUnlocked();
		$this->assertSameTime($lockedAt + 30, time());
	}
}

<?php

class CM_LockTest extends CMTest_TestCase {

	public function testLock() {
		$lock = new CM_Lock('lock-test');
		$this->assertFalse($lock->isLocked());
		$lock->lock(1);
		$this->assertTrue($lock->isLocked());

		CMTest_TH::timeForward(2);
		$this->assertFalse($lock->isLocked());
	}

	public function testUnlock() {
		$lock = new CM_Lock('unlock-test');
		$lock->lock();
		$this->assertTrue($lock->isLocked());
		$lock->unlock();
		$this->assertFalse($lock->isLocked());
	}

	public function testWaitUntilUnlocked() {
		$lock = new CM_Lock('wait-test');
		$lockedAt = time();
		$lock->lock(30);
		CMTest_TH::timeForward(30);
		$lock->waitUntilUnlocked();
		$this->assertSameTime($lockedAt + 30, time());
	}
}

Enhance testLock() by checking whether the unlocking happens


<?php
/**
 * Register a custom post type for events.
 *
 * @package Victorian Climbing Club
 */

function register_events_post_type() {
  $args = array(
    'public' => true,
    'has_archive' => true,
    'label' => 'Events',
    'rewrite' => array('slug' => 'events'),
    'supports' => array('title', 'editor')
  );
  register_post_type('event', $args);
}

add_action('init', 'register_events_post_type');
add_action('after_switch_theme', 'flush_rewrite_rules');

<?php
/**
 * Register a custom post type for events.
 *
 * @package Victorian Climbing Club
 */

function register_event_post_type() {
  $labels = array(
    'name'          => 'Events',
    'singular_name' => 'Event',
    'add_new_item'  => 'Add New Event'
  );
  $args = array(
    'public'            => true,
    'has_archive'       => true,
    'show_in_nav_menus' => true,
    'labels'            => $labels,
    'rewrite'           => array('slug' => 'events'),
    'supports'          => array('title', 'editor')
  );
  register_post_type('event', $args);
}

add_action('init', 'register_event_post_type');

function my_rewrite_flush() {
  register_event_post_type();
  flush_rewrite_rules();
}

add_action('after_switch_theme', 'my_rewrite_flush');

Configure labels for event post type.

Configure labels for event post type.


<?php

// Include config
require_once 'config/config.inc.php';

// Establish database connection

$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);

if($db->connect_errno > 0){
	die('Unable to connect to database [' . $db->connect_error . ']');
}

/* Import classes */
require_once 'include/php/classes/user.class.php';

$user = new USER();

require_once 'include/php/global.inc.php';
require_once 'include/php/checkpermissions.inc.php';

?>

<?php

// Include config
if(file_exists('config/config_override.inc.php')){
	require_once 'config/config_override.inc.php';
}
else{
	require_once 'config/config.inc.php';
}

// Establish database connection

$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);

if($db->connect_errno > 0){
	die('Unable to connect to database [' . $db->connect_error . ']');
}

/* Import classes */
require_once 'include/php/classes/user.class.php';

$user = new USER();

require_once 'include/php/global.inc.php';
require_once 'include/php/checkpermissions.inc.php';

?>

Add config override for dev purpose

Add config override for dev purpose


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Listabierta\Bundle\MunicipalesBundle\Form\Type\TownStep1Type;

class TownController extends Controller
{
	public function indexAction(Request $request = NULL)
	{
		$this->step1Action($request);
	}

	public function vote1Action($town = NULL, Request $request = NULL)
	{
		$form = $this->createForm(new TownStep1Type(), NULL, array(
				'action' => $this->generateUrl('municipales_candidacy_step1'),
				'method' => 'POST',
		)
		);

		$form->handleRequest($request);

		if ($form->isValid())
		{

		}

		return $this->render('MunicipalesBundle:Town:step1.html.twig', array(
				'town' => $town,
				'form' => $form->createView(),
				'errors' => $form->getErrors()
		));
	}
}

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Listabierta\Bundle\MunicipalesBundle\Form\Type\TownStep1Type;

class TownController extends Controller
{
	public function indexAction(Request $request = NULL)
	{
		$this->step1Action($request);
	}

	public function vote1Action($town = NULL, Request $request = NULL)
	{
		$form = $this->createForm(new TownStep1Type(), NULL, array(
				'action' => $this->generateUrl('municipales_candidacy_step1'),
				'method' => 'POST',
		)
		);

		$form->handleRequest($request);

		if ($form->isValid())
		{

		}

		return $this->render('MunicipalesBundle:Town:step1.html.twig', array(
				'town' => $town,
				'form' => $form->createView(),
				'errors' => $form->getErrors()
		));
	}

	public function resultsAction($town = NULL, Request $request = NULL)
	{
		return $this->render('MunicipalesBundle:Town:step_results.html.twig', array(
				'town' => $town,
		));
	}

}

Implement results action in town controller


<?php

declare(strict_types=1);

namespace OC\Core\Migrations;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

class Version21000Date20201120141228 extends SimpleMigrationStep {
	public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
		/** @var ISchemaWrapper $schema */
		$schema = $schemaClosure();

		if ($schema->hasTable('dav_job_status')) {
			$schema->dropTable('dav_job_status');
		}

		if ($schema->hasTable('systemtag')) {
			$table = $schema->getTable('systemtag');
			if ($table->hasColumn('systemtag')) {
				$table->dropColumn('assignable');
			}
		}

		return $schema;
	}
}

<?php

declare(strict_types=1);

namespace OC\Core\Migrations;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

class Version21000Date20201120141228 extends SimpleMigrationStep {
	public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
		/** @var ISchemaWrapper $schema */
		$schema = $schemaClosure();

		if ($schema->hasTable('dav_job_status')) {
			$schema->dropTable('dav_job_status');
		}

		if ($schema->hasTable('systemtag')) {
			$table = $schema->getTable('systemtag');
			if ($table->hasColumn('systemtag')) {
				$table->dropColumn('assignable');
			}
		}

		if ($schema->hasTable('share')) {
			$table = $schema->getTable('share');
			if ($table->hasColumn('attributes')) {
				$table->dropColumn('attributes');
			}
		}

		return $schema;
	}
}

Drop attributes on oc_share table

Drop attributes on oc_share table

Signed-off-by: Julius Härtl <bf353fa4999f2f148afcc6d8ee6cb1ee74cc07c3@bitgrid.net>


<?php

namespace SamIT\Yii2\Filters;

use SamIT\Yii2\Components\UrlSigner;
use yii\base\ActionFilter;
use yii\web\Request;

/**
 * Filter that checks for a valid HMAC in the URL.
 * @inheritdoc
 */
class HmacFilter extends ActionFilter
{
    /**
     * @var UrlSigner
     */
    public $signer;

    /**
     * @param \yii\base\Action $action
     * @return bool
     * @throws \Exception
     */
    public function beforeAction($action)
    {
        /** @var Request $request */
        $request = $action->controller->module->get('request');
        return $this->signer->verifyHMAC($request->queryParams);
    }

}

<?php

namespace SamIT\Yii2\Filters;

use SamIT\Yii2\Components\UrlSigner;
use yii\base\ActionFilter;
use yii\web\ForbiddenHttpException;
use yii\web\Request;
use yii\web\UnauthorizedHttpException;

/**
 * Filter that checks for a valid HMAC in the URL.
 * @inheritdoc
 */
class HmacFilter extends ActionFilter
{
    /**
     * @var UrlSigner
     */
    public $signer;

    /**
     * @param \yii\base\Action $action
     * @return bool
     * @throws \Exception
     */
    public function beforeAction($action)
    {
        /** @var Request $request */
        $request = $action->controller->module->get('request');
        if (!$this->signer->verifyHMAC($request->queryParams)) {
            throw new ForbiddenHttpException("No or invalid HMAC");
        }
    }

}

Add exception instead of empty response

Add exception instead of empty response


<?php

/*
   ----------------------------------------------------------------------
   FusionInventory
   Copyright (C) 2010-2011 by the FusionInventory Development Team.

   http://www.fusioninventory.org/   http://forge.fusioninventory.org/
   ----------------------------------------------------------------------

   LICENSE

   This file is part of FusionInventory.

   FusionInventory is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 2 of the License, or
   any later version.

   FusionInventory is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with FusionInventory.  If not, see <http://www.gnu.org/licenses/>.

   ------------------------------------------------------------------------
   Original Author of file: David DURIEUX
   Co-authors of file:
   Purpose of file:
   ----------------------------------------------------------------------
 */

define('GLPI_ROOT', '../../..');
include (GLPI_ROOT . "/inc/includes.php");

header("Content-Type: text/html; charset=UTF-8");
header_nocache();

checkRight('rule_ocs', 'r');

$rule = new PluginFusinvinventoryRuleEntity();
include (GLPI_ROOT."/ajax/rule.common.tabs.php");

?>

<?php

/*
   ----------------------------------------------------------------------
   FusionInventory
   Copyright (C) 2010-2011 by the FusionInventory Development Team.

   http://www.fusioninventory.org/   http://forge.fusioninventory.org/
   ----------------------------------------------------------------------

   LICENSE

   This file is part of FusionInventory.

   FusionInventory is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 2 of the License, or
   any later version.

   FusionInventory is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with FusionInventory.  If not, see <http://www.gnu.org/licenses/>.

   ------------------------------------------------------------------------
   Original Author of file: David DURIEUX
   Co-authors of file:
   Purpose of file:
   ----------------------------------------------------------------------
 */

define('GLPI_ROOT', '../../..');
include (GLPI_ROOT . "/inc/includes.php");

header("Content-Type: text/html; charset=UTF-8");
header_nocache();

Session::checkRight('rule_ocs', 'r');

$rule = new PluginFusinvinventoryRuleEntity();
include (GLPI_ROOT."/ajax/rule.common.tabs.php");

?>

Fix functions into Session class

Fix functions into Session class


<?php
// (c) Copyright 2002-2010 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$

function wikiplugin_attributes_info() {
	return array(
		'name' => tra('Attributes'),
		'documentation' => 'PluginAttributes',
		'description' => tra('Allows for generic attributes to be assigned to the current object. Attributes are provided as parameters. For tiki.geo.lat, {attributes tiki_geo_lat=...}. Removing the plugin or values in it will not remove the attributes.'),
		'prefs' => array( 'wikiplugin_attributes' ),
		'extraparams' => true,
		'defaultfilter' => 'text',
		'params' => array(
		),
	);
}

function wikiplugin_attributes_save( $context, $data, $params ) {
	global $attributelib; require_once 'lib/attributes/attributelib.php';

	foreach( $params as $key => $value ) {
		$key = str_replace( '_', '.', $key );
		$attributelib->set_attribute( $context['type'], $context['object'], $key, $value );
	}
}

function wikiplugin_attributes($data, $params) {
	return '';
}

<?php
// (c) Copyright 2002-2010 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$

function wikiplugin_attributes_info() {
	return array(
		'name' => tra('Attributes'),
		'documentation' => tra('PluginAttributes'),
		'description' => tra('Allows for generic attributes to be assigned to the current object. Attributes are provided as parameters. For tiki.geo.lat, {attributes tiki_geo_lat=...}. Removing the plugin or values in it will not remove the attributes.'),
		'prefs' => array( 'wikiplugin_attributes' ),
		'extraparams' => true,
		'defaultfilter' => 'text',
		'params' => array(
		),
	);
}

function wikiplugin_attributes_save( $context, $data, $params ) {
	global $attributelib; require_once 'lib/attributes/attributelib.php';

	foreach( $params as $key => $value ) {
		$key = str_replace( '_', '.', $key );
		$attributelib->set_attribute( $context['type'], $context['object'], $key, $value );
	}
}

function wikiplugin_attributes($data, $params) {
	return '';
}

Add tra to plugin info

Add tra to plugin info

git-svn-id: 9bac41f8ebc9458fc3e28d41abfab39641e8bd1c@31175 b456876b-0849-0410-b77d-98878d47e9d5


<?php

namespace Smartbox\Integration\FrameworkBundle\Tools\Evaluator;

use Smartbox\Integration\FrameworkBundle\Exceptions\RecoverableExceptionInterface;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;

class CustomExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
    public function getFunctions()
    {
        return [$this->createIsRecoverableFunction()];
    }

    /**
     * @return ExpressionFunction
     */
    protected function createHasHeyFunction()
    {
        return new ExpressionFunction(
            'hasKey',
            function ($key, $array) {
                return sprintf('(array_key_exists(%s,%s))', $key, $array);
            },
            function ($arguments, $key, $array) {
                if (!is_array($array)) {
                    throw new \RuntimeException('Second argument passed to "hasKey" should be an array.');
                }

                return array_key_exists($key, $array);
            }
        );
    }

    /**
     * @return ExpressionFunction
     */
    protected function createIsRecoverableFunction()
    {
        return new ExpressionFunction(
            'isRecoverable',
            function ($object) {
                return sprintf('(%s instanceof \Smartbox\Integration\FrameworkBundle\Exceptions\RecoverableExceptionInterface)', $object);
            },
            function ($arguments, $object) {
                if (!is_object($object) || !($object instanceof \Exception)) {
                    throw new \RuntimeException('First argument should be an exception');
                }

                return ($object instanceof RecoverableExceptionInterface);
            }
        );
    }
}

<?php

namespace Smartbox\Integration\FrameworkBundle\Tools\Evaluator;

use Smartbox\Integration\FrameworkBundle\Exceptions\RecoverableExceptionInterface;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;

class CustomExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
    public function getFunctions()
    {
        return [
            $this->createHasHeyFunction(),
            $this->createIsRecoverableFunction(),
        ];
    }

    /**
     * @return ExpressionFunction
     */
    protected function createHasHeyFunction()
    {
        return new ExpressionFunction(
            'hasKey',
            function ($key, $array) {
                return sprintf('(array_key_exists(%s,%s))', $key, $array);
            },
            function ($arguments, $key, $array) {
                if (!is_array($array)) {
                    throw new \RuntimeException('Second argument passed to "hasKey" should be an array.');
                }

                return array_key_exists($key, $array);
            }
        );
    }

    /**
     * @return ExpressionFunction
     */
    protected function createIsRecoverableFunction()
    {
        return new ExpressionFunction(
            'isRecoverable',
            function ($object) {
                return sprintf('(%s instanceof \Smartbox\Integration\FrameworkBundle\Exceptions\RecoverableExceptionInterface)', $object);
            },
            function ($arguments, $object) {
                if (!is_object($object) || !($object instanceof \Exception)) {
                    throw new \RuntimeException('First argument should be an exception');
                }

                return ($object instanceof RecoverableExceptionInterface);
            }
        );
    }
}

Fix error in UT because of problem with merge conflicts


<?php

namespace UWaterlooAPI\Data\JSON\Common\Components;

class ComponentFactory
{
    /**
     * Builds the given component using the given array as the data input.
     *
     * @param array  $data
     * @param string $component
     *
     * @return \UWaterlooAPI\Data\JSON\Common\Components\BaseComponent|null
     */
    public static function buildComponent(array $data, $component)
    {
        return empty($data) ? null : new $component($data);
    }

    /**
     * Builds the given component using the first element of the given array as the data input.
     *
     * @param array  $data
     * @param string $component
     *
     * @return \UWaterlooAPI\Data\JSON\Common\Components\BaseComponent|null
     */
    public static function buildComponentArray(array $data, $component)
    {
        return empty($data) ? null : new $component(reset($data));
    }

    /**
     * Builds an array of components using the elements of the given array as the data input.
     *
     * @param array  $data
     * @param string $component
     *
     * @return \UWaterlooAPI\Data\JSON\Common\Components\BaseComponent|null
     */
    public static function buildComponents(array $data, $component)
    {
        return array_map(function ($element) use ($component) {
            return new $component($element);
        }, $data);
    }
}

<?php

namespace UWaterlooAPI\Data\JSON\Common\Components;

class ComponentFactory
{
    /**
     * Builds the given component using the given array as the data input.
     *
     * @param array|null  $data
     * @param string $component
     *
     * @return \UWaterlooAPI\Data\JSON\Common\Components\BaseComponent|null
     */
    public static function buildComponent($data, $component)
    {
        return empty($data) ? null : new $component($data);
    }

    /**
     * Builds the given component using the first element of the given array as the data input.
     *
     * @param array  $data
     * @param string $component
     *
     * @return \UWaterlooAPI\Data\JSON\Common\Components\BaseComponent|null
     */
    public static function buildComponentArray(array $data, $component)
    {
        return empty($data) ? null : new $component(reset($data));
    }

    /**
     * Builds an array of components using the elements of the given array as the data input.
     *
     * @param array  $data
     * @param string $component
     *
     * @return \UWaterlooAPI\Data\JSON\Common\Components\BaseComponent|null
     */
    public static function buildComponents(array $data, $component)
    {
        return array_map(function ($element) use ($component) {
            return new $component($element);
        }, $data);
    }
}

Fix issue with null data.

Fix issue with null data.


<?php namespace System;

class Hash {

	/**
	 * Hash a string using PHPass.
	 *
	 * PHPass provides reliable bcrypt hashing, and is used by many popular PHP
	 * applications such as Wordpress and Joomla.
	 *
	 * @access public
	 * @param  string  $value
	 * @return string
	 */
	public static function make($value)
	{
		return static::hasher()->HashPassword($value);
	}

	/**
	 * Determine if an unhashed value matches a given hash.
	 *
	 * @param  string  $value
	 * @param  string  $hash
	 * @return bool
	 */
	public static function check($value, $hash)
	{
		return static::hasher()->CheckPassword($value, $hash);
	}

	/**
	 * Create a new PHPass instance.
	 *
	 * @return PasswordHash
	 */
	private static function hasher()
	{
		require_once SYS_PATH.'vendor/phpass'.EXT;

		return new \PasswordHash(10, false);
	}

}

<?php namespace System;

class Hash {

	/**
	 * Hash a string using PHPass.
	 *
	 * PHPass provides reliable bcrypt hashing, and is used by many popular PHP
	 * applications such as Wordpress and Joomla.
	 *
	 * @access public
	 * @param  string  $value
	 * @return string
	 */
	public static function make($value, $rounds = 10)
	{
		return static::hasher($rounds)->HashPassword($value);
	}

	/**
	 * Determine if an unhashed value matches a given hash.
	 *
	 * @param  string  $value
	 * @param  string  $hash
	 * @return bool
	 */
	public static function check($value, $hash)
	{
		return static::hasher()->CheckPassword($value, $hash);
	}

	/**
	 * Create a new PHPass instance.
	 *
	 * @param  int  $rounds
	 * @return PasswordHash
	 */
	private static function hasher($rounds = 10)
	{
		require_once SYS_PATH.'vendor/phpass'.EXT;

		return new \PasswordHash($rounds, false);
	}

}

Add ability to specify iteration count in Hash class.


<?php

namespace App\Listeners;

use App\Events\NewIP;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

use App\Models\DeviceIPs;

use App\Models\SSHCredentials;

class FindSSH
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  NewIP  $event
     * @return void
     */
    public function handle(NewIP $event)
    {
        $address = $event->address;

        $ip = $address['address'];
        $addressid = $address['id'];

        exec("nmap -p22 $ip",$ping);

        $ping = implode("", $ping);

        if(str_contains($ping,'22/tcp open  ssh')){

             SSHCredentials::firstOrCreate([
            'username' => NULL,
            'password' => NULL,
            'device_IP_id' => $addressid,
            ]);

        }
    }
}

<?php

namespace App\Listeners;

use App\Events\NewIP;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

use App\Models\DeviceIPs;

use App\Models\SSHCredentials;

class FindSSH
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  NewIP  $event
     * @return void
     */
    public function handle(NewIP $event)
    {
        $address = $event->address;

        $ip = $address['address'];
        $addressid = $address['id'];

        exec("nmap -p22 $ip",$ping);

        $ping = implode("", $ping);

        if(str_contains($ping,'22/tcp open  ssh')){

             SSHCredentials::firstOrCreate([
            'device_IP_id' => $addressid,
            ]);

        }
    }
}

Fix Username Password setting making new rows


<?php

namespace Psy\Test\CodeCleaner;

use Psy\CodeCleaner;
use Psy\CodeCleaner\MagicConstantsPass;
use PHPParser_Node_Name as Name;
use PHPParser_Node_Scalar_DirConst as DirConstant;
use PHPParser_Node_Scalar_FileConst as FileConstant;
use PHPParser_Node_Expr_FuncCall as FunctionCall;
use PHPParser_Node_Scalar_String as StringNode;

class MagicConstantsPassTest extends \PHPUnit_Framework_TestCase
{
    private $pass;

    public function setUp()
    {
        $this->pass = new MagicConstantsPass;
    }

    public function testProcess()
    {
        $stmts = array(new DirConstant);
        $this->pass->process($stmts);
        $this->assertEquals(array(new FunctionCall(new Name('getcwd'))), $stmts);

        $stmts = array(new FileConstant);
        $this->pass->process($stmts);
        $this->assertEquals(array(new StringNode('')), $stmts);
     }
}

<?php

namespace Psy\Test\CodeCleaner;

use Psy\CodeCleaner;
use Psy\CodeCleaner\MagicConstantsPass;
use PHPParser_Node_Name as Name;
use PHPParser_Node_Scalar_DirConst as DirConstant;
use PHPParser_Node_Scalar_FileConst as FileConstant;
use PHPParser_Node_Expr_FuncCall as FunctionCall;
use PHPParser_Node_Scalar_String as StringNode;

class MagicConstantsPassTest extends CodeCleanerTestCase
{
    private $pass;

    public function setUp()
    {
        $this->pass = new MagicConstantsPass;
    }

    /**
     * @dataProvider magicConstants
     */
    public function testProcess($from, $to)
    {
        $stmts = $this->parse($from);
        $this->pass->process($stmts);
        $this->assertEquals($to, $this->prettyPrint($stmts));
     }

     public function magicConstants()
     {
        return array(
            array('__DIR__;', 'getcwd();'),
            array('__FILE__;', "'';"),
            array('___FILE___;', "___FILE___;"),
        );
     }
}

Update magic constants test to use new test case.