<?php
declare(strict_types=1);

namespace DiscordWebhook;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

/**
 * Class Webhook
 *
 * @author Scrummer <scrummer@gmx.ch>
 * @package DiscordWebhook
 */
class Webhook implements WebhookInterface
{
    /**
     * @var Client
     */
    private $client;

    /**
     * @var string
     */
    private $username;

    /**
     * @var string
     */
    private $avatar;

    /**
     * @var string
     */
    private $message;

    /**
     * @var bool
     */
    private $tts;

    /**
     * @var array
     */
    private $file;

    /**
     * Constructor.
     *
     * @param string $url
     */
    public function __construct(string $url)
    {
        $this->client = new Client([
            'base_uri' => $url
        ]);
    }

    /**
     * Send the Webhook
     *
     * @return bool
     * @throws GuzzleException
     */
    public function send(): bool
    {
        $response = $this->client->request(
            'POST',
            $this->client->getConfig('base_uri')->getPath(),
            $this->buildPayload()
        );

        return $response->getStatusCode() === 200;
    }

    private function buildPayload(): array
    {
        $fields  = [
            'username' => 'username',
            'avatar'   => 'avatar_url',
            'message'  => 'content',
            'tts'      => 'tts',
            'file'     => 'file',
            'embeds'   => 'embeds'
        ];
        $payload = [
            'multipart' => []
        ];

        foreach ($fields as $field => $payloadField) {
            if (!property_exists($this, $field) || null === $this->$field) {
                continue;
            }

            if (is_string($this->$field) || is_bool($this->$field)) { // add string and booloan values
                $payload['multipart'][] = [
                    'name'     => $payloadField,
                    'contents' => $this->$field
                ];
            } elseif ($this->$field instanceof \SplFileInfo) { // add file
                /** @var \SplFileInfo $file */
                $file = $this->$field;

                $payload['multipart'][] = [
                    'name'     => $payloadField,
                    'contents' => $file->openFile()->fread($file->getSize()),
                    'filename' => $file->getFilename()
                ];
            }
        }

        return $payload;
    }

    /**
     * @param bool $tts
     *
     * @return WebhookInterface
     */
    public function setTts(bool $tts = false): WebhookInterface
    {
        $this->tts = $tts;

        return $this;
    }

    /**
     * @param string $username
     *
     * @return WebhookInterface
     */
    public function setUsername(string $username): WebhookInterface
    {
        $this->username = $username;

        return $this;
    }

    /**
     * @param string $url
     *
     * @return WebhookInterface
     */
    public function setAvatar(string $url): WebhookInterface
    {
        $this->avatar = $url;

        return $this;
    }

    /**
     * @param string $message
     *
     * @return WebhookInterface
     */
    public function setMessage(string $message): WebhookInterface
    {
        $this->message = $message;

        return $this;
    }

    /**
     * @param \SplFileInfo $file
     *
     * @return WebhookInterface
     */
    public function setFile(\SplFileInfo $file): WebhookInterface
    {
        $this->file = $file;

        return $this;
    }
}


<?php

namespace Fabulator\Endomondo;

/**
 * Class Workout
 * @package Fabulator\Endomondo
 */
class Workout {

    /**
     * @var array
     */
    private $source;

    /**
     * @var integer
     */
    private $typeId;

    /**
     * @var float
     */
    private $calories;

    /**
     * @var integer duration in seconds
     */
    private $duration;

    /**
     * @var \DateTime
     */
    private $start;

    /**
     * @var \DateTime
     */
    private $end;

    /**
     * @var string
     */
    private $id;

    /**
     * @var float distane in km
     */
    private $distance;

    /**
     * @var Point[]
     */
    private $points = [];

    /**
     * @var int
     */
    private $avgHeartRate;

    /**
     * @var int
     */
    private $maxHeartRate;

    /**
     * @var string
     */
    private $message;

    /**
     * @var int
     */
    private $privacyMap;

    /**
     * @var int
     */
    private $privacyWorkout;

    /**
     * @var string
     */
    private $title;

    /**
     * @var string[]
     */
    private $hashtags;

    /**
     * @var float
     */
    private $ascent;

    /**
     * @var float
     */
    private $descent;

    /**
     * @var int
     */
    private $cadence;

    /**
     * Create Endomondo workout.
     *
     * Workout constructor.
     */
    public function __construct() { }

    /**
     * Get workout type id.
     *
     * @return integer
     */
    public function getTypeId()
    {
        return $this->typeId;
    }

    /**
     * Set workout type id.
     *
     * @param $id integer
     * @return $this
     * @throws EndomondoWorkoutException when workout type is unknown.
     */
    public function setTypeId($id)
    {
        if (!WorkoutType::exist($id)) {
            throw new EndomondoWorkoutException('Unknown workout type');
        };

        $this->typeId = $id;
        return $this;
    }

    /**
     * Get human readable workout type.
     *
     * @return string
     */
    public function getTypeName()
    {
        if ($this->getTypeId() !== null) {
            return WorkoutType::getName($this->getTypeId());
        }

        return null;
    }

    /**
     * Set number of calories.
     *
     * @param $calories float
     * @return $this
     */
    public function setCalories($calories)
    {
        $this->calories = $calories;
        return $this;
    }

    /**
     * Get number of calories.
     *
     * @return float
     */
    public function getCalories()
    {
        return $this->calories;
    }

    /**
     * Get duration in seconds.
     *
     * @param $duration integer
     * @return $this
     */
    public function setDuration($duration)
    {
        $this->duration = $duration;
        return $this;
    }

    /**
     * Get duration in seconds.
     *
     * @return integer
     */
    public function getDuration()
    {
        return $this->duration;
    }

    /**
     * Get workout start time.
     *
     * @param \DateTime $start
     * @return $this
     */
    public function setStart(\DateTime $start)
    {
        $this->start = clone $start;
        return $this;
    }

    /**
     * Get start time.
     *
     * @return \DateTime
     */
    public function getStart()
    {
        return clone $this->start;
    }

    /**
     * Set end time.
     *
     * @param \DateTime $end
     * @return $this
     */
    public function setEnd(\DateTime $end)
    {
        $this->end = clone $end;
        return $this;
    }

    /**
     * Get time of end of workout. It can be manual set or it is counted based on start and duration.
     *
     * @return \DateTime
     */
    public function getEnd()
    {
        // if end property is defined, use it
        if ($this->end) {
            return clone $this->end;
        }

        $numberOfPosts = count($this->getPoints());

        // try to find last time of point and use it as end date
        if ($this->haveGPSData()) {
            return $this->getPoints()[$numberOfPosts - 1]->getTime();
        }

        // if there are no points, calculate end date from duration
        return $this->getStart()->add(new \DateInterval('PT' . $this->getDuration() . 'S'));
    }

    /**
     * Set workout Id.
     *
     * @param $id string
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

    /**
     * Get workout id.
     *
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set distance in kilometres.
     *
     * @param $distance float
     * @return $this
     */
    public function setDistance($distance)
    {
        $this->distance = $distance;
        return $this;
    }

    /**
     * Get distance in kilometres.
     *
     * @return float
     */
    public function getDistance()
    {
        return $this->distance;
    }

    /**
     * Set points.
     *
     * @param $points Point[]
     * @return $this
     */
    public function setPoints($points) {
        $this->points = $points;
        return $this;
    }

    /**
     * Get points.
     *
     * @return Point[]
     */
    public function getPoints()
    {
        return $this->points;
    }

    /**
     * Have workout some GPS data?
     *
     * @return bool
     */
    public function haveGPSData()
    {
        return count($this->getPoints()) > 0 && $this->getPoints()[0]->getLatitude();
    }

    /**
     * Get array of points as single string.
     *
     * @return string
     */
    public function getPointsAsString()
    {
        $points = '';

        foreach ($this->getPoints() as $point) {
            $points .= $point->toString();
        }

        return $points;
    }

    /**
     * Set avg heart rate.
     *
     * @param $hr int
     * @return $this
     */
    public function setAvgHeartRate($hr)
    {
        $this->avgHeartRate = $hr;
        return $this;
    }

    /**
     * Get avg heart rate
     *
     * @return int
     */
    public function getAvgHeartRate()
    {
        return $this->avgHeartRate;
    }

    /**
     * Set max heart rate
     *
     * @param $hr int
     * @return $this
     */
    public function setMaxHeartRate($hr)
    {
        $this->maxHeartRate = $hr;
        return $this;
    }

    /**
     * Get max heart rate
     *
     * @return int
     */
    public function getMaxHeartRate()
    {
        return $this->maxHeartRate;
    }

    /**
     * Set message
     *
     * @param $message string
     * @return $this
     */
    public function setMessage($message)
    {
        $this->message = $message;
        return $this;
    }

    /**
     * Get message
     *
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * Set map privacy, it should be const of Privacy class.
     *
     * @param $privacy int
     * @return $this
     */
    public function setMapPrivacy($privacy)
    {
        $this->privacyMap = $privacy;
        return $this;
    }

    /**
     * Get map privacy
     *
     * @return int
     */
    public function getMapPrivacy()
    {
        return $this->privacyMap;
    }

    /**
     * Set workout privacy, it should be const of Privacy class.
     *
     * @param $privacy int
     * @return $this
     */
    public function setWorkoutPrivacy($privacy)
    {
        $this->privacyWorkout = $privacy;
        return $this;
    }

    /**
     * Get workout privacy
     *
     * @return int
     */
    public function getWorkoutPrivacy()
    {
        return $this->privacyWorkout;
    }

    /**
     * Set workout title.
     *
     * @param $title string
     * @return $this
     */
    public function setTitle($title)
    {
        $this->title = $title;
        return $this;
    }

    /**
     * Get workout title.
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set list of hastags
     *
     * @param $hashtags string[]
     * @return $this
     */
    public function setHastags($hashtags)
    {
        $this->hashtags = $hashtags;
        return $this;
    }

    /**
     * Add single hashtag.
     *
     * @param $hashtag string
     * @return $this
     */
    public function addHastag($hashtag)
    {
        $this->hashtags[] = $hashtag;
        return $this;
    }

    /**
     * Have workout hastag?
     *
     * @param $hashtag string
     * @return bool
     */
    public function haveHashtag($hashtag)
    {
        return in_array($hashtag, $this->getHashtags());
    }

    /**
     * Get list of hashtags.
     *
     * @return string[]
     */
    public function getHashtags()
    {
        return $this->hashtags;
    }

    /**
     * Set ascent.
     *
     * @param $ascent float
     * @return $this
     */
    public function setAscent($ascent)
    {
        $this->ascent = $ascent;
        return $this;
    }

    /**
     * Get ascent.
     *
     * @return float
     */
    public function getAscent()
    {
        return $this->ascent;
    }

    /**
     * Set descent.
     *
     * @param $descent float
     * @return $this
     */
    public function setDescent($descent)
    {
        $this->descent = $descent;
        return $this;
    }

    /**
     * Get descent.
     *
     * @return int
     */
    public function getDescent()
    {
        return $this->descent;
    }

    /**
     * Get GPX of workout.
     *
     * @return string
     */
    public function getGPX()
    {
        // @TODO use some library to generate GPX files
        $xml = new \SimpleXMLElement(
            '<gpx xmlns="http://www.topografix.com/GPX/1/1" '
            . 'xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" '
            . '/>'
        );
        $trk = $xml->addChild('trk');
        $trk->addChild('type', str_replace(', ', '_', strtoupper($this->getTypeName())));
        $trkseg = $trk->addChild('trkseg');

        foreach ($this->getPoints() as $point) {
            $trkpt = $trkseg->addChild('trkpt');
            $trkpt->addChild('time', $point->getTime()->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d\TH:i:s\Z'));
            $trkpt->addAttribute('lat', $point->getLatitude());
            $trkpt->addAttribute('lon', $point->getLongitude());

            if ($point->getAltitude() !== null) {
                $trkpt->addChild('ele', $point->getAltitude());
            }

            if ($point->getHeartRate() !== null) {
                $ext = $trkpt->addChild('extensions');
                $trackPoint = $ext->addChild('gpxtpx:TrackPointExtension', '', 'gpxtpx');
                $trackPoint->addChild('gpxtpx:hr', $point->getHeartRate(), 'gpxtpx');
            }
        }

        return $xml->asXML();
    }

    /**
     * Set workout Endomondo source
     *
     * @param $source array
     * @return $this
     */
    public function setSource($source)
    {
        $this->source = $source;
        return $this;
    }

    /**
     * Get workout Endomondo source
     *
     * @return array
     */
    public function getSource()
    {
        return $this->source;
    }

    /**
     * @param $cadece int
     * @return $this
     */
    public function setCadence($cadece)
    {
        $this->cadence = $cadece;
        return $this;
    }

    /**
     * @return int
     */
    public function getCadece()
    {
        return $this->cadence;
    }

    /**
     * @return string
     */
    public function toString()
    {
        return 'Workout "' . $this->getTypeName() . '" was ' . round($this->getDuration() / 60) . 'min long.' . ($this->getDistance() ? (' Distance ' . $this->getDistance() . 'km was achived.') : '') . ' It started at ' . $this->getStart()->format('d.m.Y H:i:s e') . ' and end '. $this->getEnd()->format('d.m.Y H:i:s e') .'.';
    }
}


<?php namespace DebugBar\DataCollector;

use Slim\Http\Response;

class SlimResponseCollector extends DataCollector implements Renderable
{
    /**
     * @var \Slim\Http\Response
     */
    protected $response;

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

    /**
     * Called by the DebugBar when data needs to be collected
     *
     * @return array Collected data
     */
    function collect()
    {
        return [
            'content-type' => $this->response->header('Content-Type'),
            'status_code' => $this->response->getStatus(),
            'headers' => $this->getDataFormatter()->formatVar($this->response->headers->all()),
            'cookies' => $this->getDataFormatter()->formatVar($this->response->cookies->all()),
        ];
    }

    /**
     * Returns the unique name of the collector
     *
     * @return string
     */
    function getName()
    {
        return 'response';
    }

    /**
     * Returns a hash where keys are control names and their values
     * an array of options as defined in {@see DebugBar\JavascriptRenderer::addControl()}
     *
     * @return array
     */
    function getWidgets()
    {
        return [
            'response' => [
                'icon' => 'tags',
                'widget' => 'PhpDebugBar.Widgets.VariableListWidget',
                'map' => 'response',
                'default' => '{}',
            ]
        ];
    }
}


<?php

/*

This file is part of Eloquent Joins.

Eloquent Joins is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

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

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

*/

namespace EloquentJoins;

use Illuminate\Database\Eloquent\Builder as BaseBuilder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Arr;

class Builder extends BaseBuilder
{
    /**
     * The relationships that have been joined.
     *
     * @var array
     */
    protected $joined = [];

    /**
     * Get the hydrated models without eager loading.
     *
     * @param array $columns
     *
     * @return \Illuminate\Database\Eloquent\Model[]
     */
    public function getModels($columns = ['*'])
    {
        $results = $this->query->get($columns);

        $connection = $this->model->getConnectionName();

        // Check for joined relations
        if (!empty($this->joined)) {
            foreach ($results as $key => $result) {
                $relation_values = [];

                foreach ($result as $column => $value) {
                    Arr::set($relation_values, $column, $value);
                }

                foreach ($this->joined as $relationName) {
                    $relation = $this->getRelation($relationName);

                    $relation_values[$relationName] = $relation->getRelated()->newFromBuilder(
                        Arr::pull($relation_values, $relationName),
                        $connection
                    );
                }

                $results[$key] = $relation_values;
            }
        }

        return $this->model->hydrate($results, $connection)->all();
    }

    /**
     * Add a join clause to the query.
     *
     * @param string $relation
     * @param string $type
     * @param bool   $where
     *
     * @return $this
     */
    public function join($relationName, $type = 'inner', $where = false)
    {
        $this->joined[] = $relationName;

        $relation = $this->getRelation($relationName);

        if ($relation instanceof BelongsTo) {
            $this->query->join(
                $relation->getRelated()->getTable(),
                $this->model->getTable().'.'.$relation->getForeignKey(),
                '=',
                $relation->getRelated()->getTable().'.'.$relation->getOtherKey(),
                $type,
                $where
            );
        } elseif ($relation instanceof BelongsToMany) {
            $this->query->join(
                $relation->getTable(),
                $relation->getQualifiedParentKeyName(),
                '=',
                $relation->getForeignKey(),
                $type,
                $where
            );

            $this->query->join(
                $relation->getRelated()->getTable(),
                $relation->getRelated()->getTable().'.'.$relation->getRelated()->getKeyName(),
                '=',
                $relation->getOtherKey(),
                $type,
                $where
            );
        } else {
            $this->query->join(
                $relation->getRelated()->getTable(),
                $relation->getQualifiedParentKeyName(),
                '=',
                $relation->getForeignKey(),
                $type,
                $where
            );
        }

        $relation_columns = $this->query
            ->getConnection()
            ->getSchemaBuilder()
            ->getColumnListing($relation->getRelated()->getTable());

        array_walk($relation_columns, function (&$column) use ($relation, $relationName) {
            $column = $relation->getRelated()->getTable().'.'.$column.' as '.$relationName.'.'.$column;
        });

        $this->query->addSelect(array_merge([$this->model->getTable().'.*'], $relation_columns));

        return $this;
    }

    /**
     * Add a "join where" clause to the query.
     *
     * @param string $relation
     * @param string $type
     *
     * @return \Illuminate\Database\Eloquent\Builder|static
     */
    public function joinWhere($relation, $type = 'inner')
    {
        return $this->join($relation, $type, true);
    }

    /**
     * Add a left join to the query.
     *
     * @param string $relation
     *
     * @return \Illuminate\Database\Eloquent\Builder|static
     */
    public function leftJoin($relation)
    {
        return $this->join($relation, 'left');
    }

    /**
     * Add a "join where" clause to the query.
     *
     * @param string $relation
     *
     * @return \Illuminate\Database\Eloquent\Builder|static
     */
    public function leftJoinWhere($relation)
    {
        return $this->joinWhere($relation, 'left');
    }

    /**
     * Add a right join to the query.
     *
     * @param string $relation
     *
     * @return \Illuminate\Database\Eloquent\Builder|static
     */
    public function rightJoin($relation)
    {
        return $this->join($relation, 'right');
    }

    /**
     * Add a "right join where" clause to the query.
     *
     * @param string $relation
     *
     * @return \Illuminate\Database\Eloquent\Builder|static
     */
    public function rightJoinWhere($relation)
    {
        return $this->joinWhere($relation, 'right');
    }
}


<?php

declare(strict_types=1);

/*
 * This file is part of the Geocoder package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @license    MIT License
 */

namespace Geocoder\Provider\GeoIP2;

use Geocoder\Collection;
use Geocoder\Model\Address;
use Geocoder\Model\AddressCollection;
use Geocoder\Query\GeocodeQuery;
use Geocoder\Query\ReverseQuery;
use Geocoder\Provider\AbstractProvider;
use Geocoder\Provider\Provider;
use Geocoder\Exception\UnsupportedOperation;
use Geocoder\Exception\InvalidCredentials;
use Geocoder\Exception\QuotaExceeded;
use GeoIp2\Exception\AddressNotFoundException;
use GeoIp2\Exception\AuthenticationException;
use GeoIp2\Exception\OutOfQueriesException;

/**
 * @author Jens Wiese <jens@howtrueisfalse.de>
 */
final class GeoIP2 extends AbstractProvider implements Provider
{
    /**
     * @var GeoIP2Adapter
     */
    private $adapter;

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

    /**
     * {@inheritdoc}
     */
    public function geocodeQuery(GeocodeQuery $query): Collection
    {
        $address = $query->getText();
        $locale = $query->getLocale() ?: 'en'; // Default to English
        if (!filter_var($address, FILTER_VALIDATE_IP)) {
            throw new UnsupportedOperation('The GeoIP2 provider does not support street addresses, only IP addresses.');
        }

        if ('127.0.0.1' === $address) {
            return new AddressCollection([$this->getLocationForLocalhost()]);
        }

        $result = json_decode($this->executeQuery($address));

        if (null === $result) {
            return new AddressCollection([]);
        }

        $adminLevels = [];
        if (isset($result->subdivisions) && is_array($result->subdivisions)) {
            foreach ($result->subdivisions as $i => $subdivision) {
                $name = (isset($subdivision->names->{$locale}) ? $subdivision->names->{$locale} : null);
                $code = (isset($subdivision->iso_code) ? $subdivision->iso_code : null);

                if (null !== $name || null !== $code) {
                    $adminLevels[] = ['name' => $name, 'code' => $code, 'level' => $i + 1];
                }
            }
        }

        return new AddressCollection([
            Address::createFromArray([
                'providedBy' => $this->getName(),
                'countryCode' => (isset($result->country->iso_code) ? $result->country->iso_code : null),
                'country' => (isset($result->country->names->{$locale}) ? $result->country->names->{$locale} : null),
                'locality' => (isset($result->city->names->{$locale}) ? $result->city->names->{$locale} : null),
                'latitude' => (isset($result->location->latitude) ? $result->location->latitude : null),
                'longitude' => (isset($result->location->longitude) ? $result->location->longitude : null),
                'timezone' => (isset($result->location->time_zone) ? $result->location->time_zone : null),
                'postalCode' => (isset($result->postal->code) ? $result->postal->code : null),
                'adminLevels' => $adminLevels,
            ]),
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function reverseQuery(ReverseQuery $query): Collection
    {
        throw new UnsupportedOperation('The GeoIP2 provider is not able to do reverse geocoding.');
    }

    /**
     * {@inheritdoc}
     */
    public function getName(): string
    {
        return 'geoip2';
    }

    /**
     * @param string $address
     */
    private function executeQuery(string $address): string
    {
        $uri = sprintf('file://geoip?%s', $address);

        try {
            $result = $this->adapter->getContent($uri);
        } catch (AddressNotFoundException $e) {
            return '';
        } catch (AuthenticationException $e) {
            throw new InvalidCredentials(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        } catch (OutOfQueriesException $e) {
            throw new QuotaExceeded(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }

        return $result;
    }
}


<?php
/**
 * WP_Ajax_Helper utility
 *
 * @package PhilipNewcomer\WP_Ajax_Helper
 */

namespace PhilipNewcomer\WP_Ajax_Helper;

/**
 * Class Utility
 */
class Utility {

	/**
	 * Gets the AJAX payload from the POST request.
	 *
	 * @param string $handle The current handler's handle.
	 *
	 * @return mixed The Ajax payload.
	 */
	public static function get_ajax_payload( $handle = '' ) {
		$payload = null;

		if ( ! empty( $_POST['payload'] ) ) {
			$payload = $_POST['payload']; // Could be either a string or an array.
		}

		/**
		 * Filter the Ajax payload.
		 *
		 * @param mixed  $payload The ajax payload.
		 * @param string $handle  The current handler's handle.
		 */
		$payload = apply_filters( 'WP_Ajax_Helper\ajax_payload', $payload, $handle );

		return $payload;
	}

	/**
	 * Retrieves the response from the handle's callback function.
	 *
	 * @param string $handle        The current handler's handle.
	 * @param mixed  $callback      The callback function.
	 * @param array  $callback_args The arguments to be passed to the callback function.
	 *
	 * @return mixed The callback response.
	 */
	public static function get_callback_response( $handle, $callback, $callback_args ) {

		$ajax_payload = static::get_ajax_payload( $handle );

		$response = static::run_callback(
			$callback,
			array(
				$ajax_payload,
				$callback_args,
			)
		);

		/**
		 * Filter the callback response.
		 *
		 * @param mixed  $response      The callback response.
		 * @param string $handle        The current handle's name.
		 * @param array  $callback_args The arguments passed to the callback function.
		 * @param mixed  $ajax_payload  The Ajax payload.
		 */
		$response = apply_filters( 'WP_Ajax_Helper\callback_response', $response, $handle, $callback_args, $ajax_payload );

		return $response;
	}

	/**
	 * Executes the specified callback function, passing in with the supplied arguments.
	 *
	 * @param mixed $callback      The callback function to run.
	 * @param array $callback_args The arguments to be passed to the callback function.
	 *
	 * @return mixed The callback result, or null if the callback was not callable, or \Exception if the callback threw an exception.
	 */
	public static function run_callback( $callback = '', $callback_args = array() ) {

		if ( ! is_callable( $callback ) ) {
			return null;
		}

		try {
			$result = call_user_func_array( $callback, $callback_args );

		} catch ( \Exception $caught_exception ) {
			$result = $caught_exception;
		}

		return $result;
	}

	/**
	 * Sanitizes and validates a handle name.
	 *
	 * @param string $handle The provided handle name.
	 *
	 * @return string The sanitized handle name.
	 */
	public static function sanitize_handle( $handle = null ) {

		$handle = sanitize_key( $handle );
		$handle = str_replace( '-', '_', $handle );

		return $handle;
	}

	/**
	 * Checks whether a nonce is valid.
	 *
	 * @param string $nonce_name The nonce name.
	 *
	 * @return bool Whether the nonce was valid.
	 */
	public static function validate_nonce( $nonce_name ) {

		return check_ajax_referer( $nonce_name, 'nonce', false );
	}
}


<?php
/**
 * WP_Ajax_Helper validator
 *
 * @package PhilipNewcomer\WP_Ajax_Helper
 */

namespace PhilipNewcomer\WP_Ajax_Helper;

/**
 * Class Validator
 */
class Validator {

	/**
	 * The registered validations.
	 *
	 * @var array
	 */
	protected $registered_validations;

	/**
	 * The validations class.
	 *
	 * @var Validations
	 */
	protected $validations_class;

	/**
	 * Validator constructor.
	 *
	 * @param Validations $validations The validations class.
	 */
	public function __construct( Validations $validations ) {

		$this->validations_class = $validations;
	}

	/**
	 * Registers a validation.
	 *
	 * @param string $condition The name of the condition.
	 * @param mixed  $value     The value to validate.
	 */
	public function add_validation( $condition = '', $value = '' ) {

		$this->registered_validations[ $condition ] = $value;
	}

	/**
	 * Determines whether all validations have passed.
	 *
	 * @return bool
	 */
	public function validate_all() {

		foreach ( (array) $this->registered_validations as $condition => $value ) {

			if ( ! $this->validate_single( $condition, $value ) ) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Runs a single validation.
	 *
	 * @param string $condition The name of the condition.
	 * @param mixed  $value     The value to validate.
	 *
	 * @return bool Whether the validation passes.
	 */
	private function validate_single( $condition, $value ) {

		$validator = array( $this->validations_class, $condition );

		if ( is_callable( $validator ) ) {
			$result = call_user_func( $validator, $value );
		} else {
			$result = false;
		}

		return (bool) $result;
	}
}


<?php

/**
 * @package   contao-bootstrap
 * @author    David Molineus <david.molineus@netzmacht.de>
 * @license   LGPL 3+
 * @copyright 2013-2015 netzmacht creative David Molineus
 */

namespace Netzmacht\Bootstrap\Grid\Builder;

/**
 * A grid column being built.
 *
 * @package Netzmacht\Bootstrap\Grid\Builder
 */
class Column
{
    const EXTRA_SMALL_DEVICES = 'xs';
    const SMALL_DEVICES       = 'sm';
    const MEDIUM_DEVICES      = 'md';
    const LARGE_DEVICES       = 'lg';

    const PULL = 'pull';
    const PUSH = 'push';

    /**
     * The column sizes.
     *
     * @var array
     */
    protected $sizes = array();

    /**
     * Custom css class.
     *
     * @var string
     */
    protected $class = '';

    /**
     * The grid builder.
     *
     * @var GridBuilder
     */
    protected $builder;

    /**
     * Column resets.
     *
     * @var array
     */
    private $resets = array();

    /**
     * Construct.
     *
     * @param GridBuilder $builder The grid builder.
     */
    public function __construct(GridBuilder $builder)
    {
        $this->builder = $builder;
    }

    /**
     * Get custom css class.
     *
     * @return string
     */
    public function getClass()
    {
        return $this->class;
    }

    /**
     * Set custom css class class.
     *
     * @param string $class The css class.
     *
     * @return $this
     */
    public function setClass($class)
    {
        $this->class = $class;

        return $this;
    }

    /**
     * Create a column for a device.
     *
     * @param string   $device The device name.
     * @param int      $width  The column width.
     * @param int|null $offset Optional offset.
     * @param int|null $push   Optional push.
     * @param bool     $resets Reset columns.
     *
     * @return $this
     */
    public function forDevice($device, $width, $offset = null, $push = null, $resets = false)
    {
        $this->sizes[$device] = array('width' => $width, 'offset' => $offset, 'push' => $push);

        if ($resets) {
            $this->addReset($device);
        }

        return $this;
    }

    /**
     * Add a reset for a device.
     *
     * @param string $device The device.
     *
     * @return $this
     */
    public function addReset($device)
    {
        if (!in_array($device, $this->resets)) {
            $this->resets[] = $device;
        }

        return $this;
    }

    /**
     * Add reset device sizes.
     *
     * @param array $devices The device sizes.
     *
     * @return $this
     */
    public function addResets(array $devices)
    {
        foreach ($devices as $device) {
            $this->addReset($device);
        }

        return $this;
    }

    /**
     * Get column resets.
     *
     * @return array
     */
    public function getResets()
    {
        return $this->resets;
    }

    /**
     * Get a size for a device.
     *
     * @param string $device The device.
     *
     * @return null|array
     */
    public function getSize($device)
    {
        if (isset($this->sizes[$device])) {
            return $this->sizes[$device];
        }

        return null;
    }

    /**
     * Remove size.
     *
     * @param string $device The device name.
     *
     * @return $this
     */
    public function removeSize($device)
    {
        unset($this->sizes[$device]);

        return $this;
    }

    /**
     * Build css classes.
     *
     * @return array classes
     */
    public function build()
    {
        $classes = array();

        foreach ($this->sizes as $device => $size) {
            if ($size['width']) {
                $classes[] = sprintf('col-%s-%s', $device, $size['width']);
            } else {
                $classes[] = 'hidden-' . $device;
            }

            if ($size['offset'] !== null) {
                $classes[] = sprintf('col-%s-offset-%s', $device, $size['offset']);
            }

            if ($size['push'] !== null) {
                if (is_numeric($size['push'])) {
                    $push      = ($size['push'] < 0) ? 'pull' : 'push';
                    $classes[] = sprintf('col-%s-%s-%s', $device, $push, $size['push']);
                } else {
                    $classes[] = sprintf('col-%s-%s', $device, $size['push']);
                }
            }
        }

        if ($this->class) {
            $classes[] = $this->class;
        }

        return $classes;
    }

    /**
     * Finish the column being build.
     *
     * @return GridBuilder
     */
    public function finish()
    {
        return $this->builder;
    }
}


<?php
/**
 * WP_Ajax_Helper validations
 *
 * @package PhilipNewcomer\WP_Ajax_Helper
 */

namespace PhilipNewcomer\WP_Ajax_Helper;

/**
 * Class Validations
 */
class Validations {

	/**
	 * Tests the user login state.
	 *
	 * @param bool $login_state The login state to test.
	 *
	 * @return bool
	 */
	public function logged_in( $login_state ) {

		return is_user_logged_in() === $login_state;
	}

	/**
	 * Tests whether the current user has the specified capability.
	 *
	 * @param string $capability The capability to test.
	 *
	 * @return bool
	 */
	public function user_can( $capability ) {

		if ( ! is_user_logged_in() ) {
			return false;
		}

		return current_user_can( $capability );
	}

	/**
	 * Tests whether the current user has the specified role.
	 *
	 * @param string $role The role to test.
	 *
	 * @return bool
	 */
	public function user_is( $role ) {

		if ( ! is_user_logged_in() ) {
			return false;
		}

		$user = wp_get_current_user();
		return in_array( $role, $user->roles );
	}
}


<?php

/**
 * @package   contao-bootstrap
 * @author    David Molineus <david.molineus@netzmacht.de>
 * @license   LGPL 3+
 * @copyright 2013-2015 netzmacht creative David Molineus
 */

namespace Netzmacht\Bootstrap\Grid;

/**
 * Class Walker allows to walk through a grid and automatically create the grid html.
 *
 * @package Netzmacht\Bootstrap\Grid
 */
class Walker
{
    /**
     * The grid being used.
     *
     * @var Grid
     */
    private $grid;

    /**
     * The current index.
     *
     * @var int
     */
    private $index = -1;

    /**
     * If true only the classes are generated.
     *
     * @var bool
     */
    private $classesOnly;

    /**
     * Loop over the classes by faking an infinite column set.
     *
     * @var bool
     */
    private $infinite;

    /**
     * The infinite index.
     *
     * @var int
     */
    private $infiniteIndex = -1;

    /**
     * Construct.
     *
     * @param Grid $grid        The grid.
     * @param bool $classesOnly If true only the classes are generated.
     * @param bool $infinite    If true it fakes an infinite mode. The column resets are parsed differently then.
     */
    public function __construct(Grid $grid, $classesOnly = false, $infinite = false)
    {
        $this->grid        = $grid;
        $this->classesOnly = $classesOnly;
        $this->infinite    = $infinite;
    }

    /**
     * Get the grid.
     *
     * @return Grid
     */
    public function getGrid()
    {
        return $this->grid;
    }

    /**
     * Start a new row.
     *
     * If classesOnly is set, only the first column is returned.
     *
     * @return string
     */
    public function begin()
    {
        $this->index = 0;
        $this->infiniteIndex++;

        if ($this->classesOnly) {
            return $this->grid->getColumnAsString($this->index);
        }

        return sprintf(
            '%s%s%s
%s',
            $this->beginRow(),
            PHP_EOL,
            $this->grid->getColumnResetsAsString($this->index),
            $this->grid->getColumnAsString($this->index),
            PHP_EOL
        );
    }

    /**
     * Get the current column.
     *
     * @return string
     */
    public function column()
    {
        $this->index++;
        $this->infiniteIndex++;

        if (!$this->grid->hasColumn($this->index)) {
            $this->index = 0;
        }

        if ($this->classesOnly) {
            return $this->grid->getColumnAsString($this->index);
        }

        $buffer = sprintf(
            '%s
%s%s
%s',
            PHP_EOL,
            PHP_EOL,
            $this->grid->getColumnResetsAsString($this->index),
            $this->grid->getColumnAsString($this->index),
            PHP_EOL
        );

        return $buffer;
    }

    /**
     * End a column and the current row.
     *
     * @return string
     */
    public function end()
    {
        $this->index = 0;

        if ($this->classesOnly) {
            return '';
        }

        return sprintf('%s
%s
%s', PHP_EOL, PHP_EOL, PHP_EOL);
    }

    /**
     * Automatically walk throw the grid.
     *
     * @return string
     */
    public function walk()
    {
        if ($this->index < 0) {
            return $this->begin();
        }

        if (!$this->grid->hasColumn($this->index + 1)) {
            return $this->end() . $this->begin();
        }

        return $this->column();
    }

    /**
     * Begin a new row.
     *
     * @return string
     */
    public function beginRow()
    {
        if ($this->classesOnly) {
            return trim('row ' . $this->grid->getRowClass());
        }

        return sprintf('
', trim('row ' . $this->grid->getRowClass()));
    }

    /**
     * Get the column resets for the current position, always as html.
     *
     * @param string|null $tag Custom html tag.
     *
     * @return string
     */
    public function getColumnResets($tag = null)
    {
        if (!$this->infinite || $this->infiniteIndex === 0 || $this->grid->hasColumn($this->infiniteIndex)) {
            return $this->grid->getColumnResetsAsString($this->index, $tag);
        }

        $number = count($this->grid->getColumns());

        return $this->grid->getColumnResetsAsString(($this->infiniteIndex % $number), $tag);
    }

    /**
     * Get index.
     *
     * @param bool $ignoreInfinite If true the infinite index is ignored and the regular column index is returned.
     *
     * @return int
     */
    public function getIndex($ignoreInfinite = false)
    {
        if ($this->infinite && !$ignoreInfinite) {
            return $this->infiniteIndex;
        }

        return $this->index;
    }
}


<?php

/**
 * @package   contao-bootstrap
 * @author    David Molineus <david.molineus@netzmacht.de>
 * @license   LGPL 3+
 * @copyright 2013-2015 netzmacht creative David Molineus
 */

namespace Netzmacht\Bootstrap\Grid;

class migrate
{
    /**
     * The database connection.
     *
     * @var \Database
     */
    private $database;

    /**
     * @var
     */
    private $previousErrorHandler;

    /**
     * Column sizes used for migration.
     *
     * @var array
     */
    private $sizes = array('xs', 'sm', 'md', 'lg');

    /**
     * Construct.
     */
    public function __construct()
    {
        $this->database = \Database::getInstance();
    }

    /**
     * Run the migration.
     *
     * @return void
     */
    public function run()
    {
        /*
         * Error handler of composer plugin is broken. use our own instead
         * @see #contao-community-alliance/composer-plugin/issues/14
         */
        set_error_handler(array($this, 'handleError'), E_ALL);

        $this->migrateFromLegacy();

        restore_error_handler();
    }

    /**
     * Handle errors properly as a workaround of the broken cca/composer-plugin error handler.
     *
     * @param int    $errno   Contains the level of the error raised, as an integer.
     * @param string $errstr  The error message.
     * @param string $errfile The file in which the error occured.
     * @param int    $errline The line in the file on which the error occured.
     *
     * @return void
     *
     * @throws \ErrorException Always, the error converted to an ErrorException.
     */
    public function handleError($errno, $errstr, $errfile, $errline)
    {
        if ($errno === E_NOTICE) {
            return;
        }

        throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
    }

    /**
     * Migrate form legacy column set editor.
     *
     * @return void
     */
    private function migrateFromLegacy()
    {
        if (!$this->database->fieldExists('bootstrap_grid', 'tl_content')
            && $this->database->fieldExists('columnset_id', 'tl_content')
        ) {
            $this->database->query(
                'ALTER TABLE tl_content ADD bootstrap_grid int(10) unsigned NOT NULL default \'0\';'
            );
            $this->database->query('UPDATE tl_content SET bootstrap_grid=columnset_id WHERE bootstrap_grid = 0');
        }
    }
}

$migrate = new migrate();
$migrate->run();


<?php
/**
 * WP_Ajax_Helper handler
 *
 * @package PhilipNewcomer\WP_Ajax_Helper
 */

namespace PhilipNewcomer\WP_Ajax_Helper;

/**
 * Class Handler
 */
class Handler {

	/**
	 * The handle for this AJAX Helper instance.
	 *
	 * @var string
	 */
	protected $handle;

	/**
	 * The handle's callback function.
	 *
	 * @var mixed
	 */
	protected $handle_callback;

	/**
	 * The arguments to be passed to the handle's callback function.
	 *
	 * @var array
	 */
	protected $handle_callback_args;

	/**
	 * The frontend class.
	 *
	 * @var Frontend
	 */
	protected $frontend;

	/**
	 * The responder class.
	 *
	 * @var Responder
	 */
	protected $responder;

	/**
	 * The utility class.
	 *
	 * @var Utility
	 */
	protected $utility;

	/**
	 * The validator class.
	 *
	 * @var Validator
	 */
	protected $validator;

	/**
	 * Handler constructor.
	 *
	 * @param Responder $responder The responder class.
	 * @param Validator $validator The validator class.
	 * @param Frontend  $frontend  The frontend class.
	 * @param Utility   $utility   The utility class.
	 */
	public function __construct( Responder $responder, Validator $validator, Frontend $frontend, Utility $utility ) {

		$this->frontend    = $frontend;
		$this->responder   = $responder;
		$this->utility     = $utility;
		$this->validator   = $validator;
	}

	/**
	 * The main handler for the specfied handle.
	 *
	 * @param string $handle The instance handle.
	 *
	 * @return Handler
	 */
	public function handle( $handle ) {

		// Sanitize the handle name.
		$this->handle = $this->utility->sanitize_handle( $handle );

		// Register this handle with the frontend class.
		$this->frontend->register_handle( $this->handle );

		// Register the Ajax handler in the WordPress hook system.
		add_action( 'wp_ajax_'        . $this->handle, array( $this, 'ajax_handler' ) );
		add_action( 'wp_ajax_nopriv_' . $this->handle, array( $this, 'ajax_handler' ) );

		return $this;
	}

	/**
	 * Handles the Ajax action.
	 */
	public function ajax_handler() {

		if ( $this->utility->validate_nonce( $this->handle ) && $this->validator->validate_all() ) {

			$callback_response = $this->utility->get_callback_response( $this->handle, $this->handle_callback, $this->handle_callback_args );
			$this->responder->handle_response( $callback_response );

		} else {

			http_response_code( 403 ); // Forbidden.
		}

		die();
	}

	/**
	 * Registers the callback function to handle the request.
	 *
	 * @param mixed $callback      The callback function (function name, class method, or closure).
	 * @param array $callback_args Arguments to be passed to the callback.
	 *
	 * @return Handler
	 */
	public function with_callback( $callback = '', $callback_args = array() ) {

		$this->handle_callback      = $callback;
		$this->handle_callback_args = $callback_args;

		return $this;
	}

	/**
	 * Registers the validation settings.
	 *
	 * @param array $validations The validation settings.
	 *
	 * @return Handler
	 */
	public function with_validation( $validations = array() ) {

		foreach ( (array) $validations as $condition => $value ) {
			$this->validator->add_validation( $condition, $value );
		}

		return $this;
	}
}


<?php

/*
 * GestPayCrypt-PHP
 * Copyright (C) 2001-2015 Alessandro Astarita <aleast@capri.it>
 *
 * http://github.com/asterixcapri/gestpaycrypt-php
 *
 * GestPayCrypt-PHP is an implementation in PHP of GestPayCrypt e
 * GestPayCryptHS italian bank Banca Sella java classes. It allows to
 * connect to online credit card payment GestPay.
 *
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details at
 * http://www.gnu.org/copyleft/lgpl.html
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

class GestPayCrypt
{
    private $shopLogin;
    private $currency;
    private $amount;
    private $shopTransactionId;
    private $cardNumber;
    private $expMonth;
    private $expYear;
    private $buyerName;
    private $buyerEmail;
    private $language;
    private $customInfo;
    private $authorizationCode;
    private $errorCode;
    private $errorDescription;
    private $bankTransactionId;
    private $alertCode;
    private $alertDescription;
    private $encryptedString;
    private $decrypted;
    private $transactionResult;
    private $transport;
    private $domainName;
    private $testDomainName;
    private $paymentUrl;
    private $port;
    private $separator;
    private $min;
    private $cvv;
    private $country;
    private $vbv;
    private $vbvRisp;
    private $threeDLevel;
    private $scriptEncrypt;
    private $scriptDecrypt;
    private $testEnv;

    public function __construct()
    {
        $this->shopLogin = "";
        $this->currency = "";
        $this->amount = "";
        $this->shopTransactionId = "";
        $this->cardNumber = "";
        $this->expMonth = "";
        $this->expYear = "";
        $this->buyerName = "";
        $this->buyerEmail = "";
        $this->language = "";
        $this->customInfo = "";
        $this->authorizationCode = "";
        $this->errorCode = "0";
        $this->errorDescription = "";
        $this->bankTransactionId = "";
        $this->alertCode = "";
        $this->alertDescription = "";
        $this->encryptedString = "";
        $this->decrypted = "";
        $this->transport = "tcp";
        $this->domainName = "ecomm.sella.it";
        $this->testDomainName = "testecomm.sella.it";
        $this->paymentUrl = "/pagam/pagam.aspx";
        $this->port = "80";
        $this->scriptEncrypt = "/CryptHTTP/Encrypt.asp";
        $this->scriptDecrypt = "/CryptHTTP/Decrypt.asp";
        $this->separator = "*P1*";
        $this->min = "";
        $this->cvv = "";
        $this->country = "";
        $this->vbv = "";
        $this->vbvRisp = "";
        $this->threeDLevel = "";
        $this->testEnv = false;
    }

    /**
     * @param bool $enable
     * @return GestPayCrypt
     */
    public function setTestEnv($enable)
    {
        $this->testEnv = $enable;

        return $this;
    }

    /**
     * @return bool
     */
    public function getTestEnv()
    {
        return $this->testEnv;
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setShopLogin($val)
    {
        $this->shopLogin = $val;

        return $this;
    }

    /**
     * @return string
     */
    public function getShopLogin()
    {
        return $this->shopLogin;
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setCurrency($val)
    {
        $this->currency = $val;

        return $this;
    }

    /**
     * @return string
     */
    public function getCurrency()
    {
        return $this->currency;
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setAmount($val)
    {
        $this->amount = $val;

        return $this;
    }

    /**
     * @return string
     */
    public function getAmount()
    {
        return $this->amount;
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setShopTransactionID($val)
    {
        $this->shopTransactionId = urlencode(trim($val));

        return $this;
    }

    /**
     * @return string
     */
    public function getShopTransactionID()
    {
        return urldecode($this->shopTransactionId);
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setCardNumber($val)
    {
        $this->cardNumber = $val;

        return $this;
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setExpMonth($val)
    {
        $this->expMonth = $val;

        return $this;
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setExpYear($val)
    {
        $this->expYear = $val;

        return $this;
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setMin($val)
    {
        $this->min = $val;

        return $this;
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setCvv($val)
    {
        $this->cvv = $val;

        return $this;
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setBuyerName($val)
    {
        $this->buyerName = urlencode(trim($val));

        return $this;
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setBuyerEmail($val)
    {
        $this->buyerEmail = trim($val);

        return $this;
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setLanguage($val)
    {
        $this->language = trim($val);

        return $this;
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setCustomInfo($val)
    {
        $this->customInfo = urlencode(trim($val));

        return $this;
    }

    /**
     * @param array $arrval
     * @return GestPayCrypt|bool
     */
    public function setCustomInfoFromArray(array $arrval)
    {
        if (!is_array($arrval)) {
            return false;
        }
        //check string validity
        foreach ($arrval as $key => $val) {
            if (strlen($val) > 300) {
                $val = substr($val, 0, 300);
            }
            $arrval[$key] = urlencode($val);
        }

        $this->customInfo = http_build_query($arrval, '', $this->separator);

        return $this;
    }

    public function getCustomInfoToArray()
    {
        $allinfo = explode($this->separator, $this->customInfo);
        $customInfoArray = array();
        foreach ($allinfo as $singleInfo) {
            $tagval = explode("=", $singleInfo);
            $customInfoArray[$tagval[0]] = urldecode($tagval[1]);
        }

        return $customInfoArray;
    }

    /**
     * @return string
     */
    public function getCustomInfo()
    {
        return urldecode($this->customInfo);
    }

    /**
     * @param string $val
     *
     * @return GestPayCrypt
     */
    public function setEncryptedString($val)
    {
        $this->encryptedString = $val;

        return $this;
    }

    /**
     * @return string
     */
    public function getCountry()
    {
        return $this->country;
    }

    /**
     * @return string
     */
    public function getVbv()
    {
        return $this->vbv;
    }

    /**
     * @return string
     */
    public function getVbvRisp()
    {
        return $this->vbvRisp;
    }

    /**
     * @return string
     */
    public function get3dLevel()
    {
        return $this->threeDLevel;
    }

    /**
     * @return string
     */
    public function getBuyerName()
    {
        return urldecode($this->buyerName);
    }

    /**
     * @return string
     */
    public function getBuyerEmail()
    {
        return $this->buyerEmail;
    }

    /**
     * @return string
     */
    public function getAuthorizationCode()
    {
        return $this->authorizationCode;
    }

    /**
     * @return string
     */
    public function getErrorCode()
    {
        return $this->errorCode;
    }

    /**
     * @return string
     */
    public function getErrorDescription()
    {
        return $this->errorDescription;
    }

    /**
     * @return string
     */
    public function getBankTransactionID()
    {
        return $this->bankTransactionId;
    }

    /**
     * @return string
     */
    public function getTransactionResult()
    {
        return $this->transactionResult;
    }

    /**
     * @return string
     */
    public function getAlertCode()
    {
        return $this->alertCode;
    }

    /**
     * @return string
     */
    public function getAlertDescription()
    {
        return $this->alertDescription;
    }

    /**
     * @return string
     */
    public function getEncryptedString()
    {
        return $this->encryptedString;
    }

    /**
     * @param string $type
     *
     * @return GestPayCrypt
     */
    public function setTransport($type)
    {
        $this->transport = $type;

        return $this;
    }

    /**
     * @return string
     */
    public function getTransport()
    {
        return $this->transport;
    }

    /**
     * @param string $domain_name
     *
     * @return GestPayCrypt
     */
    public function setDomainName($domain_name)
    {
        $this->domainName = $domain_name;

        return $this;
    }

    /**
     * @return string
     */
    public function getDomainName()
    {
        if ($this->testEnv === true) {
            return $this->testDomainName;
        }

        return $this->domainName;
    }

    /**
     * @param string $port
     *
     * @return GestPayCrypt
     */
    public function setPort($port)
    {
        $this->port = $port;

        return $this;
    }

    /**
     * @return string
     */
    public function getPort()
    {
        return $this->port;
    }

    /**
     * @param string $script
     *
     * @return GestPayCrypt
     */
    public function setScriptEncrypt($script)
    {
        $this->scriptEncrypt = $script;

        return $this;
    }

    /**
     * @param string $script
     *
     * @return GestPayCrypt
     */
    public function setScriptDecrypt($script)
    {
        $this->scriptDecrypt = $script;

        return $this;
    }

    /**
     * @return string
     */
    public function getPaymentUrl()
    {
        return $this->paymentUrl;
    }

    /**
     * @param $url
     * @return GestPayCrypt
     */
    public function setPaymentUrl($url)
    {
        $this->paymentUrl = $url;

        return $this;
    }

    public function getRedirectUrl()
    {
        return 'https://' . $this->getDomainName() . $this->getPaymentUrl() .
               '?a=' . $this->getShopLogin() .
               '&b=' . $this->getEncryptedString();
    }

    /**
     * @param string $type
     *
     * @return string
     */
    public function getScriptType($type)
    {
        if ($type == "crypt") {
            return $this->scriptEncrypt;
        } else {
            return $this->scriptDecrypt;
        }
    }

    /**
     * @return bool
     */
    public function encrypt()
    {
        $this->setError('0', '');

        if (empty($this->shopLogin)) {
            $this->setError('546', 'IDshop not valid');
            return false;
        }

        if (empty($this->currency)) {
            $this->setError('552', 'Currency not valid');
            return false;
        }

        if (empty($this->amount)) {
            $this->setError('553', 'Amount not valid');
            return false;
        }

        if (empty($this->shopTransactionId)) {
            $this->setError('551', 'Shop Transaction ID not valid');
            return false;
        }

        $response = $this->_httpGetResponse("crypt", $this->shopLogin, $this->_getParsedEncryptArguments());

        if ($response == -1) {
            return false;
        }

        $this->encryptedString = $this->_parseResponse("crypt", $response);

        if ($this->encryptedString == -1) {
            return false;
        }

        return true;
    }

    /**
     * @return string
     */
    private function _getParsedEncryptArguments()
    {
        $args = "";

        $vars = array(
            "PAY1_CVV" => $this->cvv,
            "PAY1_MIN" => $this->min,
            "PAY1_UICCODE" => $this->currency,
            "PAY1_AMOUNT" => $this->amount,
            "PAY1_SHOPTRANSACTIONID" => $this->shopTransactionId,
            "PAY1_CARDNUMBER" => $this->cardNumber,
            "PAY1_EXPMONTH" => $this->expMonth,
            "PAY1_EXPYEAR" => $this->expYear,
            "PAY1_CHNAME" => $this->buyerName,
            "PAY1_CHEMAIL" => $this->buyerEmail,
            "PAY1_IDLANGUAGE" => $this->language
        );

        foreach ($vars as $name => $value) {
            if (!empty($value)) {
                $args .= $name . "=" . $value . $this->separator;
            }
        }

        $args = substr($args, 0, -strlen($this->separator));

        if (strlen($this->customInfo) > 0) {
            $args .= $this->separator . $this->getCustomInfo();
        }

        $args = str_replace(" ", chr(167), $args);

        return $args;
    }

    /**
     * @return bool
     */
    public function decrypt()
    {
        $this->setError('0', '');

        if (empty($this->shopLogin)) {
            $this->setError('546', 'IDshop not valid');
            return false;
        }

        if (empty($this->encryptedString)) {
            $this->setError('1009', 'String to Decrypt not valid');
            return false;
        }

        $response = $this->_httpGetResponse("decrypt", $this->shopLogin, $this->encryptedString);

        if ($response == -1) {
            false;
        }

        $this->decrypted = $this->_parseResponse("decrypt", $response);

        if ($this->decrypted == -1) {
            return false;
        } elseif (empty($this->decrypted)) {
            $this->setError('9999', 'Empty decrypted string');
            return false;
        }

        $this->decrypted = str_replace(chr(167), " ", $this->decrypted);

        $this->_parseDecryptedData();

        return true;
    }

    /**
     * @param string $type
     * @param string $a
     * @param string $b
     *
     * @return string
     */
    protected function _httpGetResponse($type, $a, $b)
    {
        $errno = "";
        $errstr = "";

        $socket = fsockopen(
            $this->getTransport() . "://" . $this->getDomainName(),
            $this->getPort(),
            $errno,
            $errstr,
            60
        );

        if (!$socket) {
            $this->setError(
                '9999',
                "Impossible to connect to: " .
                $this->getTransport() . "://" . $this->getDomainName() . ':' . $this->getPort()
            );
            return -1;
        }

        $uri = $this->getScriptType($type) . "?a=" . $a . "&b=" . $b;

        fputs($socket, "GET " . $uri . " HTTP/1.0\r\n\r\n");

        while (fgets($socket, 4096) != "\r\n") {
            ;
        }

        $line = fgets($socket, 4096);

        fclose($socket);

        return $line;
    }

    /**
     * @param string $type
     * @param string $response
     *
     * @return string
     */
    private function _parseResponse($type, $response)
    {
        $matches = array();

        if (preg_match("/#" . $type . "string#([\w\W]*)#\/" . $type . "string#/", $response, $matches)) {
            $parsed = trim($matches[1]);
        } elseif (preg_match("/#error#([\w\W]*)#\/error#/", $response, $matches)) {
            $err = explode("-", $matches[1]);

            if (empty($err[0]) && empty($err[1])) {
                $this->setError('9999', 'Unknown error');
            } else {
                $this->setError(trim($err[0]), trim($err[1]));
            }

            return -1;
        } else {
            $this->setError('9999', 'Response from server not valid');

            return -1;
        }

        return $parsed;
    }

    private function _parseDecryptedData()
    {
        $keyval = explode($this->separator, $this->decrypted);

        foreach ($keyval as $tagPAY1) {
            $tagPAY1val = explode("=", $tagPAY1);

            if (preg_match("/^PAY1_UICCODE/", $tagPAY1)) {
                $this->currency = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_AMOUNT/", $tagPAY1)) {
                $this->amount = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_SHOPTRANSACTIONID/", $tagPAY1)) {
                $this->shopTransactionId = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_CHNAME/", $tagPAY1)) {
                $this->buyerName = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_CHEMAIL/", $tagPAY1)) {
                $this->buyerEmail = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_AUTHORIZATIONCODE/", $tagPAY1)) {
                $this->authorizationCode = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_ERRORCODE/", $tagPAY1)) {
                $this->errorCode = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_ERRORDESCRIPTION/", $tagPAY1)) {
                $this->errorDescription = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_BANKTRANSACTIONID/", $tagPAY1)) {
                $this->bankTransactionId = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_ALERTCODE/", $tagPAY1)) {
                $this->alertCode = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_ALERTDESCRIPTION/", $tagPAY1)) {
                $this->alertDescription = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_CARDNUMBER/", $tagPAY1)) {
                $this->cardNumber = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_EXPMONTH/", $tagPAY1)) {
                $this->expMonth = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_EXPYEAR/", $tagPAY1)) {
                $this->expYear = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_COUNTRY/", $tagPAY1)) {
                $this->country = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_VBVRISP/", $tagPAY1)) {
                $this->vbvRisp = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_VBV/", $tagPAY1)) {
                $this->vbv = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_IDLANGUAGE/", $tagPAY1)) {
                $this->language = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_TRANSACTIONRESULT/", $tagPAY1)) {
                $this->transactionResult = $tagPAY1val[1];
            } elseif (preg_match("/^PAY1_3DLEVEL/", $tagPAY1)) {
                $this->threeDLevel = $tagPAY1val[1];
            } else {
                $this->customInfo .= $tagPAY1 . $this->separator;
            }
        }

        $this->customInfo = substr($this->customInfo, 0, -strlen($this->separator));
    }

    /**
     * @param string $errorCode
     * @param string $errorDescription
     * @return GestPayCrypt
     */
    protected function setError($errorCode, $errorDescription)
    {
        $this->errorCode = $errorCode;
        $this->errorDescription = $errorDescription;

        return $this;
    }
}


<?php
/**
 * WP_Ajax_Helper responder
 *
 * @package PhilipNewcomer\WP_Ajax_Helper
 */

namespace PhilipNewcomer\WP_Ajax_Helper;

/**
 * Class Responder
 */
class Responder {

	/**
	 * The callback response.
	 *
	 * @var mixed
	 */
	protected $callback_response;

	/**
	 * The response type.
	 *
	 * @var string
	 */
	protected $response_type;

	/**
	 * Handles a response.
	 *
	 * @param mixed $callback_response The response from the callback function.
	 */
	public function handle_response( $callback_response ) {

		$this->callback_response = $callback_response;
		$this->response_type = $this->get_response_type();

		$this->send_response_headers();
		$this->send_response_body();
	}

	/**
	 * Determines the type of response to return.
	 *
	 * @return string The response type.
	 */
	protected function get_response_type() {

		if ( is_array( $this->callback_response ) ) {
			$response_type = 'json';

		} elseif ( is_string( $this->callback_response ) ) {
			$response_type = 'plain';

		} else {
			// For everything else, i.e. null, WP_Error object, caught exception, etc.
			$response_type = 'error';
		}

		return $response_type;
	}

	/**
	 * Sends the appropriate HTTP headers for the response type.
	 */
	protected function send_response_headers() {

		$http_content_type = 'text/plain';

		// Set an HTTP error code if the response type is an error.
		if ( 'error' === $this->response_type ) {
			http_response_code( 500 ); // Internal server error.
		}

		// Set the content type to JSON if the callback response is an array.
		if ( 'json' === $this->response_type ) {
			$http_content_type = 'application/json';
		}

		header( sprintf( 'Content-Type: %s; charset=%s',
			$http_content_type,
			get_option( 'blog_charset' )
		) );
	}

	/**
	 * Sends the response body in the appropriate format.
	 */
	protected function send_response_body() {

		if ( 'json' === $this->response_type ) {

			$response_json = wp_json_encode( $this->callback_response );

			if ( false !== $response_json ) {
				echo $response_json;
			}

		} elseif ( 'plain' === $this->response_type ) {
			echo $this->callback_response;
		}
	}
}


<?php

declare(strict_types=1);

/*
 * This file is part of the Geocoder package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @license    MIT License
 */

namespace Geocoder\Provider\GeoIP2;

use GeoIp2\ProviderInterface;
use Geocoder\Exception\InvalidArgument;
use Geocoder\Exception\UnsupportedOperation;

/**
 * @author Jens Wiese <jens@howtrueisfalse.de>
 */
class GeoIP2Adapter
{
    /**
     * GeoIP2 models (e.g. city or country).
     */
    const GEOIP2_MODEL_CITY = 'city';

    const GEOIP2_MODEL_COUNTRY = 'country';

    /**
     * @var ProviderInterface
     */
    protected $geoIp2Provider;

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

    /**
     * @param \GeoIp2\ProviderInterface $geoIpProvider
     * @param string                    $geoIP2Model   (e.g. self::GEOIP2_MODEL_CITY)
     */
    public function __construct(ProviderInterface $geoIpProvider, $geoIP2Model = self::GEOIP2_MODEL_CITY)
    {
        $this->geoIp2Provider = $geoIpProvider;

        if (false === $this->isSupportedGeoIP2Model($geoIP2Model)) {
            throw new UnsupportedOperation(
                sprintf('Model "%s" is not available.', $geoIP2Model)
            );
        }

        $this->geoIP2Model = $geoIP2Model;
    }

    /**
     * Returns the content fetched from a given resource.
     *
     * @param string $url (e.g. file://database?127.0.0.1)
     *
     * @return string
     */
    public function getContent(string $url): string
    {
        if (false === filter_var($url, FILTER_VALIDATE_URL)) {
            throw new InvalidArgument(
                sprintf('"%s" must be called with a valid url. Got "%s" instead.', __METHOD__, $url)
            );
        }

        $ipAddress = parse_url($url, PHP_URL_QUERY);

        if (false === filter_var($ipAddress, FILTER_VALIDATE_IP)) {
            throw new InvalidArgument('URL must contain a valid query-string (an IP address, 127.0.0.1 for instance)');
        }

        $result = $this->geoIp2Provider
            ->{$this->geoIP2Model}($ipAddress)
            ->jsonSerialize();

        return json_encode($result);
    }

    /**
     * Returns the name of the Adapter.
     *
     * @return string
     */
    public function getName(): string
    {
        return 'maxmind_geoip2';
    }

    /**
     * Returns whether method is supported by GeoIP2.
     *
     * @param string $method
     *
     * @return bool
     */
    protected function isSupportedGeoIP2Model(string $method): bool
    {
        $availableMethods = [
            self::GEOIP2_MODEL_CITY,
            self::GEOIP2_MODEL_COUNTRY,
        ];

        return in_array($method, $availableMethods);
    }
}


<?php

/**
 * @package    dev
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @copyright  2014 netzmacht creative David Molineus
 * @license    LGPL 3.0
 * @filesource
 *
 */

namespace Netzmacht\Bootstrap\Grid\DataContainer;

/**
 * Class ToggleIconCallback is used as button_callback for state toggling icons.
 *
 * @package Netzmacht\Contao\DevTools\Dca
 */
class ToggleIconCallback extends \Controller
{
    /**
     * Contao user.
     *
     * @var \User
     */
    private $user;

    /**
     * The input.
     *
     * @var \Input
     */
    private $input;

    /**
     * The database connection.
     *
     * @var \Database
     */
    private $database;

    /**
     * Table name.
     *
     * @var string
     */
    private $table;

    /**
     * Column name.
     *
     * @var string
     */
    private $column;

    /**
     * State value is inversed.
     *
     * @var bool
     */
    private $inversed;

    /**
     * The disabled icon.
     *
     * @var string
     */
    private $disabledIcon;

    /**
     * Construct.
     *
     * @param \User       $user         The Contao user.
     * @param \Input      $input        The user input.
     * @param \Database   $database     The database connection.
     * @param string      $table        The table name.
     * @param string      $column       The column name.
     * @param bool        $inversed     State is inversed.
     * @param string|null $disabledIcon Custom disabled icon.
     */
    public function __construct(
        \User $user,
        \Input $input,
        \Database $database,
        $table,
        $column,
        $inversed = false,
        $disabledIcon = null
    ) {
        $this->user         = $user;
        $this->input        = $input;
        $this->table        = $table;
        $this->column       = $column;
        $this->inversed     = $inversed;
        $this->disabledIcon = $disabledIcon;
        $this->database     = $database;
    }

    /**
     * Invoke the callback.
     *
     * @param array  $row        Current data row.
     * @param string $href       Button link.
     * @param string $label      Button label.
     * @param string $title      Button title.
     * @param string $icon       Enabled button icon.
     * @param string $attributes Html attributes as string.
     *
     * @return string
     */
    public function __invoke($row, $href, $label, $title, $icon, $attributes)
    {
        if ($this->input->get('tid')) {
            $this->toggleVisibility($this->input->get('tid'), ($this->input->get('state') == 1));
            $this->redirect($this->getReferer());
        }

        if (!$this->hasAccess()) {
            return '';
        }

        $href .= '&id='.$this->input->get('id').'&tid='.$row['id'].'&state='.$row[''];

        if (!$row[$this->column] || ($this->inversed && $row[$this->column])) {
            $icon = $this->disableIcon($icon);
        }

        return sprintf(
            '%s ',
            $this->addToUrl($href),
            specialchars($title),
            $attributes,
            \Image::getHtml($icon, $label)
        );
    }

    /**
     * Toggle the visibility state.
     *
     * @param int  $recordId Record id.
     * @param bool $newState New state.
     *
     * @return void
     *
     * @SuppressWarnings(PHPMD.Superglobals)
     */
    private function toggleVisibility($recordId, $newState)
    {
        if (!$this->hasAccess()) {
            $this->log(
                sprintf('Not enough permission to show/shide record ID "%s"', $recordId),
                __METHOD__,
                TL_ERROR
            );

            $this->redirect('contao/main.php?act=error');
        }

        $versions = new \Versions($this->table, $recordId);

        if (isset($GLOBALS['TL_DCA'][$this->table]['fields'][$this->column]['save_callback'])) {
            foreach ((array) $GLOBALS['TL_DCA'][$this->table]['fields'][$this->column]['save_callback'] as $callback) {
                $instance = new $callback[0];
                $instance->{$callback[1]}($newState, $this);
            }
        }

        $this->database
            ->prepare(sprintf('UPDATE %s %s WHERE id=?', $this->table, '%s'))
            ->set(array('tstamp' => time(), $this->column => $newState ? '1' : ''))
            ->execute($recordId);

        $versions->create();
    }

    /**
     * Disable the icon.
     *
     * @param string $icon The enabled icon.
     *
     * @return string
     */
    private function disableIcon($icon)
    {
        if ($this->disabledIcon) {
            return $this->disabledIcon;
        }

        if ($icon === 'visible.gif') {
            return 'invisible.gif';
        }

        return preg_replace('\.([^\.]*)$', '._$1', $icon);
    }

    /**
     * Check if user has access.
     *
     * @return bool
     */
    private function hasAccess()
    {
        if ($this->user instanceof \BackendUser) {
            return $this->user->hasAccess($this->table . '::' . $this->column, 'alexf');
        }

        return false;
    }
}


<?php

/**
 * @package   contao-bootstrap
 * @author    David Molineus <david.molineus@netzmacht.de>
 * @license   LGPL 3+
 * @copyright 2013-2015 netzmacht creative David Molineus
 */

namespace Netzmacht\Bootstrap\Grid\Builder;

use Netzmacht\Bootstrap\Grid\Grid;

/**
 * Class GridBuilder is used to create the grid definition.
 *
 * @package Netzmacht\Bootstrap\Grid\Builder
 */
class GridBuilder
{
    /**
     * The grid columns.
     *
     * @var Column[]
     */
    protected $columns = array();

    /**
     * Create the grid builder.
     *
     * @return GridBuilder
     */
    public static function create()
    {
        return new static();
    }

    /**
     * Add a new column.
     *
     * @return Column
     */
    public function addColumn()
    {
        $column          = new Column($this);
        $this->columns[] = $column;

        return $column;
    }

    /**
     * Get a column.
     *
     * @param int $index The column index.
     *
     * @return Column
     */
    public function getColumn($index)
    {
        return $this->columns[$index];
    }

    /**
     * Build the grid.
     *
     * @return Grid
     */
    public function build()
    {
        $grid = new Grid();

        foreach ($this->columns as $index => $column) {
            $grid->addColumn($column->build());
            $grid->addColumnResets($index, $column->getResets());
        }

        return $grid;
    }
}


<?php

/**
 * @package   contao-bootstrap
 * @author    David Molineus <david.molineus@netzmacht.de>
 * @license   LGPL 3+
 * @copyright 2013-2015 netzmacht creative David Molineus
 */

namespace Netzmacht\Bootstrap\Grid;

/**
 * Class Grid stores the grid columns definitions.
 *
 * @package Netzmacht\Bootstrap\Grid
 */
class Grid
{
    /**
     * The columns definition.
     *
     * @var array
     */
    protected $columns = array();

    /**
     * Column resets after for each column.
     *
     * @var array
     */
    private $columnResets = array();

    /**
     * Custom row class.
     *
     * @var string
     */
    private $rowClass;

    /**
     * Construct.
     *
     * @param array $columns Column definitions.
     */
    public function __construct(array $columns = array())
    {
        foreach ($columns as $column) {
            $this->addColumn($column);
        }
    }

    /**
     * Lod grid from database.
     *
     * @param int $gridId The databse grid id.
     *
     * @return Grid
     *
     * @throws \InvalidArgumentException If grid is not defined.
     *
     * @deprecated Method get removed. Use the factory instead!
     */
    public static function loadFromDatabase($gridId)
    {
        return Factory::createById($gridId);
    }

    /**
     * Add a column.
     *
     * @param array $column The column definition.
     *
     * @return $this
     */
    public function addColumn(array $column)
    {
        $this->columns[] = $column;

        return $this;
    }

    /**
     * Get a column by it's index. If not defined an empty array is returned.
     *
     * @param int $index The column index.
     *
     * @return array
     */
    public function getColumn($index)
    {
        if (isset($this->columns[$index])) {
            return $this->columns[$index];
        }

        return array();
    }

    /**
     * Check is a column exists.
     *
     * @param int $index The index.
     *
     * @return bool
     */
    public function hasColumn($index)
    {
        return isset($this->columns[$index]);
    }

    /**
     * Get column as class string.
     *
     * @param int $index Column index.
     *
     * @return string
     */
    public function getColumnAsString($index)
    {
        if (isset($this->columns[$index])) {
            return implode(' ', $this->columns[$index]);
        }

        return '';
    }

    /**
     * Get all columns.
     *
     * @return array
     */
    public function getColumns()
    {
        return $this->columns;
    }

    /**
     * Add column clear fix for a specific column and size.
     *
     * @param int    $column The column index.
     * @param string $size   The grid size.
     *
     * @return $this
     */
    public function addColumnReset($column, $size)
    {
        if (!isset($this->columnResets[$column])) {
            $this->columnResets[$column] = array();
        }

        if (!in_array($size, $this->columnResets[$column])) {
            $this->columnResets[$column][] = $size;
        }

        return $this;
    }

    /**
     * Add clear fix for a column.
     *
     * @param int   $column The column index.
     * @param array $sizes  The grid sizes.
     *
     * @return $this
     */
    public function addColumnResets($column, array $sizes)
    {
        if (!isset($this->columnResets[$column])) {
            $this->columnResets[$column] = $sizes;
        } else {
            $this->columnResets[$column] = array_unique(array_merge($this->columnResets[$column], $sizes));
        }

        return $this;
    }

    /**
     * Get resets for a column.
     *
     * @param int $index The column index.
     *
     * @return array
     */
    public function getColumnResets($index)
    {
        $index = intval($index);

        if (isset($this->columnResets[$index])) {
            return $this->columnResets[$index];
        }

        return array();
    }

    /**
     * Check if column as a clear fix for a specific size.
     *
     * @param int    $column The column index.
     * @param string $size   The grid column size.
     *
     * @return bool
     */
    public function hasColumnResetForSize($column, $size)
    {
        if (!isset($this->columnResets[$column])) {
            return false;
        }

        return in_array($size, $this->columnResets[$column]);
    }

    /**
     * Get column resets as string.
     *
     * @param int         $index Column index.
     * @param string|null $tag   Custom html tag. Default divs are created.
     *
     * @return string
     */
    public function getColumnResetsAsString($index, $tag = null)
    {
        $tag = $tag ?: 'div';

        return implode(
            PHP_EOL,
            array_map(
                function ($item) use ($tag) {
                    return sprintf(
                        '<%s class="clearfix visible-%s-block"></%s>' . PHP_EOL,
                        $tag,
                        $item,
                        $tag
                    );
                },
                $this->getColumnResets($index)
            )
        );
    }

    /**
     * Get rowClass.
     *
     * @return string
     */
    public function getRowClass()
    {
        return $this->rowClass;
    }

    /**
     * Set rowClass.
     *
     * @param string $rowClass RowClass.
     *
     * @return $this
     */
    public function setRowClass($rowClass)
    {
        $this->rowClass = $rowClass;

        return $this;
    }
}


<?php

/*
 * GestPayCrypt-PHP
 * Copyright (C) 2001-2015 Alessandro Astarita <aleast@capri.it>
 *
 * http://github.com/asterixcapri/gestpaycrypt-php
 *
 * GestPayCrypt-PHP is an implementation in PHP of GestPayCrypt e
 * GestPayCryptHS italian bank Banca Sella java classes. It allows to
 * connect to online credit card payment GestPay.
 *
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details at
 * http://www.gnu.org/copyleft/lgpl.html
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

class GestPayCryptHS extends GestPayCrypt
{
    private $curlBin;

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

        $this->curlBin = "/usr/bin/curl";

        $this->setTransport("ssl");
        $this->setDomainName("ecomm.sella.it");
        $this->setPort("443");
        $this->setScriptEncrypt("/CryptHTTPS/Encrypt.asp");
        $this->setScriptDecrypt("/CryptHTTPS/Decrypt.asp");
    }

    /**
     * @return string
     */
    public function getCurlBin()
    {
        return $this->curlBin;
    }

    /**
     * @param string $curlBin
     *
     * @return GestPayCryptHS
     */
    public function setCurlBin($curlBin)
    {
        $this->curlBin = $curlBin;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    protected function _httpGetResponse($type, $a, $b)
    {
        if (extension_loaded("openssl")) {
            return parent::_httpGetResponse($type, $a, $b);
        } elseif (extension_loaded("curl")) {
            $uri = $this->getScriptType($type) . "?a=" . $a . "&b=" . $b;

            $curl = curl_init("https://" . $this->getDomainName() . $uri);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $tmp = curl_exec($curl);
            curl_close($curl);

            $lines = explode("\n", $tmp);

            return $lines[0];
        } else {
            $uri = $this->getScriptType($type) . "?a=" . $a . "&b=" . $b;

            $exec_str = $this->getCurlBin() . " -s -m 120 -L " .
                        escapeshellarg("https://" . $this->getDomainName() . $uri);

            exec($exec_str, $ret_arr, $ret_num);

            if ($ret_num != 0) {
                $this->setError('9999', 'Error while executing: ' . $exec_str);
                return -1;
            }

            if (!is_array($ret_arr)) {
                $this->setError('9999', 'Error while executing: ' . $exec_str. ' - $ret_arr is not an array');
                return -1;
            }

            return $ret_arr[0];
        }
    }
}


<?php
/**
 * WP_Ajax_Helper frontend
 *
 * @package PhilipNewcomer\WP_Ajax_Helper;
 */

namespace PhilipNewcomer\WP_Ajax_Helper;

/**
 * Class Frontend
 */
class Frontend {

	/**
	 * The singleton instance.
	 *
	 * @var Frontend
	 */
	private static $instance;

	/**
	 * The registered handles.
	 *
	 * @var array
	 */
	protected $registered_handles = array();

	/**
	 * Returns the singleton instance of the class.
	 *
	 * @return Frontend
	 */
	public static function get_instance() {

		if ( null === static::$instance ) {
			static::$instance = new static();
		}

		return static::$instance;
	}

	/**
	 * Registers an instance handle.
	 *
	 * @param string $handle The handle name.
	 */
	public function register_handle( $handle = '' ) {

		$this->registered_handles[] = $handle;

		// Only call add_actions() the first time a handle is registered, as the actions will still be registered for
		// subsequent handles.
		if ( 1 === count( $this->registered_handles ) ) {
			$this->add_actions();
		}
	}

	/**
	 * Registers the class's actions in the WordPress hook system.
	 */
	protected function add_actions() {
		add_action( 'wp_enqueue_scripts',    array( static::$instance, 'enqueue_scripts' ) );
		add_action( 'admin_enqueue_scripts', array( static::$instance, 'enqueue_scripts' ) );
	}

	/**
	 * Enqueues the library's scripts.
	 */
	public function enqueue_scripts() {

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

		$script_url = plugin_dir_url( trailingslashit( __DIR__ ) . '../../../' ) . 'assets/js/wp-ajax-helper.js';

		wp_enqueue_script( 'wp-ajax-helper', $script_url, array( 'jquery' ), null, true );

		wp_localize_script(
			'wp-ajax-helper',
			'wpAjaxHelper',
			array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'handles' => $this->get_nonces(),
			)
		);
	}

	/**
	 * Generates nonces for each of the registered handles.
	 *
	 * @return array The handles with their associated nonces.
	 */
	protected function get_nonces() {
		$nonces = array();

		foreach ( (array) $this->registered_handles as $handle ) {
			$nonces[ $handle ] = wp_create_nonce( $handle );
		}

		return $nonces;
	}
}


<?php

/**
 * @package   contao-bootstrap
 * @author    David Molineus <david.molineus@netzmacht.de>
 * @license   LGPL 3+
 * @copyright 2013-2015 netzmacht creative David Molineus
 */

namespace Netzmacht\Bootstrap\Grid\Integration;

use Netzmacht\Bootstrap\Grid\Event\GetGridsEvent;
use Netzmacht\Bootstrap\Grid\Factory;
use Netzmacht\Bootstrap\Grid\Grid;

/**
 * SemanticHtml5 integration.
 *
 * @package Netzmacht\Bootstrap\Grid\Integration
 */
class SemanticHtml5
{
    /**
     * Column count indexes.
     *
     * @var array
     */
    public static $count = array();

    /**
     * The used grids.
     *
     * @var Grid[]
     */
    public static $grids = array();

    /**
     * Setup semantic html5 grid integration.
     *
     * @return void
     *
     * @SuppressWarnings(PHPMD.Superglobals)
     */
    public static function setUp()
    {
        if (static::isActive()) {
            $GLOBALS['TL_HOOKS']['parseTemplate'][] = array(
                'Netzmacht\Bootstrap\Grid\Integration\SemanticHtml5',
                'hookParseTemplate'
            );

            $GLOBALS['TL_HOOKS']['getContentElement'][] = array(
                'Netzmacht\Bootstrap\Grid\Integration\SemanticHtml5',
                'hookGetContentElement'
            );

            $GLOBALS['TL_EVENTS'][GetGridsEvent::NAME][] = get_called_class() . '::getGrids';
        }
    }

    /**
     * Check if semantic html is active.
     *
     * @return bool
     */
    public static function isActive()
    {
        return in_array('semantic_html5', \Config::getInstance()->getActiveModules());
    }

    /**
     * Get grids from the database.
     *
     * @param GetGridsEvent $event The subscribed event.
     *
     * @return void
     *
     * @SuppressWarnings(PHPMD.Superglobals)
     */
    public static function getGrids(GetGridsEvent $event)
    {
        $model = $event->getModel();
        $grids = $event->getGrids();

        if ($model->type == 'semantic_html5') {
            $query  = 'SELECT * FROM tl_columnset WHERE published=1 ORDER BY title';
            $result = \Database::getInstance()->query($query);

            while ($result->next()) {
                $key = sprintf($GLOBALS['TL_LANG']['tl_content']['bootstrap_columns'], $result->columns);

                $grids[$key][$result->id] = $result->title;
            }
        }
    }

    /**
     * Inject bootstrap isGridElement to semantic html5 palette.
     *
     * @return void
     *
     * @SuppressWarnings(PHPMD.Superglobals)
     */
    public function callbackGeneratePalette()
    {
        $GLOBALS['TL_DCA']['tl_content']['palettes']['semantic_html5'] = str_replace(
            'sh5_additional',
            'sh5_additional,bootstrap_isGridElement',
            $GLOBALS['TL_DCA']['tl_content']['palettes']['semantic_html5']
        );
    }

    /**
     * Use the parse template hook to inject column and row classes.
     *
     * @param \Template $template The template.
     *
     * @return void
     */
    public function hookParseTemplate(\Template $template)
    {
        if (substr($template->getName(), 0, 3) != 'ce_'
            || $template->type != 'semantic_html5'
            || $template->sh5_tag != 'start'
        ) {
            return;
        }

        $this->createRow($template);
        $this->createColumn($template);
    }

    /**
     * Add clear fixes for a column.
     *
     * @param \ContentModel $model  The content model.
     * @param string        $buffer The content element output.
     *
     * @return string
     */
    public function hookGetContentElement($model, $buffer)
    {
        if ($model->type === 'semantic_html5'
            && $model->sh5_tag === 'start'
            && $model->bootstrap_isGridElement === 'column'
            && static::$grids[$model->bootstrap_gridRow]
        ) {
            $row  = $model->bootstrap_gridRow;
            $grid = static::$grids[$row];

            // Index is already incremented, so go back
            $index = (static::$count[$row] - 1);

            $buffer = $grid->getColumnResetsAsString($index) . $buffer;
        }

        return $buffer;
    }

    /**
     * Get all grid elements.
     *
     * @param \DataContainer $dataContainer The data container driver.
     *
     * @return array
     *
     * @SuppressWarnings(PHPMD.Superglobals)
     */
    public function getGridElements($dataContainer)
    {
        $elements = array();

        if ($dataContainer->activeRecord) {
            $query = <<<SQL
SELECT
    c.*, g.title as gridTitle, g.columns as gridColumns
FROM
    tl_content c
LEFT JOIN
    tl_columnset g
ON
    g.id = c.bootstrap_grid
WHERE
    (c.ptable=? OR c.ptable=?)
    AND c.pid=?
    AND c.type=?
    AND c.sh5_tag=?
    AND c.bootstrap_isGridElement=?
    AND c.sorting < ?
ORDER BY
    sorting
SQL;

            $ptable = $GLOBALS['TL_DCA'][$dataContainer->table]['config']['ptable'];
            $result = \Database::getInstance()
                ->prepare($query)
                ->execute(
                    $ptable,
                    $ptable == 'tl_article' ? '' : $ptable,
                    $dataContainer->activeRecord->pid,
                    'semantic_html5',
                    'start',
                    'row',
                    $dataContainer->activeRecord->sorting
                );

            while ($result->next()) {
                $headline              = deserialize($result->headline, true);
                $elements[$result->id] = ($headline['value'] ?: ('ID ' . $result->id)) . ' [' .
                    $result->gridColumns . ' - ' . $result->gridTitle . ']';
            }
        }

        return $elements;
    }

    /**
     * Create the row class.
     *
     * @param \Template $template The template.
     *
     * @return void
     */
    private function createRow($template)
    {
        // semantic html5 element is marked as beginning of new grid row
        if ($template->bootstrap_isGridElement == 'row') {
            try {
                static::$grids[$template->id] = Factory::createById($template->bootstrap_grid);
                static::$count[$template->id] = 0;
            } catch (\InvalidArgumentException $e) {
                echo $e->getMessage();

                return;
            }

            $class = ($template->class ? ' ' : '') . 'row';

            if (static::$grids[$template->id]->getRowClass()) {
                $class .= ' ' . static::$grids[$template->id]->getRowClass();
            }

            $template->class .= $class;
        }
    }

    /**
     * Create the column classes.
     *
     * @param \Template $template The template.
     *
     * @return void
     */
    private function createColumn($template)
    {
        // semantic html5 element is marked as an grid column
        if ($template->bootstrap_isGridElement == 'column') {
            if (static::$grids[$template->bootstrap_gridRow]) {
                $row   = $template->bootstrap_gridRow;
                $grid  = static::$grids[$row];
                $index = static::$count[$row];

                $template->class .= ($template->class ? ' ' : '') . $grid->getColumnAsString($index);
                static::$count[$row]++;
            }
        }
    }
}