<?php

/*
 * admin42
 *
 * @package admin42
 * @link https://github.com/kiwi-suite/admin42
 * @copyright Copyright (c) 2010 - 2017 kiwi suite (https://www.kiwi-suite.com)
 * @license MIT License
 * @author kiwi suite <tech@kiwi-suite.com>
 */

namespace Admin42\FormElements\Service;

use Admin42\FormElements\AngularAwareInterface;
use Admin42\FormElements\Fieldset;
use Admin42\FormElements\Form;
use Zend\Form\ElementInterface;
use Zend\Form\FieldsetInterface;

class Factory extends \Core42\Form\Service\Factory
{
    /**
     * Create an element
     *
     * @param  array $spec
     * @return ElementInterface
     */
    public function createElement($spec)
    {
        return $this->create($spec);
    }

    /**
     * Create a fieldset
     *
     * @param  array $spec
     * @return ElementInterface
     */
    public function createFieldset($spec)
    {
        if (!isset($spec['type'])) {
            $spec['type'] = Fieldset::class;
        }

        return $this->create($spec);
    }

    /**
     * Create a form
     *
     * @param  array $spec
     * @return ElementInterface
     */
    public function createForm($spec)
    {
        if (!isset($spec['type'])) {
            $spec['type'] = Form::class;
        }

        return $this->create($spec);
    }

    /**
     * @param ElementInterface $element
     * @param array|\ArrayAccess|\Traversable $spec
     * @return ElementInterface
     */
    public function configureElement(ElementInterface $element, $spec)
    {
        if (!($element instanceof AngularAwareInterface)) {
            return parent::configureElement($element, $spec);
        }
        $spec['attributes'] = [];
        $spec['options'] = [];

        if (!empty($spec['name'])) {
            $element->setName($spec['name']);
            unset($spec['name']);
        }

        if (!empty($spec['value'])) {
            $element->setValue($spec['value']);
            unset($spec['value']);
        }

        $readonly = (isset($spec['readonly']) && $spec['readonly'] === true);
        $element->setReadonly($readonly);
        unset($spec['readonly']);

        $required = (isset($spec['required']) && $spec['required'] === true);
        $element->setRequired($required);
        unset($spec['required']);

        if (isset($spec['description'])) {
            $element->setDescription($spec['description']);
            unset($spec['description']);
        }

        if (isset($spec['template'])) {
            $element->setTemplate($spec['template']);
            unset($spec['template']);
        }

        if (isset($spec['label'])) {
            $element->setLabel($spec['label']);
            unset($spec['label']);
        }

        $element->setOptions($spec);

        return $element;
    }

    /**
     * @param FieldsetInterface $fieldset
     * @param array|\ArrayAccess|\Traversable $spec
     * @return ElementInterface|FieldsetInterface
     */
    public function configureFieldset(FieldsetInterface $fieldset, $spec)
    {
        $spec = $this->validateSpecification($spec, __METHOD__);
        $fieldset = $this->configureElement($fieldset, $spec);

        if (isset($spec['elements'])) {
            $this->prepareAndInjectElements($spec['elements'], $fieldset, __METHOD__);
        }

        //$this->prepareAndInjectFactory($this, $fieldset, __METHOD__);

        return $fieldset;
    }

    /**
     * Takes a list of element specifications, creates the elements, and injects them into the provided fieldset
     *
     * @param  array|Traversable|ArrayAccess $elements
     * @param  FieldsetInterface $fieldset
     * @param  string $method Method invoking this one (for exception messages)
     * @return void
     */
    protected function prepareAndInjectElements($elements, FieldsetInterface $fieldset, $method)
    {
        $elements = $this->validateSpecification($elements, $method);

        foreach ($elements as $elementSpecification) {
            if (null === $elementSpecification) {
                continue;
            }

            $fieldset->add($elementSpecification);
        }
    }
}


<?php

namespace Shoko\TwitchApiBundle\Repository;

/**
 * Class MeRepository.
 */
class MeRepository extends AbstractRepository
{
    const ENDPOINT = 'user/';

    /**
     * Get authenticated user.
     *
     * @param string $accessToken
     *
     * @return Me
     */
    public function getMe($accessToken)
    {
        if (empty($accessToken)) {
            throw new \InvalidArgumentException('Empty access token provided', 1);
        }
        $response = $this->getClient()->get(self::ENDPOINT, array('Authorization' => 'OAuth '.$accessToken));
        $data = $this->jsonResponse($response);

        return $this->getFactory()->createEntity($data);
    }
}


<?php
/**
 * Devbr\Router
 * PHP version 7
 *
 * @category  Access
 * @package   Librarys
 * @author    Bill Rocha <prbr@ymail.com>
 * @copyright 2016 Bill Rocha <http://google.com/+BillRocha>
 * @license   <https://opensource.org/licenses/MIT> MIT
 * @version   GIT: 0.0.1
 * @link      https://github.com/devbr
 */
namespace Devbr;

/**
 * Router Class
 *
 * @category Access
 * @package  Librarys
 * @author   Bill Rocha <prbr@ymail.com>
 * @license  <https://opensource.org/licenses/MIT> MIT
 * @link     https://github.com/devbr
 */
class Router
{
    private $autorun = true;
    private $url = false;
    private $http = '';
    private $base = '';
    private $request = false;
    private $routers = [];
    private $params = [];
    private $all = [];
    private $method = 'GET'; //CLI, GET, POST, DELETE, PUT, PATCH, OPTIONS, HEAD
    private $separator = '::';
    private $controller = '';
    private $action = '';

    //WEB
    private $defaultController = 'App';
    private $defaultAction = 'pageNotFound';
    private $namespacePrefix = ''; //namespace prefix for MVC systems - ex.: '\Controller'

    //CLI
    private $defaultCliController = 'Main';
    private $defaultCliAction = 'cliHelp';
    private $namespaceCliPrefix = 'Devbr\Cli';

    //Statics
    private static $node = null;
    private static $ctrl = null;

    //GETs -----------------------------------------------------------------
    function getUrl()
    {
        return $this->url;
    }
    function getHttp()
    {
        return $this->http;
    }
    function getBase()
    {
        return $this->base;
    }
    function getRequest()
    {
        return $this->request;
    }
    function getRouters()
    {
        return $this->routers;
    }
    function getAll()
    {
        return $this->all;
    }
    function getMethod()
    {
        return $this->method;
    }

    function getController()
    {
        return $this->controller;
    }
    function getAction()
    {
        return $this->action;
    }
    function getSeparator()
    {
        return $this->separator;
    }
    function getParams()
    {
        return count($this->params) > 0 ? $this->params : null;
    }
    //SETs -----------------------------------------------------------------
    function setSeparator($v)
    {
        $this->separator = $v;
        return $this;
    }

    function setDefaultController($v)
    {
        $this->defaultController = trim( str_replace('/', '\\', $v), '\\/ ');
        return $this;
    }

    function setDefaultAction($v)
    {
        $this->defaultAction = trim($v, '\\/ ');
        return $this;
    }

    function setNamespacePrefix($v)
    {
        $this->namespacePrefix = $v === '' ? '' : '\\'.trim( str_replace('/', '\\', $v), '\\/ ');
        return $this;
    }

    //CLI
    function setDefaultCliController($v)
    {
        $this->defaultCliController = trim( str_replace('/', '\\', $v), '\\/ ');
        return $this;
    }

    function setDefaultCliAction($v)
    {
        $this->defaultCliAction = trim($v, '\\/ ');
        return $this;
    }

    function setNamespaceCliPrefix($v)
    {
        $this->namespaceCliPrefix = $v === '' ? '' : '\\'.trim( str_replace('/', '\\', $v), '\\/ ');
        return $this;
    }

    /**
     * Constructor
     */
    function __construct(
        $autorun = true,
        $request = null,
        $url = null
    ) {
        if ($autorun === false){
            $this->autorun = false;
        }

        if ($request !== null) {
            $this->request = $request;
        }

        if ($url !== null) {
            $this->url = $url;
        }

        $this->method = $this->requestMethod();
        $this->mount();

        //Saving this object in static node (for future static access)
        if (!is_object(static::$node)) {
            static::$node = $this;
        }
    }
    /**
     * Singleton instance
     *
     */
    public static function this()
    {
        if (is_object(static::$node)) {
            return static::$node;
        }
        //else...
        list($routers, $request, $url) = array_merge(func_get_args(), [null, null, null]);
        return static::$node = new static($routers, $request, $url);
    }

    /**
     *  Get Controller Object
     */
    public static function getCtrl()
    {
        return static::$ctrl;
    }

    function loadConfig()
    {
        if (class_exists('\Config\Devbr\Router')) {
            new \Config\Devbr\Router($this);
        }

        return $this;
    }

    /**
     * Make happen...
     *
     */
    function run()
    {
        //Resolve request
        $this->resolve();

        //If is a CALLBACK...
        if (is_object($this->controller)) {
            exit(call_user_func_array($this->controller, [$this->request, $this->params]));
        }
        if ($this->controller === null) {
            $this->controller = $this->method == 'CLI' ? $this->defaultCliController : $this->defaultController;
        }
        if ($this->action === null) {
            $this->action = $this->method == 'CLI' ? $this->defaultCliAction : $this->defaultAction;
        }

        //Name format to Controller namespace
        $ctrl = $this->formatePrsr4Name($this->controller, $this->method == 'CLI' ? $this->namespaceCliPrefix : $this->namespacePrefix);

        //Save the controller...
        $this->controller = $ctrl;

        //Check whether to automatically run the Controller
        //      or return this object
        if(!$this->autorun) {
            return $this;
        }

        //Instantiate the controller
        if (class_exists($ctrl)) {
            static::$ctrl = new $ctrl($this->params, $this->request);
            //IN CLI mode finish in this point: Cli\Main::__construct return to CMD.
        } else {
            if($this->method != 'CLI') {
                header("HTTP/1.0 404 Not Found");
                exit('Page not Found!');
            }
            exit("\nController not found!");
        }

        //Seeking for the METHOD...
        if (!method_exists(static::$ctrl, $this->action)) {
            $this->action = $this->method == 'CLI' ? $this->defaultCliAction : $this->defaultAction;
            if(!method_exists(static::$ctrl, $this->action)){
                if($this->method != 'CLI') {
                    header("HTTP/1.0 404 Not Found");
                    exit('Page not Found!');
                }
                exit();
            }
        }

        //Call action
        return call_user_func_array([static::$ctrl, $this->action],
                                    [$this->request, $this->params]);
    }

    /**
     * Resolve routers
     *
     */
    function resolve()
    {
        if ($this->method == 'CLI') {
            $route = $this->searchCliRoute();
        } else {
        //first: serach in ALL
            $route = $this->searchRouter($this->all);
        //now: search for access method
            if ($route === false && isset($this->routers[$this->method])) {
                $route = $this->searchRouter($this->routers[$this->method]);
            }
        }
        //not match...
        if ($route === false) {
            $route['controller'] = $route['action'] = $route['params'] = $route['request'] = null;
        }
        //set params
        $this->controller = $route['controller'];
        $this->action = $route['action'];
        $this->params = $route['params'];
        //out with decoded router OR all null
        return $route;
    }
    /**
     * Insert/config routers
     *
     */
    function respond(
        $method = 'all',
        $request = '',
        $controller = null,
        $action = null
    ) {

        $method = strtoupper(trim($method));
        //Para sintaxe: CONTROLLER::ACTION
        if (!is_object($controller) && strpos($controller, $this->separator) !== false) {
            $a = explode($this->separator, $controller);
            $controller = isset($a[0]) ? $a[0] : null;
            $action = isset($a[1]) ? $a[1] : null;
        }
        if ($method == 'ALL') {
            $this->all[] = ['request' => trim($request, '/'), 'controller' => $controller, 'action' => $action];
        } else {
            foreach (explode('|', $method) as $mtd) {
                $this->routers[$mtd][] = ['request' => trim($request, '/'), 'controller' => $controller, 'action' => $action];
            }
        }
            return $this;
    }
    /**
     * Mount
     */
    private function mount()
    {
        if ($this->method === 'CLI') {
            global $argv;

            if (isset($argv[0]) && $argv[0] == 'index.php') {
                array_shift($argv);
            }

            $this->request = $argv;

            return;
        }
        //Detect SSL access
        if (!isset($_SERVER['SERVER_PORT'])) {
            $_SERVER['SERVER_PORT'] = 80;
        }
        $this->http = (isset($_SERVER['HTTPS']) && ($_SERVER["HTTPS"] == "on" || $_SERVER["HTTPS"] == 1 || $_SERVER['SERVER_PORT'] == 443)) ? 'https://' : 'http://';
        //What's base??!
        $this->base = isset($_SERVER['PHAR_SCRIPT_NAME']) ? dirname($_SERVER['PHAR_SCRIPT_NAME']) : rtrim(str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']), ' /');
        if ($_SERVER['SERVER_PORT'] != 80  && $_SERVER['SERVER_PORT'] != 443) {
            $this->base .= ':' . $_SERVER['SERVER_PORT'];
        }

        //URL & REQST Constants:
        if($this->request === false) {
            $this->request = urldecode(isset($_SERVER['REQUEST_URI']) ? urldecode(trim(str_replace($this->base, '', trim($_SERVER['REQUEST_URI'])), ' /')) : '');
        }
        defined('_RQST') || define('_RQST', $this->request);

        if($this->url === false) {
            $this->url = isset($_SERVER['SERVER_NAME']) ? $this->http . $_SERVER['SERVER_NAME'] . $this->base . '/' : '';
        }
        defined('_URL') || define('_URL', $this->url);

        //Load configurations
        $this->loadConfig();
    }

    /**
     * [formatePrsr4Name description]
     *
     * @param  [type] $name   [description]
     * @param  string $prefix [description]
     *
     * @return [type]         [description]
     */
    private function formatePrsr4Name($name, $prefix = '')
    {
        $tmp = explode('\\', str_replace('/', '\\', $name));
        $name = $prefix;
        foreach ($tmp as $tmp1) {
            $name .= '\\'.ucfirst($tmp1);
        }

        return $name;
    }

    /**
     * [searchCliRoute description]
     *
     * @return [type] [description]
     */
    private function searchCliRoute()
    {
        $request = $this->request;
        $this->request = implode(' ', $this->request);

        $route = ['request'=>$request, 'controller'=>false, 'action'=>null, 'params'=>null];

        if (isset($request[0])) {
            $tmp = explode($this->separator, $request[0]);
            if (isset($tmp[0])) {
                $route['controller'] = $tmp[0];
            }
            if (isset($tmp[1])) {
                $route['action'] = $tmp[1];
            }
            array_shift($request);

            if (count($request) > 0) {
                $route['params'] = $request;
            }
        }

        return $route;
    }

    /**
     * Search for valide router
     *
     * @params
     */
    private function searchRouter($routes)
    {
        foreach ($routes as $route) {
            if ($route['controller'] === null
              || !preg_match_all('#^' . $route['request'] . '$#',
                    $this->request,
                    $matches,
                    PREG_SET_ORDER)
                  ) {
                continue;
            }
            $route['params'] = array_slice($matches[0], 1);
            return $route;
        }
        //não existe rotas
        return false;
    }
    /**
     * Get all request headers
     * @return array The request headers
     */
    private function requestHeaders()
    {
        // getallheaders available, use that
        if (function_exists('getallheaders')) {
            return getallheaders();
        }
        // getallheaders not available: manually extract 'm
        $headers = array();
        foreach ($_SERVER as $name => $value) {
            if ((substr($name, 0, 5) == 'HTTP_') || ($name == 'CONTENT_TYPE') || ($name == 'CONTENT_LENGTH')) {
                $headers[str_replace(array(' ', 'Http'), array('-', 'HTTP'), ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
    /**
     * Get the request method used, taking overrides into account
     * @return string The Request method to handle
     */
    private function requestMethod()
    {
        if (php_sapi_name() === 'cli') {
            return 'CLI';
        }
        // Take the method as found in $_SERVER
        $method = $_SERVER['REQUEST_METHOD'];
        if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
            ob_start();
            $method = 'GET';
        } // If it's a POST request, check for a method override header
        elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $headers = $this->requestHeaders();
            if (isset($headers['X-HTTP-Method-Override']) && in_array($headers['X-HTTP-Method-Override'], array('PUT', 'DELETE', 'PATCH'))) {
                $method = $headers['X-HTTP-Method-Override'];
            }
        }
        return $method;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: crwgr
 * Date: 5/13/2016
 * Time: 3:29 PM
 */

namespace Nativerank\Logger\Utilities;

use Nativerank\Logger\Model\LoggerORM;
use Nativerank\Logger\Model\LoggerOptionsORM;

use Pagekit\Application as App;

class LogTruck
{

    protected $index;

    protected $module;

    /**
     * LogTruck constructor.
     */
    public function __construct()
    {
        $this->module = App::module('pagekit-logger');
    }

    /**
     * Abraham Lincoln lived in a log cabin
     * @return array
     */
    public function getLogs()
    {
        $logsArray = [];

        $logs = LoggerORM::findAll();

        foreach ($logs as $log) {

            $isException = false;

            $log = (array) $log;

            $logCabin = [];

            if ($log['exception'] !== null && is_array($log['exception']) && count($log['exception']) > 0) {

                $isException = true;

                foreach ($log['exception'] as $key => $value) {

                    $key = $this->deathByCamels($key);

                    $logCabin[$key] = $value;
                }

                if (($options = $this->getOptions($log['log_hash'])) !== null) {

                    $logCabin['options'] = $options->details;

                } else {

                    $logCabin['options'] = [
                        'keep_dates' => $this->module->config('log_dates'),
                        'keep_messages' => $this->module->config('log_messages')
                    ];
                }
            }

            $logCabin['message'] = $log['messages'];

            $logCabin['dates'] = array_map(function($date) {

                if ($date === null) {

                    return null;
                }
                $date = new \DateTime($date);

                return date_format($date, 'Y/m/d H:i:s');

            }, $log['dates']);

            $logCabin['count'] = $log['count'];

            $logCabin['errorLevel'] = $log['error_level'];

            $logCabin['loggerName'] = $log['logger_name'];

            $logCabin['id'] = $log['id'];

            $logCabin['logHash'] = $log['log_hash'];

            $logsArray[] = $isException ? ['exception' => $logCabin] : ['message' => $logCabin];
        }

        return $logsArray;
    }

    /**
     * @param $hash
     * @return mixed
     */
    public function getOptions($hash)
    {
        return LoggerOptionsORM::where(['log_hash = :hash'], ['hash' => $hash])->first();
    }

    /**
     * @param $hash
     * @return mixed
     */
    public function getLog($hash)
    {
        return LoggerORM::where(['log_hash = :hash'], ['hash' => $hash])->first();
    }

    /**
     * Returns a Javascript formatted name from a database formatted one
     * hello_world => helloWorld
     * @param $string
     * @return string
     */
    private function deathByCamels($string)
    {
        $this->index = 0;
        return implode('', array_map(function($el) {
            $this->index++;
            return $this->index === 1 ? $el : ucfirst($el);
        }, explode(' ', str_replace('_', ' ', $string))));
    }
}


<?php

/**
 * @file
 * TeamSpeak 3 PHP Framework
 *
 * $Id: Convert.php 9/26/2011 7:06:29 scp@orilla $
 *
 * This program 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.
 *
 * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package   TeamSpeak3
 * @version   1.1.8-beta
 * @author    Sven 'ScP' Paulsen
 * @copyright Copyright (c) 2010 by Planet TeamSpeak. All rights reserved.
 */

namespace ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper;

/**
 * @class TeamSpeak3_Helper_Convert
 * @brief Helper class for data conversion.
 */
class Convert
{
  /**
   * Converts bytes to a human readable value.
   *
   * @param  integer $bytes
   * @return string
   */
  public static function bytes($bytes)
  {
    $kbytes = sprintf("%.02f", $bytes/1024);
    $mbytes = sprintf("%.02f", $kbytes/1024);
    $gbytes = sprintf("%.02f", $mbytes/1024);
    $tbytes = sprintf("%.02f", $gbytes/1024);

    if($tbytes >= 1)
      return $tbytes . " TB";
    if($gbytes >= 1)
      return $gbytes . " GB";
    if($mbytes >= 1)
      return $mbytes . " MB";
    if($kbytes >= 1)
      return $kbytes . " KB";

    return $bytes . " B";
  }

  /**
   * Converts seconds/milliseconds to a human readable value.
   *
   * @param  integer $seconds
   * @param  boolean $is_ms
   * @param  string  $format
   * @return string
   */
  public static function seconds($seconds, $is_ms = FALSE, $format = "%dD %02d:%02d:%02d")
  {
    if($is_ms) $seconds = $seconds/1000;

    return sprintf($format, $seconds/60/60/24, ($seconds/60/60)%24, ($seconds/60)%60, $seconds%60);
  }

  /**
   * Converts a given codec ID to a human readable name.
   *
   * @param  integer $codec
   * @return string
   */
  public static function codec($codec)
  {
    if($codec == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::CODEC_SPEEX_NARROWBAND)
      return "Speex Narrowband (8 kHz)";
    if($codec == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::CODEC_SPEEX_WIDEBAND)
      return "Speex Wideband (16 kHz)";
    if($codec == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::CODEC_SPEEX_ULTRAWIDEBAND)
      return "Speex Ultra-Wideband (32 kHz)";
    if($codec == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::CODEC_CELT_MONO)
      return "CELT Mono (48 kHz)";

    return "Unknown";
  }

  /**
   * Converts a given group type ID to a human readable name.
   *
   * @param  integer $type
   * @return string
   */
  public static function groupType($type)
  {
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::GROUP_DBTYPE_TEMPLATE)
      return "Template";
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::GROUP_DBTYPE_REGULAR)
      return "Regular";
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::GROUP_DBTYPE_SERVERQUERY)
      return "ServerQuery";

    return "Unknown";
  }

  /**
   * Converts a given permission type ID to a human readable name.
   *
   * @param  integer $type
   * @return string
   */
  public static function permissionType($type)
  {
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_TYPE_SERVERGROUP)
      return "Server Group";
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_TYPE_CLIENT)
      return "Client";
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_TYPE_CHANNEL)
      return "Channel";
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_TYPE_CHANNELGROUP)
      return "Channel Group";
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_TYPE_CHANNELCLIENT)
      return "Channel Client";

    return "Unknown";
  }

  /**
   * Converts a given permission category value to a human readable name.
   *
   * @param  integer $pcat
   * @return string
   */
  public static function permissionCategory($pcat)
  {
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_GLOBAL)
      return "Global";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_GLOBAL_INFORMATION)
      return "Global / Information";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_GLOBAL_SERVER_MGMT)
      return "Global / Virtual Server Management";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_GLOBAL_ADM_ACTIONS)
      return "Global / Administration";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_GLOBAL_SETTINGS)
      return "Global / Settings";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_SERVER)
      return "Virtual Server";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_SERVER_INFORMATION)
      return "Virtual Server / Information";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_SERVER_ADM_ACTIONS)
      return "Virtual Server / Administration";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_SERVER_SETTINGS)
      return "Virtual Server / Settings";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_CHANNEL)
      return "Channel";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_CHANNEL_INFORMATION)
      return "Channel / Information";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_CHANNEL_CREATE)
      return "Channel / Create";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_CHANNEL_MODIFY)
      return "Channel / Modify";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_CHANNEL_DELETE)
      return "Channel / Delete";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_CHANNEL_ACCESS)
      return "Channel / Access";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_GROUP)
      return "Group";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_GROUP_INFORMATION)
      return "Group / Information";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_GROUP_CREATE)
      return "Group / Create";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_GROUP_MODIFY)
      return "Group / Modify";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_GROUP_DELETE)
      return "Group / Delete";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_CLIENT)
      return "Client";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_CLIENT_INFORMATION)
      return "Client / Information";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_CLIENT_ADM_ACTIONS)
      return "Client / Admin";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_CLIENT_BASICS)
      return "Client / Basics";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_CLIENT_MODIFY)
      return "Client / Modify";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_FILETRANSFER)
      return "File Transfer";
    if($pcat == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_CAT_NEEDED_MODIFY_POWER)
      return "Grant";

    return "Unknown";
  }

  /**
   * Converts a given log level ID to a human readable name and vice versa.
   *
   * @param  mixed  $level
   * @return string
   */
  public static function logLevel($level)
  {
    if(is_numeric($level))
    {
      if($level == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_CRITICAL)
        return "CRITICAL";
      if($level == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_ERROR)
        return "ERROR";
      if($level == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_DEBUG)
        return "DEBUG";
      if($level == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_WARNING)
        return "WARNING";
      if($level == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_INFO)
        return "INFO";

      return "DEVELOP";
    }
    else
    {
      if(strtoupper($level) == "CRITICAL")
        return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_CRITICAL;
      if(strtoupper($level) == "ERROR")
        return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_ERROR;
      if(strtoupper($level) == "DEBUG")
        return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_DEBUG;
      if(strtoupper($level) == "WARNING")
        return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_WARNING;
      if(strtoupper($level) == "INFO")
        return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_INFO;

      return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_DEVEL;
    }
  }

  /**
   * Converts a specified log entry string into an array containing the data.
   *
   * @param  string $entry
   * @return array
   */
  public static function logEntry($entry)
  {
    $parts = explode("|", $entry, 5);
    $array = array();

    if(count($parts) != 5)
    {
      $array["timestamp"] = 0;
      $array["level"]     = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_ERROR;
      $array["channel"]   = "ParamParser";
      $array["server_id"] = "";
      $array["msg"]       = "convert error (" . trim($entry) . ")";
      $array["msg_plain"] = $entry;
      $array["malformed"] = TRUE;
    }
    else
    {
      $array["timestamp"] = strtotime(trim($parts[0]));
      $array["level"]     = self::logLevel(trim($parts[1]));
      $array["channel"]   = trim($parts[2]);
      $array["server_id"] = trim($parts[3]);
      $array["msg"]       = trim($parts[4]);
      $array["msg_plain"] = $entry;
      $array["malformed"] = FALSE;
    }

    return $array;
  }

  /**
   * Converts a given string to a ServerQuery password hash.
   *
   * @param  string $plain
   * @return string
   */
  public static function password($plain)
  {
    return base64_encode(sha1($plain, TRUE));
  }

  /**
   * Returns a client-like formatted version of the TeamSpeak 3 version string.
   *
   * @param  string $version
   * @param  string $format
   * @return string
   */
  public static function version($version, $format = "Y-m-d h:i:s")
  {
    if(!$version instanceof String)
    {
      $version = new String($version);
    }

    $buildno = $version->section("[", 1)->filterDigits()->toInt();

    return ($buildno <= 15001) ? $version : $version->section("[")->append("(" . date($format, $buildno) . ")");
  }

  /**
   * Tries to detect the type of an image by a given string and returns it.
   *
   * @param  string $binary
   * @return string
   */
  public static function imageMimeType($binary)
  {
    if(!preg_match('/\A(?:(\xff\xd8\xff)|(GIF8[79]a)|(\x89PNG\x0d\x0a)|(BM)|(\x49\x49(\x2a\x00|\x00\x4a))|(FORM.{4}ILBM))/', $binary, $matches))
    {
      return "application/octet-stream";
    }

    $type = array(
      1 => "image/jpeg",
      2 => "image/gif",
      3 => "image/png",
      4 => "image/x-windows-bmp",
      5 => "image/tiff",
      6 => "image/x-ilbm",
    );

    return $type[count($matches)-1];
  }
}


<?php namespace Gears\Arrays\Conversions\From;
////////////////////////////////////////////////////////////////////////////////
// __________ __             ________                   __________
// \______   \  |__ ______  /  _____/  ____ _____ ______\______   \ _______  ___
//  |     ___/  |  \\____ \/   \  ____/ __ \\__  \\_  __ \    |  _//  _ \  \/  /
//  |    |   |   Y  \  |_> >    \_\  \  ___/ / __ \|  | \/    |   (  <_> >    <
//  |____|   |___|  /   __/ \______  /\___  >____  /__|  |______  /\____/__/\_ \
//                \/|__|           \/     \/     \/             \/            \/
// -----------------------------------------------------------------------------
//          Designed and Developed by Brad Jones <brad @="bjc.id.au" />
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////

use \Zend\Dom\Query;
use \Gears\Arrays\Conversions\Template;
use \Gears\Arrays\Conversions\From\Dom;

class Table extends Template
{
	/**
	 * Property: table_location
	 * =========================================================================
	 * This is either a CSS or Xpath Query to give the location of the
	 * HTML Table you would like to convert toi an array.
	 */
	protected $table_location = 'table';

	/**
	 * Property: table_headings
	 * =========================================================================
	 * Do you want to treat the first row of the table as the headings
	 * for each column.
	 */
	protected $table_headings = true;

	/**
	 * Property: query_type
	 * =========================================================================
	 * This will take either css or xpath
	 */
	protected $query_type = 'css';

	/**
	 * Method: Convert
	 * =========================================================================
	 * This will do the actual converting
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * $data - The HTML string that contains the table to convert to an array.
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * array
	 */
	public function Convert($data)
	{
		// First of all lets do some simple string manipulation
		$data = str_replace(['
', '
', '
', '
', '
', '
'], '', $data);
		$data = str_replace(['<th', '</th'], ['<td', 'query_type)
		{
			case 'css': $table = $dom->execute($this->table_location); break;
			case 'xpath': $table = $dom->queryXpath($this->table_location); break;
		}

		// Convert the table node into an array
		$array = new Dom();
		$dom_array = $array->Convert($table->current());

		// Then tidy up that array
		$table_array = array();

		// We wish to use the first row of the table as the keys for the array
		if ($this->table_headings)
		{
			// Create a simple counter
			$x = -1;

			// Loop through each row
			foreach ($dom_array as $tr_num => $tr)
			{
				// Ignoring anything else
				if (strpos($tr_num, 'tr_') !== false)
				{
					// Ignore the first row as that only contains the headings
					if ($x == -1) { $x++; continue; }

					// Loop through each of the TD Elements
					foreach ($tr as $td_num => $td)
					{
						// Ignoring anything else
						if (strpos($td_num, 'td_') !== false)
						{
							// Work out what the key name is
							$key = $dom_array['tr_0'][$td_num]['#text_0'];

							// Add the cell to the array
							$table_array[$x][$key] = $td['#text_0'];
						}
					}

					// Increase the row count
					$x++;
				}
			}
		}
		else
		{
			// Create a simple counter
			$x = 0;

			// Loop through each row
			foreach ($dom_array as $tr_num => $tr)
			{
				// Ignoring anything else
				if (strpos($tr_num, 'tr_') !== false)
				{
					// Loop through each of the TD Elements
					foreach ($tr as $td_num => $td)
					{
						// Ignoring anything else
						if (strpos($td_num, 'td_') !== false)
						{
							// Add the cell to the array
							$table_array[$x][] = $td['#text_0'];
						}
					}

					// Increase the row count
					$x++;
				}
			}
		}

		return $table_array;
	}
}


<?php

namespace Shoko\TwitchApiBundle\Factory;

use Shoko\TwitchApiBundle\Model\Entity\Channel;
use Shoko\TwitchApiBundle\Model\Entity\ChannelList;
use Shoko\TwitchApiBundle\Model\Entity\ChannelToken;

/**
 * Class ChannelFactory.
 */
class ChannelFactory implements FactoryInterface
{
    /**
     * @param array $data
     * @param false|Channel $channel
     *
     * @return Channel
     */
    public function createEntity(array $data, $channel = false)
    {
        if (false === $channel) {
            $channel = Channel::create();
        }

        if (isset($data['mature'])) {
            $channel = $channel->setMature($data['mature']);
        }

        if (isset($data['status'])) {
            $channel = $channel->setStatus($data['status']);
        }

        if (isset($data['broadcaster_language'])) {
            $channel = $channel->setBroadcasterLanguage($data['broadcaster_language']);
        }

        if (isset($data['game'])) {
            $channel = $channel->setGame($data['game']);
        }

        if (isset($data['delay'])) {
            $channel = $channel->setDelay($data['delay']);
        }

        if (isset($data['language'])) {
            $channel = $channel->setLanguage($data['language']);
        }

        if (isset($data['banner'])) {
            $channel = $channel->setBanner($data['banner']);
        }

        if (isset($data['video_banner'])) {
            $channel = $channel->setVideoBanner($data['video_banner']);
        }

        if (isset($data['background'])) {
            $channel = $channel->setBackground($data['background']);
        }

        if (isset($data['profile_banner'])) {
            $channel = $channel->setProfileBanner($data['profile_banner']);
        }

        if (isset($data['profile_banner_background_color'])) {
            $channel = $channel->setProfileBannerBackgroundColor($data['profile_banner_background_color']);
        }

        if (isset($data['partner'])) {
            $channel = $channel->setPartner($data['partner']);
        }

        if (isset($data['url'])) {
            $channel = $channel->setUrl($data['url']);
        }

        if (isset($data['views'])) {
            $channel = $channel->setViews($data['views']);
        }

        if (isset($data['followers'])) {
            $channel = $channel->setFollowers($data['followers']);
        }

        if (isset($data['name'])) {
            $channel = $channel->setName($data['name']);
        }

        if (isset($data['created_at'])) {
            $channel = $channel->setCreatedAt(new \DateTime($data['created_at']));
        }

        if (isset($data['updated_at'])) {
            $channel = $channel->setUpdatedAt(new \DateTime($data['updated_at']));
        }

        if (isset($data['_links'])) {
            $channel = $channel->setLinks($data['_links']);
        }

        if (isset($data['logo'])) {
            $channel = $channel->setLogo($data['logo']);
        }

        if (isset($data['_id'])) {
            $channel = $channel->setId($data['_id']);
        }

        if (isset($data['display_name'])) {
            $channel = $channel->setDisplayName($data['display_name']);
        }

        return $channel;
    }

    /**
     * @param array             $data
     * @param false|ChannelList $channelList
     *
     * @return ChannelList
     */
    public function createList(array $data, $channelList = false)
    {
        if (false === $channelList) {
            $channelList = ChannelList::create();
        }

        if (isset($data['channels'])) {
            $channelList = $channelList->setChannels($this->createChannels($data['channels']));
        }

        if (isset($data['_links'])) {
            $channelList = $channelList->setLinks($data['_links']);
        }

        if (isset($data['_total'])) {
            $channelList = $channelList->setTotal($data['_total']);
        }

        return $channelList;
    }

    /**
     * @param array $channels
     *
     * @return array
     */
    public function createChannels(array $channels)
    {
        $tmp = [];
        foreach ($channels as $entry) {
            $tmp[] = $this->createEntity($entry);
        }

        return $tmp;
    }

    /**
     * @param array $data
     *
     * @return ChannelToken
     */
    public function createChannelToken(array $data)
    {
        $channelToken = ChannelToken::create();

        if (isset($data['token'])) {
            $channelToken = $channelToken->setToken($data['token']);
        }

        if (isset($data['sig'])) {
            $channelToken = $channelToken->setSig($data['sig']);
        }

        if (isset($data['mobile_restricted'])) {
            $channelToken = $channelToken->setMobileRestricted($data['mobile_restricted']);
        }

        return $channelToken;
    }
}


<?php

namespace SheaDawson\TimedNotice;

use SheaDawson\TimedNotice\TimedNotice;
use SilverStripe\Admin\ModelAdmin;
use SilverStripe\Core\Config\Config;
use SilverStripe\Forms\DropdownField;
use SilverStripe\ORM\ArrayLib;

/**
 * TimedNoticeAdmin
 *
 * @package timednotices
 * @author shea@silverstripe.com.au
 **/
class TimedNoticeAdmin extends ModelAdmin
{
    /**
     * @var array
     */
    private static $managed_models = [
        TimedNotice::class
    ];

    /**
     * @var string
     */
    private static $url_segment = 'timed-notices';

    /**
     * @var string
     */
    private static $menu_title = 'Timed Notices';

    /**
     * @var string
     *
     * Regression: $menu_icon not currently working in SS4.2. See this link for more information:
     * https://github.com/silverstripe/silverstripe-admin/issues/558
     */
    // private static $menu_icon = 'silverstripe-timednotices/images/bell.png';

    /**
     * @var boolean
     */
    public $showImportForm = false;

    /**
     * Update the SearchForm to use dropdown fields for MessageType/Status filters
     *
     * @return Form
     **/
    public function SearchForm()
    {
        $form = parent::SearchForm();
        $fields = $form->Fields();
        $q = $this->getRequest()->requestVar('q');

        $fields->removeByName('q[MessageType]');

        $fields->push(
            DropdownField::create(
                'q[MessageType]',
                'Message Type',
                ArrayLib::valuekey(Config::inst()->get(TimedNotice::class, 'message_types')),
                isset($q['MessageType']) ? $q['MessageType'] : []
            )->setEmptyString(' ')
        );

        $fields->push(
            DropdownField::create(
                'q[Status]',
                'Status',
                ArrayLib::valuekey(Config::inst()->get(TimedNotice::class, 'status_options')),
                isset($q['Status']) ? $q['Status'] : []
            )->setEmptyString(' ')
        );

        return $form;
    }

    /**
     * Custom filtering on "Status"
     *
     * @return Form
     **/
    public function getList()
    {
        $list = parent::getList();
        $r = $this->getRequest();
        if ($q = $r->requestVar('q')) {
            if (isset($q['Status'])) {
                $status = $q['Status'];
                $now = date('Y-m-d H:i:s');
                if ($status == 'Future') {
                    return $list->where("StartTime > '$now'");
                } else if ($status == 'Expired') {
                    return $list->where("EndTime < $now");
                } else if ($status == 'Current') {
                    return $list->where("
                        StartTime < '$now' AND
                        (EndTime > '$now' OR EndTime IS NULL)
                    ");
                }
            }
        }

        return $list;
    }
}


<?php

/**
 * @file
 * TeamSpeak 3 PHP Framework
 *
 * $Id: Blacklist.php 9/26/2011 7:06:29 scp@orilla $
 *
 * This program 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.
 *
 * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package   TeamSpeak3
 * @version   1.1.8-beta
 * @author    Sven 'ScP' Paulsen
 * @copyright Copyright (c) 2010 by Planet TeamSpeak. All rights reserved.
 */

namespace ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter;

/**
 * @class TeamSpeak3_Adapter_Blacklist
 * @brief Provides methods to check if an IP address is currently blacklisted.
 */
class Blacklist extends AbstractAdapter
{
  /**
   * The IPv4 address or FQDN of the TeamSpeak Systems update server.
   *
   * @var string
   */
  protected $default_host = "blacklist.teamspeak.com";

  /**
   * The UDP port number of the TeamSpeak Systems update server.
   *
   * @var integer
   */
  protected $default_port = 17385;

  /**
   * Stores an array containing the latest build numbers.
   *
   * @var array
   */
  protected $build_numbers = null;

  /**
   * Connects the TeamSpeak3_Transport_Abstract object and performs initial actions on the remote
   * server.
   *
   * @return void
   */
  public function syn()
  {
    if(!isset($this->options["host"]) || empty($this->options["host"])) $this->options["host"] = $this->default_host;
    if(!isset($this->options["port"]) || empty($this->options["port"])) $this->options["port"] = $this->default_port;

    $this->initTransport($this->options, '\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Transport\UDP');
    $this->transport->setAdapter($this);

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Profiler::init(spl_object_hash($this));

    ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("blacklistConnected", $this);
  }

  /**
   * The TeamSpeak3_Adapter_Blacklist destructor.
   *
   * @return void
   */
  public function __destruct()
  {
    if($this->getTransport() instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Transport\AbstractTransport && $this->getTransport()->isConnected())
    {
      $this->getTransport()->disconnect();
    }
  }

  /**
   * Returns TRUE if a specified $host IP address is currently blacklisted.
   *
   * @param  string $host
   * @throws Blacklist\Exception
   * @return boolean
   */
  public function isBlacklisted($host)
  {
    if(ip2long($host) === FALSE)
    {
      $addr = gethostbyname($host);

      if($addr == $host)
      {
        throw new Blacklist\Exception("unable to resolve IPv4 address (" . $host . ")");
      }

      $host = $addr;
    }

    $this->getTransport()->send("ip4:" . $host);
    $repl = $this->getTransport()->read(1);
    $this->getTransport()->disconnect();

    if(!count($repl))
    {
      return FALSE;
    }

    return ($repl->toInt()) ? FALSE : TRUE;
  }
}


<?php

namespace DevGroup\Entity\traits;

use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\StringHelper;

/**
 * Class EntityTrait
 * @package DevGroup\Entity\traits
 */
trait EntityTrait
{
    /**
     * @var array of trait names by model class name
     */
    protected static $traitsList = [];

    /**
     * @var array of rules by model class name
     */
    protected static $rulesList = [];

    /**
     * @var array of attribute labels by model class name
     */
    protected static $attributeLabelsList = [];

    /**
     * @var array of attribute hints by model class name
     */
    protected static $attributeHintsList = [];

    /**
     * Get all traits that uses for model
     * @return mixed
     */
    protected static function getTraits()
    {
        if (isset(static::$traitsList[static::class]) === false) {
            $className = static::class;
            static::$traitsList[static::class] = [];
            do {
                foreach (class_uses($className) as $value) {
                    static::$traitsList[static::class][$value] = StringHelper::basename($value);
                }
                $className = get_parent_class($className);
            } while ($className !== false);
        }
        return static::$traitsList[static::class];
    }

    /**
     * Call a trait method and return a result or null in not exists.
     * This method builds a full method name, checks it and calls if exists.
     * @param string $traitName
     * @param string $methodName
     * @return null|mixed
     */
    protected function callTraitMethod($traitName, $methodName)
    {
        return method_exists($this, $traitName . $methodName)
            ? $this->{$traitName . $methodName}()
            : null;
    }

    /**
     * Call trait event methods.
     * @param string $eventName
     */
    protected function callEvents($eventName)
    {
        foreach (static::getTraits() as $name) {
            if ($name === 'EntityTrait') {
                continue;
            }
            $this->callTraitMethod($name, $eventName);
        }
    }

    protected function initI18n()
    {
        if (isset(Yii::$app->i18n->translations['entity']) === false) {
            Yii::$app->i18n->translations['entity'] = [
                'class' => \yii\i18n\PhpMessageSource::class,
                'sourceLanguage' => 'en-US',
                'basePath' => '@DevGroup/Entity/messages',
            ];
        }
    }

    /**
     * Get all model rules.
     * This method merges a model rules (it must consists in $model->rules)
     * with rules of all used traits (it must be defined as `public function TraitnameRules`).
     *
     * @return array
     */
    public function rules()
    {
        if (isset(static::$rulesList[static::class]) === false) {
            static::$rulesList[static::class] = isset($this->rules) === true
                ? $this->rules
                : [];
            foreach (static::getTraits() as $name) {
                if (null !== $rules = $this->callTraitMethod($name, 'Rules')) {
                    static::$rulesList[static::class] = ArrayHelper::merge(
                        static::$rulesList[static::class],
                        $rules
                    );
                }
            }
        }
        return static::$rulesList[static::class];
    }

    /**
     * Get all attribute labels.
     * This method merges a model attributeLabels with attribute labels of all used traits.
     * @return array
     */
    public function attributeLabels()
    {
        if (isset(static::$attributeLabelsList[static::class]) === false) {
            static::$attributeLabelsList[static::class] = isset($this->attributeLabels) === true
                ? $this->attributeLabels
                : [];
            foreach (static::getTraits() as $name) {
                if (null !== $attributeLabels = $this->callTraitMethod($name, 'AttributeLabels')) {
                    static::$attributeLabelsList[static::class] = ArrayHelper::merge(
                        static::$attributeLabelsList[static::class],
                        $attributeLabels
                    );
                }
            }
        }
        return static::$attributeLabelsList[static::class];
    }

    /**
     * Get all attribute hints.
     * This method merges a model attributeHints with attribute hints of all used traits.
     * @return array
     */
    public function attributeHints()
    {
        if (isset(static::$attributeHintsList[static::class]) === false) {
            static::$attributeHintsList[static::class] = isset($this->attributeHints) === true
                ? $this->attributeHints
                : [];
            foreach (static::getTraits() as $name) {
                if (null !== $attributeHints = $this->callTraitMethod($name, 'AttributeHints')) {
                    static::$attributeHintsList[static::class] = ArrayHelper::merge(
                        static::$attributeHintsList[static::class],
                        $attributeHints
                    );
                }
            }
        }
        return static::$attributeHintsList[static::class];
    }

    /**
     * Init traits.
     * This method register a translation and call init methods of all uses traits.
     */
    public function EntityTraitInit()
    {
        $this->initI18n();
        $this->callEvents('Init');
    }

    /**
     * Clear rules and attribute labels for current class
     */
    public static function EntityTraitClear()
    {
        unset(static::$attributeLabelsList[static::class], static::$rulesList[static::class]);
    }

    /**
     * Trait initialisation.
     */
    public function init()
    {
        parent::init();
        $this->EntityTraitInit();
    }

    /**
     * Run an init method after unserializing
     */
    public function __wakeup()
    {
        $this->initI18n();
    }
}


<?php

/*
 * admin42
 *
 * @package admin42
 * @link https://github.com/kiwi-suite/admin42
 * @copyright Copyright (c) 2010 - 2017 kiwi suite (https://www.kiwi-suite.com)
 * @license MIT License
 * @author kiwi suite <tech@kiwi-suite.com>
 */

namespace Admin42\View\Helper\Form;

use Zend\Form\FormInterface;
use Zend\View\Helper\AbstractHelper;

class Form extends AbstractHelper
{
    /**
     * @param FormInterface|null $form
     * @return $this|string
     */
    public function __invoke(FormInterface $form = null)
    {
        if (!$form) {
            return $this;
        }

        return $this->render($form);
    }

    /**
     * Render a form from the provided $form,
     *
     * @param  FormInterface $form
     * @return string
     */
    public function render(FormInterface $form)
    {
        if (\method_exists($form, 'prepare')) {
            $form->prepare();
        }

        $formContent = '';

        foreach ($form as $element) {
            $formContent .= $this->getView()->formRow($element);
        }

        return $formContent;
    }
}


<?php

namespace Shoko\TwitchApiBundle\Factory;

use Shoko\TwitchApiBundle\Model\Entity\Rank;

/**
 * Class RankFactory.
 */
class RankFactory implements FactoryInterface
{
    /**
     * @param array      $data
     * @param false|Rank $rank
     *
     * @return Rank
     */
    public function createEntity(array $data, $rank = false)
    {
        if (false === $rank) {
            $rank = Rank::create();
        }

        if (isset($data['game'])) {
            $rank->setGame((new GameFactory())->createEntity($data['game']));
        }

        if (isset($data['viewers'])) {
            $rank->setViewers($data['viewers']);
        }

        if (isset($data['channels'])) {
            $rank->setChannels($data['channels']);
        }

        if (isset($data['_links'])) {
            $rank = $rank->setLinks($data['_links']);
        }

        return $rank;
    }
}


<?php

/**
 * @file
 * TeamSpeak 3 PHP Framework
 *
 * $Id: Reply.php 9/26/2011 7:06:29 scp@orilla $
 *
 * This program 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.
 *
 * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package   TeamSpeak3
 * @version   1.1.8-beta
 * @author    Sven 'ScP' Paulsen
 * @copyright Copyright (c) 2010 by Planet TeamSpeak. All rights reserved.
 */

namespace ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery;

/**
 * @class TeamSpeak3_Adapter_ServerQuery_Reply
 * @brief Provides methods to analyze and format a ServerQuery reply.
 */
class Reply
{
  /**
   * Stores the command used to get this reply.
   *
   * @var \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String
   */
  protected $cmd = null;

  /**
   * Stores the servers reply (if available).
   *
   * @var \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String
   */
  protected $rpl = null;

  /**
   * Stores connected TeamSpeak3_Node_Host object.
   *
   * @var \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Host
   */
  protected $con = null;

  /**
   * Stores an assoc array containing the error info for this reply.
   *
   * @var array
   */
  protected $err = array();

  /**
   * Sotres an array of events that occured before or during this reply.
   *
   * @var array
   */
  protected $evt = array();

  /**
   * Creates a new TeamSpeak3_Adapter_ServerQuery_Reply object.
   *
   * @param  array  $rpl
   * @param  string $cmd
   * @param  \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Host $con
   * @return Reply
   */
  public function __construct(array $rpl, $cmd = null, \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Host $con = null)
  {
    $this->cmd = new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String($cmd);
    $this->con = $con;

    $this->fetchError(array_pop($rpl));
    $this->fetchReply($rpl);
  }

  /**
   * Returns the reply as an \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String object.
   *
   * @return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String
   */
  public function toString()
  {
    return (!func_num_args()) ? $this->rpl->unescape() : $this->rpl;
  }

  /**
   * Returns the reply as a standard PHP array where each element represents one item.
   *
   * @return array
   */
  public function toLines()
  {
    if(!count($this->rpl)) return array();

    $list = $this->toString(0)->split(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_LIST);

    if(!func_num_args())
    {
      for($i = 0; $i < count($list); $i++) $list[$i]->unescape();
    }

    return $list;
  }

  /**
   * Returns the reply as a standard PHP array where each element represents one item in table format.
   *
   * @return array
   */
  public function toTable()
  {
    $table = array();

    foreach($this->toLines(0) as $cells)
    {
      $pairs = $cells->split(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_CELL);

      if(!func_num_args())
      {
        for($i = 0; $i < count($pairs); $i++) $pairs[$i]->unescape();
      }

      $table[] = $pairs;
    }

    return $table;
  }

  /**
   * Returns a multi-dimensional array containing the reply splitted in multiple rows and columns.
   *
   * @return array
   */
  public function toArray()
  {
    $array = array();
    $table = $this->toTable(1);

    for($i = 0; $i < count($table); $i++)
    {
      foreach($table[$i] as $pair)
      {
        if(!$pair->contains(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_PAIR))
        {
          $array[$i][$pair->toString()] = null;
        }
        else
        {
          list($ident, $value) = $pair->split(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_PAIR, 2);

          $array[$i][$ident->toString()] = $value->isInt() ? $value->toInt() : (!func_num_args() ? $value->unescape() : $value);
        }
      }
    }

    return $array;
  }

  /**
   * Returns a multi-dimensional assoc array containing the reply splitted in multiple rows and columns.
   * The identifier specified by key will be used while indexing the array.
   *
   * @param  $key
   * @return array
   */
  public function toAssocArray($ident)
  {
    $nodes = (func_num_args() > 1) ? $this->toArray(1) : $this->toArray();
    $array = array();

    foreach($nodes as $node)
    {
      if(array_key_exists($ident, $node))
      {
        $array[(is_object($node[$ident])) ? $node[$ident]->toString() : $node[$ident]] = $node;
      }
      else
      {
        throw new Exception("invalid parameter", 0x602);
      }
    }

    return $array;
  }

  /**
   * Returns an array containing the reply splitted in multiple rows and columns.
   *
   * @return array
   */
  public function toList()
  {
    $array = func_num_args() ? $this->toArray(1) : $this->toArray();

    if(count($array) == 1)
    {
      return array_shift($array);
    }

    return $array;
  }

  /**
   * Returns an array containing stdClass objects.
   *
   * @return ArrayObject
   */
  public function toObjectArray()
  {
    $array = (func_num_args() > 1) ? $this->toArray(1) : $this->toArray();

    for($i = 0; $i < count($array); $i++)
    {
      $array[$i] = (object) $array[$i];
    }

    return $array;
  }

  /**
   * Returns the command used to get this reply.
   *
   * @return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String
   */
  public function getCommandString()
  {
    return new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String($this->cmd);
  }

  /**
   * Returns an array of events that occured before or during this reply.
   *
   * @return array
   */
  public function getNotifyEvents()
  {
    return $this->evt;
  }

  /**
   * Returns the value for a specified error property.
   *
   * @param  string $ident
   * @param  mixed  $default
   * @return mixed
   */
  public function getErrorProperty($ident, $default = null)
  {
    return (array_key_exists($ident, $this->err)) ? $this->err[$ident] : $default;
  }

  /**
   * Parses a ServerQuery error and throws a TeamSpeak3_Adapter_ServerQuery_Exception object if
   * there's an error.
   *
   * @param  string $err
   * @throws Exception
   * @return void
   */
  protected function fetchError($err)
  {
    $cells = $err->section(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_CELL, 1, 3);

    foreach($cells->split(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_CELL) as $pair)
    {
      list($ident, $value) = $pair->split(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_PAIR);

      $this->err[$ident->toString()] = $value->isInt() ? $value->toInt() : $value->unescape();
    }

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("notifyError", $this);

    if($this->getErrorProperty("id", 0x00) != 0x00)
    {
      if($permid = $this->getErrorProperty("failed_permid"))
      {
        try
        {
          $suffix = " (failed on " . $this->con->permissionGetNameById($permid) . ")";
        }
        catch(Exception $e)
        {
          $suffix = " (failed on " . $this->cmd->section(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_CELL) . " " . $permid . "/0x" . strtoupper(dechex($permid)) . ")";
        }
      }
      elseif($details = $this->getErrorProperty("extra_msg"))
      {
        $suffix = " (" . $details . ")";
      }
      else
      {
        $suffix = "";
      }

      throw new Exception($this->getErrorProperty("msg") . $suffix, $this->getErrorProperty("id"));
    }
  }

  /**
   * Parses a ServerQuery reply and creates a \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String object.
   *
   * @param  string $rpl
   * @return void
   */
  protected function fetchReply($rpl)
  {
    foreach($rpl as $key => $val)
    {
      if($val->startsWith(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::GREET))
      {
        unset($rpl[$key]);
      }
      elseif($val->startsWith(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::EVENT))
      {
        $this->evt[] = new Event($rpl[$key], $this->con);
        unset($rpl[$key]);
      }
    }

    $this->rpl = new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String(implode(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_LIST, $rpl));
  }
}


<?php

namespace Encore\Wx\Element;

use wxSize;
use wxPanel;
use Encore\Giml\ElementTrait;
use Encore\Wx\Element\Traits\Wx;
use Encore\Giml\ElementInterface;

class Panel implements ElementInterface
{
    use ElementTrait;
    use Wx;

    /**
     * Initialise the object
     *
     * @return void
     */
    public function init()
    {
        $this->element = new wxPanel(null, wxID_ANY, wxDefaultPosition, new wxSize($this->width, $this->height), wxTAB_TRAVERSAL, $this->title);
    }
}


<?php

/*
 * admin42
 *
 * @package admin42
 * @link https://github.com/kiwi-suite/admin42
 * @copyright Copyright (c) 2010 - 2017 kiwi suite (https://www.kiwi-suite.com)
 * @license MIT License
 * @author kiwi suite <tech@kiwi-suite.com>
 */

namespace Admin42\Authentication;

use Admin42\Model\User;
use Admin42\TableGateway\UserTableGateway;
use Zend\Authentication\Result;

class AuthenticationService extends \Core42\Authentication\AuthenticationService
{
    /**
     * @var User
     */
    protected $identity;

    /**
     * @var UserTableGateway
     */
    protected $tableGateway;

    /**
     * @param UserTableGateway $tableGateway
     */
    public function setTableGateway(UserTableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    /**
     * Authenticates and provides an authentication result
     *
     * @return Result
     */
    public function authenticate()
    {
        $result = parent::authenticate();

        if (!$result->isValid()) {
            return $result;
        }

        $this->getIdentity();
    }

    /**
     * Returns the authenticated identity or null if no identity is available
     *
     * @return User|null
     */
    public function getIdentity()
    {
        if ($this->identity instanceof User) {
            return $this->identity;
        }

        $identity = parent::getIdentity();

        if (empty($identity)) {
            $this->clearIdentity();

            return;
        }

        $identity = $this->tableGateway->selectByPrimary($identity);
        if (!($identity instanceof User)) {
            $this->clearIdentity();

            return;
        }

        if (!\in_array($identity->getStatus(), [User::STATUS_ACTIVE])) {
            $this->clearIdentity();

            return;
        }

        $this->identity = $identity;

        return $identity;
    }

    /**
     * Clears the identity
     *
     * @return void
     */
    public function clearIdentity()
    {
        parent::clearIdentity();
        $this->identity = null;
    }

    /**
     * Returns true if and only if an identity is available
     *
     * @return bool
     */
    public function hasIdentity()
    {
        $storageCheck = !$this->getStorage()->isEmpty();
        if (!$storageCheck) {
            return false;
        }

        return $this->getIdentity() instanceof User;
    }
}


<?php

namespace Shoko\TwitchApiBundle\Factory;

use Shoko\TwitchApiBundle\Model\Entity\Stream;
use Shoko\TwitchApiBundle\Model\Entity\StreamList;

/**
 * Class StreamFactory.
 */
class StreamFactory implements FactoryInterface
{
    /**
     * @param array $data
     * @param false|Stream $stream
     *
     * @return Stream
     */
    public function createEntity(array $data, $stream = false)
    {
        if (false === $stream) {
            $stream = Stream::create();
        }

        if (isset($data['is_playlist'])) {
            $stream = $stream->setPlaylist($data['is_playlist']);
        }

        if (isset($data['game'])) {
            $stream = $stream->setGame($data['game']);
        }

        if (isset($data['delay'])) {
            $stream = $stream->setDelay($data['delay']);
        }

        if (isset($data['viewers'])) {
            $stream = $stream->setViewers($data['viewers']);
        }

        if (isset($data['created_at'])) {
            $stream = $stream->setCreatedAt(new \DateTime($data['created_at']));
        }

        if (isset($data['_links'])) {
            $stream = $stream->setLinks($data['_links']);
        }

        if (isset($data['_id'])) {
            $stream = $stream->setId($data['_id']);
        }

        if (isset($data['average_fps'])) {
            $stream = $stream->setAverageFps($data['average_fps']);
        }

        if (isset($data['video_height'])) {
            $stream = $stream->setVideoHeight($data['video_height']);
        }

        if (isset($data['channel'])) {
            $stream = $stream->setChannel((new ChannelFactory())->createEntity($data['channel']));
        }

        if (isset($data['preview'])) {
            $stream = $stream->setPreview($data['preview']);
        }

        return $stream;
    }

    /**
     * @param array            $data
     * @param false|StreamList $streamList
     *
     * @return StreamList
     */
    public function createList(array $data, $streamList = false)
    {
        if (false === $streamList) {
            $streamList = StreamList::create();
        }

        if (isset($data['streams'])) {
            $streamList = $streamList->setStreams($this->createStreams($data['streams']));
        }

        if (isset($data['_links'])) {
            $streamList = $streamList->setLinks($data['_links']);
        }

        if (isset($data['_total'])) {
            $streamList = $streamList->setTotal($data['_total']);
        }

        return $streamList;
    }

    /**
     * @param array $streams
     *
     * @return array
     */
    public function createStreams(array $streams)
    {
        $tmp = [];
        foreach ($streams as $entry) {
            $tmp[] = $this->createEntity($entry);
        }

        return $tmp;
    }

    /**
     * @param array $data
     *
     * @return FeaturedStreams
     */
    public function createFeatured(array $data)
    {
        return (new FeaturedFactory())->createEntity($data);
    }
}


<?php

namespace Shoko\TwitchApiBundle\Factory;

use Shoko\TwitchApiBundle\Model\ValueObject\Token;
use Shoko\TwitchApiBundle\Model\ValueObject\Authorization;

/**
 * Class TokenFactory.
 */
class TokenFactory implements FactoryInterface
{
    /**
     * @param array $data
     *
     * @return Authorization
     */
    protected function createAuthorization(array $data)
    {
        return Authorization::create($data);
    }

    /**
     * @param array $data
     * @param false|Token $token
     *
     * @return Token
     */
    public function createEntity(array $data, $token = false)
    {
        if (false === $token) {
            $token = Token::create();
        }

        if (isset($data['authorization'])) {
            $token = $token->setAuthorization($this->createAuthorization($data['authorization']));
        }

        if (isset($data['user_name'])) {
            $token = $token->setUserName($data['user_name']);
        }

        if (isset($data['valid'])) {
            $token = $token->setValid($data['valid']);
        }

        return $token;
    }
}


<?php

namespace Encore\Wx\Element;

use wxCalendarCtrl;
use Encore\Giml\ElementTrait;
use Encore\Giml\ElementInterface;
use Encore\Wx\Element\Traits\Wx;
use Encore\Wx\Element\Traits\Events;
use Encore\Wx\Element\Traits\Sizable;
use Encore\Wx\Element\Traits\Positionable;

class DatePicker implements ElementInterface
{
    use ElementTrait;
    use Events;
    use Wx;
    use Positionable;
    use Sizable;

    protected $events = [
        'onDayChange' => wxEVT_CALENDAR_DAY_CHANGED,
        'onMonthChange' => wxEVT_CALENDAR_MONTH_CHANGED,
        'onYearChange' => wxEVT_CALENDAR_YEAR_CHANGED,
        'onChange' => wxEVT_CALENDAR_SEL_CHANGED,
        'onDoubleClick' => wxEVT_CALENDAR_DOUBLECLICKED,
        'onClick' => wxEVT_CALENDAR_WEEKDAY_CLICKED
    ];

    /**
     * Initialise the object
     *
     * @return void
     */
    public function init()
    {
        $id = $this->collection->getTrueId($this->id);
        $date = $this->date ? strtotime($this->date) : wxDefaultDateTime;

        $this->element = new wxCalendarCtrl($this->parent->getParent()->getRaw(), $id, $date, $this->getPosition(), $this->getSize(), 0 );

        $this->bindEvents();

        $this->parent->getRaw()->Add($this->element);
    }
}


<?php

namespace DevGroup\Entity\traits;

use yii\db\ActiveRecord;
use yii\base\ModelEvent;
use Yii;

/**
 * Class SoftDeleteTrait
 * @property string $isDeletedAttribute
 * @package DevGroup\Entity\traits
 */
trait SoftDeleteTrait
{
    /**
     * @var bool whether to use a soft deletion.
     */
    protected $softMode = true;

    /**
     * Get a default attribute name.
     * If you need to set custom attribute name just add a field `isDeletedAttribute` to your model.
     * @return string
     */
    protected function getIsDeletedAttribute()
    {
        return 'is_deleted';
    }

    /**
     * Init a trait.
     * There is an event attaching here.
     */
    public function SoftDeleteTraitInit()
    {
        /** @var ActiveRecord $this */
        $this->on(
            ActiveRecord::EVENT_BEFORE_DELETE,
            [$this, 'SoftDeleteTraitInitHandler'],
            null,
            false
        );
    }

    /**
     * Get attribute labels list
     * @return array attributes list
     */
    public function SoftDeleteTraitAttributeLabels()
    {
        return [
            $this->isDeletedAttribute => Yii::t('entity', 'Deleted'),
        ];
    }

    /**
     * Get trait rules
     * @return array rules list
     */
    public function SoftDeleteTraitRules()
    {
        return [
            [$this->isDeletedAttribute, 'filter', 'filter' => 'boolval'],
        ];
    }

    /**
     * @param ModelEvent $event
     */
    public function SoftDeleteTraitInitHandler(ModelEvent $event)
    {
        if ($event->sender->softMode === true) {
            if ($event->sender->{$event->sender->isDeletedAttribute} != true) {
                $event->sender->{$event->sender->isDeletedAttribute} = true;
                $event->sender->save(false, [$event->sender->isDeletedAttribute]);
            }
            $event->isValid = false;
        }
    }

    /**
     * Delete a record from database.
     * @return false|int
     * @throws \Exception
     */
    public function hardDelete()
    {
        $this->softMode = false;
        /** @var ActiveRecord $this */
        return $this->delete();
    }

    /**
     * Restore a record after soft deleting.
     * @return bool
     */
    public function restore()
    {
        /** @var ActiveRecord $this */
        if (((boolean) $this->{$this->isDeletedAttribute}) !== false) {
            $this->{$this->isDeletedAttribute} = false;
            return $this->save(true, [$this->isDeletedAttribute]);
        }
        return true;
    }

    /**
     * Return Deleted Status
     * @return bool
     */
    public function isDeleted()
    {
        return (boolean) $this->{$this->isDeletedAttribute};
    }
}


<?php namespace Gears\Arrays\Conversions\From;
////////////////////////////////////////////////////////////////////////////////
// __________ __             ________                   __________
// \______   \  |__ ______  /  _____/  ____ _____ ______\______   \ _______  ___
//  |     ___/  |  \\____ \/   \  ____/ __ \\__  \\_  __ \    |  _//  _ \  \/  /
//  |    |   |   Y  \  |_> >    \_\  \  ___/ / __ \|  | \/    |   (  <_> >    <
//  |____|   |___|  /   __/ \______  /\___  >____  /__|  |______  /\____/__/\_ \
//                \/|__|           \/     \/     \/             \/            \/
// -----------------------------------------------------------------------------
//          Designed and Developed by Brad Jones <brad @="bjc.id.au" />
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////

use \Zend\Json\Json;
use \Gears\Arrays\Conversions\Template;

class Xml extends Template
{
	/**
	 * Property: drop_attributes
	 * =========================================================================
	 * Do we preserve the XML Attributes or do we simply ignore them.
	 */
	protected $drop_attributes = false;

	/**
	 * METHOD: Convert
	 * =========================================================================
	 * This will do the actual converting
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * $data - The XML to convert to an array
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * array
	 */
	public function Convert($data)
	{
		// Convert XML To JSON
		$json = Json::fromXml($data, $this->drop_attributes);

		// Convert the Json to PHP Array
		return json_decode($json, true);
	}
}


<?php

namespace Shoko\TwitchApiBundle\Repository;

use Shoko\TwitchApiBundle\Lib\Client;
use Shoko\TwitchApiBundle\Factory\FollowFactory;

/**
 * Class UserRepository.
 */
class UserRepository extends AbstractRepository
{
    const ENDPOINT = 'users/';

    /**
     * Get user.
     *
     * @param string $userId
     *
     * @return User
     */
    public function getUser($userId)
    {
        $response = $this->getClient()->get(self::ENDPOINT.$userId);
        $data = $this->jsonResponse($response);

        return $this->getFactory()->createEntity($data);
    }

    /**
     * Get user followed games.
     *
     * @param string $userId
     * @param array  $params
     *
     * @return GameList
     */
    public function getUserFollowedGames($userId, $params = array())
    {
        $params = 0 < count($params) ? '?'.http_build_query($params) : '';
        // need old api version to get user's followed games
        $client = $this->getClient()->setUrl(Client::URL_PROTOCOL.'://'.Client::URL_HOST.'/'.Client::URL_OLD_VERSION.'/');
        $response = $this->setClient($client)->getClient()->get(self::ENDPOINT.$userId.'/follows/games/live/'.$params);
        // reset api endpoint to current version
        $client = $this->getClient()->setUrl(Client::URL_PROTOCOL.'://'.Client::URL_HOST.'/'.Client::URL_VERSION.'/');
        $this->setClient($client);
        $data = $this->jsonResponse($response);

        return $this->setFactory(new FollowFactory())->getFactory()->createGameList($data);
    }
}


<?php

namespace SheaDawson\TimedNotice;

use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\ListboxField;
use SilverStripe\Forms\OptionsetField;
use SilverStripe\Forms\ReadonlyField;
use SilverStripe\Forms\RequiredFields;
use SilverStripe\Forms\TimeField;
use SilverStripe\ORM\ArrayLib;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\Security\Group;
use SilverStripe\Security\Member;
use SilverStripe\Security\PermissionProvider;
use SilverStripe\Security\Permission;
use UncleCheese\DisplayLogic\Extensions\DisplayLogic;

/**
 * TimedNotice
 *
 * @package timednotices
 * @author shea@silverstripe.com.au
 **/
class TimedNotice extends DataObject implements PermissionProvider
{

    /**
     * @var string
     */
    private static $singular_name = 'Timed Notice';

    /**
     * @var string
     */
    private static $plural_name = 'Timed Notices';

    /**
     * @var array
     */
    private static $db = [
        'Context'        => "Enum('Website,CMS','CMS')",
        'Message'        => 'Text',
        'MessageType'    => 'Varchar',
        'StartTime'      => 'Datetime',
        'EndTime'        => 'Datetime',
        'CanViewType'    => 'Enum("Anyone, LoggedInUsers, OnlyTheseUsers, LoggedInUsers")',
    ];

    /**
     * @var string
     */
    private static $table_name = "TimedNotice";

    /**
     * @var array
     */
    private static $many_many = [
        'ViewerGroups'   => Group::class,
    ];

    /**
     * @var array
     */
    private static $defaults = [
        'CanViewType'    => 'LoggedInUsers',
    ];

    /**
     * @var array
     */
    private static $summary_fields = [
        'StartTime'      => "Start Time",
        'EndTime'        => "End Time",
        'StatusLabel'    => "Status",
        'MessageType'    => "Message Type",
        'Message'        => "Message",
    ];

    /**
     * @var array
     */
    private static $searchable_fields = [
        'MessageType',
    ];

    /**
     * @var array
     */
    private static $message_types = [
        'good',
        'warning',
        'bad',
    ];

    /**
     * @var array
     */
    private static $status_options = [
        'Current',
        'Future',
        'Expired',
    ];

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

        $fields->removeFieldFromTab('Root', 'ViewerGroups');

        // prepare options for the target groups
        $viewersOptionsSource['Anyone'] = _t(
            'TimedNotice.ANYONE',
            'Anyone'
        );

        $viewersOptionsSource['LoggedInUsers'] = _t(
            'TimedNotice.ACCESSLOGGEDIN',
            'Logged-in users'
        );

        $viewersOptionsSource['OnlyTheseUsers'] = _t(
            'TimedNotice.ACCESSONLYTHESE',
            'Only these people (choose from list)'
        );

        $fields->addFieldToTab(
            'Root.Main',
            $canViewTypeField = OptionsetField::create(
                "CanViewType",
                _t('TimedNotice.ACCESSHEADER', "Who should see this notice?"),
                $viewersOptionsSource
            )
        );

        $groupsMap = Group::get()->map('ID', 'Breadcrumbs')->toArray();
        asort($groupsMap);

        $fields->addFieldToTab(
            'Root.Main',
            $viewerGroupsField = ListboxField::create(
                "ViewerGroups",
                _t('TimedNotice.VIEWERGROUPS', "Only people in these groups")
            )
            // ->setMultiple(true)
            ->setSource($groupsMap)
            ->setAttribute(
                'data-placeholder',
                _t('TimedNotice.GroupPlaceholder', 'Click to select group')
            )
        );

        $viewerGroupsField->displayIf("CanViewType")->isEqualTo("OnlyTheseUsers");

        $fields->addFieldToTab(
            'Root.Main',
            DropdownField::create(
                'MessageType',
                'Message Type',
                ArrayLib::valuekey($this->config()->get('message_types'))
            ),
            'Message'
        );

        $fields->addFieldToTab(
            'Root.Main',
            ReadonlyField::create(
                'TZNote',
                'Note',
                sprintf(_t(
                    'TimedNotice.TZNote',
                    'Your dates and times should be based on the server timezone: %s'),
                    date_default_timezone_get()
                )
            ),
            'StartTime'
        );

        $start = $fields->dataFieldByName('StartTime');
        $end   = $fields->dataFieldByName('EndTime');

        /**
         * ToDo: Add a calendar
         */
        // $start->getDateField()->setConfig('showcalendar', true);
        // $end->getDateField()->setConfig('showcalendar', true);

        // $start->setTimeField(
        //     TimeField::create('StartTime[time]', '')
        //         ->addExtraClass('fieldgroup-field')
        // );

        // $end->setTimeField(
        //     TimeField::create('EndTime[time]', '')
        //         ->addExtraClass('fieldgroup-field')
        // );

        return $fields;
    }

    /**
     * @return array
     */
    public function providePermissions()
    {
        return [
            'TIMEDNOTICE_EDIT' => [
                'name' => 'Edit a Timed Notice',
                'category' => 'Timed Notices',
            ],
            'TIMEDNOTICE_DELETE' => [
                'name' => 'Delete a Timed Notice',
                'category' => 'Timed Notices',
            ],
            'TIMEDNOTICE_CREATE' => [
                'name' => 'Create a Timed Notice',
                'category' => 'Timed Notices'
           ]
        ];
    }

    /**
     * Gets any notices relevant to the present time, context and current users
     *
     * @param string $context (default: CMS)
     * @return ArrayList
     **/
    public static function get_notices($context = null)
    {
        // fallback to the CMS as the context - this is required to be consistent with the original behaviour.
        if ($context == null) {
            $context = 'CMS';
        }

         // prepare and filter the possible result
        $now     = DBDatetime::now()->getValue();
        $member  = Member::currentUser();

        $notices = TimedNotice::get()->filter(
            [
                "Context" => $context,
                "StartTime:LessThan" => $now
            ]
        )->filterAny(
            [
                "EndTime:GreaterThan" => $now,
                "EndTime" => null
            ]
        );

         // if there are notices verify if those are allowed for this group
        if ($notices->count()) {
            // turn the DataList into an ArrayList to make it editable.
            $notices = ArrayList::create($notices->toArray());
             foreach ($notices as $notice) {
                if ($notice->CanViewType == 'OnlyTheseUsers') {
                    if ($member && !$member->inGroups($notice->ViewerGroups())) {
                        $notices->remove($notice);
                    }
                }
            }
        }

         return $notices;
    }

    /**
     * @return boolean
     */
    public function canView($member = null)
    {
        return true;
    }

    /**
     * @return boolean
     */
    public function canEdit($member = null)
    {
        return Permission::check('ADMIN') || Permission::check('TIMEDNOTICE_EDIT');
    }

    /**
     * @return boolean
     */
    public function canDelete($member = null)
    {
        return Permission::check('ADMIN') || Permission::check('TIMEDNOTICE_DELETE');
    }

    /**
     * @return boolean
     */
    public function canCreate($member = null, $content = [])
    {
        return Permission::check('ADMIN') || Permission::check('TIMEDNOTICE_CREATE');
    }

    /**
     * @return string
     */
    public function getStatusLabel()
    {
        $now = DBDatetime::now()->getValue();
        if ($this->StartTime > $now) {
            return 'Future';
        } elseif ($this->EndTime && $this->EndTime <= $now) {
            return 'Expired';
        } else {
            return 'Current';
        }
    }

    /**
     * @return RequiredFields
     */
    public function getCMSValidator()
    {
        return RequiredFields::create(
            [
                'Context',
                'Message',
                'StartTime'
            ]
        );
    }

    /**
     * @return TimedNotice $notice
     */
    public static function add_notice($message, $context, $end, $start = null, $type = 'good', $viewBy = null)
    {
        if (!$start) {
            $start = DBDatetime::now()->getValue();
        } else {
            $start = date('Y-m-d H:i:s', strtotime($start));
        }

        $end = date('Y-m-d H:i:s', strtotime($end));

        $notice = TimedNotice::create(
            [
                'Message'        => $message,
                'Context'        => $context,
                'StartTime'      => $start,
                'EndTime'        => $end,
                'CanViewType'    => 'LoggedInUsers',
                'MessageType'    => $type,
            ]
        );

        if ($viewBy == 'Anyone') {
            $notice->CanViewType = 'Anyone';
        }

        if ($viewBy instanceof Group) {
            $notice->CanViewType = 'OnlyTheseUsers';
        }

        $notice->write();

        if ($viewBy instanceof Group) {
            $notice->ViewerGroups()->add($viewBy);
        }

        return $notice;
    }
}


<?php

namespace Shoko\TwitchApiBundle\Repository;

use Shoko\TwitchApiBundle\Lib\Client;

/**
 * Class ChannelRepository.
 */
class ChannelRepository extends AbstractRepository
{
    const ENDPOINT = 'channels/';

    /**
     * Get channel.
     *
     * @param string $channelId
     *
     * @return Channel
     */
    public function getChannel($channelId)
    {
        $response = $this->getClient()->get(self::ENDPOINT.$channelId);
        $data = $this->jsonResponse($response);

        return $this->getFactory()->createEntity($data);
    }

    public function getChannelToken($channelId)
    {
        $client = $this->getClient()->setUrl(Client::URL_PROTOCOL.'://'.Client::URL_HOST.'/'.Client::URL_OLD_VERSION.'/');
        $response = $this->setClient($client)->getClient()->get(self::ENDPOINT.$channelId.'/access_token');
        // reset api endpoint to current version
        $client = $this->getClient()->setUrl(Client::URL_PROTOCOL.'://'.Client::URL_HOST.'/'.Client::URL_VERSION.'/');
        $this->setClient($client);
        $data = $this->jsonResponse($response);

        return $this->getFactory()->createChannelToken($data);
    }
}