<?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\Crud\Service;

use Interop\Container\ContainerInterface;
use Interop\Container\Exception\ContainerException;
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
use Zend\ServiceManager\Exception\ServiceNotFoundException;
use Zend\ServiceManager\Factory\AbstractFactoryInterface;

class CrudOptionsFallbackAbstractFactory implements AbstractFactoryInterface
{
    /**
     * @param string $name
     * @return bool|string
     */
    protected function getFQCN($name)
    {
        if (\class_exists($name)) {
            return $name;
        }

        if (\mb_strpos($name, '\\') === false) {
            return false;
        }

        $parts = \explode('\\', $name, 2);

        return '\\' . $parts[0] . '\\Crud\\' . $parts[1] . 'Options';
    }

    /**
     * Can the factory create an instance for the service?
     *
     * @param  ContainerInterface $container
     * @param  string $requestedName
     * @return bool
     */
    public function canCreate(ContainerInterface $container, $requestedName)
    {
        $fqcn = $this->getFQCN($requestedName);
        if ($fqcn === false) {
            return false;
        }

        return \class_exists($fqcn);
    }

    /**
     * Create an object
     *
     * @param  ContainerInterface $container
     * @param  string $requestedName
     * @param  null|array $options
     * @throws ServiceNotFoundException if unable to resolve the service
     * @throws ServiceNotCreatedException if an exception is raised when
     *     creating a service
     * @throws ContainerException if any other error occurs
     * @return object
     */
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $fqcn = $this->getFQCN($requestedName);

        return new $fqcn();
    }
}


<?php

namespace L5Starter\PermissionManager\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use L5Starter\PermissionManager\Http\Requests\CreateRoleRequest;
use L5Starter\PermissionManager\Http\Requests\UpdateRoleRequest;
use L5Starter\PermissionManager\Repositories\PermissionRepository;
use L5Starter\PermissionManager\Repositories\RoleRepository;
use Response;

class RoleController extends Controller
{
    private $roleRepository;
    private $permissionRepository;

    public function __construct(RoleRepository $roleRepository, PermissionRepository $permissionRepository)
    {
        $this->roleRepository = $roleRepository;
        $this->permissionRepository = $permissionRepository;
    }

    /**
     * Display a listing of the Role.
     *
     * @return Response
     */
    public function index()
    {
        $roles = $this->roleRepository->paginate(config('settings.resultsPerPage'));

        return view('roles::index')->with('roles', $roles);
    }

    /**
     * Show the form for creating a new Role.
     *
     * @return Response
     */
    public function create()
    {
        return view('roles::create')->with([
            'permissions' => $this->permissionRepository->all(),
        ]);
    }

    /**
     * Store a newly created Role in storage.
     *
     * @param CreateRoleRequest $request
     *
     * @return Response
     */
    public function store(CreateRoleRequest $request)
    {
        $input = $request->all();

        $role = $this->roleRepository->create([
            'name' => $input['name'],
        ]);

        foreach ($input['permissions'] as $permission) {
            $role->permissions()->attach($permission);
        }

        \Flash::success(trans('l5starter::messages.create.success'));

        return redirect(route('admin.roles.index'));
    }

    /**
     * Show the form for editing the specified Role.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $role = $this->roleRepository->findWithoutFail($id);

        if (empty($role)) {
            \Flash::error(trans('l5starter::messages.404_not_found'));

            return redirect(route('admin.roles.index'));
        }

        return view('roles::edit')->with([
            'permissions' => $this->permissionRepository->all(),
            'role' => $role,
        ]);
    }

    /**
     * Update the specified Role in storage.
     *
     * @param  int $id
     * @param UpdateRoleRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateRoleRequest $request)
    {
        $role = $this->roleRepository->findWithoutFail($id);

        if (empty($role)) {
            \Flash::error(trans('l5starter::messages.404_not_found'));

            return redirect(route('admin.roles.index'));
        }

        $input = $request->all();

        $role = $this->roleRepository->update([
            'name' => $input['name'],
        ], $id);

        $permissions = [];

        if (!empty($input['permissions'])) {
            foreach ($input['permissions'] as $permission) {
                $permissions[$permission] = $permission;
            }
        }

        $role->permissions()->sync($permissions);

        \Flash::success(trans('l5starter::messages.update.success'));

        return redirect(route('admin.roles.index'));
    }

    /**
     * Remove the specified Role from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $role = $this->roleRepository->findWithoutFail($id);

        if (empty($role)) {
            \Flash::error(trans('l5starter::messages.404_not_found'));

            return redirect(route('admin.roles.index'));
        }

        $this->roleRepository->delete($id);

        \Flash::success(trans('l5starter::messages.delete.success'));

        return redirect(route('admin.roles.index'));
    }
}


<?php

namespace Shoko\TwitchApiBundle\Lib;

use GuzzleHttp\Client as Guzzle;

/**
 * Client class.
 */
class Client
{
    /**
     * Url $protocol: https.
     */
    const URL_PROTOCOL = 'https';

    /**
     * Url $hostname: api.twitch.tv.
     */
    const URL_HOST = 'api.twitch.tv';

    /**
     * Url $version, Twitch api version: v3 - kraken.
     */
    const URL_VERSION = 'kraken';

    /**
     * Url old version, Twitch api old version: api.
     */
    const URL_OLD_VERSION = 'api';

    /**
     * Guzzle $guzzle.
     *
     * @var Guzzle
     */
    private $guzzle = null;

    /**
     * Headers $headers.
     *
     * @var array
     */
    private $headers = array();

    /**
     * Url string $url.
     *
     * @var string
     */
    private $url;

    /**
     * Constructor method.
     *
     * @param null|string $clientId
     * @param false|Guzzle $guzzle
     */
    public function __construct($clientId = null, $guzzle = false)
    {
        $this->guzzle = $guzzle ? $guzzle : new Guzzle();
        $this->url = self::URL_PROTOCOL.'://'.self::URL_HOST.'/'.self::URL_VERSION.'/';
        $this->headers = null !== $clientId ? array(
          'Accept' => 'application/vnd.twitchtv.v3+json',
          'Client-ID' => $clientId,
        ) : array(
          'Accept' => 'application/vnd.twitchtv.v3+json',
        );
    }

    /**
     * Get default twitch v3 api url.
     *
     * @return Url
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * Set url $url.
     *
     * @param string $url
     *
     * @return Client
     */
    public function setUrl($url)
    {
        $this->url = $url;

        return $this;
    }

    /**
     * Get headers.
     *
     * @return array
     */
    public function getHeaders()
    {
        return $this->headers;
    }

    /**
     * Set headers.
     *
     * @param array $headers
     *
     * @return Client
     */
    public function setHeaders(array $headers)
    {
        $this->headers = $headers;

        return $this;
    }

    /**
     * Get guzzle.
     *
     * @return Guzzle
     */
    public function getGuzzle()
    {
        return $this->guzzle;
    }

    /**
     * Set guzzle $guzzle.
     *
     * @param Guzzle $guzzle
     *
     * @return Client
     */
    public function setGuzzle(Guzzle $guzzle)
    {
        $this->guzzle = $guzzle;

        return $this;
    }

    /**
     * Get resource.
     *
     * @param string $resource
     * @param array  $headers
     *
     * @return \Guzzle\Http\Message\Response
     */
    public function get($resource, $headers = array())
    {
        return $this->getGuzzle()->request(
          'GET',
          $this->getUrl().$resource,
          ['headers' => array_merge($this->getHeaders(), $headers)]
        );
    }
}


<?php

/**
 * @file
 * TeamSpeak 3 PHP Framework
 *
 * $Id: Text.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\Viewer;

/**
 * @class TeamSpeak3_Viewer_Html
 * @brief Renders nodes used in HTML-based TeamSpeak 3 viewers.
 */
class Html implements ViewerInterface
{
  /**
   * A pre-defined pattern used to display a node in a TeamSpeak 3 viewer.
   *
   * @var string
   */
  protected $pattern = "

%4	%7 %8	%10%11

\n";

  /**
   * The TeamSpeak3_Node_Abstract object which is currently processed.
   *
   * @var \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\AbstractNode
   */
  protected $currObj = null;

  /**
   * An array filled with siblingsfor the  TeamSpeak3_Node_Abstract object which is currently
   * processed.
   *
   * @var array
   */
  protected $currSib = null;

  /**
   * An internal counter indicating the number of fetched TeamSpeak3_Node_Abstract objects.
   *
   * @var integer
   */
  protected $currNum = 0;

  /**
   * The relative URI path where the images used by the viewer can be found.
   *
   * @var string
   */
  protected $iconpath = null;

  /**
   * The relative URI path where the country flag icons used by the viewer can be found.
   *
   * @var string
   */
  protected $flagpath = null;

  /**
   * The relative path of the file transter client script on the server.
   *
   * @var string
   */
  protected $ftclient = null;

  /**
   * Stores an array of local icon IDs.
   *
   * @var array
   */
  protected $cachedIcons = array(100, 200, 300, 400, 500, 600);

  /**
   * Stores an array of remote icon IDs.
   *
   * @var array
   */
  protected $remoteIcons = array();

  /**
   * The TeamSpeak3_Viewer_Html constructor.
   *
   * @param  string $iconpath
   * @param  string $flagpath
   * @param  string $ftclient
   * @param  string $pattern
   * @return void
   */
  public function __construct($iconpath = "images/viewer/", $flagpath = null, $ftclient = null, $pattern = null)
  {
    $this->iconpath = $iconpath;
    $this->flagpath = $flagpath;
    $this->ftclient = $ftclient;

    if($pattern)
    {
      $this->pattern = $pattern;
    }
  }

  /**
   * Returns the code needed to display a node in a TeamSpeak 3 viewer.
   *
   * @param  \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\AbstractNode $node
   * @param  array $siblings
   * @return string
   */
  public function fetchObject(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\AbstractNode $node, array $siblings = array())
  {
    $this->currObj = $node;
    $this->currSib = $siblings;

    $args = array(
      $this->getContainerIdent(),
      $this->getContainerClass(),
      $this->getRowClass(),
      $this->getPrefixClass(),
      $this->getPrefix(),
      $this->getCorpusClass(),
      $this->getCorpusTitle(),
      $this->getCorpusIcon(),
      $this->getCorpusName(),
      $this->getSuffixClass(),
      $this->getSuffixIcon(),
      $this->getSuffixFlag(),
    );

    return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String::factory($this->pattern)->arg($args);
  }

  /**
   * Returns a unique identifier for the current node which can be used as a HTML id
   * property.
   *
   * @return string
   */
  protected function getContainerIdent()
  {
    return $this->currObj->getUniqueId();
  }

  /**
   * Returns a dynamic string for the current container element which can be used as
   * a HTML class property.
   *
   * @return string
   */
  protected function getContainerClass()
  {
    return "ts3_viewer " . $this->currObj->getClass(null);
  }

  /**
   * Returns a dynamic string for the current row element which can be used as a HTML
   * class property.
   *
   * @return string
   */
  protected function getRowClass()
  {
    return ++$this->currNum%2 ? "row1" : "row2";
  }

  /**
   * Returns a string for the current prefix element which can be used as a HTML class
   * property.
   *
   * @return string
   */
  protected function getPrefixClass()
  {
    return "prefix " . $this->currObj->getClass(null);
  }

  /**
   * Returns the HTML img tags to display the prefix of the current node.
   *
   * @return string
   */
  protected function getPrefix()
  {
    $prefix = "";

    if(count($this->currSib))
    {
      $last = array_pop($this->currSib);

      foreach($this->currSib as $sibling)
      {
        $prefix .=  ($sibling) ? $this->getImage("tree_line.gif") : $this->getImage("tree_blank.png");
      }

      $prefix .= ($last) ? $this->getImage("tree_end.gif") : $this->getImage("tree_mid.gif");
    }

    return $prefix;
  }

  /**
   * Returns a string for the current corpus element which can be used as a HTML class
   * property. If the current node is a channel spacer the class string will contain
   * additional class names to allow further customization of the content via CSS.
   *
   * @return string
   */
  protected function getCorpusClass()
  {
    $extras = "";

    if($this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Channel && $this->currObj->isSpacer())
    {
      switch($this->currObj->spacerGetType())
      {
        case (string) \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SPACER_SOLIDLINE:
          $extras .= " solidline";
          break;

        case (string) \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SPACER_DASHLINE:
          $extras .= " dashline";
          break;

        case (string) \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SPACER_DASHDOTLINE:
          $extras .= " dashdotline";
          break;

        case (string) \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SPACER_DASHDOTDOTLINE:
          $extras .= " dashdotdotline";
          break;

        case (string) \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SPACER_DOTLINE:
          $extras .= " dotline";
          break;
      }

      switch($this->currObj->spacerGetAlign())
      {
        case \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SPACER_ALIGN_CENTER:
          $extras .= " center";
          break;

        case \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SPACER_ALIGN_RIGHT:
          $extras .= " right";
          break;

        case \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SPACER_ALIGN_LEFT:
          $extras .= " left";
          break;
      }
    }

    return "corpus " . $this->currObj->getClass(null) . $extras;
  }

  /**
   * Returns the HTML img tags which can be used to display the various icons for a
   * TeamSpeak_Node_Abstract object.
   *
   * @return string
   */
  protected function getCorpusTitle()
  {
    if($this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Server)
    {
      return "ID: " . $this->currObj->getId() . " | Clients: " . $this->currObj->clientCount() . "/" . $this->currObj["virtualserver_maxclients"] . " | Uptime: " . \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Convert::seconds($this->currObj["virtualserver_uptime"]);
    }
    elseif($this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Channel && !$this->currObj->isSpacer())
    {
      return "ID: " . $this->currObj->getId() . " | Codec: " . \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Convert::codec($this->currObj["channel_codec"]) . " | Quality: " . $this->currObj["channel_codec_quality"];
    }
    elseif($this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Client)
    {
      return "ID: " . $this->currObj->getId() . " | Version: " . \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Convert::version($this->currObj["client_version"]) . " | Platform: " . $this->currObj["client_platform"];
    }
    elseif($this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Servergroup || $this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Channelgroup)
    {
      return "ID: " . $this->currObj->getId() . " | Type: " . \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Convert::groupType($this->currObj["type"]) . " (" . ($this->currObj["savedb"] ? "Permanent" : "Temporary") . ")";
    }
  }

  /**
   * Returns a HTML img tag which can be used to display the status icon for a
   * TeamSpeak_Node_Abstract object.
   *
   * @return string
   */
  protected function getCorpusIcon()
  {
    if($this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Channel && $this->currObj->isSpacer()) return;

    return $this->getImage($this->currObj->getIcon() . ".png");
  }

  /**
   * Returns a string for the current corpus element which contains the display name
   * for the current TeamSpeak_Node_Abstract object.
   *
   * @return string
   */
  protected function getCorpusName()
  {
    if($this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Channel && $this->currObj->isSpacer())
    {
      if($this->currObj->spacerGetType() != \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SPACER_CUSTOM) return;

      $string = $this->currObj["channel_name"]->section("]", 1);

      if($this->currObj->spacerGetAlign() == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SPACER_ALIGN_REPEAT)
      {
        $string->resize(30, $string);
      }

      return htmlspecialchars($string);
    }

    if($this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Client)
    {
      $before = array();
      $behind = array();

      foreach($this->currObj->memberOf() as $group)
      {
        if($group->getProperty("namemode") == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::GROUP_NAMEMODE_BEFORE)
        {
          $before[] = "[" . htmlspecialchars($group["name"]) . "]";
        }
        elseif($group->getProperty("namemode") == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::GROUP_NAMEMODE_BEHIND)
        {
          $behind[] = "[" . htmlspecialchars($group["name"]) . "]";
        }
      }

      return implode("", $before) . " " . htmlspecialchars($this->currObj) . " " . implode("", $behind);
    }

    return htmlspecialchars($this->currObj);
  }

  /**
   * Returns a string for the current suffix element which can be used as a HTML
   * class property.
   *
   * @return string
   */
  protected function getSuffixClass()
  {
    return "suffix " . $this->currObj->getClass(null);
  }

  /**
   * Returns the HTML img tags which can be used to display the various icons for a
   * TeamSpeak_Node_Abstract object.
   *
   * @return string
   */
  protected function getSuffixIcon()
  {
    if($this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Server)
    {
      return $this->getSuffixIconServer();
    }
    elseif($this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Channel)
    {
      return $this->getSuffixIconChannel();
    }
    elseif($this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Client)
    {
      return $this->getSuffixIconClient();
    }
  }

  /**
   * Returns the HTML img tags which can be used to display the various icons for a
   * TeamSpeak_Node_Server object.
   *
   * @return string
   */
  protected function getSuffixIconServer()
  {
    $html = "";

    if($this->currObj["virtualserver_icon_id"])
    {
      if(!$this->currObj->iconIsLocal("virtualserver_icon_id") && $this->ftclient)
      {
        if(!isset($this->cacheIcon[$this->currObj["virtualserver_icon_id"]]))
        {
          $download = $this->currObj->transferInitDownload(rand(0x0000, 0xFFFF), 0, $this->currObj->iconGetName("virtualserver_icon_id"));

          if($this->ftclient == "data:image")
          {
            $download = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3::factory("filetransfer://" . $download["host"] . ":" . $download["port"])->download($download["ftkey"], $download["size"]);
          }

          $this->cacheIcon[$this->currObj["virtualserver_icon_id"]] = $download;
        }
        else
        {
          $download = $this->cacheIcon[$this->currObj["virtualserver_icon_id"]];
        }

        if($this->ftclient == "data:image")
        {
          $html .= $this->getImage("data:" . \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Convert::imageMimeType($download) . ";base64," . base64_encode($download), "Server Icon", null, FALSE);
        }
        else
        {
          $html .= $this->getImage($this->ftclient . "?ftdata=" . base64_encode(serialize($download)), "Server Icon", null, FALSE);
        }
      }
      elseif(in_array($this->currObj["virtualserver_icon_id"], $this->cachedIcons))
      {
        $html .= $this->getImage("group_icon_" . $this->currObj["virtualserver_icon_id"] . ".png", "Server Icon");
      }
    }

    return $html;
  }

  /**
   * Returns the HTML img tags which can be used to display the various icons for a
   * TeamSpeak_Node_Channel object.
   *
   * @return string
   */
  protected function getSuffixIconChannel()
  {
    if($this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Channel && $this->currObj->isSpacer()) return;

    $html = "";

    if($this->currObj["channel_flag_default"])
    {
      $html .= $this->getImage("channel_flag_default.png", "Default Channel");
    }

    if($this->currObj["channel_flag_password"])
    {
      $html .= $this->getImage("channel_flag_password.png", "Password-protected");
    }

    if($this->currObj["channel_codec"] == 3)
    {
      $html .= $this->getImage("channel_flag_music.png", "Music Codec");
    }

    if($this->currObj["channel_needed_talk_power"])
    {
      $html .= $this->getImage("channel_flag_moderated.png", "Moderated");
    }

    if($this->currObj["channel_icon_id"])
    {
      if(!$this->currObj->iconIsLocal("channel_icon_id") && $this->ftclient)
      {
        if(!isset($this->cacheIcon[$this->currObj["channel_icon_id"]]))
        {
          $download = $this->currObj->getParent()->transferInitDownload(rand(0x0000, 0xFFFF), 0, $this->currObj->iconGetName("channel_icon_id"));

          if($this->ftclient == "data:image")
          {
            $download = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3::factory("filetransfer://" . $download["host"] . ":" . $download["port"])->download($download["ftkey"], $download["size"]);
          }

          $this->cacheIcon[$this->currObj["channel_icon_id"]] = $download;
        }
        else
        {
          $download = $this->cacheIcon[$this->currObj["channel_icon_id"]];
        }

        if($this->ftclient == "data:image")
        {
          $html .= $this->getImage("data:" . \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Convert::imageMimeType($download) . ";base64," . base64_encode($download), "Channel Icon", null, FALSE);
        }
        else
        {
          $html .= $this->getImage($this->ftclient . "?ftdata=" . base64_encode(serialize($download)), "Channel Icon", null, FALSE);
        }
      }
      elseif(in_array($this->currObj["channel_icon_id"], $this->cachedIcons))
      {
        $html .= $this->getImage("group_icon_" . $this->currObj["channel_icon_id"] . ".png", "Channel Icon");
      }
    }

    return $html;
  }

  /**
   * Returns the HTML img tags which can be used to display the various icons for a
   * TeamSpeak_Node_Client object.
   *
   * @return string
   */
  protected function getSuffixIconClient()
  {
    $html = "";

    if($this->currObj["client_is_priority_speaker"])
    {
      $html .= $this->getImage("client_priority.png", "Priority Speaker");
    }

    if($this->currObj["client_is_channel_commander"])
    {
      $html .= $this->getImage("client_cc.png", "Channel Commander");
    }

    if($this->currObj["client_is_talker"])
    {
      $html .= $this->getImage("client_talker.png", "Talk Power granted");
    }

    foreach($this->currObj->memberOf() as $group)
    {
      if(!$group["iconid"]) continue;

      $type = ($group instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Servergroup) ? "Server Group" : "Channel Group";

      if(!$group->iconIsLocal("iconid") && $this->ftclient)
      {
        if(!isset($this->cacheIcon[$group["iconid"]]))
        {
          $download = $group->getParent()->transferInitDownload(rand(0x0000, 0xFFFF), 0, $group->iconGetName("iconid"));

          if($this->ftclient == "data:image")
          {
            $download = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3::factory("filetransfer://" . $download["host"] . ":" . $download["port"])->download($download["ftkey"], $download["size"]);
          }

          $this->cacheIcon[$group["iconid"]] = $download;
        }
        else
        {
          $download = $this->cacheIcon[$group["iconid"]];
        }

        if($this->ftclient == "data:image")
        {
          $html .= $this->getImage("data:" . \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Convert::imageMimeType($download) . ";base64," . base64_encode($download), $group . " [" . $type . "]", null, FALSE);
        }
        else
        {
          $html .= $this->getImage($this->ftclient . "?ftdata=" . base64_encode(serialize($download)), $group . " [" . $type . "]", null, FALSE);
        }
      }
      elseif(in_array($group["iconid"], $this->cachedIcons))
      {
        $html .= $this->getImage("group_icon_" . $group["iconid"] . ".png", $group . " [" . $type . "]");
      }
    }

    if($this->currObj["client_icon_id"])
    {
      if(!$this->currObj->iconIsLocal("client_icon_id") && $this->ftclient)
      {
        if(!isset($this->cacheIcon[$this->currObj["client_icon_id"]]))
        {
          $download = $this->currObj->getParent()->transferInitDownload(rand(0x0000, 0xFFFF), 0, $this->currObj->iconGetName("client_icon_id"));

          if($this->ftclient == "data:image")
          {
            $download = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3::factory("filetransfer://" . $download["host"] . ":" . $download["port"])->download($download["ftkey"], $download["size"]);
          }

          $this->cacheIcon[$this->currObj["client_icon_id"]] = $download;
        }
        else
        {
          $download = $this->cacheIcon[$this->currObj["client_icon_id"]];
        }

        if($this->ftclient == "data:image")
        {
          $html .= $this->getImage("data:" . \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Convert::imageMimeType($download) . ";base64," . base64_encode($download), "Client Icon", null, FALSE);
        }
        else
        {
          $html .= $this->getImage($this->ftclient . "?ftdata=" . base64_encode(serialize($download)), "Client Icon", null, FALSE);
        }
      }
      elseif(in_array($this->currObj["client_icon_id"], $this->cachedIcons))
      {
        $html .= $this->getImage("group_icon_" . $this->currObj["client_icon_id"] . ".png", "Client Icon");
      }
    }

    return $html;
  }

  /**
   * Returns a HTML img tag which can be used to display the country flag for a
   * TeamSpeak_Node_Client object.
   *
   * @return string
   */
  protected function getSuffixFlag()
  {
    if(!$this->currObj instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Client) return;

    if($this->flagpath && $this->currObj["client_country"])
    {
      return $this->getImage($this->currObj["client_country"]->toLower() . ".png", $this->currObj["client_country"], null, FALSE, TRUE);
    }
  }

  /**
   * Returns the code to display a custom HTML img tag.
   *
   * @param  string  $name
   * @param  string  $text
   * @param  string  $class
   * @param  boolean $iconpath
   * @param  boolean $flagpath
   * @return string
   */
  protected function getImage($name, $text = "", $class = null, $iconpath = TRUE, $flagpath = FALSE)
  {
    $src = "";

    if($iconpath)
    {
      $src = $this->iconpath;
    }

    if($flagpath)
    {
      $src = $this->flagpath;
    }

    return "";
  }
}


<?php

/**
 * @file
 * TeamSpeak 3 PHP Framework
 *
 * $Id: FileTransfer.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_FileTransfer
 * @brief Provides low-level methods for file transfer communication with a TeamSpeak 3 Server.
 */
class FileTransfer extends AbstractAdapter
{
  /**
   * Connects the TeamSpeak3_Transport_Abstract object and performs initial actions on the remote
   * server.
   *
   * @throws TeamSpeak3_Adapter_Exception
   * @return void
   */
  public function syn()
  {
    $this->initTransport($this->options);
    $this->transport->setAdapter($this);

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

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

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

  /**
   * Sends a valid file transfer key to the server to initialize the file transfer.
   *
   * @param  string $ftkey
   * @throws FileTransfer\Exception
   * @return void
   */
  protected function init($ftkey)
  {
    if(strlen($ftkey) != 32)
    {
      throw new FileTransfer\Exception("invalid file transfer key format");
    }

    $this->getProfiler()->start();
    $this->getTransport()->send($ftkey);

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

  /**
   * Sends the content of a file to the server.
   *
   * @param  string  $ftkey
   * @param  integer $seek
   * @param  string  $data
   * @throws FileTransfer\Exception
   * @return void
   */
  public function upload($ftkey, $seek, $data)
  {
    $this->init($ftkey);

    $size = strlen($data);
    $seek = intval($seek);
    $pack = 4096;

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("filetransferUploadStarted", $ftkey, $seek, $size);

    for(;$seek < $size;)
    {
      $rest = $size-$seek;
      $pack = $rest < $pack ? $rest : $pack;
      $buff = substr($data, $seek, $pack);
      $seek = $seek+$pack;

      $this->getTransport()->send($buff);

      \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("filetransferUploadProgress", $ftkey, $seek, $size);
    }

    $this->getProfiler()->stop();

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("filetransferUploadFinished", $ftkey, $seek, $size);

    if($seek < $size)
    {
      throw new FileTransfer\Exception("incomplete file upload (" . $seek . " of " . $size . " bytes)");
    }
  }

  /**
   * Returns the content of a downloaded file as a \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String object.
   *
   * @param  string  $ftkey
   * @param  integer $size
   * @param  boolean $passthru
   * @throws FileTransfer\Exception
   * @return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String
   */
  public function download($ftkey, $size, $passthru = FALSE)
  {
    $this->init($ftkey);

    if($passthru)
    {
      return $this->passthru($size);
    }

    $buff = new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String("");
    $size = intval($size);
    $pack = 4096;

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("filetransferDownloadStarted", $ftkey, count($buff), $size);

    for($seek = 0;$seek < $size;)
    {
      $rest = $size-$seek;
      $pack = $rest < $pack ? $rest : $pack;
      $data = $this->getTransport()->read($rest < $pack ? $rest : $pack);
      $seek = $seek+$pack;

      $buff->append($data);

      \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("filetransferDownloadProgress", $ftkey, count($buff), $size);
    }

    $this->getProfiler()->stop();

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("filetransferDownloadFinished", $ftkey, count($buff), $size);

    if(strlen($buff) != $size)
    {
      throw new FileTransfer\Exception("incomplete file download (" . count($buff) . " of " . $size . " bytes)");
    }

    return $buff;
  }

  /**
   * Outputs all remaining data on a TeamSpeak 3 file transfer stream using PHP's fpassthru()
   * function.
   *
   * @param  integer $size
   * @throws FileTransfer\Exception
   * @return void
   */
  protected function passthru($size)
  {
    $buff_size = fpassthru($this->getTransport()->getStream());

    if($buff_size != $size)
    {
      throw new FileTransfer\Exception("incomplete file download (" . intval($buff_size) . " of " . $size . " bytes)");
    }
  }
}


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

use \Gears\Arrays\Conversions\Template;

class Csv extends Template
{
	/**
	 * Property: delimiter
	 * =========================================================================
	 * This is the delimiter or seperator that is used in the CSV.
	 * For example you could actually turn this into a TSV Driver by using "\t"
	 *
	 * Defaults to ,
	 */
	protected $delimiter = ',';

	/**
	 * Property: enclosure
	 * =========================================================================
	 * This is the character that is used to enclose or surround the values.
	 * Eg:
	 * 	row1, abc, 123			(WITHOUT ENCLOSURE)
	 * 	"row2", "abc", "123"	(WITH ENCLOSURE)
	 *
	 * Defaults to "
	 */
	protected $enclosure = '"';

	/**
	 * Property: memory
	 * =========================================================================
	 * This is the amount of memory that we will take up to create a
	 * file pointer to a temporay place in main memory.
	 *
	 * Defaults to 5MB
	 */
	protected $memory = 5;

	/**
	 * Property: length
	 * =========================================================================
	 * Must be greater than the longest line (in characters) to be found in the
	 * CSV (allowing for trailing line-end characters). It became optional in
	 * PHP 5 and setting it to 0 will let PHP work it out for you.
	 * However it is slightly slower.
	 *
	 * Defaults to 0
	 */
	protected $length = 0;

	/**
	 * Property: headings
	 * =========================================================================
	 * Do we treat the first row in the CSV as headings for our array.
	 * Or do we just output a number indexed array.
	 *
	 * Defaults to true
	 */
	protected $headings = true;

	/**
	 * Method: Convert
	 * =========================================================================
	 * This will do the actual converting
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * $csv - The CSV to convert to an array
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * array
	 */
	public function Convert($csv)
	{
		// Create a file pointer to our CSV Data
		$fp = fopen('php://temp/maxmemory:'.$this->memory*(1024*1024), 'r+');
		fputs($fp, $csv);
		rewind($fp);

		// Loop through the CSV Lines
		$row = 1; $rows = array();
		while (($data = fgetcsv($fp, $this->length, $this->delimiter, $this->enclosure)) !== false)
		{
			// Create the heading array
			if ($this->headings == true && $row == 1) $headingTexts = $data;

			// Add the csv line into the array using the heading names
			elseif ($this->headings == true)
			{
				foreach ($data as $key => $value)
				{
					unset($data[$key]);
					$data[$headingTexts[$key]] = $value;
				}
				$rows[] = $data;
			}

			// Otherwise dont worry about the headings at all
			else $rows[] = $data;

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

		// Finish Up
		fclose($fp);
		return $rows;
	}
}


<?php
/**
 * Openbizx Framework
 *
 * This file contain BizApplication class, the C from MVC of phpOpenBiz framework,
 * and execute it. So bootstrap script simply include this file. For sample of
 * bootstrap script please see controller.php under baseapp/bin
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: BizApplication.php 5321 2013-03-21 07:20:24Z rockyswen@gmail.com $
 */

namespace Openbizx;

use Openbizx\Openbizx;
use Openbizx\Core\TypeManager;
use Openbizx\Helpers\XHProf;
use Openbizx\Web\ClientProxy;
use Openbizx\Web\Request;
use Openbizx\Web\SessionContext;
use Openbizx\Web\UserAgent;
use Openbizx\Object\ObjectFactoryHelper;
use Openbizx\Helpers\MessageHelper;

// run controller
//
//session_cache_limiter('public');
//ob_start();

// @todo move to response / clientproxy object
//header('Content-Type: text/html; charset=utf-8');

//include_once("sysheader_inc.php");

/**
 * BizApplication is the class that dispatches client requests to proper objects
 *
 * @package   openbiz.bin
 * @author    Rocky Swen <rocky@phpopenbiz.org>
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @access    public
 */
class Application //extends \Openbizx\Object\Object
{

    const DEFAULT_THEME = 'default';

    /**
     * Request object, initialized when BizApplication created
     * @var Request
     */
    public $request;
    public $timeZone = 'Asia/jakarta';
    private $_userTimeoutView = OPENBIZ_USER_TIMEOUT_WEBPAGE;
    private $_accessDeniedView = OPENBIZ_ACCESS_DENIED_WEBPAGE;
    private $_securityDeniedView = OPENBIZ_SECURITY_DENIED_WEBPAGE;
    private $_defaultThemeName;
    private $_cssUrl;
    private $_jsUrl;
    private $_currentTheme;
    private $_modulePath = null;

    public function __construct()
    {
        Openbizx::$app = $this;

        //$this->isInitialized = true;
        // preInit
        // registerErrorHandlers
        // registerCoreComponent

        $this->request = new Request($this);
        $this->initSystemDefaultTimezone();

        // define default class alias
        $classAliases = [
            'BizDataObj' => 'Openbizx\\Data\\BizDataObj',
            'BizField' => 'Openbizx\\Data\\BizField',
            'EasyForm' => 'Openbizx\\Easy\\EasyForm',
            'EasyFormTree' => 'Openbizx\\Easy\\EasyForm',
            'WebPage' => 'Openbizx\\Easy\\WebPage',
            'PickerForm' => 'Openbizx\\Easy\\PickerForm',
            'FormReference' => 'Openbizx\\Easy\\FormReference',
            'AutoSuggest' => 'Openbizx\\Easy\\Element\\AutoSuggest',
            'BarcodeScanner' => 'Openbizx\\Easy\\Element\\BarcodeScanner',
            'Button' => 'Openbizx\\Easy\\Element\\Button',
            'Checkbox' => 'Openbizx\\Easy\\Element\\Checkbox',
            'CheckListbox' => 'Openbizx\\Easy\\Element\\CheckListbox',
            'CKEditor' => 'Openbizx\\Easy\\Element\\CKEditor',
            'ColorPicker' => 'Openbizx\\Easy\\Element\\ColorPicker',
            'ColumnBar' => 'Openbizx\\Easy\\Element\\ColumnBar',
            'ColumnBool' => 'Openbizx\\Easy\\Element\\ColumnBool',
            'ColumnHidden' => 'Openbizx\\Easy\\Element\\ColumnHidden',
            'ColumnImage' => 'Openbizx\\Easy\\Element\\ColumnImage',
            'ColumnInputText' => 'Openbizx\\Easy\\Element\\ColumnInputText',
            'ColumnList' => 'Openbizx\\Easy\\Element\\ColumnList',
            'ColumnListbox' => 'Openbizx\\Easy\\Element\\ColumnListbox',
            'ColumnPassword' => 'Openbizx\\Easy\\Element\\ColumnPassword',
            'ColumnShare' => 'Openbizx\\Easy\\Element\\ColumnShare',
            'ColumnSorting' => 'Openbizx\\Easy\\Element\\ColumnSorting',
            'ColumnStyle' => 'Openbizx\\Easy\\Element\\ColumnStyle',
            'ColumnText' => 'Openbizx\\Easy\\Element\\ColumnText',
            'ColumnValue' => 'Openbizx\\Easy\\Element\\ColumnValue',
            'DropDownList' => 'Openbizx\\Easy\\Element\\DropDownList',
            'EditCombobox' => 'Openbizx\\Easy\\Element\\EditCombobox',
            'Element' => 'Openbizx\\Easy\\Element\\Element',
            'EventHandler' => 'Openbizx\\Easy\\Element\\EventHandler',
            'File' => 'Openbizx\\Easy\\Element\\File',
            'FileInput' => 'Openbizx\\Easy\\Element\\FileInput',
            'FileUploader' => 'Openbizx\\Easy\\Element\\FileUploader',
            'FormElement' => 'Openbizx\\Easy\\Element\\FormElement',
            'Hidden' => 'Openbizx\\Easy\\Element\\Hidden',
            'HTMLBlock' => 'Openbizx\\Easy\\Element\\HTMLBlock',
            'HTMLButton' => 'Openbizx\\Easy\\Element\\HTMLButton',
            'HTMLPreview' => 'Openbizx\\Easy\\Element\\HTMLPreview',
            'IDCardReader' => 'Openbizx\\Easy\\Element\\IDCardReader',
            'IFrameBox' => 'Openbizx\\Easy\\Element\\IFrameBox',
            'ImageSelector' => 'Openbizx\\Easy\\Element\\ImageUploader',
            'ImageUploader' => 'Openbizx\\Easy\\Element\\ImageUploader',
            'InputDate' => 'Openbizx\\Easy\\Element\\InputDate',
            'InputDateRangePicker' => 'Openbizx\\Easy\\Element\\InputDateRangePicker',
            'InputDatetime' => 'Openbizx\\Easy\\Element\\InputDatetime',
            'InputElement' => 'Openbizx\\Easy\\Element\\InputElement',
            'InputPassword' => 'Openbizx\\Easy\\Element\\InputPassword',
            'InputPicker' => 'Openbizx\\Easy\\Element\\InputPicker',
            'InputText' => 'Openbizx\\Easy\\Element\\InputText',
            'LabelBack' => 'Openbizx\\Easy\\Element\\LabelBack',
            'LabelBar' => 'Openbizx\\Easy\\Element\\LabelBar',
            'LabelBool' => 'Openbizx\\Easy\\Element\\LabelBool',
            'LabelImage' => 'Openbizx\\Easy\\Element\\LabelImage',
            'LabelList' => 'Openbizx\\Easy\\Element\\LabelList',
            'LabelPassword' => 'Openbizx\\Easy\\Element\\LabelPassword',
            'LabelText' => 'Openbizx\\Easy\\Element\\LabelText',
            'LabelTextarea' => 'Openbizx\\Easy\\Element\\LabelTextarea',
            'LabelTextPaging' => 'Openbizx\\Easy\\Element\\LabelTextPaging',
            'Listbox' => 'Openbizx\\Easy\\Element\\Listbox',
            'OptionElement' => 'Openbizx\\Easy\\Element\\OptionElement',
            'PageSelector' => 'Openbizx\\Easy\\Element\\PageSelector',
            'PagesizeSelector' => 'Openbizx\\Easy\\Element\\PagesizeSelector',
            'Password' => 'Openbizx\\Easy\\Element\\Password',
            'Radio' => 'Openbizx\\Easy\\Element\\Radio',
            'RawData' => 'Openbizx\\Easy\\Element\\RawData',
            'ResetButton' => 'Openbizx\\Easy\\Element\\ResetButton',
            'RichText' => 'Openbizx\\Easy\\Element\\RichText',
            'RowCheckbox' => 'Openbizx\\Easy\\Element\\RowCheckbox',
            'Spacer' => 'Openbizx\\Easy\\Element\\Spacer',
            'SubmitButton' => 'Openbizx\\Easy\\Element\\SubmitButton',
            'Textarea' => 'Openbizx\\Easy\\Element\\Textarea',
            'TreeLabelText' => 'Openbizx\\Easy\\Element\\TreeLabelText',
            'TreeListbox' => 'Openbizx\\Easy\\Element\\TreeListbox',
        ];

        Openbizx::objectFactory()->setClassAliases($classAliases);
    }

    private $_confgiuration = null;

    /**
     * Get the Configuration object
     *
     * @return Configuration the Configuration object
     */
    public function getConfiguration()
    {
        if (!$this->_confgiuration) {
            $this->_confgiuration = new ApplicationConfiguration();
        }
        return $this->_confgiuration;
    }

    private $_clientProxy = null;

    /**
     * Get the ClientProxy object
     *
     * @return ClientProxy the ClientProxy object
     */
    public function getClientProxy()
    {
        if (!$this->_clientProxy) {
            $this->_clientProxy = new ClientProxy();
        }
        return $this->_clientProxy;
    }

    private $_sessionContext = null; // instant of SessionContext class

    /**
     * Get the SessionContext object
     *
     * @return \Openbizx\Web\SessionContext the SessionContext object
     */

    public function getSessionContext()
    {
        if (!$this->_sessionContext) {
            $this->_sessionContext = new SessionContext();
            $this->_sessionContext->retrieveSessionObjects();
        }
        return $this->_sessionContext;
    }

    private $_typeManager = null;

    /**
     * Get the TypeManager object
     *
     * @return TypeManager the TypeManager object
     */
    public function getTypeManager()
    {
        if (!$this->_typeManager) {
            $this->_typeManager = new TypeManager();

            /* @var $localeInfoService localeInfoService */
            $localeInfoService = Openbizx::getService(LOCALEINFO_SERVICE);
            $localeInfo = $localeInfoService->getLocaleInfo();

            if ($localeInfo) {
                $this->_typeManager->setLocaleInfo($localeInfo);
            }
        }
        return $this->_typeManager;
    }

    private $_dbConnection = array();

    /**
     * Get the database connection object
     *
     * @param string $dbName    database name declared in config.xml
     * @return \Zend_Db_Adapter_Abstract
     */
    public function getDBConnection($dbName = null)
    {
        $rDBName = (!$dbName) ? "Default" : $dbName;
        if (isset($this->_dbConnection[$rDBName])) {
            $db = $this->_dbConnection[$rDBName];
            if (!CLI) {
                return $db;
            }
        }

        $dbInfo = $this->getConfiguration()->getDatabaseInfo($rDBName);

        //require_once 'Zend/Db.php';

        $params = array(
            'host' => $dbInfo["Server"],
            'username' => $dbInfo["User"],
            'password' => $dbInfo["Password"],
            'dbname' => $dbInfo["DBName"],
            'port' => $dbInfo["Port"],
            'charset' => $dbInfo["Charset"]
        );
        if ($dbInfo["Options"]) {
            $options = explode(";", $dbInfo["Options"]);
            foreach ($options as $opt) {
                list($k, $v) = explode("=", $opt);
                $params[$k] = $v;
            }
        }
        foreach ($params as $name => $val) {
            if (empty($val)) {
                unset($params[$name]);
            }
        }
        if (strtoupper($dbInfo["Driver"]) == "PDO_MYSQL") {
            $pdoParams = array(
                \PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
            );
            $params["driver_options"] = $pdoParams;
        }

        $db = \Zend_Db::factory($dbInfo["Driver"], $params);
        $db->setFetchMode(\PDO::FETCH_NUM);

        if (strtoupper($dbInfo["Driver"]) == "PDO_MYSQL" &&
                $dbInfo["Charset"] != "") {
            $db->query("SET NAMES '" . $params['charset'] . "'");
        }
        $this->_dbConnection[$rDBName] = $db;
        return $db;
    }

    /**
     * Remove database connection by name
     * @param string $dbName
     * @return \Zend_Db_Adapter_Abstract
     */
    public function removeDBConnection($dbName = "Default")
    {
        if (isset($this->_dbConnection[$dbName])) {
            $this->_dbConnection[$dbName]->closeConnection();
            unset($this->_dbConnection[$dbName]);
        }
        return $this->getDBConnection($dbName);
    }

//=========================================

    private $_defaultModule = 'user';

    /**
     * Get default URL
     * @return string
     */
    public function getDefaultModule()
    {
        return $this->_defaultModule;
    }

    /**
     * Set default module name.
     * @param string $module new module name
     */
    public function setDefaultModule($module)
    {
        $this->_defaultModule = $module;
    }

    private $_defaultShortView = "LoginView";

    /**
     * Get default view name, without namespace
     * @return type
     */
    public function getDefaultShortView()
    {
        return $this->_defaultShortView;
    }

    /**
     * Set default view
     * @param string $view view name, without namespace
     */
    public function setDefaultShortView($view)
    {
        $this->_defaultShortView = $view;
    }

    private $_defaultUrl;

    /**
     * Get default URL.
     * @return string
     */
    public function getDefaultUrl()
    {
        if (!$this->_defaultUrl) {
            $this->_defaultUrl = 'index.php/' . $this->getDefaultModule() . ' /login';
        }
        return $this->_defaultUrl;
    }

    /**
     * Set default URL.
     * @param string $url The url that will be set as default.
     */
    public function setDefaultUrl($url)
    {
        $this->_defaultUrl = $url;
    }

    /**
     * Process Security Filters
     *
     * @return boolean true if success, and false if have error
     */
    public function processSecurityFilters()
    {
        $securityService = Openbizx::getService(SECURITY_SERVICE);
        $securityService->processFilters();
        $err_msg = $securityService->getErrorMessage();
        if ($err_msg) {
            if ($this->_securityDeniedView) {
                $webpage = $this->_securityDeniedView;
            } else {
                $webpage = $this->_accessDeniedView;
            }
            $this->renderView($webpage);
            return false;
        }
        return true;
    }

    /**
     * Dispatches client requests to proper objects, print the returned html text.
     *
     * @return string
     */
    public function dispatchRequest()
    {
        if ($this->request->hasInvocation()) {
            if ($this->isSessionTimeout()) {
                $this->getSessionContext()->destroy();
                $this->getClientProxy()->redirectView($this->_userTimeoutView);
            }
            return $this->dispatchRPC();
        } else {
            return $this->dispatchView();
        }
    }

    /**
     * Get the parameter from the url
     *
     * @return array parameter array
     */
    private function getParameters()
    {
        $getKeys = array_keys($_GET);
        $params = null;
        // read parameters "param:name=value"
        foreach ($getKeys as $key) {
            if (substr($key, 0, 6) == "param:") {
                $paramName = substr($key, 6);
                $paramValue = $_GET[$key];
                $params[$paramName] = $paramValue;
            }
        }
        return $params;
    }

    /**
     * Check if session timed out.
     *
     * @return boolean true - session timed out, false - session alive
     */
    private function isSessionTimeout()
    {
        return $this->getSessionContext()->isTimeout();
    }

    /**
     * Check if the view can be accessed by current user. Call accessService to do the check
     *
     * @param string $viewName view name
     * @return boolean true= allow, false not allow
     */
    private function canUserAccessView($viewName)
    {
        $svcobj = Openbizx::getService(ACCESS_SERVICE);
        return $svcobj->allowViewAccess($viewName);
    }

    /**
     * Render a bizview
     *
     * @param string $webpageName name of bizview
     * @param string $rule the search rule of a bizform who is not depent on (a subctrl of) another bizform
     * @return void
     */
    public function renderView($webpageName, $form = "", $rule = "", $params = null, $hist = "")
    {
        /* @var $webpage \Openbizx\Easy\WebPage */
        if ($webpageName == "__DynPopup") {
            $webpage = Openbizx::getWebpageObject($webpageName);
            return $webpage->render();
        }
        $this->setCurrentViewName($webpageName);
        $webpage = Openbizx::getWebpageObject($webpageName);
        if (!$webpage) {
            return '';
        }

        $viewSet = $webpage->getViewSet();
        $this->setCurrentViewSet($viewSet);
        $this->getSessionContext()->clearSessionObjects(true);

        if ($hist == "N") { // clean view history
            $webpage->cleanViewHistory();
        }
        if ($form != "" && $rule != "") {
            $webpage->processRule($form, $rule, TRUE);
        }
        if ($params) {
            $webpage->setParameters($params);
        }
        if (isset($_GET['mode'])) {   // can specify mode of form
            $webpage->setFormMode($form, $_GET['mode']);
        }
        return $webpage->render();
    }

    /**
     * Invoke the action passed from browser
     *
     * @return HTML content
     */
    protected function invokeRPC()
    {
        $request = $this->request;
        if (!$request->hasInvocation()) {
            return '';
        }
        if (!$request->isValidInvocation()) {
            $invocationType = $request->getInvocationType();
            trigger_error("$invocationType is not a valid invocation", E_USER_ERROR);
        }
        if ($request->isRPCInvokeInvocation()) {
            $this->getClientProxy()->setRpcFlag(true);
        }
        $rpcParams = $this->request->getRpcParameters();

        $num_arg = count($rpcParams);
        if ($num_arg < 2) {
            //$errmsg = MessageHelper::getMessage("SYS_ERROR_RPCARG", array($class));
            $errmsg = MessageHelper::getMessage("SYS_ERROR_RPCARG");
            trigger_error($errmsg, E_USER_ERROR);
        } else {
            $objName = array_shift($rpcParams);
            $methodName = array_shift($rpcParams);
            return $this->executeRpcMethod($objName, $methodName, $rpcParams);
        }
    }

    private function executeRpcMethod($objName, $methodName, $params)
    {
        $obj = Openbizx::getObject($objName);
        if ($obj) {
            if (method_exists($obj, $methodName)) {
                if (!$this->validateRequest($obj, $methodName)) {
                    $errmsg = MessageHelper::getMessage("SYS_ERROR_REQUEST_REJECT", array($obj->objectName, $methodName));
                    trigger_error($errmsg, E_USER_ERROR);
                }
                switch (count($params)) {
                    case 0: $rt_val = $obj->$methodName();
                        break;
                    case 1: $rt_val = $obj->$methodName($params[0]);
                        break;
                    case 2: $rt_val = $obj->$methodName($params[0], $params[1]);
                        break;
                    case 3: $rt_val = $obj->$methodName($params[0], $params[1], $params[2]);
                        break;
                    default: $rt_val = call_user_func_array(array($obj, $methodName), $params);
                }
            } else {
                $errmsg = MessageHelper::getMessage("SYS_ERROR_METHODNOTFOUND", array($objName, $methodName));
                trigger_error($errmsg, E_USER_ERROR);
            }
        } else {
            $errmsg = MessageHelper::getMessage("SYS_ERROR_CLASSNOTFOUND", array($objName));
            trigger_error($errmsg, E_USER_ERROR);
        }

        $invocationType = $this->request->getInvocationType();
        if ($invocationType == "Invoke") {  // no RPC invoke, page reloaded -> rerender view
            if ($this->getClientProxy()->hasOutput()) {
                $this->getClientProxy()->printOutput();
            }
        } else if ($invocationType == "RPCInvoke") {  // RPC invoke
            if ($this->getClientProxy()->hasOutput()) {
                if ($_REQUEST['jsrs'] == 1) {
                    echo "<form name=\"jsrs_Form\"><textarea name=\"jsrs_Payload\" id=\"jsrs_Payload\">";
                }
                $this->getClientProxy()->printOutput();
                if ($_REQUEST['jsrs'] == 1) {
                    echo "</textarea></form>";
                }
            } else {
                return $rt_val;
            }
        }
    }

    /**
     * Validate the request from client.
     *
     * @param object $obj the to be called object
     * @param string $methodName the to be called method name
     * @return boolean
     */
    protected function validateRequest($obj, $methodName)
    {
        if (is_a($obj, "Openbizx\Easy\EasyForm") || is_a($obj, "BaseForm")) {
            if ($obj->validateRequest($methodName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Dispatch request to view
     */
    private function dispatchView()
    {
        $request = $this->request;

        if (!ObjectFactoryHelper::getXmlFileWithPath($request->view)) {
            return $this->renderNotFoundView();
        }
        if (!$this->canUserAccessView($request->view)) {  //access denied error
            return $this->renderView($this->_accessDeniedView);
        }
        return $this->renderView($request->view, $request->form, $request->rule, $request->params, $request->hist);
    }

    private function renderNotFoundView()
    {
        if (defined('OPENBIZ_NOTFOUND_VIEW')) {
            $request = $this->request;
            return $this->renderView(OPENBIZ_NOTFOUND_VIEW, $request->form, $request->rule, $request->params, $request->hist);
        } else {
            throw new Exception("'Not Found View' not defined.");
        }
    }

    /**
     * Dispatch request as RPC (remote procedure call)
     */
    public function dispatchRPC()
    {
        if ($this->request->hasContainerView()) {
            $this->setCurrentViewName($this->request->getContainerViewName());
        }
        return $this->invokeRPC();
    }

    /**
     * Goto default view of module
     *
     * @param string $pmodule
     * @todo need to move to front controller
     */
    public function redirectToDefaultModuleView($pmodule)
    {
        $module = strtolower($pmodule);
        $modfile = $this->getModulePath() . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . 'mod.xml';
        $xml = simplexml_load_file($modfile);
        $defaultURL = OPENBIZ_APP_INDEX_URL . $xml->Menu->MenuItem['URL'];
        header("Location: $defaultURL");
    }

    /**
     * Goto default view of user
     *
     * @todo have options : redirect or renderDefaultView
     */
    public function redirectToDefaultUserView()
    {
        $profile = $this->getUserProfile();
        if ($profile['roleStartpage'][0]) {
            $DEFAULT_URL = OPENBIZ_APP_INDEX_URL . $profile['roleStartpage'][0];
        }
        header("Location: $DEFAULT_URL");
        exit;
    }

    /**
     * Run application
     *
     * @todo use respond object instead "echo" command
     */
    public function run()
    {
        $this->onBeforeRun();
        $this->getSessionContext();
        $eventlog = Openbizx::getService(OPENBIZ_EVENTLOG_SERVICE);
        $logComment = array('address', $_SERVER['REMOTE_ADDR']);
        $eventlog->log("LOGIN", "MSG_LOGIN_SUCCESSFUL", $logComment);
        if ($this->processSecurityFilters()) {
            echo $this->dispatchRequest() . '';
        }
        $this->onAfterRun();
    }

    public function onBeforeRun()
    {
        XHProf::setEnable(true);
        XHProf::setPath('/Users/jixian/xhprof/');
        XHProf::setUrl('http://localhost/xhprof/xhprof_html/index.php?source=xhprof_testing&run=');
        XHProf::start();
    }

    public function onAfterRun()
    {
        XHProf::finish();
    }

    public function getDefaultThemeName()
    {
        if ($this->_defaultThemeName !== null) {
            $userAgent = new UserAgent();
            if ($userAgent->isTouch()) {
                $this->_defaultThemeName = 'touch';
            } else {
                $this->_defaultThemeName = 'default';
            }
        }
    }

    public $isForceDefaultTheme = false;
    private $_themeName;

    public function getThemeName()
    {
        if ($this->_themeName !== null) {
            if ($this->isForceDefaultTheme) {
                $this->_themeName = $this->getDefaultThemeName();
            } else {
                if (isset($_GET['theme'])) {
                    $this->_themeName = $_GET['theme'];
                    setcookie("OPENBIZ_THEME_NAME", $_GET['theme'], time() + 86400 * 365, "/");
                } elseif (isset($_COOKIE['OPENBIZ_THEME_NAME'])) {
                    $this->_themeName = $_COOKIE['OPENBIZ_THEME_NAME'];
                } else {
                    $this->_themeName = $this->getDefaultThemeName();
                }
            }
        }
        return $this->_themeName;
    }

    protected function initSystemDefaultTimezone()
    {
        $defaultTimezone = $this->getSessionContext()->getVar("TIMEZONE");
        if ($defaultTimezone == "") {
            $defaultTimezone = $this->timeZone;
        }
        date_default_timezone_set($defaultTimezone);
    }

    //=========== USER MANAGEMENT

    /**
     * Check if user can access the given resource action
     *
     * @param string $resourceAction resource action
     * @return boolean true or false
     */
    public function allowUserAccess($resourceAction)
    {
        $serviceObj = Openbizx::getService(ACL_SERVICE);
        return $serviceObj->allowAccess($resourceAction);
    }

    /**
     * Initialize User Profile
     *
     * @param string $username
     * @return array Profile array
     * @todo need to move, only used in profileService
     */
    public function initUserProfile($username)
    {
        /* @var $profileService profileService */
        $profileService = Openbizx::getService(PROFILE_SERVICE);
        if (method_exists($profileService, 'InitProfile')) {
            $profile = $profileService->initProfile($username);
        } else {
            $profile = $profileService->getProfile($username);
        }
        $this->getSessionContext()->setVar("_USER_PROFILE", $profile);
        return $profile;
    }

    /**
     * Get user profile
     *
     * @param string $attribute user attribute
     * @return array user profile array
     */
    public function getUserProfile($attribute = null)
    {
        if (!ObjectFactoryHelper::getXmlFileWithPath(PROFILE_SERVICE)) {
            return null;
        }
        $profileService = Openbizx::getService(PROFILE_SERVICE);
        $profile = $this->getSessionContext()->getVar("_USER_PROFILE");
        if (method_exists($profileService, 'getProfile')) {
            return $profileService->getProfile($attribute);
        } else {
            $profile = $this->getSessionContext()->getVar("_USER_PROFILE");
            return isset($profile[$attribute]) ? $profile[$attribute] : "";
        }
    }

    /**
     * Get user preference
     *
     * @param string $attribute key that representing attribute
     * @return mixed
     */
    public function getUserPreference($attribute = null)
    {
        if (!ObjectFactoryHelper::getXmlFileWithPath(OPENBIZ_PREFERENCE_SERVICE)) {
            return null;
        }
        $preferenceService = Openbizx::getService(OPENBIZ_PREFERENCE_SERVICE);
        if (method_exists($preferenceService, 'getPreference')) {
            return $preferenceService->getPreference($attribute);
        } else {
            $preference = $this->getSessionContext()->getVar("_USER_PREFERENCE");
            return isset($preference[$attribute]) ? $preference[$attribute] : "";
        }
    }

    /**
     * Get default user perm
     * @param type $pgroup
     * @return string
     */
    public function getDefaultPerm($pgroup)
    {
        $group = strtolower($pgroup);
        switch ($group) {
            default:
            case 'owner':
                $setting = $this->getUserPreference('owner_perm');
                if ($setting != '') {
                    $perm_code = $setting;
                } else {
                    $perm_code = OPENBIZ_DEFAULT_OWNER_PERM;
                }
                break;
            case 'group':
                $setting = $this->getUserPreference('owner_group');
                if ($setting != '') {
                    $perm_code = $setting;
                } else {
                    $perm_code = OPENBIZ_DEFAULT_GROUP_PERM;
                }
                break;
            case 'other':
                $setting = $this->getUserPreference('owner_other');
                if ($setting != '') {
                    $perm_code = $setting;
                } else {
                    $perm_code = OPENBIZ_DEFAULT_OTHER_PERM;
                }
                break;
        }
        return $perm_code;
    }

    private $_currentViewName = "";

    /**
     * Get the current view name
     *
     * @return string current view name
     */
    public function getCurrentViewName()
    {
        if ($this->_currentViewName == "") {
            $this->_currentViewName = $this->getSessionContext()->getVar("CVN"); // CVN stands for CurrentViewName
        }
        return $this->_currentViewName;
    }

    /**
     * Set the current view name
     *
     * @param string $viewname new current view name
     */
    public function setCurrentViewName($viewname)
    {
        $this->_currentViewName = $viewname;
        $this->getSessionContext()->setVar("CVN", $this->_currentViewName);   // CVN stands for CurrentViewName
    }

    private $_currentViewSet = "";

    /**
     * Get the current view set
     *
     * @return string current view set
     */
    public function getCurrentViewSet()
    {
        if ($this->_currentViewSet == "") {
            $this->_currentViewSet = $this->getSessionContext()->getVar("CVS");
        }   // CVS stands for CurrentViewSet
        return $this->_currentViewSet;
    }

    /**
     * Set current view set
     *
     * @param <type> $viewSet
     */
    public function setCurrentViewSet($viewSet)
    {
        $this->_currentViewSet = $viewSet;
        $this->getSessionContext()->setVar("CVS", $this->_currentViewSet);   // CVS stands for CurrentViewSet
    }

    /**
     * get log service
     * @return logService
     */
    public function getLog()
    {
        return Openbizx::getService(LOG_SERVICE);
    }

    public function getProfile()
    {
        return Openbizx::getService(PROFILE_SERVICE);
    }

    /**
     * @var string the root directory of the application.
     */
    private $_basePath;

    /**
     * Returns the root directory of the application.
     * It defaults to the directory containing the application class file.
     *
     * Note: this method will replace OPENBIZ_APP_PATH const.
     *
     * @return string the root directory of the module.
     * @see OPENBIZ_APP_PATH
     */
    public function getBasePath()
    {
        if ($this->_basePath === null) {
            $class = new \ReflectionClass($this);
            $this->_basePath = dirname($class->getFileName());
        }
        return $this->_basePath;
    }

    /**
     * Sets the root directory of the application.
     * This method can only be invoked at the beginning of the constructor.
     *
     * @param string $path the root directory of the application.
     * @throws InvalidParamException if the directory does not exist.
     */
    public function setBasePath($path)
    {
        $p = realpath($path);
        if ($p !== false && is_dir($p)) {
            $this->_basePath = $p;
        } else {
            throw new Exception("The directory does not exist: $path");
        }
    }

    /**
     * Returns the time zone used by this application.
     * This is a simple wrapper of PHP function date_default_timezone_get().
     * If time zone is not configured in php.ini or application config,
     * it will be set to UTC by default.
     * @return string the time zone used by this application.
     * @see http://php.net/manual/en/function.date-default-timezone-get.php
     */
    public function getTimeZone()
    {
        return date_default_timezone_get();
    }

    /**
     * Sets the time zone used by this application.
     * This is a simple wrapper of PHP function date_default_timezone_set().
     * @param string $value the time zone used by this application.
     * @see http://php.net/manual/en/function.date-default-timezone-set.php
     */
    public function setTimeZone($value)
    {
        date_default_timezone_set($value);
    }

    private $_imageUrl;

    /**
     * Get image URL
     * @return string
     */
    public function getImageUrl()
    {
        if (isset($this->_imageUrl)) {
            return $this->_imageUrl;
        }
        $useTheme = !defined('OPENBIZ_USE_THEME') ? 0 : OPENBIZ_USE_THEME;
        $themeUrl = !defined('OPENBIZ_THEME_URL') ? "../themes" : OPENBIZ_THEME_URL;
        $themeName = $this->getCurrentTheme();
        if ($useTheme) {
            $this->_imageUrl = "$themeUrl/$themeName/images";
        } else {
            $this->_imageUrl = "../images";
        }
        return $this->_imageUrl;
    }

    /**
     * Get CSS URL
     * @return string
     */
    public function getCssUrl()
    {
        if (isset($this->_cssUrl)) {
            return $this->_cssUrl;
        }
        $useTheme = !defined('OPENBIZ_USE_THEME') ? 0 : OPENBIZ_USE_THEME;
        $themeUrl = !defined('OPENBIZ_THEME_URL') ? OPENBIZ_APP_URL . "/themes" : OPENBIZ_THEME_URL;
        $themeName = $this->getCurrentTheme();
        if ($useTheme) {
            $this->_cssUrl = "$themeUrl/$themeName/css";
        } else {
            $this->_cssUrl = OPENBIZ_APP_URL . "/css";
        }
        return $this->_cssUrl;
    }

    /**
     * Get JavaScript(JS) URL
     * @return string
     */
    public function getJsUrl()
    {
        if (isset($this->_jsUrl)) {
            return $this->_jsUrl;
        }
        $this->_jsUrl = !defined('OPENBIZ_JS_URL') ? OPENBIZ_APP_URL . "/js" : OPENBIZ_JS_URL;
        return $this->_jsUrl;
    }

    /**
     * theme selection priority: url, session, userpref, system(constant)
     * @todo user pereference has language setting
     * @return type
     */
    public function getCurrentTheme()
    {
        if ($this->_currentTheme != null) {
            return $this->_currentTheme;
        }
        $currentTheme = "";
        if (isset($_GET['theme'])) {
            $currentTheme = $_GET['theme'];
        }
        if ($currentTheme == "") {
            $currentTheme = $this->getSessionContext()->getVar("THEME");
        }
        if ($currentTheme == "") {
            $currentTheme = $this->getUserPreference("theme");
        }
        if ($currentTheme == "" && defined('OPENBIZ_THEME_NAME')) {
            $currentTheme = OPENBIZ_THEME_NAME;
        }
        if ($currentTheme == "") {
            $currentTheme = self::DEFAULT_THEME;
        }
        $this->getSessionContext()->setVar("THEME", $currentTheme);
        $this->_currentTheme = $currentTheme;
        return $currentTheme;
    }

    /**
     * Get module path of application.
     * @return string
     */
    public function getModulePath()
    {
        if ($this->_modulePath === null) {
            $this->_modulePath = OPENBIZ_APP_PATH . DIRECTORY_SEPARATOR . "modules";
        }
        return $this->_modulePath;
    }

    /**
     * Set module path of application
     * @param string $path
     */
    public function setModulePath($path)
    {
        $this->_modulePath = $path;
    }

}


<?php
declare(strict_types = 1);

namespace Innmind\Rest\Client\Server;

use Innmind\Rest\Client\{
    Server as ServerInterface,
    Identity,
    HttpResource,
    Request\Range,
    Exception\NormalizationException,
    Exception\DenormalizationException,
};
use Innmind\HttpTransport\Exception\ClientError;
use Innmind\Http\Message\StatusCode\StatusCode;
use Innmind\Url\UrlInterface;
use Innmind\Immutable\SetInterface;
use Innmind\Specification\Specification;

/**
 * This implementation will retry a failed request once after it has refreshed
 * the server capabilities in order to make sure the resource definitions are
 * up-to-date
 */
final class RetryServer implements ServerInterface
{
    private $server;

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

    /**
     * {@iinheritdoc}
     */
    public function all(
        string $name,
        Specification $specification = null,
        Range $range = null
    ): SetInterface {
        try {
            return $this->server->all($name, $specification, $range);
        } catch (\Throwable $e) {
            if (!$this->shouldRetryAfter($e)) {
                throw $e;
            }

            $this->server->capabilities()->refresh();

            return $this->server->all($name, $specification, $range);
        }
    }

    public function read(string $name, Identity $identity): HttpResource
    {
        try {
            return $this->server->read($name, $identity);
        } catch (\Throwable $e) {
            if (!$this->shouldRetryAfter($e)) {
                throw $e;
            }

            $this->server->capabilities()->refresh();

            return $this->server->read($name, $identity);
        }
    }

    public function create(HttpResource $resource): Identity
    {
        try {
            return $this->server->create($resource);
        } catch (\Throwable $e) {
            if (!$this->shouldRetryAfter($e)) {
                throw $e;
            }

            $this->server->capabilities()->refresh();

            return $this->server->create($resource);
        }
    }

    public function update(
        Identity $identity,
        HttpResource $resource
    ): ServerInterface {
        try {
            $this->server->update($identity, $resource);
        } catch (\Throwable $e) {
            if (!$this->shouldRetryAfter($e)) {
                throw $e;
            }

            $this->server->capabilities()->refresh();
            $this->server->update($identity, $resource);
        }

        return $this;
    }

    public function remove(string $name, Identity $identity): ServerInterface
    {
        try {
            $this->server->remove($name, $identity);
        } catch (\Throwable $e) {
            if (!$this->shouldRetryAfter($e)) {
                throw $e;
            }

            $this->server->capabilities()->refresh();
            $this->server->remove($name, $identity);
        }

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function link(
        string $name,
        Identity $identity,
        SetInterface $links
    ): ServerInterface {
        try {
            $this->server->link($name, $identity, $links);
        } catch (\Throwable $e) {
            if (!$this->shouldRetryAfter($e)) {
                throw $e;
            }

            $this->server->capabilities()->refresh();
            $this->server->link($name, $identity, $links);
        }

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function unlink(
        string $name,
        Identity $identity,
        SetInterface $links
    ): ServerInterface {
        try {
            $this->server->unlink($name, $identity, $links);
        } catch (\Throwable $e) {
            if (!$this->shouldRetryAfter($e)) {
                throw $e;
            }

            $this->server->capabilities()->refresh();
            $this->server->unlink($name, $identity, $links);
        }

        return $this;
    }

    public function capabilities(): Capabilities
    {
        return $this->server->capabilities();
    }

    public function url(): UrlInterface
    {
        return $this->server->url();
    }

    private function shouldRetryAfter(\Throwable $e): bool
    {
        if (
            $e instanceof NormalizationException ||
            $e instanceof DenormalizationException
        ) {
            return true;
        }

        if (!$e instanceof ClientError) {
            return false;
        }

        return $e->response()->statusCode()->value() === StatusCode::codes()->get('BAD_REQUEST');
    }
}


<?php

namespace Environaut\Checks;

use Environaut\Checks\Check;

/**
 * Basic check to ask the user for environment configuration settings.
 *
 * Supported parameters are:
 * - "introduction": text to display before this check
 * - "question": text to ask user for a value
 * - "setting": name of setting variable
 * - "setting_group": group the configured setting belongs to (for export; defaults to "config")
 * - "choices": array of autocomplete values or choices for selection (depending on check configuration)
 * - "default": default value if none is given by the user
 * - "hidden": hidden question to user (e,g. for credentials)
 * - "allow_fallback": allow fallback to visible input if hidden input does not work
 * - "validator": class/method to use for validation of value - must return valid value or throw helpful exception
 * - "max_attempts": maximum attempts if validator is specified
 * - "confirm": simple yes/no confirmation question (only y/n are accepted answers)
 * - "select": select value from the list of choices
 */
class Configurator extends Check
{
    /**
     * Default group of settings that this check stores in the result.
     */
    const DEFAULT_SETTING_GROUP_NAME = 'config';

    /**
     * Default group name used in messages of the report.
     * By default also used as default setting group name if not customized.
     */
    const DEFAULT_CUSTOM_GROUP_NAME = 'Configuration';

    /**
     * Returns the default group name this check uses when none is specified.
     *
     * @return string default group name of the check
     */
    public function getDefaultGroupName()
    {
        return self::DEFAULT_CUSTOM_GROUP_NAME;
    }

    /**
     * Returns the default group name this check uses for settings when none is specified.
     *
     * @return string default group name of settings of this check
     */
    public function getDefaultSettingGroupName()
    {
        if ($this->group !== self::DEFAULT_CUSTOM_GROUP_NAME) {
            return $this->group;
        }

        return self::DEFAULT_SETTING_GROUP_NAME;
    }

    /**
     * Asks the user a question and sets the answer as a setting on the result.
     *
     * @return boolean true if configuration could be added to the result; false otherwise
     *
     * @throws \InvalidArgumentException on setup errors like "choices" can't be interpreted
     * @throws \RuntimeException in case "allow_fallback" is deactivated but the response can't be "hidden"
     * @throws \RuntimeException if there is no data to read in the input stream
     * @throws \Exception when the maximum number of attempts has been reached and no valid response has been given
     */
    public function run()
    {
        $dialog = $this->getDialogHelper();
        $output = $this->getOutputStream();

        $output->writeln(PHP_EOL); // to get some margin to the progress bar

        $introduction = $this->parameters->get('introduction', false);
        if (false !== $introduction) {
            $output->writeln($introduction);
            $output->writeln('');
        }

        $name = $this->parameters->get('setting', $this->getName());
        $setting_group = $this->parameters->get('setting_group');
        $choices = $this->parameters->get('choices', array());
        $default = $this->parameters->get('default', null);
        $validator = $this->parameters->get('validator', false);
        $hidden = (bool) $this->parameters->get('hidden', false);
        $allow_fallback = (bool) $this->parameters->get('allow_fallback', false);
        $max_attempts = $this->parameters->get('max_attempts', false);
        $confirm = (bool) $this->parameters->get('confirm', false);
        $select = (bool) $this->parameters->get('select', false);

        if ($this->cache->has($name, $setting_group)) {
            $cached_setting = $this->cache->get($name, $setting_group);
            $this->addInfo(
                "Setting [" . $cached_setting->getGroup() . "][$name] already configured. Using " .
                'value: ' . var_export($cached_setting->getValue(), true)
            );
            // add cached value directly as cachable setting to the result of this check
            $this->result->addSetting($cached_setting);

            return true;
        }

        $question = '<question>' . $this->parameters->get('question', '"setting_question" is not set');

        // a simple yes/no confirmation dialog
        if ($confirm) {
            $default = (bool) ($default === null ? true : $default);
            $default_text = ($default ? 'y' : 'n');
            $question .= "</question> (Type [y/n/<return>], default=$default_text): ";

            $value = $dialog->askConfirmation($output, $question, $default);

            $default_text = ($default ? 'enabled' : 'disabled');
            $this->addInfo($name . ' is ' . $default_text);

            $this->addCachableSetting($name, $value, $setting_group);

            return true;
        }

        // add default value to question if specified
        if (null !== $default) {
            $question .= "</question> (Default: $default)";
        } else {
            $question .=  '</question>';
        }
        $question .= ': ';

        // selection dialog to choose values from a list of choices
        if ($select) {
            $value = $dialog->select($output, $question, $choices, $default, $max_attempts);
            $this->addCachableSetting($name, $choices[$value], $setting_group);
            $this->addInfo('Selected value for "' . $name . '" is "' . $choices[$value] . '".');

            return true;
        }

        if (false !== $validator) { // use value validation?
            if ($hidden) {
                $value = $dialog->askHiddenResponseAndValidate(
                    $output,
                    $question,
                    $validator,
                    $max_attempts,
                    $allow_fallback
                );
            } else {
                $value = $dialog->askAndValidate(
                    $output,
                    $question,
                    $validator,
                    $max_attempts,
                    $default,
                    $choices
                );
            }
        } else { // do not use value validation
            if ($hidden) {
                $value = $dialog->askHiddenResponse($output, $question, $allow_fallback);
            } else {
                $value = $dialog->ask($output, $question, $default, $choices);
            }
        }

        $this->addInfo('Successfully configured "' . $name . '".');
        $this->addCachableSetting($name, $value, $setting_group);

        $output->writeln('');

        return true;
    }
}


<?PHP

/**
 * Openbizx Framework
 *
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin
 * @copyright Copyright (c) 2005-2011, Rocky Swen
 * @license   http://www.opensource.org/licenses/bsd-license.php     BSD
 * @link      http://www.phpopenbiz.org/
 * @version   $Id: Configuration.php 3334 2012-05-30 08:07:05Z agus.suhartono@gmail.com $
 */

namespace Openbizx;

use Openbizx\Object\ObjectFactoryHelper;

/**
 * Configuration class
 * Configuration management class that has help methods to get data from config.xml
 *
 * @package   openbiz.bin
 * @author    Rocky Swen <rocky@phpopenbiz.org>
 * @copyright Copyright (c) 2005-2009, Rocky Swen
 * @access    public
 * @version	  $Id: Configuration.php 3334 2012-05-30 08:07:05Z agus.suhartono@gmail.com $
 */
class ApplicationConfiguration
{

    /**
     * Array of XML Data
     *
     * @var array
     */
    private $_xmlArr;

    /**
     * Associate Array of pre-configure database conections
     *
     * @var array
     */
    private $_databaseInfo;
    private $_themeInfo;

    /**
     * Read application.xml into a internal array.
     */
    public function __construct()
    {
        $xmlFile = ObjectFactoryHelper::getXmlFileWithPath("application");
        $this->_xmlArr = &ObjectFactoryHelper::getXmlArray($xmlFile);
    }

    /**
     * Returns the database info from <DataSource> defined in application.xml as an array.
     * Returned array is a 2D map.
     * (DBName1 => ["Name"], ["Driver"], ["Server"], ["DBName"], ["User"], {"Password"])
     * (DBName2 => ["Name"], ["Driver"], ["Server"], ["DBName"], ["User"], {"Password"])
     * (...)
     * If DBName is given, returns the record only related to the given DBName,
     * otherwise returns all records
     *
     * @param string $dbName
     * @return array database information
     */
    public function getDatabaseInfo($dbName = null)
    {
        if ($dbName && $this->_databaseInfo[$dbName]) {
            return $this->_databaseInfo[$dbName];
        }
        if (!$this->_xmlArr["APPLICATION"]["DATASOURCE"]) {
            $errMsg = MessageHelper::getMessage("SYS_ERROR_NODBINFO");
            trigger_error($errMsg, E_USER_ERROR);
        }
        $breakFlag = false;
        foreach ($this->_xmlArr["APPLICATION"]["DATASOURCE"]["DATABASE"] as $db) {
            if (isset($this->_xmlArr["APPLICATION"]["DATASOURCE"]["DATABASE"]['ATTRIBUTES'])) {
                $db = $this->_xmlArr["APPLICATION"]["DATASOURCE"]["DATABASE"];
                $breakFlag = true;
            }
            $tmp["Name"] = $db["ATTRIBUTES"]["NAME"];
            $tmp["Driver"] = $db["ATTRIBUTES"]["DRIVER"];
            $tmp["Server"] = $db["ATTRIBUTES"]["SERVER"];
            $tmp["DBName"] = $db["ATTRIBUTES"]["DBNAME"];
            $tmp["User"] = $db["ATTRIBUTES"]["USER"];
            $tmp["Password"] = $db["ATTRIBUTES"]["PASSWORD"];
            $tmp["Port"] = isset($db["ATTRIBUTES"]["PORT"]) ? $db["ATTRIBUTES"]["PORT"] : null;
            $tmp["Charset"] = isset($db["ATTRIBUTES"]["CHARSET"]) ? $db["ATTRIBUTES"]["CHARSET"] : null;
            $tmp["Options"] = isset($db["ATTRIBUTES"]["OPTIONS"]) ? $db["ATTRIBUTES"]["OPTIONS"] : null;

            $this->_databaseInfo[$tmp["Name"]] = $tmp;
            if ($breakFlag) {
                break;
            }
        }

        if ($dbName && $this->_databaseInfo[$dbName]) {
            return $this->_databaseInfo[$dbName];
        }
        if ($dbName && !isset($this->_databaseInfo[$dbName])) {
            $errMsg = MessageHelper::getMessage("DATA_INVALID_DBNAME", array($dbName, $dbName));
            trigger_error($errMsg, E_USER_ERROR);
        }
        if (!$dbName) {
            return $this->_databaseInfo;
        }
    }

}


<?php

declare(strict_types=1);

namespace NAttreid\Utils;

use Nette\Database\Table\Selection;
use Nette\InvalidArgumentException;
use Nextras\Dbal\QueryBuilder\QueryBuilder;
use Nextras\Orm\Mapper\Dbal\DbalCollection;

/**
 * Pomocna trida pro hashovani
 *
 * @author Attreid <attreid@gmail.com>
 */
class Hasher
{

	private $salt;

	/**
	 * Konstruktor tridy
	 * @param string $salt
	 */
	public function __construct(string $salt)
	{
		$this->salt = $salt;
	}

	/**
	 * Zahashuje retezec
	 * @param mixed $string
	 * @return string
	 */
	public function hash($string): string
	{
		return hash('sha256', $string . $this->salt);
	}

	/**
	 * Vyhleda podle hashe
	 * @param Selection|QueryBuilder|DbalCollection $data
	 * @param string|array $columns
	 * @param string $hash
	 * @return Selection|QueryBuilder
	 * @throws InvalidArgumentException
	 */
	public function hashSQL($data, $columns, string $hash)
	{
		if (is_string($columns)) {
			$columns = [$columns];
		}

		if (is_array($columns)) {
			if ($data instanceof DbalCollection) {
				$data = $data->getQueryBuilder();
			}

			if ($data instanceof Selection) {
				$col = '';
				foreach ($columns as $column) {
					if ($col !== '') {
						$col += ',';
					}
					$col += '`$column`';
				}
				return $data->where("SHA2(CONCAT($columns,  '{$this->salt}'), 256)", $hash);
			} elseif ($data instanceof QueryBuilder) {
				return $data->andWhere('SHA2(CONCAT(%column[], %s), 256) = %s', $columns, $this->salt, $hash);
			}
		}
		throw new InvalidArgumentException;
	}

	/**
	 * Zkontroluje zda je hash vytvoren z daneho retezce
	 * @param mixed $string
	 * @param string $hash
	 * @return bool
	 */
	public function check($string, string $hash): bool
	{
		return hash_equals($this->hash($string), $hash);
	}

}


<?php

namespace Interpro\QS\Db;

use Illuminate\Support\Facades\DB;
use Interpro\Core\Contracts\Ref\ARef;
use Interpro\Core\Taxonomy\Enum\TypeRank;
use Interpro\Extractor\Contracts\Db\JoinMediator;
use Interpro\Extractor\Contracts\Selection\SelectionUnit;
use Interpro\Extractor\Db\QueryBuilder;
use Interpro\QS\Exception\QSException;
use Interpro\Core\Helpers;

class QSQuerier
{
    private $joinMediator;

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

    public function getRefValues($owner_name, $owner_id)
    {
        $refs_query = new QueryBuilder(DB::table('refs'));
        $refs_query->where('refs.entity_name', '=', $owner_name);

        if(is_array($owner_id))
        {
            $refs_query->whereIn('refs.entity_id', $owner_id);
        }
        else
        {
            $refs_query->where('refs.entity_id', '=', $owner_id);
        }

        $refs_result = Helpers::laravel_db_result_to_array($refs_query->get());
        $refs_values = [];

        foreach($refs_result as $ref_array)
        {
            $key = $ref_array['name'].'_'.$ref_array['entity_id'];
            $refs_values[$key] = $ref_array;
        }

        return $refs_values;
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     *
     * @return \Interpro\Extractor\Db\QueryBuilder
     */
    public function selectByRef(ARef $ref)
    {
        $type  = $ref->getType();
        $type_name = $type->getName();
        $id = $ref->getId();

        if($type->getRank() === TypeRank::BLOCK)
        {
            $table = 'blocks';
        }
        elseif($type->getRank() === TypeRank::GROUP)
        {
            $table = 'groups';
        }
        else
        {
            throw new QSException('При получении данных элемента передана ссылка на тип с рангом отличным от блока и группы: '.$type->getRank().'!');
        }

        $query = new QueryBuilder(DB::table($table));
        $query->where($table.'.name', '=', $type_name);

        if($id > 0)
        {
            $query->where($table.'.id', '=', $id);
        }

        return $query;
    }

    /**
     * @param SelectionUnit $selectionUnit
     *
     * @return \Interpro\Extractor\Db\QueryBuilder
     * @throws \Interpro\QS\Exception\QSException
     */
    public function selectByUnit(SelectionUnit $selectionUnit)
    {
        $type  = $selectionUnit->getType();

        $entity_name    = $type->getName();
        $rank_name      = $type->getRank();

        if($rank_name === TypeRank::BLOCK)
        {
            $model_table = 'blocks';
        }
        elseif($rank_name === TypeRank::GROUP)
        {
            $model_table = 'groups';
        }
        else
        {
            throw new QSException('Не корректный ранг типа '.$entity_name.': '.$rank_name);
        }

        //Группировка путей с общими отрезками
        //-------------------------------------------------------------
        $join_fields = $selectionUnit->getJoinFieldsPaths();

        $join_array = ['sub_levels' => [], 'full_field_names' => [], 'value_level' => false];//первый уровень - соединение с главным запросом + пути к полям по уровням

        foreach($join_fields as $field)
        {
            if ($field === 'title' or
                $field === 'created_at' or
                $field === 'updated_at' or
                $field === 'slug' or
                $field === 'sorter' or
                $field === 'predefined' or
                $field === 'id' or
                $field === 'name' or
                $field === 'show')
            {
                continue;
            }

            $curr_level_array = & $join_array;

            $field_array     = explode('.', $field);
            $full_field_name = str_replace('.', '_', $field);

            $curr_level_array['full_field_names'][] = $full_field_name;

            foreach($field_array as $field_name)
            {
                if(!array_key_exists($field_name, $curr_level_array['sub_levels']))
                {
                    $curr_level_array['sub_levels'][$field_name] = ['sub_levels' => [], 'full_field_names' => [], 'value_level' => false];
                }

                $curr_level_array = &$curr_level_array['sub_levels'][$field_name];

                $curr_level_array['full_field_names'][] = $full_field_name;
            }

            $curr_level_array['value_level'] = true;//В конце всегда должно стоять поле скалярного типа
        }
        //-------------------------------------------------------------

        //В главном запросе можно пользоваться биндингом, а в подзапросах нельзя, так как порядок параметров будет сбиваться параметрами подзапросов
        $main_query = new QueryBuilder(DB::table($model_table));
        $main_query->where($model_table.'.name', '=', $entity_name);

        $get_fields = [
            $model_table.'.id',
            $model_table.'.name',
            $model_table.'.title',
            $model_table.'.created_at',
            $model_table.'.updated_at',
            $model_table.'.slug',
            $model_table.'.sorter',
            $model_table.'.predefined',
            $model_table.'.show'
        ];

        //Сначала подсоединяем все, кроме slug, title, sorter, show ...
        //$field - путь к полю разделенный точками
        foreach($join_array['sub_levels'] as $level0_field_name => $sub_array)
        {
            $Field = $type->getField($level0_field_name);
            $join_q = $this->joinMediator->externalJoin($Field, $sub_array);

            $main_query->leftJoin(DB::raw('('.$join_q->toSql().') AS '.$level0_field_name.'_table'), function($join) use ($level0_field_name, $model_table)
            {
                $join->on($model_table.'.name', '=', $level0_field_name.'_table.entity_name');
                $join->on($model_table.'.id',   '=', $level0_field_name.'_table.entity_id');
            });

            //$main_query->addBinding($join_q->getBindings());

            $get_fields = array_merge($get_fields, $sub_array['full_field_names']);
        }

        //Применим все параметры условия и сортировки выборки к запросу:
        $selectionUnit->apply($main_query);

        $main_query->select($get_fields);

        return $main_query;
    }

}