<?php

/**
 * This file contains the base abstract controller class.
 *
 * PHP Version 5.3
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */

/**
 * Base Controller class
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */
abstract class Controller
{

    /**
     * Constructor
     */
    public function __construct()
    {

    }

    /**
     * Destructor
     */
    public function __destruct()
    {

    }

    /**
     * Handle unimplemented calls
     *
     * @param String $name      Method name
     * @param array  $arguments Arguments passed to the method
     *
     * @return String JSON encoded error String
     */
    public function __call($name, $arguments)
    {
        return Json::error("not_implemented");
    }

    /**
     * Default method as defined in conf.application.inc.php
     *
     * @return void
     */
    abstract public function index();

}

?>

<?php

/**
 * This file contains the base abstract controller class.
 *
 * PHP Version 5.3
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */

/**
 * Base Controller class
 *
 * @category   Libraries
 * @package    Core
 * @subpackage Libraries
 * @author     M2Mobi <info@m2mobi.com>
 * @author     Heinz Wiesinger <heinz@m2mobi.com>
 */
abstract class Controller
{

    /**
     * Constructor.
     */
    public function __construct()
    {

    }

    /**
     * Destructor.
     */
    public function __destruct()
    {

    }

    /**
     * Handle unimplemented calls.
     *
     * @param String $name      Method name
     * @param array  $arguments Arguments passed to the method
     *
     * @return String JSON encoded error String
     */
    public function __call($name, $arguments)
    {
        return Json::error("not_implemented");
    }

    /**
     * Default method as defined in conf.application.inc.php.
     *
     * @return void
     */
    abstract public function index();

}

?>

Fix style for controller class

system: Fix style for controller class


<?php
declare(strict_types = 1);

namespace Pages\Controllers\Mixed;

use Database\Objects\TrackerInfo;
use Generator;
use Pages\Controllers\AbstractHandlerController;
use Pages\Controllers\Handlers\OptionallyLoadTracker;
use Pages\Controllers\Handlers\RequireLoginState;
use Pages\IAction;
use Pages\Models\Mixed\LoginModel;
use Pages\Views\Mixed\LoginPage;
use Routing\Request;
use Session\Session;
use function Pages\Actions\redirect;
use function Pages\Actions\view;

class LoginController extends AbstractHandlerController{
  private ?TrackerInfo $tracker;

  protected function prerequisites(): Generator{
    yield new RequireLoginState(false);
    yield new OptionallyLoadTracker($this->tracker);
  }

  protected function finally(Request $req, Session $sess): IAction{
    $model = new LoginModel($req, $this->tracker);
    $data = $req->getData();

    if (!empty($data) && $model->loginUser($data, $sess)){
      return redirect([BASE_URL_ENC,
                       $req->getBasePath()->encoded(),
                       isset($_GET['return']) ? ltrim($_GET['return'], '/') : '']);
    }

    return view(new LoginPage($model->load()));
  }
}

?>

<?php
declare(strict_types = 1);

namespace Pages\Controllers\Mixed;

use Database\Objects\TrackerInfo;
use Generator;
use Pages\Controllers\AbstractHandlerController;
use Pages\Controllers\Handlers\OptionallyLoadTracker;
use Pages\Controllers\Handlers\RequireLoginState;
use Pages\IAction;
use Pages\Models\Mixed\LoginModel;
use Pages\Views\Mixed\LoginPage;
use Routing\Request;
use Session\Session;
use function Pages\Actions\redirect;
use function Pages\Actions\view;

class LoginController extends AbstractHandlerController{
  private ?TrackerInfo $tracker;

  protected function prerequisites(): Generator{
    yield new RequireLoginState(false);
    yield new OptionallyLoadTracker($this->tracker);
  }

  protected function finally(Request $req, Session $sess): IAction{
    $model = new LoginModel($req, $this->tracker);
    $data = $req->getData();

    if (!empty($data) && $model->loginUser($data, $sess)){
      return redirect([BASE_URL_ENC, isset($_GET['return']) ? ltrim($_GET['return'], '/') : '']);
    }

    return view(new LoginPage($model->load()));
  }
}

?>

Fix wrong login return page for tracker URLs


<?php

namespace Spark\Controller;

use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
use Spark\Core\ApplicationAware;

abstract class Base implements ApplicationAware
{
    use ActionHelper\Filters;
    use ActionHelper\Redirect;
    use ActionHelper\Layout;

    protected $application;
    protected $response;
    protected $flash;

    function __construct()
    {
        $this->response = new Response;
        $this->setup();
    }

    function setup()
    {}

    function render($options = [])
    {
        $attributes = $this->request()->attributes;

        if (!$options) {
            $options['script'] = $attributes->get('controller') . '/' . $attributes->get('action');
        }

        if (isset($options['status'])) {
            $this->response()->setStatusCode($options['status']);
            unset($options['status']);
        }

        return $this->application['spark.render_pipeline']->render($options, $this->response());
    }

    function request()
    {
        return $this->application['request'];
    }

    function response()
    {
        return $this->response;
    }

    function flash()
    {
        return $this->flash ?: $this->flash = $this->application['session']->getFlashBag();
    }

    function session()
    {
        return $this->application['session'];
    }

    function application()
    {
        return $this->application;
    }

    function setApplication(Application $application)
    {
        $this->application = $application;
    }
}

<?php

namespace Spark\Controller;

use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
use Spark\Core\ApplicationAware;

abstract class Base implements ApplicationAware
{
    use ActionHelper\Filters;
    use ActionHelper\Redirect;
    use ActionHelper\Layout;

    protected $application;
    protected $response;
    protected $flash;

    function __construct()
    {
        $this->response = new Response;
        $this->setup();
    }

    function setup()
    {}

    function render($options = [])
    {
        $attributes = $this->request()->attributes;

        if (!$options) {
            $options['script'] = $attributes->get('controller') . '/' . $attributes->get('action');
        }

        if (isset($options['status'])) {
            $this->response()->setStatusCode($options['status']);
            unset($options['status']);
        }

        if (isset($options['response'])) {
            $response = $options['response'];
            unset($options['response']);
        } else {
            $response = $this->response();
        }

        return $this->application['spark.render_pipeline']->render($options, $response);
    }

    function request()
    {
        return $this->application['request'];
    }

    function response()
    {
        return $this->response;
    }

    function flash()
    {
        return $this->flash ?: $this->flash = $this->application['session']->getFlashBag();
    }

    function session()
    {
        return $this->application['session'];
    }

    function application()
    {
        return $this->application;
    }

    function setApplication(Application $application)
    {
        $this->application = $application;
    }
}

Add option 'response' to render

Add option 'response' to render


<?php

	class DeviceBlackBerry extends MobileDevice {
		static protected $instance;

		public function initialize() {
			$this->{'name'} = 'BlackBerry';
			$this->{'user-agent'} = 'Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en-GB) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+';
			$this->{'user-agent'} = 'BlackBerry9500/5.0.0.484 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/-1';
			$this->{'user-agent'} = 'BlackBerry9000/4.6.0.307 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/-1';

			// Positive matching:
			$this->allow(
				'%blackberry%i'
			);

			// Version matching:
			$this->capture(
				'software-version',
				'%(BlackBerry[0-9]{4}|\bVersion)/([0-9]\.[0-9])%',
				'\2'
			);
		}
	}

	MobileDevice::instance('DeviceBlackBerry');

?>

<?php

	class DeviceBlackBerry extends MobileDevice {
		static protected $instance;

		public function initialize() {
			$this->{'name'} = 'BlackBerry';
			$this->{'user-agent'} = 'Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en-GB) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+';
			$this->{'user-agent'} = 'BlackBerry9500/5.0.0.484 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/-1';
			$this->{'user-agent'} = 'BlackBerry9000/4.6.0.307 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/-1';

			// Positive matching:
			$this->allow(
				'%blackberry%i',
				'%bb%i'
			);

			// Version matching:
			$this->capture(
				'software-version',
				'%(BlackBerry[0-9]{4}|\bVersion)/([0-9]\.[0-9])%',
				'\2'
			);
		}
	}

	MobileDevice::instance('DeviceBlackBerry');

?>

Add detection for newer Blackberry devices


<?php namespace Illuminate\Html;

use Illuminate\Support\ServiceProvider;

class HtmlServiceProvider extends ServiceProvider {

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

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['form'] = $this->app->share(function($app)
		{
			return new FormBuilder($app['url'], $app['session']->getToken());
		});
	}

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

}

<?php namespace Illuminate\Html;

use Illuminate\Support\ServiceProvider;

class HtmlServiceProvider extends ServiceProvider {

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

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['form'] = $this->app->share(function($app)
		{
			$form = new FormBuilder($app['url'], $app['session']->getToken());

			$form->setSessionStore($app['session']);

			return $form;
		});
	}

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

}

Set session on form builder.

Set session on form builder.


<?php

namespace NS\SentinelBundle\Repository;

use NS\SecurityBundle\Doctrine\SecuredEntityRepository;
use NS\UtilBundle\Service\AjaxAutocompleteRepositoryInterface;

/**
 * Description of Common
 *
 * @author gnat
 */
class Common extends SecuredEntityRepository implements AjaxAutocompleteRepositoryInterface
{
    public function getAllSecuredQueryBuilder($alias = 'o')
    {
        return $this->secure($this->createQueryBuilder($alias)->orderBy("$alias.name","ASC"));
    }

    public function getForAutoComplete($fields, array $value, $limit)
    {
        $alias = 'd';
        $qb    = $this->_em->createQueryBuilder()
                              ->select($alias)
                              ->from($this->getClassName(), $alias)
                              ->setMaxResults($limit);

        if(!empty($value) && $value['value'][0]=='*')
            return $qb->getQuery();

        if(!empty($value))
        {
            if(is_array($fields))
            {
                foreach ($fields as $f)
                {
                    $field = "$alias.$f";
                    $qb->addOrderBy($field)
                       ->orWhere("$field LIKE :param")->setParameter('param',$value['value'].'%');
                }
            }
            else
            {
                $field = "$alias.$fields";
                $qb->orderBy($field)->andWhere("$field LIKE :param")->setParameter('param',$value['value'].'%');
            }
        }

        return $qb->getQuery();
    }
}

<?php

namespace NS\SentinelBundle\Repository;

use NS\SecurityBundle\Doctrine\SecuredEntityRepository;
use NS\UtilBundle\Service\AjaxAutocompleteRepositoryInterface;

/**
 * Description of Common
 *
 * @author gnat
 */
class Common extends SecuredEntityRepository implements AjaxAutocompleteRepositoryInterface
{
    public function getAllSecuredQueryBuilder($alias = 'o')
    {
        return $this->secure($this->createQueryBuilder($alias)->orderBy("$alias.name","ASC"));
    }

    public function getForAutoComplete($fields, array $value, $limit)
    {
        $alias = 'd';
        $qb    = $this->createQueryBuilder($alias)->setMaxResults($limit);

        if(!empty($value) && $value['value'][0]=='*')
            return $qb->getQuery();

        if(!empty($value))
        {
            if(is_array($fields))
            {
                foreach ($fields as $f)
                {
                    $field = "$alias.$f";
                    $qb->addOrderBy($field)
                       ->orWhere("$field LIKE :param")->setParameter('param',$value['value'].'%');
                }
            }
            else
            {
                $field = "$alias.$fields";
                $qb->orderBy($field)->andWhere("$field LIKE :param")->setParameter('param',$value['value'].'%');
            }
        }

        return $qb->getQuery();
    }
}

Use the local createQueryBuilder with alias


<?php
namespace Loct\Pinger\Provider;

use \Loct\Pinger\Notifier\MailgunNotifier;
use \Mailgun\Mailgun;
use \Pimple\Container;
use \Pimple\ServiceProviderInterface;

/**
 * Service provider for notifier related classes and parameters.
 *
 * @author herloct <herloct@gmail.com>
 */
class NotifierProvider implements ServiceProviderInterface
{

    /**
     * Registers services on the given container.
     *
     * This method should only be used to configure services and parameters.
     * It should not get services.
     *
     * @param Container $pimple An Container instance
     */
    public function register(Container $pimple)
    {
        $pimple['notifier'] = function ($pimple)
        {
            $config = $pimple['config'];

            $apiKey = $config->get('pinger.notifications.mailgun.api_key');
            $domain = $config->get('pinger.notifications.mailgun.domain');
            $recipients = $config->get('pinger.notifications.mailgun.recipients');

            $mailgun = new Mailgun($apiKey);
            return new MailgunNotifier($mailgun, $domain, $recipients);
        };
    }
}

Add empty line before return to follow Symfony2 code style


<?php
function smarty_function_call_webservice($params, &$smarty) {
    require_once 'webservice//WebService.php';
    $service = WebService::factory($params['path']);
    if ($service[0] != null) {
        $ret = $service[0]->execute($params['data']);
        $smarty->assign($params['assign'], $ret);
    }
}
?>

<?php
function smarty_function_call_webservice($params, &$smarty) {
    $service = WebService::factory($params['path']);
    if ($service[0] != null) {
        $ret = $service[0]->execute($params['data']);
        $smarty->assign($params['assign'], $ret);
    }
}
?>

Remove obsolete require_once in smarty plugin


<?php

/*
 * This file is part of the Active Collab DatabaseStructure project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\DatabaseStructure\Behaviour;

use ActiveCollab\DateValue\DateTimeValueInterface;

interface CreatedAtInterface
{
    /**
     * Return object ID.
     *
     * @return int
     */
    public function getId();

    /**
     * Return value of created_at field.
     *
     * @return DateTimeValueInterface|null
     */
    public function getCreatedAt(): ?DateTimeValueInterface;

    /**
     * @param  DateTimeValueInterface|null $value
     * @return $this
     */
    public function &setCreatedAt(?DateTimeValueInterface $value);
}

<?php

/*
 * This file is part of the Active Collab DatabaseStructure project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\DatabaseStructure\Behaviour;

use ActiveCollab\DateValue\DateTimeValueInterface;
use ActiveCollab\Object\ObjectInterface;

interface CreatedAtInterface extends ObjectInterface
{
    /**
     * Return value of created_at field.
     *
     * @return DateTimeValueInterface|null
     */
    public function getCreatedAt(): ?DateTimeValueInterface;

    /**
     * @param  DateTimeValueInterface|null $value
     * @return $this
     */
    public function &setCreatedAt(?DateTimeValueInterface $value);
}

Use object interface in created at interface


<?php
$path_prefix = '../';
require('../inc/common.php');

role_needed(ROLE_ADMIN);

$title = 'Administration Panel';
include('admin_top.php');
include('../inc/start_html.php');
?>

Manage Languages

Add and remove languages

Manage Users

Add new users, alter user roles

Import Documents

Import existing documents to the translation system.

Manage Documents

Rename or remove documents.

Manage Resources

Add, remove, modify external resources.

Export Documents

Export edited and translated documents to the repository.

Log Viewer

View server logs.

<?php
include('../inc/end_html.php');
?>

<?php
$path_prefix = '../';
require('../inc/common.php');

role_needed(ROLE_ADMIN);

$title = 'Administration Panel';
include('admin_top.php');
include('../inc/start_html.php');
?>

Manage Languages

Add and remove languages

Manage Users

Add new users, alter user roles

Import Documents

Import existing documents to the translation system.

Manage Documents

Rename or remove documents.

Manage Resources

Add, remove, modify external resources.

Export Documents

Export edited and translated documents to the repository.

<?php
include('../inc/end_html.php');
?>

Remove link to server logs

Remove link to server logs

The handler was already removed in 66bf9a966069897ba651a596c7d2148c4d76ba1b.


<?php if (array_key_exists('submit', $_POST)): ?>
Data From Sensor #<?php echo $_POST["uid"]; ?>

Level: <?php echo $_POST["level"]; ?>

Max Level: <?php echo $_POST["levelmax"]; ?>

Fill Percentage: <?php echo 100*(intval($_POST["level"])/intval($_POST["levelmax"])) ?>

Battery Level: <?php echo $_POST["battlevel"]; ?>

<?php else: ?>

<form action="/public/test2.php" method="post">
Bin Level: <input type="text" name="level">

Bin Level Max: <input type="text" name="levelmax">

Battery Level: <input type="text" name="battlevel">

UID: <input type="text" name="uid">

<input type="submit" name="submit">
</form>

<?php endif ?>

<?php if (array_key_exists('submit', $_POST)): ?>
Data From Sensor #<?php echo $_POST["uid"]; ?>

Level: <?php echo $_POST["level"]; ?>

Max Level: <?php echo $_POST["levelmax"]; ?>

Fill Percentage: <?php echo 100*(intval($_POST["level"])/intval($_POST["levelmax"])) ?>

Battery Level: <?php echo $_POST["battlevel"]; ?>

<?php else: ?>

<form action="/public/GroupDesignProjectServer/backend..php" method="post">
Bin Level: <input type="text" name="level">

Bin Level Max: <input type="text" name="levelmax">

Battery Level: <input type="text" name="battlevel">

UID: <input type="text" name="uid">

<input type="submit" name="submit">
</form>

<?php endif ?>

Change form submit url to match change in folder heirarchy


<?php namespace Lucasmichot\Laraveldotenv;

use Illuminate\Support\ServiceProvider;

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

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        // if .env file is readable, process it like a .ini file (without sections)
        $variables = parse_ini_file(base_path().'/.env', false);
        if ($variables !== false) {
            // merge variables into $_ENV and $_SERVER arrays
            $_ENV    = array_merge($_ENV, $variables);
            $_SERVER = array_merge($_SERVER, $variables);
        }
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        // no service provided
    }
}

<?php namespace Lucasmichot\Laraveldotenv;

use Illuminate\Support\ServiceProvider;

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

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        // get .env filename
        $env_filename = base_path() . '/.env';

        // if .env file exists
        if (file_exists($env_filename)) {
            // if .env file is readable, process it like a .ini file (without sections)
            $variables = parse_ini_file(base_path() . '/.env', false);
            if ($variables !== false) {
                // merge variables into $_ENV and $_SERVER arrays
                $_ENV = array_merge($_ENV, $variables);
                $_SERVER = array_merge($_SERVER, $variables);
            }
        }
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        // no service provided
    }
}

Check if .env file exists

Check if .env file exists


<?php
set_time_limit(0);

// Configuration
include 'config/config.php';

// Version Functions
include 'functions/getVersion.php';
include 'functions/checkVersion.php';

// Debugging Functions
include 'functions/debug.php';

echo "LinMon slave version ".getVersion("version")." started. \n\n";
echo checkVersion();
echo "Collecting data every ".$config['updateinterval']." seconds \n\n";

while (true){
	echo "Starting data collection \n";
	sleep($config['updateinterval']);
}
?>

<?php
set_time_limit(0);

// Configuration
include 'config/config.php';

// Version Functions
include 'functions/getVersion.php';
include 'functions/checkVersion.php';

// Debugging Functions
include 'functions/debug.php';

echo "LinMon slave version ".getVersion("version")." started. \n\n";
echo checkVersion();
echo "Collecting data every ".$config['updateinterval']." seconds \n\n";

while (true){
	collectionInfoStart();
	sleep($config['updateinterval']);
}
?>

Add debugging to slave daemon

Add debugging to slave daemon


<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;

trait VerifiesEmails
{
    use RedirectsUsers;

    /**
     * Show the email verification notice.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {
        return $request->user()->hasVerifiedEmail()
                        ? redirect($this->redirectPath())
                        : view('auth.verify');
    }

    /**
     * Mark the authenticated user's email address as verified.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function verify(Request $request)
    {
        if ($request->route('id') == $request->user()->getKey() &&
            $request->user()->markEmailAsVerified()) {
            event(new Verified($request->user()));
        }

        return redirect($this->redirectPath())->with('verified', true);
    }

    /**
     * Resend the email verification notification.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function resend(Request $request)
    {
        if ($request->user()->hasVerifiedEmail()) {
            return redirect($this->redirectPath());
        }

        $request->user()->sendEmailVerificationNotification();

        return back()->with('resent', true);
    }
}

<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;

trait VerifiesEmails
{
    use RedirectsUsers;

    /**
     * Show the email verification notice.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {
        return $request->user()->hasVerifiedEmail()
                        ? redirect($this->redirectPath())
                        : view('auth.verify');
    }

	/**
	 * Mark the authenticated user's email address as verified.
	 *
	 * @param  \Illuminate\Http\Request $request
	 * @return \Illuminate\Http\Response
	 * @throws AuthorizationException
	 */
    public function verify(Request $request)
    {
		if ($request->route('id') != $request->user()->getKey()) {
			throw new AuthorizationException();
		}

		if ($request->user()->markEmailAsVerified()) {
			event(new Verified($request->user()));
		}

        return redirect($this->redirectPath())->with('verified', true);
    }

    /**
     * Resend the email verification notification.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function resend(Request $request)
    {
        if ($request->user()->hasVerifiedEmail()) {
            return redirect($this->redirectPath());
        }

        $request->user()->sendEmailVerificationNotification();

        return back()->with('resent', true);
    }
}

Add verify of current user id on email verification


<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Setups\MetaBoxes;

use GrottoPress\Jentil\Setups\AbstractSetup;
use GrottoPress\Jentil\IdentityTrait;

abstract class AbstractMetaBox extends AbstractSetup
{
    use IdentityTrait;

    /**
     * @var string 'normal', 'side', or 'advanced'.
     */
    protected $context;

    protected function getContext(): string
    {
        return $this->context;
    }
}

<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Setups\MetaBoxes;

use GrottoPress\Jentil\Setups\AbstractSetup;
use GrottoPress\Jentil\IdentityTrait;

abstract class AbstractMetaBox extends AbstractSetup
{
    use IdentityTrait;

    /**
     * @var string $context 'normal', 'side', or 'advanced'.
     */
    protected $context;

    protected function getContext(): string
    {
        return $this->context;
    }
}

Add missing variable name in doc block

Add missing variable name in doc block


<?php
namespace Sil\SilAuth\auth;

use Psr\Log\LoggerInterface;

class IdBroker
{
    /** @var LoggerInterface */
    protected $logger;

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

    public function getUserAttributesFor($username)
    {
        throw new \Exception('Not yet implemented.');
    }
}

<?php
namespace Sil\SilAuth\auth;

use Psr\Log\LoggerInterface;

class IdBroker
{
    /** @var LoggerInterface */
    protected $logger;

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

    public function getUserAttributesFor($username)
    {
        throw new \Exception('Not yet implemented.');
    }

    public function isValidCredentials(string $username, string $password)
    {
        throw new \Exception('Not yet implemented.');
    }
}

Add (empty-ish) method that will eventually need to exist.


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

namespace Darvin\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * User controller
 */
class UserController extends Controller
{
    /**
     * @param \Symfony\Component\HttpFoundation\Request $request Request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function profileAction(Request $request)
    {
        return new Response($this->getUserFormRenderer()->renderProfileForm($request->isXmlHttpRequest()));
    }

    /**
     * @return \Darvin\UserBundle\Form\Renderer\UserFormRenderer
     */
    private function getUserFormRenderer()
    {
        return $this->get('darvin_user.user.form.renderer');
    }
}

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

namespace Darvin\UserBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * User controller
 */
class UserController extends Controller
{
    /**
     * @param \Symfony\Component\HttpFoundation\Request $request Request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @Security("is_granted('IS_AUTHENTICATED_REMEMBERED')")
     */
    public function profileAction(Request $request)
    {
        return new Response($this->getUserFormRenderer()->renderProfileForm($request->isXmlHttpRequest()));
    }

    /**
     * @return \Darvin\UserBundle\Form\Renderer\UserFormRenderer
     */
    private function getUserFormRenderer()
    {
        return $this->get('darvin_user.user.form.renderer');
    }
}

Secure user profile controller action.

Secure user profile controller action.


<?php

namespace FD\PrivateMessageBundle\Validator;

use FD\PrivateMessageBundle\Entity\Conversation;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
 * Class ConversationValidator.
 */
class ConversationValidator
{
    /**
     * Error message when user set himself as recipient of the conversation.
     */
    const RECIPIENT_VIOLATION = 'You cannot send a message to yourself';

    /**
     * Entry point of the conversation's validation process.
     *
     * @param Conversation              $conversation : instance of the conversation to validate.
     * @param ExecutionContextInterface $context      : instance of the execution context.
     */
    public static function validate(Conversation $conversation, ExecutionContextInterface $context)
    {
        self::validateRecipients($conversation, $context);
    }

    /**
     * Make sure the author of the conversation is not sending a message to himself.
     *
     * @param Conversation              $conversation : instance of the conversation to validate.
     * @param ExecutionContextInterface $context      : instance of the execution context.
     */
    private static function validateRecipients(Conversation $conversation, ExecutionContextInterface $context)
    {
        $recipients = $conversation->getRecipients();

        if ($recipients->contains($conversation->getAuthor())) {
            $context
                ->buildViolation(self::RECIPIENT_VIOLATION)
                ->atPath('recipients')
                ->addViolation();
        }
    }
}

<?php

namespace FD\PrivateMessageBundle\Validator;

use FD\PrivateMessageBundle\Entity\Conversation;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
 * Class ConversationValidator.
 */
class ConversationValidator
{
    /**
     * Error message when user set himself as recipient of the conversation.
     */
    const RECIPIENT_VIOLATION = 'You cannot send a message to yourself';

    /**
     * Entry point of the conversation's validation process.
     *
     * @param Conversation              $conversation : The conversation object to validate.
     * @param ExecutionContextInterface $context      : The execution context object.
     */
    public static function validate(Conversation $conversation, ExecutionContextInterface $context)
    {
        if ($context->getGroup() == 'creation') {
            self::validateRecipients($conversation, $context);
        }
    }

    /**
     * Make sure the author of the conversation is not sending a message to himself.
     *
     * @param Conversation              $conversation : The conversation object to validate.
     * @param ExecutionContextInterface $context      : The execution context object.
     */
    private static function validateRecipients(Conversation $conversation, ExecutionContextInterface $context)
    {
        $recipients = $conversation->getRecipients();

        if ($recipients->contains($conversation->getAuthor())) {
            $context
                ->buildViolation(self::RECIPIENT_VIOLATION)
                ->atPath('recipients')
                ->addViolation();
        }
    }
}

Validate recipients only when creating a new conversation


<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>@yield('title', 'Laravit')</title>
    <link rel="stylesheet" href="{{ asset('css/style.css') }}">
</head>
<body>
@include('partials.navigation')
<div class="container-fluid">
    @yield('content')
</div>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>@yield('title', 'Laravit') | Laravit</title>
    <link rel="stylesheet" href="{{ asset('css/style.css') }}">
</head>
<body>
@include('partials.navigation')
<div class="container-fluid">
    @yield('content')
</div>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

Modify title to always include Laravit string


<?php

    class DB_MYSQLI implements IDriver
    {
        private $mysqli;

        public function connect($host, $user, $password)
        {
            $this->mysqli = new mysqli($host, $user, $password);
            return !((bool)$this->mysqli->connect_error);
        }

        public function database($name)
        {
            $this->mysqli->select_db($name);
            return !((bool)$this->mysqli->connect_error);
        }

        public function query($sql)
        {

        }

        public function bind($sql, $data=[])
        {
            $length = count($data);
            for ($i=0;$i<$length;$i++)
            {
                $data[$i] = mysqli_escape_string($data[$i]);
            }

            $subs = 0;
            while (($pos = strpos($sql, '?')) !== false)
            {
                $sql = substr_replace($sql, $data[$subs], $pos);
                $subs++;
            }

            return $sql;
        }

        public function lastError()
        {
            return '';
        }
    }

?>

<?php
    namespace DB\Driver;

    class MYSQLI implements IDriver
    {
        private $mysqli;

        public function connect($host, $user, $password)
        {
            $this->mysqli = new \mysqli($host, $user, $password);
        }

        public function database($name)
        {
            $this->mysqli->select_db($name);
        }

        public function query($sql)
        {

        }

        public function bind($sql, $data=[])
        {
            $length = count($data);
            for ($i=0;$i<$length;$i++)
            {
                $data[$i] = mysqli_escape_string($data[$i]);
            }

            $subs = 0;
            while (($pos = strpos($sql, '?')) !== false)
            {
                $sql = substr_replace($sql, $data[$subs], $pos);
                $subs++;
            }

            return $sql;
        }

        public function lastError()
        {
            return '';
        }
    }

?>

Fix mysqli driver connect, name and database


<?php
require_once('init.php');
require_once(INCLUDES_PATH.'/system-functions.php');
require_once(INCLUDES_PATH.'/routing.php');

$options = [
    'min_range' => 1,
    'max_range' => 6,
    'default' => 1
];
$step = filter_input(INPUT_GET, 'step', FILTER_VALIDATE_INT, ['options' => $options]);

[$title, $page] = route($step);
build($title, $page, $step);

<?php
require_once('init.php');
require_once(INCLUDES_PATH.'/system-functions.php');
require_once(INCLUDES_PATH.'/routing.php');

$options = [
    'min_range' => 1,
    'max_range' => 6,
    'default' => 1
];
$step = filter_input(INPUT_GET, 'step', FILTER_VALIDATE_INT, ['options' => $options]);

$route = route($step);
build($route[0], $route[1], $step);

Fix backwards compatibility in installer


<?php

class EchoEditThresholdPresentationModel extends EchoEventPresentationModel {

	public function getIconType() {
		return 'edit';
	}

	public function getHeaderMessageKey() {
		return 'notification-header-thank-you-' . $this->event->getExtraParam( 'editCount' ) . '-edit';
	}

	public function getPrimaryLink() {
		return array(
			'url' => $this->event->getTitle()->getLocalURL(),
			'label' => $this->msg( 'notification-link-thank-you-edit', $this->getViewingUserForGender() )->text()
		);
	}

	public function canRender() {
		return $this->event->getTitle() !== null;
	}
}

<?php

class EchoEditThresholdPresentationModel extends EchoEventPresentationModel {

	public function getIconType() {
		return 'edit';
	}

	public function getHeaderMessageKey() {
		return 'notification-header-thank-you-' . $this->event->getExtraParam( 'editCount' ) . '-edit';
	}

	public function getPrimaryLink() {
		if ( !$this->event->getTitle() ) {
			return false;
		}
		return array(
			'url' => $this->event->getTitle()->getLocalURL(),
			'label' => $this->msg( 'notification-link-thank-you-edit', $this->getViewingUserForGender() )->text()
		);
	}
}

Make 'Edit threshhold' notif appear regardless of title existence

If a user recieves 'this is your X edit' they should get this notif
regardless of whether the edit they created was deleted. We should
make sure the title is there only for deciding whether or not to
create a link for it; otherwise, the notification will just appear
without a link to the revision.

Change-Id: I00ed4278bb4e15b1e9ddfa2c3af8fad0540fc5f8


Change API key to unit test version

Change API key to unit test version


<?php

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

namespace Symfony\Component\Security\Http\Authentication;

use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

/**
 * This class is used when the authenticator system is activated.
 *
 * This is used to not break AuthenticationChecker and ContextListener when
 * using the authenticator system. Once the authenticator system is no longer
 * experimental, this class can be used to trigger deprecation notices.
 *
 * @internal
 *
 * @author Wouter de Jong <wouter@wouterj.nl>
 */
class NoopAuthenticationManager implements AuthenticationManagerInterface
{
    public function authenticate(TokenInterface $token)
    {
        return $token;
    }
}

<?php

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

namespace Symfony\Component\Security\Http\Authentication;

use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

/**
 * This class is used when the authenticator system is activated.
 *
 * This is used to not break AuthenticationChecker and ContextListener when
 * using the authenticator system. Once the authenticator system is no longer
 * experimental, this class can be used to trigger deprecation notices.
 *
 * @author Wouter de Jong <wouter@wouterj.nl>
 *
 * @internal
 */
class NoopAuthenticationManager implements AuthenticationManagerInterface
{
    public function authenticate(TokenInterface $token): TokenInterface
    {
        return $token;
    }
}

Add some missing return types to internal/final classes


<?php

if (!function_exists('is_field_translatable')) {
    /**
     * Check if a Field is translatable.
     *
     * @param Illuminate\Database\Eloquent\Model      $model
     * @param Illuminate\Database\Eloquent\Collection $row
     */
    function is_field_translatable($model, $row)
    {
        if (!is_bread_translatable($model)) {
            return;
        }

        return isset($model['translatable']) &&
            in_array($row->field, $model['translatable']);
    }
}

if (!function_exists('get_field_translations')) {
    /**
     * Return all field translations.
     *
     * @param Illuminate\Database\Eloquent\Model $model
     * @param string                             $field
     * @param string                             $rowType
     * @param bool                               $stripHtmlTags
     */
    function get_field_translations($model, $field, $rowType = '', $stripHtmlTags = false)
    {
        $_out = $model->getTranslationsOf($field);

        if ($stripHtmlTags && $rowType == 'rich_text_box') {
            foreach ($_out as $language => $value) {
                $_out[$language] = strip_tags($_out[$language]);
            }
        }

        return json_encode($_out);
    }
}

if (!function_exists('is_bread_translatable')) {
    /**
     * Check if BREAD is translatable.
     *
     * @param Illuminate\Database\Eloquent\Model $model
     */
    function is_bread_translatable($model)
    {
        return config('voyager.multilingual.enabled')
            && isset($model, $model['translatable']);
    }
}

<?php

if (!function_exists('is_field_translatable')) {
    /**
     * Check if a Field is translatable.
     *
     * @param Illuminate\Database\Eloquent\Model      $model
     * @param Illuminate\Database\Eloquent\Collection $row
     */
    function is_field_translatable($model, $row)
    {
        if (!is_bread_translatable($model)) {
            return;
        }

        return $model->translatable() &&
            in_array($row->field, $model->getTranslatableAttributes());
    }
}

if (!function_exists('get_field_translations')) {
    /**
     * Return all field translations.
     *
     * @param Illuminate\Database\Eloquent\Model $model
     * @param string                             $field
     * @param string                             $rowType
     * @param bool                               $stripHtmlTags
     */
    function get_field_translations($model, $field, $rowType = '', $stripHtmlTags = false)
    {
        $_out = $model->getTranslationsOf($field);

        if ($stripHtmlTags && $rowType == 'rich_text_box') {
            foreach ($_out as $language => $value) {
                $_out[$language] = strip_tags($_out[$language]);
            }
        }

        return json_encode($_out);
    }
}

if (!function_exists('is_bread_translatable')) {
    /**
     * Check if BREAD is translatable.
     *
     * @param Illuminate\Database\Eloquent\Model $model
     */
    function is_bread_translatable($model)
    {
        return config('voyager.multilingual.enabled')
            && isset($model)
            && $model->translatable();
    }
}

Use methods instead of property

Use methods instead of property


<?php

namespace Cassowary\Adapter;

class RedisAdapter implements AdapterInterface
{
    const BLACKLIST_KEY = 'blacklist';

    /**
     * @var \Redis
     */
    private static $redis;

    /**
     * @var string
     */
    private static $prefix;

    /**
     * @var int
     */
    private static $duration;

    public static function init(array $params)
    {
        $redis = new \Redis();
        $redis->connect($params['host'], $params['port']);
        $redis->select($params['index']);
        self::$redis = $redis;
        self::$prefix = $params['prefix'];
        self::$duration = $params['duration'];
    }

    public static function getCount($host)
    {
        return self::$redis->get(self::$prefix.$host);
    }

    public static function increment($host)
    {
        $count = self::$redis->incrBy(self::$prefix.$host, 1);
        if (self::$redis->get(self::$prefix.$host) == 1) {
            self::$redis->setTimeout(self::$prefix.$host, self::$duration);
        }

        return $count;
    }

    public static function addToBlacklist($host)
    {
        self::$redis->sAdd(self::$prefix. self::BLACKLIST_KEY, $host);
    }

    public static function getBlacklist()
    {
        return self::$redis->sMembers(self::$prefix. self::BLACKLIST_KEY);
    }
}

<?php

namespace Cassowary\Adapter;

class RedisAdapter implements AdapterInterface
{
    const BLACKLIST_KEY = 'blacklist';

    /**
     * @var \Redis
     */
    private static $redis;

    /**
     * @var string
     */
    private static $prefix;

    /**
     * @var int
     */
    private static $duration;

    public static function init(array $params)
    {
        $redis = new \Redis();
        if (array_key_exists('socket', $params)) {
            $redis->connect($params['socket']);
        } else {
            $redis->connect($params['host'], $params['port']);
        }
        $redis->select($params['index']);
        self::$redis = $redis;
        self::$prefix = $params['prefix'];
        self::$duration = $params['duration'];
    }

    public static function getCount($host)
    {
        return self::$redis->get(self::$prefix. $host);
    }

    public static function increment($host)
    {
        $count = self::$redis->incrBy(self::$prefix. $host, 1);
        if (self::$redis->get(self::$prefix. $host) == 1) {
            self::$redis->setTimeout(self::$prefix. $host, self::$duration);
        }

        return $count;
    }

    public static function addToBlacklist($host)
    {
        self::$redis->sAdd(self::$prefix. self::BLACKLIST_KEY, $host);
    }

    public static function getBlacklist()
    {
        return self::$redis->sMembers(self::$prefix. self::BLACKLIST_KEY);
    }
}

Fix code format with php-cs-fixer

Fix code format with php-cs-fixer


<?= t('Board settings') ?>

<form method="post" action="<?= $this->url->href('ConfigController', 'save', array('redirect' => 'board')) ?>" autocomplete="off">
    <?= $this->form->csrf() ?>

    <fieldset>
        <?= $this->form->label(t('Task highlight period'), 'board_highlight_period') ?>
        <?= $this->form->number('board_highlight_period', $values, $errors) ?>

<?= t('Period (in second) to consider a task was modified recently (0 to disable, 2 days by default)') ?>

        <?= $this->form->label(t('Refresh interval for public board'), 'board_public_refresh_interval') ?>
        <?= $this->form->number('board_public_refresh_interval', $values, $errors) ?>

<?= t('Frequency in second (60 seconds by default)') ?>

        <?= $this->form->label(t('Refresh interval for private board'), 'board_private_refresh_interval') ?>
        <?= $this->form->number('board_private_refresh_interval', $values, $errors) ?>

<?= t('Frequency in second (0 to disable this feature, 10 seconds by default)') ?>

    </fieldset>

        <button type="submit" class="btn btn-blue"><?= t('Save') ?></button>

</form>

<?= t('Board settings') ?>

<form method="post" action="<?= $this->url->href('ConfigController', 'save', array('redirect' => 'board')) ?>" autocomplete="off">
    <?= $this->form->csrf() ?>

    <fieldset>
        <?= $this->form->label(t('Task highlight period'), 'board_highlight_period') ?>
        <?= $this->form->number('board_highlight_period', $values, $errors) ?>

<?= t('Period (in second) to consider a task was modified recently (0 to disable, 2 days by default)') ?>

        <?= $this->form->label(t('Refresh interval for public board'), 'board_public_refresh_interval') ?>
        <?= $this->form->number('board_public_refresh_interval', $values, $errors) ?>

<?= t('Frequency in second (60 seconds by default)') ?>

        <?= $this->form->label(t('Refresh interval for private board'), 'board_private_refresh_interval') ?>
        <?= $this->form->number('board_private_refresh_interval', $values, $errors) ?>

<?= t('Frequency in second (0 to disable this feature, 10 seconds by default)') ?>

    </fieldset>

    <?= $this->hook->render('template:config:board', array('values' => $values, 'errors' => $errors)) ?>

        <button type="submit" class="btn btn-blue"><?= t('Save') ?></button>

</form>

Add hook to Board Settings

Add hook to Board Settings


<?php

class InvalidClassException extends Exception {}
class NotFoundException extends RuntimeException {}
class DataAccessException extends RuntimeException {}
class CacheException extends DataAccessException {}

// User Safe Exceptions are exceptions where the message is safe to display to the user
class UserSafeException extends RuntimeException {}
class UnauthroizedException extends UserSafeException {}
class MissingAssetException extends UserSafeException {}

<?php

class InvalidClassException extends Exception {}
class NotFoundException extends RuntimeException {}
class DataAccessException extends RuntimeException {}
class CacheException extends DataAccessException {}

// User Safe Exceptions are exceptions where the message is safe to display to the user
class UserSafeException extends RuntimeException {}
class UnauthorizedException extends UserSafeException {}
class MissingAssetException extends UserSafeException {}

Fix typo in exception name

Fix typo in exception name


<?php
/**
 * Search events listeners
 */
namespace Minds\Core\Search;

class Client extends \Elasticsearch\Client
{
  public function __construct(array $opts = [])
  {
    $hosts = Config::_()->elasticsearch_hosts ?: 'localhost';

    if (!is_array($hosts)) {
      $hosts = [ $hosts ];
    }

    $opts = array_merge([
      'hosts' => $hosts
    ], $opts);

    parent::__construct($opts);
  }
}

<?php
/**
 * Search events listeners
 */
namespace Minds\Core\Search;

use Minds\Core\Config;

class Client extends \Elasticsearch\Client
{
  public function __construct(array $opts = [])
  {
    $hosts = Config::_()->elasticsearch_hosts ?: 'localhost';

    if (!is_array($hosts)) {
      $hosts = [ $hosts ];
    }

    $opts = array_merge([
      'hosts' => $hosts
    ], $opts);

    parent::__construct($opts);
  }
}

Use main config for elasticsearch hosts

(fix): Use main config for elasticsearch hosts


<?php

namespace Hatimeria\BankBundle\Currency;

use Hatimeria\BankBundle\Decimal\Decimal;

/**
 * Currency exchanger
 *
 * supported currencies: PLN, Virtual
 *
 * @author michal
 */
class Exchanger
{
    // pln to virtual ratio
    private $ratio;

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

    /**
     * Get exchanged amount
     *
     * @param int $amount
     * @param string $originalCurrency
     * @param string $destinationCurrency
     */
    public function exchange($amount, $originalCurrency, $destinationCurrency = null)
    {
        if (null !== $destinationCurrency) {
            if ($originalCurrency == $destinationCurrency) {
                return $amount;
            }
        }

        $amount = new Decimal($amount);

        if($originalCurrency == CurrencyCode::PLN) {
            return $amount->mul($this->ratio)->getAmount();
        } else {
            return $amount/$this->ratio;
        }
    }
}

<?php

namespace Hatimeria\BankBundle\Currency;

use Hatimeria\BankBundle\Decimal\Decimal;

/**
 * Currency exchanger
 *
 * supported currencies: PLN, Virtual
 *
 * @author michal
 */
class Exchanger
{
    // pln to virtual ratio
    private $ratio;

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

    /**
     * Get exchanged amount
     *
     * @param int $amount
     * @param string $originalCurrency
     * @param string $destinationCurrency
     */
    public function exchange($amount, $originalCurrency, $destinationCurrency = null)
    {
        if (null !== $destinationCurrency) {
            if ($originalCurrency == $destinationCurrency) {
                return $amount;
            }
        }

        $amount = new Decimal($amount);

        if($originalCurrency == CurrencyCode::PLN) {
            return $amount->mul($this->ratio)->getAmount();
        } else {
            return $amount->getAmount()/$this->ratio;
        }
    }
}

Fix exchanger issue while changing Virtual currency to PLN


<?php
    date_default_timezone_set('America/Chicago');
    $dir = $_SERVER['DOCUMENT_ROOT'];

    $file = $_FILES['uploadedfile']['tmp_name'];
    $names = $_FILES['uploadedfile']['name'];

    $target = $dir.'/In/'.$names;
    move_uploaded_file( $_FILES['uploadedfile']['tmp_name'], $target);

    $command = escapeshellcmd("python2.7 read.py $target");
    exec($command, $output);
    echo "
";
    echo "something";
    echo $output;
    echo 'Download Report';
    echo "
";

//  Re-route to directory to download the file.
//    $domain = $_SERVER['HTTP_HOST'];
//    $path = implode("/",$fullPath);
//    $toLogin = 'http://'.$domain.$path."/out";
//    header('Location:'.$toLogin);
?>

<?php
    date_default_timezone_set('America/Chicago');
    $dir = $_SERVER['DOCUMENT_ROOT'];

    $file = $_FILES['uploadedfile']['tmp_name'];
    $names = $_FILES['uploadedfile']['name'];

    $target = $dir.'/In/'.$names;
    move_uploaded_file( $_FILES['uploadedfile']['tmp_name'], $target);

    $command = escapeshellcmd("python2.7 read.py $target");
    exec($command, $output);
    echo "
";
    echo "something";
    echo $output[0];
    echo 'Download Report';
    echo "
";

//  Re-route to directory to download the file.
//    $domain = $_SERVER['HTTP_HOST'];
//    $path = implode("/",$fullPath);
//    $toLogin = 'http://'.$domain.$path."/out";
//    header('Location:'.$toLogin);
?>

Include dynamic file name link

Include dynamic file name link


<?php
namespace CfdiUtils\Elements\ImpLocal10;

use CfdiUtils\Elements\Common\AbstractElement;

class ImpuestosLocales extends AbstractElement
{
    public function addRetencionLocal(array $attributes = []): RetencionesLocales
    {
        $retencion = new RetencionesLocales($attributes);
        $this->addChild($retencion);
        return $retencion;
    }

    public function addTrasladoLocal(array $attributes = []): TrasladosLocales
    {
        $traslado = new TrasladosLocales($attributes);
        $this->addChild($traslado);
        return $traslado;
    }

    public function getElementName(): string
    {
        return 'implocal:ImpuestosLocales';
    }

    public function getChildrenOrder(): array
    {
        return ['implocal:RetencionesLocales', 'implocal:TrasladosLocales'];
    }

    public function getFixedAttributes(): array
    {
        return [
            'xmlns:implocal' => 'http://www.sat.gob.mx/implocal',
            'xsi:schemaLocation' => 'http://www.sat.gob.mx/implocal'
                . ' http://www.sat.gob.mx/sitio_internet/cfd/implocal/implocal.xsd',
            'Version' => '1.0',
        ];
    }
}

<?php
namespace CfdiUtils\Elements\ImpLocal10;

use CfdiUtils\Elements\Common\AbstractElement;

class ImpuestosLocales extends AbstractElement
{
    public function addRetencionLocal(array $attributes = []): RetencionesLocales
    {
        $retencion = new RetencionesLocales($attributes);
        $this->addChild($retencion);
        return $retencion;
    }

    public function addTrasladoLocal(array $attributes = []): TrasladosLocales
    {
        $traslado = new TrasladosLocales($attributes);
        $this->addChild($traslado);
        return $traslado;
    }

    public function getElementName(): string
    {
        return 'implocal:ImpuestosLocales';
    }

    public function getChildrenOrder(): array
    {
        return ['implocal:RetencionesLocales', 'implocal:TrasladosLocales'];
    }

    public function getFixedAttributes(): array
    {
        return [
            'xmlns:implocal' => 'http://www.sat.gob.mx/implocal',
            'xsi:schemaLocation' => 'http://www.sat.gob.mx/implocal'
                . ' http://www.sat.gob.mx/sitio_internet/cfd/implocal/implocal.xsd',
            'version' => '1.0',
        ];
    }
}

Fix name attribute in impuestos locales

Fix name attribute in impuestos locales


<?php namespace Illuminate\Session\Console;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;

class SessionTableCommand extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'session:table';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Create a migration for the session database table';

	/**
	 * The filesystem instance.
	 *
	 * @var \Illuminate\Filesystem\Filesystem
	 */
	protected $files;

	/**
	 * Create a new session table command instance.
	 *
	 * @param  \Illuminate\Filesystem\Filesystem  $files
	 * @return void
	 */
	public function __construct(Filesystem $files)
	{
		parent::__construct();

		$this->files = $files;
	}

	/**
	 * Execute the console command.
	 *
	 * @return void
	 */
	public function fire()
	{
		$fullPath = $this->createBaseMigration();

		$this->files->put($fullPath, $this->files->get(__DIR__.'/stubs/database.stub'));

		$this->info('Migration created successfully!');
	}

	/**
	 * Create a base migration file for the session.
	 *
	 * @return string
	 */
	protected function createBaseMigration()
	{
		$name = 'create_session_table';

		$path = $this->laravel['path'].'/database/migrations';

		return $this->laravel['migration.creator']->create($name, $path);
	}

}

<?php namespace Illuminate\Session\Console;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;

class SessionTableCommand extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'session:table';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Create a migration for the session database table';

	/**
	 * The filesystem instance.
	 *
	 * @var \Illuminate\Filesystem\Filesystem
	 */
	protected $files;

	/**
	 * Create a new session table command instance.
	 *
	 * @param  \Illuminate\Filesystem\Filesystem  $files
	 * @return void
	 */
	public function __construct(Filesystem $files)
	{
		parent::__construct();

		$this->files = $files;
	}

	/**
	 * Execute the console command.
	 *
	 * @return void
	 */
	public function fire()
	{
		$fullPath = $this->createBaseMigration();

		$this->files->put($fullPath, $this->files->get(__DIR__.'/stubs/database.stub'));

		$this->info('Migration created successfully!');

		$this->call('dump-autoload');
	}

	/**
	 * Create a base migration file for the session.
	 *
	 * @return string
	 */
	protected function createBaseMigration()
	{
		$name = 'create_session_table';

		$path = $this->laravel['path'].'/database/migrations';

		return $this->laravel['migration.creator']->create($name, $path);
	}

}

Call Artisan dump-autoload after session:table


@extends('orchestra/foundation::layout.main')

@section('content')

			<?php foreach ($resources['list'] as $name => $resource) : ?>
			<a href="<?php echo resources($name); ?>"
				class="list-group-item <?php echo Request::is("*/resources/{$name}*") ? 'active' : ''; ?>">
				<?php echo $resource->name; ?>

			<?php endforeach; ?>

		@placeholder("orchestra.resources: {$resource->name}")
		@placeholder('orchestra.resources')

		<?php echo $content; ?>

@stop

Add .pull-right to resources sidebar nav.

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


<?php

namespace App\Module\Web\Controller;

use Air\View\ViewFactoryInterface;

/**
 * Class AbstractWebController
 * @package App\Module\Web\Controller
 * @author Petr Pliska <petr.pliska@post.cz>
 */
abstract class AbstractWebController
{
    /**
     * @inject
     * @var ViewFactoryInterface
     */
    protected $viewFactory;
}

<?php

namespace App\Module\Web\Controller;

use Air\View\ViewFactoryInterface;

/**
 * Class AbstractWebController
 * @package App\Module\Web\Controller
 * @author Petr Pliska <petr.pliska@post.cz>
 */
abstract class AbstractWebController
{
    /**
     * @var ViewFactoryInterface
     */
    protected $viewFactory;

    /**
     * AbstractWebController constructor.
     * @param ViewFactoryInterface $viewFactory
     */
    public function __construct(ViewFactoryInterface $viewFactory)
    {
        $this->viewFactory = $viewFactory;
    }
}

Replace annotation with constructor injection


<?php

/**
 * Solr response
 *
 * @category Asm
 * @package Asm_Solr
 * @author Ingo Renner <ingo@infielddesign.com>
 */
class Asm_Solr_Model_Solr_Response
{
	/**
	 * @var Apache_Solr_Response
	 */
	protected $rawResponse;

	/**
	 * Constructor
	 *
	 */
	public function __construct(array $responseParameters = array()) {
		$this->rawResponse = $responseParameters['rawResponse'];
	}

	/**
	 * Gets the number of results found
	 *
	 * @return integer Number of results found
	 */
	public function getNumberOfResults() {
		return $this->rawResponse->response->numFound;
	}

	/**
	 * Gets the result documents
	 *
	 * @return Apache_Solr_Document[] Array of Apache_Solr_Document
	 */
	public function getDocuments() {
		return $this->rawResponse->response->docs;
	}

	/**
	 * Gets the field facets
	 *
	 * @return Asm_Solr_Model_Solr_Facet_Facet[] Array of Asm_Solr_Model_Solr_Facet_Facet
	 */
	public function getFacetFields() {

	}

	/* TODO add range and query facet support
	public function getFacetRanges() {

	}

	public function getFacetQueries() {

	}
	*/
}

Adjust braces to match Magento conventions


<?php
/**
 * Ted.php
 *
 * @package Providers
 * @author Michael Pratt <pratt@hablarmierda.net>
 * @link   http://www.michael-pratt.com/
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Embera\Providers;

/**
 * The ted.com Provider
 * @link http://ted.com
 */
class Ted extends \Embera\Adapters\Service
{
    /** inline {@inheritdoc} */
    protected $apiUrl = 'http://www.ted.com/talks/oembed.json';

    /** inline {@inheritdoc} */
    protected function validateUrl()
    {
        return (preg_match('~ted\.com/talks/(?:.*)\.html$~i', $this->url));
    }

    /** inline {@inheritdoc} */
    public function fakeResponse()
    {
        $url = preg_replace('~http(?:.*)ted\.com/~i', 'http://embed.ted.com/$1', $this->url);
        return array(
            'type' => 'video',
            'provider_name' => 'TED',
            'provider_url' => 'http://ted.com',
            'html' => '<iframe src="' . $url . '" width="{width}" height="{height}" frameborder="0" scrolling="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe',
        );
    }
}

?>

<?php
/**
 * Ted.php
 *
 * @package Providers
 * @author Michael Pratt <pratt@hablarmierda.net>
 * @link   http://www.michael-pratt.com/
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Embera\Providers;

/**
 * The ted.com Provider
 * @link http://ted.com
 */
class Ted extends \Embera\Adapters\Service
{
    /** inline {@inheritdoc} */
    protected $apiUrl = 'http://www.ted.com/talks/oembed.json';

    /** inline {@inheritdoc} */
    protected function validateUrl()
    {
        return (preg_match('~ted\.com/talks/(?:\S*)$~i', $this->url));
    }

    /** inline {@inheritdoc} */
    public function fakeResponse()
    {
        $url = preg_replace('~http(?:.*)ted\.com/~i', 'http://embed.ted.com/$1', $this->url);
        return array(
            'type' => 'video',
            'provider_name' => 'TED',
            'provider_url' => 'http://ted.com',
            'html' => '<iframe src="' . $url . '" width="{width}" height="{height}" frameborder="0" scrolling="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe',
        );
    }
}

Adjust for TED urls without html suffix

Adjust for TED urls without html suffix


<?php

namespace Backend\Modules\Analytics\Actions;

use Backend\Core\Engine\Base\ActionDelete;
use Backend\Core\Engine\Model;

/**
 * This is the reset-action. It will remove your coupling with analytics
 *
 * @author Wouter Sioen <wouter@sumocoders.be>
 */
final class Reset extends ActionDelete
{
    /**
     * The form instance
     *
     * @var Form
     */
    private $form;

    public function execute()
    {
        $this->get('fork.settings')->delete($this->getModule(), 'certificate');
        $this->get('fork.settings')->delete($this->getModule(), 'email');
        $this->get('fork.settings')->delete($this->getModule(), 'account');
        $this->get('fork.settings')->delete($this->getModule(), 'web_property_id');
        $this->get('fork.settings')->delete($this->getModule(), 'profile');

        return $this->redirect(Model::createURLForAction('Settings'));
    }
}

<?php

namespace Backend\Modules\Analytics\Actions;

use Backend\Core\Engine\Base\ActionDelete;
use Backend\Core\Engine\Model;

/**
 * This is the reset-action. It will remove your coupling with analytics
 *
 * @author Wouter Sioen <wouter@sumocoders.be>
 */
final class Reset extends ActionDelete
{
    public function execute()
    {
        $this->get('fork.settings')->delete($this->getModule(), 'certificate');
        $this->get('fork.settings')->delete($this->getModule(), 'email');
        $this->get('fork.settings')->delete($this->getModule(), 'account');
        $this->get('fork.settings')->delete($this->getModule(), 'web_property_id');
        $this->get('fork.settings')->delete($this->getModule(), 'profile');

        return $this->redirect(Model::createURLForAction('Settings'));
    }
}

Remove unused form class variable.

Remove unused form class variable.


<?php

ini_set('date.timezone', 'UTC');

use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;

/**
 * @var \Symfony\Component\ClassLoader\ClassLoader
 */
$loader = require __DIR__.'/../app/autoload.php';
include_once __DIR__.'/../app/bootstrap.php.cache';

// Use APC for autoloading to improve performance.
if (function_exists('apc_store')) {
    $apcLoader = new ApcClassLoader(sha1(__FILE__), $loader);
    $loader->unregister();
    $apcLoader->register(true);
}

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

ini_set('date.timezone', 'UTC');

use Symfony\Component\HttpFoundation\Request;

/**
 * @var \Symfony\Component\ClassLoader\ClassLoader
 */
$loader = require __DIR__.'/../app/autoload.php';
include_once __DIR__.'/../app/bootstrap.php.cache';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Remove usage of apc class loader

Remove usage of apc class loader


<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Mail;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        'Symfony\Component\HttpKernel\Exception\HttpException'
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        if (env('APP_ENV', 'local')!='local') {
            Mail::raw($e, function ($message) {
                $message->from(env('MAIL_FROM_ADDRESS', 'root@localhost'), env('SYSLOG_APPNAME', ''));
                $message->to(env('ROOT_REPORT_MAIL', 'root@localhost'));
            });
        }
        return parent::report($e);
    }

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

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Mail;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        'Symfony\Component\HttpKernel\Exception\HttpException'
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        if (env('APP_ENV', 'local')!='local') {
            Mail::raw($e, function ($message) {
                $message->subject('[ROOT] Exception Report');
                $message->from(env('MAIL_FROM_ADDRESS', 'root@localhost'), env('SYSLOG_APPNAME', ''));
                $message->to(env('ROOT_REPORT_MAIL', 'root@localhost'));
            });
        }
        return parent::report($e);
    }

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

Add email subject for exception reporting


<?php

declare(strict_types=1);

namespace App\Console;

use App\Jobs\DailyDuesSummary;
use App\Jobs\NoAttendanceJediPush;
use App\Jobs\WeeklyAttendanceEmail;
use App\Jobs\WeeklyAttendanceSlack;
use Bugsnag\BugsnagLaravel\Commands\DeployCommand;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array<string>
     */
    protected $commands = [
        DeployCommand::class,
    ];

    /**
     * Define the application's command schedule.
     */
    protected function schedule(Schedule $schedule): void
    {
        $schedule->command('horizon:snapshot')->everyFiveMinutes();

        $schedule->job(new WeeklyAttendanceEmail())->weekly()->sundays()->at('1:00');
        $schedule->job(new WeeklyAttendanceSlack())->weekly()->sundays()->at('11:00');
        $schedule->job(new DailyDuesSummary())->daily()->at('11:00');
        $schedule->job(new NoAttendanceJediPush())->daily()->at('10:00');
    }

    /**
     * Register the commands for the application.
     */
    protected function commands(): void
    {
        $this->load(__DIR__.'/Commands');

        include base_path('routes/console.php');
    }
}

<?php

declare(strict_types=1);

namespace App\Console;

use App\Jobs\DailyDuesSummary;
use App\Jobs\NoAttendanceJediPush;
use App\Jobs\WeeklyAttendanceEmail;
use App\Jobs\WeeklyAttendanceSlack;
use Bugsnag\BugsnagLaravel\Commands\DeployCommand;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array<string>
     */
    protected $commands = [
        DeployCommand::class,
    ];

    /**
     * Define the application's command schedule.
     */
    protected function schedule(Schedule $schedule): void
    {
        $schedule->command('horizon:snapshot')->everyFiveMinutes();

        $schedule->job(new WeeklyAttendanceEmail())->weekly()->sundays()->at('1:00');
        $schedule->job(new WeeklyAttendanceSlack())->weekly()->sundays()->at('12:34');
        $schedule->job(new DailyDuesSummary())->daily()->at('11:00');
        $schedule->job(new NoAttendanceJediPush())->daily()->at('10:00');
    }

    /**
     * Register the commands for the application.
     */
    protected function commands(): void
    {
        $this->load(__DIR__.'/Commands');

        include base_path('routes/console.php');
    }
}

Make the time not 11:00

Make the time not 11:00

11:00 is not a very pretty time, so changing it to 12:34 makes it more interesting.


<?php
declare (strict_types = 1);

\Jentil()->utilities->loader->loadPartial('header', 'micro'); ?>

<?php \do_action('jentil_before_header'); ?>

<header id="header" class="site-header" itemscope itemtype="http://schema.org/WPHeader">
    <?php \do_action('jentil_inside_header'); ?>
</header><!-- #header -->

<?php \do_action('jentil_after_header'); ?>

<div id="main">

<?php
declare (strict_types = 1);

\Jentil()->utilities->loader->loadPartial('header', 'micro');

\do_action('jentil_before_header'); ?>

<header id="header" class="site-header" itemscope itemtype="http://schema.org/WPHeader">
    <?php \do_action('jentil_inside_header'); ?>
</header><!-- #header -->

<?php \do_action('jentil_after_header'); ?>

<div id="main">

Remove closing php tag and immediately-followed opening php tag


<?php

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

namespace Symfony\Component\Console\Tests\Helper;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Helper\TableCellStyle;

class TableCellStyleTest extends TestCase
{
    public function testCreateTableCellStyle()
    {
        $tableCellStyle = new TableCellStyle(['fg' => 'red']);
        $this->assertEquals('red', $tableCellStyle->getOptions()['fg']);

        $this->expectException('Symfony\Component\Console\Exception\InvalidArgumentException');
        new TableCellStyle(['wrong_key' => null]);
    }
}

<?php

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

namespace Symfony\Component\Console\Tests\Helper;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Helper\TableCellStyle;

class TableCellStyleTest extends TestCase
{
    public function testCreateTableCellStyle()
    {
        $tableCellStyle = new TableCellStyle(['fg' => 'red']);
        $this->assertEquals('red', $tableCellStyle->getOptions()['fg']);

        $this->expectException(\Symfony\Component\Console\Exception\InvalidArgumentException::class);
        new TableCellStyle(['wrong_key' => null]);
    }
}

Use ::class keyword when possible

Use ::class keyword when possible


<?php

namespace Rudolf\Component\Helpers\Navigation;

class MenuItemCollection
{
    private $collection;

    public function add(MenuItem $item)
    {
        if (null == $item->getId()) {
            $item->setId(count($this->collection) + 1);
        }

        $this->collection[] = $item;

        return $item->getId();
    }

    public function getAll()
    {
        return $this->collection;
    }

    /**
     * Get menu items by type.
     *
     * @param string $type
     *
     * @return array of MenuItem
     */
    public function getByType($type)
    {
        $items = [];

        foreach ($this->collection as $key => $item) {
            if ($type === $item->getType()) {
                $items[] = $item;
            }
        }

        usort($items, function ($a, $b) {
            return strcmp($a->getPosition(), $b->getPosition());
        });

        return $items;
    }
}

<?php

namespace Rudolf\Component\Helpers\Navigation;

class MenuItemCollection
{
    private $collection;

    public function add(MenuItem $item)
    {
        if (null == $item->getId()) {
            $item->setId(count($this->collection) + 1);
        }

        $this->collection[] = $item;

        return $item->getId();
    }

    public function getAll()
    {
        return $this->collection;
    }

    /**
     * Get menu items by type.
     *
     * @param string $type
     *
     * @return array of MenuItem
     */
    public function getByType($type)
    {
        if (empty($this->collection)) {
            return;
        }
        $items = [];

        foreach ($this->collection as $key => $item) {
            if ($type === $item->getType()) {
                $items[] = $item;
            }
        }

        usort($items, function ($a, $b) {
            return strcmp($a->getPosition(), $b->getPosition());
        });

        return $items;
    }
}

Check is collection empty before foreach


@if ( ! empty($title))

			{!! $title !!}

@endif

@yield('before.card')
@yield('before.panel')

		@if ($creatable)

				 {{ $newEntryButtonText }}

		@endif

			@yield('card.heading.actions')
			@yield('panel.heading.actions')

			@yield('card.buttons')
			@yield('panel.buttons')

	@yield('card.heading')
	@yield('panel.heading')

	@foreach($extensions as $ext)
		{!! $ext->render() !!}
	@endforeach

	@yield('card.footer')
	@yield('panel.footer')

@yield('after.card')
@yield('after.panel')

Move card.heading & panel.heading yields to .card-heading


<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '10.0.2.2', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();

require_once __DIR__.'/../app/AppKernel.php';

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '10.0.2.2', '192.168.56.1', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();

require_once __DIR__.'/../app/AppKernel.php';

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Allow puphpet machine to see dev env

Allow puphpet machine to see dev env


<?php

namespace App\Http\Requests\Admin;

use App\Http\Requests\Request;

class DestroyUserRequest extends Request
{
    /**
     * 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 [
            'id'            =>'required|integer|exists:user,id',
            'confirmation'  => 'required|accepted',
        ];
    }
}

<?php

namespace App\Http\Requests\Admin;

use App\Http\Requests\Request;

class DestroyUserRequest extends Request
{
    /**
     * 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 [
            'id'            =>'required|integer|exists:users,id',
            'confirmation'  => 'required|accepted',
        ];
    }
}

Fix user destroy destroy table name

Fix user destroy destroy table name


<?php

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

class AddApiTokenOnUsers extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('api_token')->unique()->after('role');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropColumn('api_token');
        });
    }
}

<?php

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

class AddApiTokenOnUsers extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (Schema::hasTable('users')) {
            Schema::table('users', function ($table) {
                $table->string('api_token')->unique()->nullable()->after('role');
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        if (Schema::hasColumn('users', 'api_token')) {
            Schema::table('users', function ($table) {
                $table->dropColumn('api_token');
            });
        }
    }
}

Add nullable on api_token column

Add nullable on api_token column


<?PHP

/**
 *  An Address value object.
 *
 * This Value Object use commerceguys/addressing library
 * (https://github.com/commerceguys/addressing).
 *
 * Other useful libraries:
 * - https://github.com/black-project/Address
 * - https://github.com/adamlc/address-format
 *
 * @package  Serendipity\Framework
 * @subpackage ValueObjects
 *
 *  @author      Adamo Crespi <hello@aerendir.me>
 *  @copyright   Copyright (c) 2015, Adamo Crespi
 *  @license     MIT License
 */

namespace SerendipityHQ\Component\ValueObjects\Tests\Address;

use SerendipityHQ\Component\ValueObjects\Address\Address;

class AddressTest extends \PHPUnit_Framework_TestCase
{
    public function testAddress()
    {
        $options = [
            'locale' => 'en_EN'
            ];

        $resource = new Address($options);

        $this->assertEquals($options['locale'], $resource->getLocale());
    }
}

<?PHP

/**
 *  An Address value object.
 *
 * This Value Object use commerceguys/addressing library
 * (https://github.com/commerceguys/addressing).
 *
 * Other useful libraries:
 * - https://github.com/black-project/Address
 * - https://github.com/adamlc/address-format
 *
 * @package  Serendipity\Framework
 * @subpackage ValueObjects
 *
 *  @author      Adamo Crespi <hello@aerendir.me>
 *  @copyright   Copyright (c) 2015, Adamo Crespi
 *  @license     MIT License
 */

namespace SerendipityHQ\Component\ValueObjects\Tests\Address;

use SerendipityHQ\Component\ValueObjects\Address\Address;

class AddressTest extends \PHPUnit_Framework_TestCase
{
    public function testAddress()
    {
        $options = [
            'locale' => 'en_EN'
            ];

        $resource = new Address($options);
    }
}

Update unit test for `Address`.

Update unit test for `Address`.


<?php

namespace Frontend\Modules\Instagram\Engine;

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

use Frontend\Core\Engine\Model as FrontendModel;

/**
 * The frontend Instagram Model
 *
 * @author Jesse Dobbelaere <jesse@dobbelae.re>
 */
class Model
{
    /**
     * Fetches a certain item
     *
     * @param string $id
     * @return array
     */
    public static function get($id)
    {
        $item = (array) FrontendModel::get('database')->getRecord(
            'SELECT i.*
             FROM instagram_users AS i
             WHERE i.id = ? AND i.hidden = ?',
            array((int) $id, 'N')
        );

        // no results?
        if (empty($item)) {
            return array();
        }

        return $item;
    }

    public static function getRecentMedia($userId, $count = 10)
    {
        $recentData = Helper::getUserMedia($userId, $count);
        return isset($recentData) ? $recentData->data : null;
    }
}

<?php

namespace Frontend\Modules\Instagram\Engine;

use Frontend\Core\Engine\Model as FrontendModel;

/**
 * The frontend Instagram Model
 *
 * @author Jesse Dobbelaere <jesse@dobbelae.re>
 */
class Model
{
    /**
     * Fetches a certain item
     *
     * @param string $id
     * @return array
     */
    public static function get($id)
    {
        $item = (array) FrontendModel::get('database')->getRecord(
            'SELECT i.*
             FROM instagram_users AS i
             WHERE i.id = ? AND i.hidden = ?',
            array((int) $id, 'N')
        );

        // no results?
        if (empty($item)) {
            return array();
        }

        return $item;
    }

    public static function getRecentMedia($userId, $count = 10)
    {
        $recentData = Helper::getUserMedia($userId, $count);
        return isset($recentData) ? $recentData->data : null;
    }
}

Remove Fork cms copyright comment

Remove Fork cms copyright comment


<?php

namespace League\StatsD\Laravel5\Provider;

use Illuminate\Support\ServiceProvider;
use League\StatsD\Client as Statsd;

/**
 * StatsD Service provider for Laravel
 *
 * @author Aran Wilkinson <aran@aranw.net>
 */
class StatsdServiceProvider extends ServiceProvider
{

    /**
     * Boot the service provider.
     *
     * @return void
     */
    public function boot()
    {
		// Publish config files
		$this->publishes([
			__DIR__.'/../../../../config/config.php' => config_path('statsd.php'),
		]);
    }

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

    /**
     * Register Statsd
     *
     * @return void
     */
    protected function registerStatsD()
    {
        $this->app['statsd'] = $this->app->share(
            function ($app) {
                // Set Default host and port
                $options = array();
                if (isset($app['config']['statsd.host'])) {
                    $options['host'] = $app['config']['statsd.host'];
                }
                if (isset($app['config']['statsd.port'])) {
                    $options['port'] = $app['config']['statsd.port'];
                }
                if (isset($app['config']['statsd.namespace'])) {
                    $options['namespace'] = $app['config']['statsd.namespace'];
                }

                // Create
                $statsd = new Statsd();
                $statsd->configure($options);
                return $statsd;
            }
        );
    }
}

<?php

namespace League\StatsD\Laravel5\Provider;

use Illuminate\Support\ServiceProvider;
use League\StatsD\Client as Statsd;

/**
 * StatsD Service provider for Laravel
 *
 * @author Aran Wilkinson <aran@aranw.net>
 */
class StatsdServiceProvider extends ServiceProvider
{

    /**
     * Boot the service provider.
     *
     * @return void
     */
    public function boot()
    {
		// Publish config files
		$this->publishes([
			__DIR__.'/../../../config/config.php' => config_path('statsd.php'),
		]);
    }

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

    /**
     * Register Statsd
     *
     * @return void
     */
    protected function registerStatsD()
    {
        $this->app['statsd'] = $this->app->share(
            function ($app) {
                // Set Default host and port
                $options = array();
                if (isset($app['config']['statsd.host'])) {
                    $options['host'] = $app['config']['statsd.host'];
                }
                if (isset($app['config']['statsd.port'])) {
                    $options['port'] = $app['config']['statsd.port'];
                }
                if (isset($app['config']['statsd.namespace'])) {
                    $options['namespace'] = $app['config']['statsd.namespace'];
                }

                // Create
                $statsd = new Statsd();
                $statsd->configure($options);
                return $statsd;
            }
        );
    }
}

Adjust path one last time.

Adjust path one last time.


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

namespace App\Validator\Constraints;

use App\Entity\Interfaces\UserInterface;
use App\Repository\UserRepository;
use Doctrine\ORM\NonUniqueResultException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Class UniqueEmailValidator
 *
 * @package App\Validator\Constraints
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class UniqueEmailValidator extends ConstraintValidator
{
    private UserRepository $repository;

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

    /**
     * {@inheritdoc}
     *
     * @throws NonUniqueResultException
     */
    public function validate($value, Constraint $constraint): void
    {
        if ($value instanceof UserInterface
            && !$this->repository->isEmailAvailable($value->getEmail(), $value->getId())
        ) {
            $this->context
                ->buildViolation(UniqueEmail::MESSAGE)
                ->setCode(UniqueEmail::IS_UNIQUE_EMAIL_ERROR)
                ->addViolation();
        }
    }
}

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

namespace App\Validator\Constraints;

use App\Entity\Interfaces\UserInterface;
use App\Repository\UserRepository;
use Doctrine\ORM\NonUniqueResultException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Class UniqueEmailValidator
 *
 * @package App\Validator\Constraints
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class UniqueEmailValidator extends ConstraintValidator
{
    public function __construct(
        private UserRepository $repository,
    ) {
    }

    /**
     * {@inheritdoc}
     *
     * @throws NonUniqueResultException
     */
    public function validate($value, Constraint $constraint): void
    {
        if ($value instanceof UserInterface
            && !$this->repository->isEmailAvailable($value->getEmail(), $value->getId())
        ) {
            $this->context
                ->buildViolation(UniqueEmail::MESSAGE)
                ->setCode(UniqueEmail::IS_UNIQUE_EMAIL_ERROR)
                ->addViolation();
        }
    }
}

Use PHP 8 constructor property promotion


<?php
namespace wcf\data\user;
use wcf\system\edit\EditHistoryManager;
use wcf\system\WCF;

/**
 * Executes actions on user generated content.
 *
 * @author	Tim Duesterhus
 * @copyright	2001-2015 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	com.woltlab.wcf
 * @subpackage	data.user
 * @category	Community Framework
 */
class UserContentAction extends UserAction {
	/**
	 * Checks permissions to bulk revert.
	 */
	public function validateBulkRevert() {
		WCF::getSession()->checkPermissions('admin.content.canBulkRevertContentChanges');
	}

	/**
	 * Bulk reverts changes made to history saving objects.
	 */
	public function bulkRevert() {
		$this->readInteger('timeframe', true);
		if (!$this->parameters['timeframe']) {
			$this->parameters['timeframe'] = 86400 * 7;
		}

		EditHistoryManager::getInstance()->bulkRevert($this->objectIDs, $this->parameters['timeframe']);
	}
}

<?php
namespace wcf\data\user;
use wcf\system\edit\EditHistoryManager;
use wcf\system\WCF;

/**
 * Executes actions on user generated content.
 *
 * @author	Tim Duesterhus
 * @copyright	2001-2015 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	com.woltlab.wcf
 * @subpackage	data.user
 * @category	Community Framework
 */
class UserContentAction extends UserAction {
	/**
	 * Checks permissions to bulk revert.
	 */
	public function validateBulkRevert() {
		WCF::getSession()->checkPermissions(array('admin.content.canBulkRevertContentChanges'));
	}

	/**
	 * Bulk reverts changes made to history saving objects.
	 */
	public function bulkRevert() {
		$this->readInteger('timeframe', true);
		if (!$this->parameters['timeframe']) {
			$this->parameters['timeframe'] = 86400 * 7;
		}

		EditHistoryManager::getInstance()->bulkRevert($this->objectIDs, $this->parameters['timeframe']);
	}
}

Fix permission check in `UserContentAction::validateBulkRevert()`


<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Application Debug Mode
    |--------------------------------------------------------------------------
    |
    | When your application is in debug mode, detailed error messages with
    | stack traces will be shown on every error that occurs within your
    | application. If disabled, a simple generic error page is shown.
    |
    */

    'debug' => false,

    /*
    |--------------------------------------------------------------------------
    | Application URL
    |--------------------------------------------------------------------------
    |
    | This URL is used by the console to properly generate URLs when using
    | the Artisan command line tool. You should set this to the root of
    | your application so that it is used when running Artisan tasks.
    |
    */

    'url' => 'http://production.yourserver.com',

    /*
    |--------------------------------------------------------------------------
    | Encryption Key
    |--------------------------------------------------------------------------
    |
    | This key is used by the Illuminate encrypter service and should be set
    | to a random, 32 character string, otherwise these encrypted strings
    | will not be safe. Please do this before deploying an application!
    |
    | Run a php artisan key:generate --env=staging to create a random one
    */

    'key' => 'Change_this_key_or_snipe_will_get_ya',

);

<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Application Debug Mode
    |--------------------------------------------------------------------------
    |
    | When your application is in debug mode, detailed error messages with
    | stack traces will be shown on every error that occurs within your
    | application. If disabled, a simple generic error page is shown.
    |
    */

    'debug' => false,

    /*
    |--------------------------------------------------------------------------
    | Application URL
    |--------------------------------------------------------------------------
    |
    | This URL is used by the console to properly generate URLs when using
    | the Artisan command line tool. You should set this to the root of
    | your application so that it is used when running Artisan tasks.
    |
    */

    'url' => 'https://production.yourserver.com',

    /*
    |--------------------------------------------------------------------------
    | Encryption Key
    |--------------------------------------------------------------------------
    |
    | This key is used by the Illuminate encrypter service and should be set
    | to a random, 32 character string, otherwise these encrypted strings
    | will not be safe. Please do this before deploying an application!
    |
    | Run a php artisan key:generate --env=staging to create a random one
    */

    'key' => 'Change_this_key_or_snipe_will_get_ya',

);

Set https as default app url

Set https as default app url


@extends('layouts.app')

@section('content')

Test Types

@foreach ($testtypes->chunk(2) as $chunk )

		@foreach ($chunk as $testtype)
			{{ $testtype->id }}
			{{ $testtype->test_type }}
			<form action="/admin/testtypes/{{ $testtype->id }}/edit" method="POST">
				<button type="submit">Edit</button>
			</form>
		@endforeach

@endforeach

Add a Test Type

<form action="/admin/testtypes" method="POST">
	{{ csrf_field() }}
New Test Type: <input type="TEXT" name="testtype" size="30" />
<button type="SUBMIT">Add test type</button> / Main
</form>

@endsection

@extends('layouts.app')

@section('content')

Test Types

Click a test type to edit

@foreach ($testtypes->chunk(2) as $chunk )

		@foreach ($chunk as $testtype)
			{{ $testtype->id }}
			id }}/edit">{{ $testtype->test_type }}
		@endforeach

@endforeach

Add a Test Type

<form class="form-inline" action="/admin/testtypes" method="POST">

		{{ csrf_field() }}
		New Test Type: <input class="form-control" type="TEXT" id="testtype" name="testtype" size="30" />
		<button class="btn btn-default" type="SUBMIT">Add test type</button> / Main

</form>

@endsection

Make each test type a link to the edit page instead of using a form