public function permissionGetIdByName($name)
  {
    if(!array_key_exists((string) $name, $this->permissionList()))
    {
      throw new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception("invalid permission ID", 0xA02);
    }

    return $this->permissionList[(string) $name]["permid"];
  }

public
function
permissionGetIdByName
(
$
name
)
{
if
(
!
array_key_exists
(
(
string
)
$
name
,
$
this
->
permissionList
(
)
)
)
{
throw
new
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Adapter
\
ServerQuery
\
Exception
(
"invalid permission ID"
,
0xA02
)
;
}
return
$
this
->
permissionList
[
(
string
)
$
name
]
[
"permid"
]
;
}

Returns the ID of the permission matching the given name.

@param  string $name
@throws \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception
@return integer

Returns the ID of the permission matching the given name .


public function permissionGetNameById($permid)
  {
    foreach($this->permissionList() as $name => $perm)
    {
      if($perm["permid"] == $permid) return new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String($name);
    }

    throw new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception("invalid permission ID", 0xA02);
  }

public
function
permissionGetNameById
(
$
permid
)
{
foreach
(
$
this
->
permissionList
(
)
as
$
name
=>
$
perm
)
{
if
(
$
perm
[
"permid"
]
==
$
permid
)
return
new
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Helper
\
String
(
$
name
)
;
}
throw
new
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Adapter
\
ServerQuery
\
Exception
(
"invalid permission ID"
,
0xA02
)
;
}

Returns the name of the permission matching the given ID.

@param  integer $permid
@throws \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception
@return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String

Returns the name of the permission matching the given ID .


public function permissionGetCategoryById($permid)
  {
    if(!is_numeric($permid))
    {
      $permid = $this->permissionGetIdByName($permid);
    }

    return (int) $permid >> 8;
  }

public function permissionGetCategoryById ( $ permid ) { if ( ! is_numeric ( $ permid ) ) { $ permid = $ this -> permissionGetIdByName ( $ permid ) ; } return ( int ) $ permid >> 8 ; }

Returns the internal category of the permission matching the given ID.

All permission IDs are are 2 bytes wide. The first byte identifies the category while the second
byte is the permission count within that group.

@param  integer $permid
@return integer

Returns the internal category of the permission matching the given ID .


public function selfPermCheck($permid)
  {
    $permident = (is_numeric($permid)) ? "permid" : "permsid";

    return $this->execute("permget", array($permident => $permid))->toAssocArray("permsid");
  }

public function selfPermCheck ( $ permid ) { $ permident = ( is_numeric ( $ permid ) ) ? "permid" : "permsid" ; return $ this -> execute ( "permget" , array ( $ permident => $ permid ) ) -> toAssocArray ( "permsid" ) ; }

Returns an array containing the value of a specified permission for your own client.

@param  integer $permid
@return array

Returns an array containing the value of a specified permission for your own client .


public function logAdd($logmsg, $loglevel = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_INFO)
  {
    $sid = $this->serverSelectedId();

    $this->serverDeselect();
    $this->execute("logadd", array("logmsg" => $logmsg, "loglevel" => $loglevel));
    $this->serverSelect($sid);
  }

public function logAdd ( $ logmsg , $ loglevel = \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: LOGLEVEL_INFO ) { $ sid = $ this -> serverSelectedId ( ) ; $ this -> serverDeselect ( ) ; $ this -> execute ( "logadd" , array ( "logmsg" => $ logmsg , "loglevel" => $ loglevel ) ) ; $ this -> serverSelect ( $ sid ) ; }

Writes a custom entry into the server instance log.

@param  string  $logmsg
@param  integer $loglevel
@return void

Writes a custom entry into the server instance log .


public function login($username, $password)
  {
    $this->execute("login", array("client_login_name" => $username, "client_login_password" => $password));
    $this->whoamiReset();

    $crypt = new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Crypt($username);

    $this->setStorage("_login_user", $username);
    $this->setStorage("_login_pass", $crypt->encrypt($password));

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

public function login ( $ username , $ password ) { $ this -> execute ( "login" , array ( "client_login_name" => $ username , "client_login_password" => $ password ) ) ; $ this -> whoamiReset ( ) ; $ crypt = new \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ Helper \ Crypt ( $ username ) ; $ this -> setStorage ( "_login_user" , $ username ) ; $ this -> setStorage ( "_login_pass" , $ crypt -> encrypt ( $ password ) ) ; \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ Helper \ Signal :: getInstance ( ) -> emit ( "notifyLogin" , $ this ) ; }

Authenticates with the TeamSpeak 3 Server instance using given ServerQuery login credentials.

@param  string $username
@param  string $password
@return void

Authenticates with the TeamSpeak 3 Server instance using given ServerQuery login credentials .


public function logout()
  {
    $this->request("logout");
    $this->whoamiReset();

    $this->delStorage("_login_user");
    $this->delStorage("_login_pass");

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

public function logout ( ) { $ this -> request ( "logout" ) ; $ this -> whoamiReset ( ) ; $ this -> delStorage ( "_login_user" ) ; $ this -> delStorage ( "_login_pass" ) ; \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ Helper \ Signal :: getInstance ( ) -> emit ( "notifyLogout" , $ this ) ; }

Deselects the active virtual server and logs out from the server instance.

@return void

Deselects the active virtual server and logs out from the server instance .


public function whoamiSet($ident, $value = null)
  {
    $this->whoami();

    $this->whoami[$ident] = (is_numeric($value)) ? intval($value) : \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String::factory($value);
  }

public function whoamiSet ( $ ident , $ value = null ) { $ this -> whoami ( ) ; $ this -> whoami [ $ ident ] = ( is_numeric ( $ value ) ) ? intval ( $ value ) : \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ Helper \ String :: factory ( $ value ) ; }

Sets a single value in the current ServerQuery connection info.

@param  string $ident
@param  mixed  $value
@return mixed

Sets a single value in the current ServerQuery connection info .


protected function getValidator(ServiceLocatorInterface $serviceLocator, string $name, array $options): object
    {
        return $serviceLocator->getService($name, $options);
    }

protected function getValidator ( ServiceLocatorInterface $ serviceLocator , string $ name , array $ options ) : object { return $ serviceLocator -> getService ( $ name , $ options ) ; }

Get validator for name.

@param ServiceLocatorInterface $serviceLocator
@param string                  $name
@param array                   $options
@return ValidatorInterface
@throws ServiceLocatorException


private function setCurlContent($curl, PageFetcherRequestInterface $request): void
    {
        $rawContent = $request->getRawContent();
        if ($rawContent !== '') {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $rawContent);

            return;
        }

        $postFields = [];
        $hasFiles = false;

        foreach ($request->getFiles() as $name => $filePath) {
            /** @var FilePathInterface $filePath */
            $curlFile = curl_file_create($filePath->__toString(), mime_content_type($filePath->__toString()), $filePath->getFilename());
            $postFields[$name] = $curlFile;
            $hasFiles = true;
        }

        foreach ($request->getPostFields() as $name => $value) {
            $postFields[$name] = $value;
        }

        if (count($postFields) === 0) {
            return;
        }

        curl_setopt($curl, CURLOPT_POSTFIELDS, $hasFiles ? $postFields : http_build_query($postFields));
    }

private
function
setCurlContent
(
$
curl
,
PageFetcherRequestInterface
$
request
)
:
void
{
$
rawContent
=
$
request
->
getRawContent
(
)
;
if
(
$
rawContent
!==
''
)
{
curl_setopt
(
$
curl
,
CURLOPT_POSTFIELDS
,
$
rawContent
)
;
return
;
}
$
postFields
=
[
]
;
$
hasFiles
=
false
;
foreach
(
$
request
->
getFiles
(
)
as
$
name
=>
$
filePath
)
{
/** @var FilePathInterface $filePath */
$
curlFile
=
curl_file_create
(
$
filePath
->
__toString
(
)
,
mime_content_type
(
$
filePath
->
__toString
(
)
)
,
$
filePath
->
getFilename
(
)
)
;
$
postFields
[
$
name
]
=
$
curlFile
;
$
hasFiles
=
true
;
}
foreach
(
$
request
->
getPostFields
(
)
as
$
name
=>
$
value
)
{
$
postFields
[
$
name
]
=
$
value
;
}
if
(
count
(
$
postFields
)
===
0
)
{
return
;
}
curl_setopt
(
$
curl
,
CURLOPT_POSTFIELDS
,
$
hasFiles
$
postFields
:
http_build_query
(
$
postFields
)
)
;
}

Sets the CURL content from request.

@param resource                    $curl    The CURL instance.
@param PageFetcherRequestInterface $request The request.


private function parseResult(string $result): PageFetcherResponseInterface
    {
        $resultParts = explode("\r\n\r\n", $result, 2);

        $headers = explode("\r\n", $resultParts[0]);
        $statusLine = array_shift($headers);
        $statusLineParts = explode(' ', $statusLine);
        $httpCode = intval($statusLineParts[1]);
        if ($httpCode === 100) {
            return $this->parseResult($resultParts[1]);
        }

        $content = count($resultParts) > 1 ? $resultParts[1] : '';

        $response = new PageFetcherResponse($httpCode, $content);
        foreach ($headers as $header) {
            $response->addHeader(trim($header));
        }

        return $response;
    }

private
function
parseResult
(
string
$
result
)
:
PageFetcherResponseInterface
{
$
resultParts
=
explode
(
"\r\n\r\n"
,
$
result
,
2
)
;
$
headers
=
explode
(
"\r\n"
,
$
resultParts
[
0
]
)
;
$
statusLine
=
array_shift
(
$
headers
)
;
$
statusLineParts
=
explode
(
' '
,
$
statusLine
)
;
$
httpCode
=
intval
(
$
statusLineParts
[
1
]
)
;
if
(
$
httpCode
===
100
)
{
return
$
this
->
parseResult
(
$
resultParts
[
1
]
)
;
}
$
content
=
count
(
$
resultParts
)
>
1
$
resultParts
[
1
]
:
''
;
$
response
=
new
PageFetcherResponse
(
$
httpCode
,
$
content
)
;
foreach
(
$
headers
as
$
header
)
{
$
response
->
addHeader
(
trim
(
$
header
)
)
;
}
return
$
response
;
}

Parses the CURL result into a PageFetcherResponse.

@param string $result The CURL result.

@return PageFetcherResponseInterface The PageFetcherResponse.

Parses the CURL result into a PageFetcherResponse .


public function commonApplicationAttributes()
    {
        return [
            'components' => [
                'i18n' => [
                    'translations' => [
                        'extensions-manager' => [
                            'class' => 'yii\i18n\PhpMessageSource',
                            'basePath' => __DIR__ . '/messages',
                        ]
                    ]
                ],
            ],
            'modules' => [
                'extensions-manager' => [
                    'class' => ExtensionsManager::class,
                    'extensionsStorage' => $this->extensionsStorage,
                    'packagistUrl' => $this->packagistUrl,
                    'githubAccessToken' => $this->githubAccessToken,
                    'applicationName' => $this->applicationName,
                    'githubApiUrl' => $this->githubApiUrl,
                    'extensionsPerPage' => $this->extensionsPerPage,
                    'composerPath' => $this->composerPath,
                    'verbose' => $this->verbose,
                ]
            ],
        ];
    }

public function commonApplicationAttributes ( ) { return [ 'components' => [ 'i18n' => [ 'translations' => [ 'extensions-manager' => [ 'class' => 'yii\i18n\PhpMessageSource' , 'basePath' => __DIR__ . '/messages' , ] ] ] , ] , 'modules' => [ 'extensions-manager' => [ 'class' => ExtensionsManager :: class , 'extensionsStorage' => $ this -> extensionsStorage , 'packagistUrl' => $ this -> packagistUrl , 'githubAccessToken' => $ this -> githubAccessToken , 'applicationName' => $ this -> applicationName , 'githubApiUrl' => $ this -> githubApiUrl , 'extensionsPerPage' => $ this -> extensionsPerPage , 'composerPath' => $ this -> composerPath , 'verbose' => $ this -> verbose , ] ] , ] ; }

Returns array of module configuration that should be stored in application config.
Array should be ready to merge in app config.
Used both for web and console.

@return array

Returns array of module configuration that should be stored in application config . Array should be ready to merge in app config . Used both for web and console .


protected function getOption($option)
    {
        return in_array($option, $this->getOptions())
            ? $this->getOptions()[$option]
            : null;
    }

protected function getOption ( $ option ) { return in_array ( $ option , $ this -> getOptions ( ) ) ? $ this -> getOptions ( ) [ $ option ] : null ; }

Get a option constant from its name

@param  string $option
@return integer


protected function buildOptions(array $defaults = null)
    {
        $options = $this->getOptions();

        if ($defaults) $options = array_merge($defaults, $options);

        foreach ($options as $option) {
            if ( ! array_key_exists($option, $this->options)) continue;

            if ( ! isset($optionsBitwise)) {
                $optionsBitwise = $this->options[$option];
                continue;
            }

            $optionsBitwise = $optionsBitwise | $this->options[$option];
        }

        return isset($optionsBitwise) ? $optionsBitwise : null;
    }

protected function buildOptions ( array $ defaults = null ) { $ options = $ this -> getOptions ( ) ; if ( $ defaults ) $ options = array_merge ( $ defaults , $ options ) ; foreach ( $ options as $ option ) { if ( ! array_key_exists ( $ option , $ this -> options ) ) continue ; if ( ! isset ( $ optionsBitwise ) ) { $ optionsBitwise = $ this -> options [ $ option ] ; continue ; } $ optionsBitwise = $ optionsBitwise | $ this -> options [ $ option ] ; } return isset ( $ optionsBitwise ) ? $ optionsBitwise : null ; }

Build the options constant using the bitwise operator

@param  array $defaults
@return integer


public function user($type, $params = array()) {
    $command_mapping = array(
      'auth'      => 'UserAuth',
      'info'      => 'UserInfo',
      'add'       => 'UserAdd',
      'provision' => 'UserProvision',
      'list'      => 'UserList',
      'delete'    => 'UserDelete'
    );

    if (!isset($command_mapping[$type])) {
      throw new InvalidArgumentException(sprintf('"%s" is not a valid user command.', $type));
    }

    // check if exists a specific implementation for this command
    $override_func = 'user' . ucfirst($type);
    if (function_exists($override_func)) {
      return $override_func($params);
    }

    $command = $this->client->getCommand($command_mapping[$type], $params);
    return $this->execute($command);
  }

User API callback

@param string $type API call type
@param string $config API parameters

@return array|null Response array
@throws InvalidArgumentException


public function ping()
  {
    $command = $this->client->getCommand('Ping');
    $res = $this->execute($command);
    return $res;
  }

public function ping ( ) { $ command = $ this -> client -> getCommand ( 'Ping' ) ; $ res = $ this -> execute ( $ command ) ; return $ res ; }

Ping Securepass API

@return array|null Response array


public function setAttribute($key, $value)
    {
        switch ($key) {
            case 'orientation':
                $this->attributes[$key] =
                    $value == 'horizontal' ?
                    wxHORIZONTAL :
                    wxVERTICAL
                ;
            default:
                $this->attributes[$key] = $value;
            break;
        }
    }

public function setAttribute ( $ key , $ value ) { switch ( $ key ) { case 'orientation' : $ this -> attributes [ $ key ] = $ value == 'horizontal' ? wxHORIZONTAL : wxVERTICAL ; default : $ this -> attributes [ $ key ] = $ value ; break ; } }

Set the an element attribute

@param string $key
@param mixed $value


public function format(bool $displayCountryForUS = false): string
    {
        $formatter = new NumberFormatter('en', NumberFormatter::CURRENCY);

        if ($displayCountryForUS && $this->currency === 'USD') {
            if ($this->amount >= 0) {
                return 'US' . $formatter->formatCurrency($this->amount, $this->currency);
            }
            return '-US' . $formatter->formatCurrency(-$this->amount, $this->currency);
        }
        return $formatter->formatCurrency($this->amount, $this->currency);
    }

public function format ( bool $ displayCountryForUS = false ) : string { $ formatter = new NumberFormatter ( 'en' , NumberFormatter :: CURRENCY ) ; if ( $ displayCountryForUS && $ this -> currency === 'USD' ) { if ( $ this -> amount >= 0 ) { return 'US' . $ formatter -> formatCurrency ( $ this -> amount , $ this -> currency ) ; } return '-US' . $ formatter -> formatCurrency ( - $ this -> amount , $ this -> currency ) ; } return $ formatter -> formatCurrency ( $ this -> amount , $ this -> currency ) ; }

Returns a rounded string with the currency symbol

@param bool $displayCountryForUS Set to true if you would like 'US$' instead of just '$'
@return string


public function formatForAccounting(): string
    {
        $amount = $this->getRoundedAmount();
        $negative = 0 > $amount;
        if ($negative) {
            $amount *= -1;
        }
        $amount = number_format($amount, Intl::getCurrencyBundle()->getFractionDigits($this->currency));
        return $negative ? '(' . $amount . ')' : $amount;
    }

public function formatForAccounting ( ) : string { $ amount = $ this -> getRoundedAmount ( ) ; $ negative = 0 > $ amount ; if ( $ negative ) { $ amount *= - 1 ; } $ amount = number_format ( $ amount , Intl :: getCurrencyBundle ( ) -> getFractionDigits ( $ this -> currency ) ) ; return $ negative ? '(' . $ amount . ')' : $ amount ; }

Returns a rounded number without currency
If the number is negative, the currency is within parentheses

Returns a rounded number without currency If the number is negative the currency is within parentheses


public function getRoundedAmount(): float
    {
        $fractionDigits = Intl::getCurrencyBundle()->getFractionDigits($this->currency);
        $roundingIncrement = Intl::getCurrencyBundle()->getRoundingIncrement($this->currency);

        $value = round($this->amount, $fractionDigits);

        // Swiss rounding
        if (0 < $roundingIncrement && 0 < $fractionDigits) {
            $roundingFactor = $roundingIncrement / pow(10, $fractionDigits);
            $value = round($value / $roundingFactor) * $roundingFactor;
        }

        return $value;
    }

public
function
getRoundedAmount
(
)
:
float
{
$
fractionDigits
=
Intl
::
getCurrencyBundle
(
)
->
getFractionDigits
(
$
this
->
currency
)
;
$
roundingIncrement
=
Intl
::
getCurrencyBundle
(
)
->
getRoundingIncrement
(
$
this
->
currency
)
;
$
value
=
round
(
$
this
->
amount
,
$
fractionDigits
)
;
// Swiss rounding
if
(
0
<
$
roundingIncrement
&&
0
<
$
fractionDigits
)
{
$
roundingFactor
=
$
roundingIncrement
/
pow
(
10
,
$
fractionDigits
)
;
$
value
=
round
(
$
value
/
$
roundingFactor
)
*
$
roundingFactor
;
}
return
$
value
;
}

Returns the amount rounded to the correct number of decimal places for that currency


public function split(array $percentages, bool $round = true): array
    {
        $totalPercentage = array_sum($percentages);
        if ($totalPercentage > 100) {
            throw new InvalidArgumentException('Only 100% can be allocated');
        }
        $amounts = [];
        $total = 0;
        if (!$round) {
            foreach ($percentages as $percentage) {
                $share = $this->percentage($percentage);
                $total += $share->getAmount();
                $amounts[] = $share;
            }
            if ($totalPercentage != 100) {
                $amounts[] = new static($this->amount - $total, $this->currency);
            }
            return $amounts;
        }

        $count = 0;

        if ($totalPercentage != 100) {
            $percentages[] = 0; //Dummy record to trigger the rest of the amount being assigned to a final pot
        }

        foreach ($percentages as $percentage) {
            ++$count;
            if ($count == count($percentages)) {
                $amounts[] = new static($this->amount - $total, $this->currency);
            } else {
                $share = $this->percentage($percentage)->round();
                $total += $share->getAmount();
                $amounts[] = $share;
            }
        }

        return $amounts;
    }

Pass in an array of percentages to allocate Money in those amounts.
Final entry in array gets any remaining units.
If the percentages total less than 100, remaining money is allocated to an extra return value.

By default, the amounts are rounded to the correct number of decimal places for that currency. This can be disabled by passing false as the second argument.

@param float[] $percentages An array of percentages that must total 100 or less
@param bool $round
@return Money[]

Pass in an array of percentages to allocate Money in those amounts . Final entry in array gets any remaining units . If the percentages total less than 100 remaining money is allocated to an extra return value .


protected function prepareAndInjectElements($elements, FieldsetInterface $fieldset, $method)
    {
        $elements = $this->validateSpecification($elements, $method);

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

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

protected function prepareAndInjectElements ( $ elements , FieldsetInterface $ fieldset , $ method ) { $ elements = $ this -> validateSpecification ( $ elements , $ method ) ; foreach ( $ elements as $ elementSpecification ) { if ( null === $ elementSpecification ) { continue ; } $ fieldset -> add ( $ elementSpecification ) ; } }

Takes a list of element specifications, creates the elements, and injects them into the provided fieldset

@param  array|Traversable|ArrayAccess $elements
@param  FieldsetInterface $fieldset
@param  string $method Method invoking this one (for exception messages)
@return void

Takes a list of element specifications creates the elements and injects them into the provided fieldset


public function getMe($accessToken)
    {
        if (empty($accessToken)) {
            throw new \InvalidArgumentException('Empty access token provided', 1);
        }
        $response = $this->getClient()->get(self::ENDPOINT, array('Authorization' => 'OAuth '.$accessToken));
        $data = $this->jsonResponse($response);

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

public
function
getMe
(
$
accessToken
)
{
if
(
empty
(
$
accessToken
)
)
{
throw
new
\
InvalidArgumentException
(
'Empty access token provided'
,
1
)
;
}
$
response
=
$
this
->
getClient
(
)
->
get
(
self
::
ENDPOINT
,
array
(
'Authorization'
=>
'OAuth '
.
$
accessToken
)
)
;
$
data
=
$
this
->
jsonResponse
(
$
response
)
;
return
$
this
->
getFactory
(
)
->
createEntity
(
$
data
)
;
}

Get authenticated user.

@param string $accessToken

@return Me


function run()
    {
        //Resolve request
        $this->resolve();

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

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

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

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

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

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

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


private function searchRouter($routes)
    {
        foreach ($routes as $route) {
            if ($route['controller'] === null
              || !preg_match_all('#^' . $route['request'] . '$#',
                    $this->request,
                    $matches,
                    PREG_SET_ORDER)
                  ) {
                continue;
            }
            $route['params'] = array_slice($matches[0], 1);
            return $route;
        }
        //não existe rotas
        return false;
    }

private
function
searchRouter
(
$
routes
)
{
foreach
(
$
routes
as
$
route
)
{
if
(
$
route
[
'controller'
]
===
||
!
preg_match_all
(
'#^'
.
$
route
[
'request'
]
.
'$#'
,
$
this
->
request
,
$
matches
,
PREG_SET_ORDER
)
)
{
continue
;
}
$
route
[
'params'
]
=
array_slice
(
$
matches
[
0
]
,
1
)
;
return
$
route
;
}
//não existe rotas
return
false
;
}


private function requestMethod()
    {
        if (php_sapi_name() === 'cli') {
            return 'CLI';
        }
        // Take the method as found in $_SERVER
        $method = $_SERVER['REQUEST_METHOD'];
        if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
            ob_start();
            $method = 'GET';
        } // If it's a POST request, check for a method override header
        elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $headers = $this->requestHeaders();
            if (isset($headers['X-HTTP-Method-Override']) && in_array($headers['X-HTTP-Method-Override'], array('PUT', 'DELETE', 'PATCH'))) {
                $method = $headers['X-HTTP-Method-Override'];
            }
        }
        return $method;
    }

Get the request method used, taking overrides into account
@return string The Request method to handle

Get the request method used taking overrides into account


public function getLogs()
    {
        $logsArray = [];

        $logs = LoggerORM::findAll();

        foreach ($logs as $log) {

            $isException = false;

            $log = (array) $log;

            $logCabin = [];

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

                $isException = true;

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

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

                    $logCabin[$key] = $value;
                }

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

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

                } else {

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

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

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

                if ($date === null) {

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

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

            }, $log['dates']);

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

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

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

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

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

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

        return $logsArray;
    }

public
function
getLogs
(
)
{
$
logsArray
=
[
]
;
$
logs
=
LoggerORM
::
findAll
(
)
;
foreach
(
$
logs
as
$
log
)
{
$
isException
=
false
;
$
log
=
(
array
)
$
log
;
$
logCabin
=
[
]
;
if
(
$
log
[
'exception'
]
!==
&&
is_array
(
$
log
[
'exception'
]
)
&&
count
(
$
log
[
'exception'
]
)
>
0
)
{
$
isException
=
true
;
foreach
(
$
log
[
'exception'
]
as
$
key
=>
$
value
)
{
$
key
=
$
this
->
deathByCamels
(
$
key
)
;
$
logCabin
[
$
key
]
=
$
value
;
}
if
(
(
$
options
=
$
this
->
getOptions
(
$
log
[
'log_hash'
]
)
)
!==
)
{
$
logCabin
[
'options'
]
=
$
options
->
details
;
}
else
{
$
logCabin
[
'options'
]
=
[
'keep_dates'
=>
$
this
->
module
->
config
(
'log_dates'
)
,
'keep_messages'
=>
$
this
->
module
->
config
(
'log_messages'
)
]
;
}
}
$
logCabin
[
'message'
]
=
$
log
[
'messages'
]
;
$
logCabin
[
'dates'
]
=
array_map
(
function
(
$
date
)
{
if
(
$
date
===
)
{
return
;
}
$
date
=
new
\
DateTime
(
$
date
)
;
return
date_format
(
$
date
,
'Y/m/d H:i:s'
)
;
}
,
$
log
[
'dates'
]
)
;
$
logCabin
[
'count'
]
=
$
log
[
'count'
]
;
$
logCabin
[
'errorLevel'
]
=
$
log
[
'error_level'
]
;
$
logCabin
[
'loggerName'
]
=
$
log
[
'logger_name'
]
;
$
logCabin
[
'id'
]
=
$
log
[
'id'
]
;
$
logCabin
[
'logHash'
]
=
$
log
[
'log_hash'
]
;
$
logsArray
[
]
=
$
isException
[
'exception'
=>
$
logCabin
]
:
[
'message'
=>
$
logCabin
]
;
}
return
$
logsArray
;
}

Abraham Lincoln lived in a log cabin
@return array


private function deathByCamels($string)
    {
        $this->index = 0;
        return implode('', array_map(function($el) {
            $this->index++;
            return $this->index === 1 ? $el : ucfirst($el);
        }, explode(' ', str_replace('_', ' ', $string))));
    }

private
function
deathByCamels
(
$
string
)
{
$
this
->
index
=
0
;
return
implode
(
''
,
array_map
(
function
(
$
el
)
{
$
this
->
index
++
;
return
$
this
->
index
===
1
$
el
:
ucfirst
(
$
el
)
;
}
,
explode
(
' '
,
str_replace
(
'_'
,
' '
,
$
string
)
)
)
)
;
}

Returns a Javascript formatted name from a database formatted one
hello_world => helloWorld
@param $string
@return string

Returns a Javascript formatted name from a database formatted one hello_world = > helloWorld


public static function bytes($bytes)
  {
    $kbytes = sprintf("%.02f", $bytes/1024);
    $mbytes = sprintf("%.02f", $kbytes/1024);
    $gbytes = sprintf("%.02f", $mbytes/1024);
    $tbytes = sprintf("%.02f", $gbytes/1024);

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

    return $bytes . " B";
  }

public
static
function
bytes
(
$
bytes
)
{
$
kbytes
=
sprintf
(
"%.02f"
,
$
bytes
/
1024
)
;
$
mbytes
=
sprintf
(
"%.02f"
,
$
kbytes
/
1024
)
;
$
gbytes
=
sprintf
(
"%.02f"
,
$
mbytes
/
1024
)
;
$
tbytes
=
sprintf
(
"%.02f"
,
$
gbytes
/
1024
)
;
if
(
$
tbytes
>=
1
)
return
$
tbytes
.
" TB"
;
if
(
$
gbytes
>=
1
)
return
$
gbytes
.
" GB"
;
if
(
$
mbytes
>=
1
)
return
$
mbytes
.
" MB"
;
if
(
$
kbytes
>=
1
)
return
$
kbytes
.
" KB"
;
return
$
bytes
.
" B"
;
}

Converts bytes to a human readable value.

@param  integer $bytes
@return string

Converts bytes to a human readable value .


public static function codec($codec)
  {
    if($codec == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::CODEC_SPEEX_NARROWBAND)
      return "Speex Narrowband (8 kHz)";
    if($codec == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::CODEC_SPEEX_WIDEBAND)
      return "Speex Wideband (16 kHz)";
    if($codec == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::CODEC_SPEEX_ULTRAWIDEBAND)
      return "Speex Ultra-Wideband (32 kHz)";
    if($codec == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::CODEC_CELT_MONO)
      return "CELT Mono (48 kHz)";

    return "Unknown";
  }

public
static
function
codec
(
$
codec
)
{
if
(
$
codec
==
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
CODEC_SPEEX_NARROWBAND
)
return
"Speex Narrowband (8 kHz)"
;
if
(
$
codec
==
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
CODEC_SPEEX_WIDEBAND
)
return
"Speex Wideband (16 kHz)"
;
if
(
$
codec
==
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
CODEC_SPEEX_ULTRAWIDEBAND
)
return
"Speex Ultra-Wideband (32 kHz)"
;
if
(
$
codec
==
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
CODEC_CELT_MONO
)
return
"CELT Mono (48 kHz)"
;
return
"Unknown"
;
}

Converts a given codec ID to a human readable name.

@param  integer $codec
@return string

Converts a given codec ID to a human readable name .


public static function groupType($type)
  {
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::GROUP_DBTYPE_TEMPLATE)
      return "Template";
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::GROUP_DBTYPE_REGULAR)
      return "Regular";
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::GROUP_DBTYPE_SERVERQUERY)
      return "ServerQuery";

    return "Unknown";
  }

public static function groupType ( $ type ) { if ( $ type == \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: GROUP_DBTYPE_TEMPLATE ) return "Template" ; if ( $ type == \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: GROUP_DBTYPE_REGULAR ) return "Regular" ; if ( $ type == \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: GROUP_DBTYPE_SERVERQUERY ) return "ServerQuery" ; return "Unknown" ; }

Converts a given group type ID to a human readable name.

@param  integer $type
@return string

Converts a given group type ID to a human readable name .


public static function permissionType($type)
  {
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_TYPE_SERVERGROUP)
      return "Server Group";
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_TYPE_CLIENT)
      return "Client";
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_TYPE_CHANNEL)
      return "Channel";
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_TYPE_CHANNELGROUP)
      return "Channel Group";
    if($type == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::PERM_TYPE_CHANNELCLIENT)
      return "Channel Client";

    return "Unknown";
  }

public
static
function
permissionType
(
$
type
)
{
if
(
$
type
==
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
PERM_TYPE_SERVERGROUP
)
return
"Server Group"
;
if
(
$
type
==
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
PERM_TYPE_CLIENT
)
return
"Client"
;
if
(
$
type
==
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
PERM_TYPE_CHANNEL
)
return
"Channel"
;
if
(
$
type
==
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
PERM_TYPE_CHANNELGROUP
)
return
"Channel Group"
;
if
(
$
type
==
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
PERM_TYPE_CHANNELCLIENT
)
return
"Channel Client"
;
return
"Unknown"
;
}

Converts a given permission type ID to a human readable name.

@param  integer $type
@return string

Converts a given permission type ID to a human readable name .


public static function logLevel($level)
  {
    if(is_numeric($level))
    {
      if($level == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_CRITICAL)
        return "CRITICAL";
      if($level == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_ERROR)
        return "ERROR";
      if($level == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_DEBUG)
        return "DEBUG";
      if($level == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_WARNING)
        return "WARNING";
      if($level == \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::LOGLEVEL_INFO)
        return "INFO";

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

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

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

Converts a given log level ID to a human readable name and vice versa.

@param  mixed  $level
@return string

Converts a given log level ID to a human readable name and vice versa .


public static function logEntry($entry)
  {
    $parts = explode("|", $entry, 5);
    $array = array();

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

    return $array;
  }

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

Converts a specified log entry string into an array containing the data.

@param  string $entry
@return array

Converts a specified log entry string into an array containing the data .


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

        return $list;
    }

Custom filtering on "Status"

@return Form


protected static function getTraits()
    {
        if (isset(static::$traitsList[static::class]) === false) {
            $className = static::class;
            static::$traitsList[static::class] = [];
            do {
                foreach (class_uses($className) as $value) {
                    static::$traitsList[static::class][$value] = StringHelper::basename($value);
                }
                $className = get_parent_class($className);
            } while ($className !== false);
        }
        return static::$traitsList[static::class];
    }

protected static function getTraits ( ) { if ( isset ( static :: $ traitsList [ static :: class ] ) === false ) { $ className = static :: class ; static :: $ traitsList [ static :: class ] = [ ] ; do { foreach ( class_uses ( $ className ) as $ value ) { static :: $ traitsList [ static :: class ] [ $ value ] = StringHelper :: basename ( $ value ) ; } $ className = get_parent_class ( $ className ) ; } while ( $ className !== false ) ; } return static :: $ traitsList [ static :: class ] ; }

Get all traits that uses for model
@return mixed


protected function callTraitMethod($traitName, $methodName)
    {
        return method_exists($this, $traitName . $methodName)
            ? $this->{$traitName . $methodName}()
            : null;
    }

protected function callTraitMethod ( $ traitName , $ methodName ) { return method_exists ( $ this , $ traitName . $ methodName ) ? $ this -> { $ traitName . $ methodName } ( ) : null ; }

Call a trait method and return a result or null in not exists.
This method builds a full method name, checks it and calls if exists.
@param string $traitName
@param string $methodName
@return null|mixed

Call a trait method and return a result or null in not exists . This method builds a full method name checks it and calls if exists .


protected function callEvents($eventName)
    {
        foreach (static::getTraits() as $name) {
            if ($name === 'EntityTrait') {
                continue;
            }
            $this->callTraitMethod($name, $eventName);
        }
    }

protected function callEvents ( $ eventName ) { foreach ( static :: getTraits ( ) as $ name ) { if ( $ name === 'EntityTrait' ) { continue ; } $ this -> callTraitMethod ( $ name , $ eventName ) ; } }

Call trait event methods.
@param string $eventName


public function attributeLabels()
    {
        if (isset(static::$attributeLabelsList[static::class]) === false) {
            static::$attributeLabelsList[static::class] = isset($this->attributeLabels) === true
                ? $this->attributeLabels
                : [];
            foreach (static::getTraits() as $name) {
                if (null !== $attributeLabels = $this->callTraitMethod($name, 'AttributeLabels')) {
                    static::$attributeLabelsList[static::class] = ArrayHelper::merge(
                        static::$attributeLabelsList[static::class],
                        $attributeLabels
                    );
                }
            }
        }
        return static::$attributeLabelsList[static::class];
    }

public function attributeLabels ( ) { if ( isset ( static :: $ attributeLabelsList [ static :: class ] ) === false ) { static :: $ attributeLabelsList [ static :: class ] = isset ( $ this -> attributeLabels ) === true ? $ this -> attributeLabels : [ ] ; foreach ( static :: getTraits ( ) as $ name ) { if ( null !== $ attributeLabels = $ this -> callTraitMethod ( $ name , 'AttributeLabels' ) ) { static :: $ attributeLabelsList [ static :: class ] = ArrayHelper :: merge ( static :: $ attributeLabelsList [ static :: class ] , $ attributeLabels ) ; } } } return static :: $ attributeLabelsList [ static :: class ] ; }

Get all attribute labels.
This method merges a model attributeLabels with attribute labels of all used traits.
@return array

Get all attribute labels . This method merges a model attributeLabels with attribute labels of all used traits .


public function attributeHints()
    {
        if (isset(static::$attributeHintsList[static::class]) === false) {
            static::$attributeHintsList[static::class] = isset($this->attributeHints) === true
                ? $this->attributeHints
                : [];
            foreach (static::getTraits() as $name) {
                if (null !== $attributeHints = $this->callTraitMethod($name, 'AttributeHints')) {
                    static::$attributeHintsList[static::class] = ArrayHelper::merge(
                        static::$attributeHintsList[static::class],
                        $attributeHints
                    );
                }
            }
        }
        return static::$attributeHintsList[static::class];
    }

public function attributeHints ( ) { if ( isset ( static :: $ attributeHintsList [ static :: class ] ) === false ) { static :: $ attributeHintsList [ static :: class ] = isset ( $ this -> attributeHints ) === true ? $ this -> attributeHints : [ ] ; foreach ( static :: getTraits ( ) as $ name ) { if ( null !== $ attributeHints = $ this -> callTraitMethod ( $ name , 'AttributeHints' ) ) { static :: $ attributeHintsList [ static :: class ] = ArrayHelper :: merge ( static :: $ attributeHintsList [ static :: class ] , $ attributeHints ) ; } } } return static :: $ attributeHintsList [ static :: class ] ; }

Get all attribute hints.
This method merges a model attributeHints with attribute hints of all used traits.
@return array

Get all attribute hints . This method merges a model attributeHints with attribute hints of all used traits .


public function toArray()
  {
    $array = array();
    $table = $this->toTable(1);

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

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

    return $array;
  }

public function toArray ( ) { $ array = array ( ) ; $ table = $ this -> toTable ( 1 ) ; for ( $ i = 0 ; $ i < count ( $ table ) ; $ i ++ ) { foreach ( $ table [ $ i ] as $ pair ) { if ( ! $ pair -> contains ( \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: SEPARATOR_PAIR ) ) { $ array [ $ i ] [ $ pair -> toString ( ) ] = null ; } else { list ( $ ident , $ value ) = $ pair -> split ( \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: SEPARATOR_PAIR , 2 ) ; $ array [ $ i ] [ $ ident -> toString ( ) ] = $ value -> isInt ( ) ? $ value -> toInt ( ) : ( ! func_num_args ( ) ? $ value -> unescape ( ) : $ value ) ; } } } return $ array ; }

Returns a multi-dimensional array containing the reply splitted in multiple rows and columns.

@return array

Returns a multi - dimensional array containing the reply splitted in multiple rows and columns .


protected function fetchError($err)
  {
    $cells = $err->section(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_CELL, 1, 3);

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

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

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

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

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

protected
function
fetchError
(
$
err
)
{
$
cells
=
$
err
->
section
(
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
SEPARATOR_CELL
,
1
,
3
)
;
foreach
(
$
cells
->
split
(
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
SEPARATOR_CELL
)
as
$
pair
)
{
list
(
$
ident
,
$
value
)
=
$
pair
->
split
(
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
SEPARATOR_PAIR
)
;
$
this
->
err
[
$
ident
->
toString
(
)
]
=
$
value
->
isInt
(
)
$
value
->
toInt
(
)
:
$
value
->
unescape
(
)
;
}
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Helper
\
Signal
::
getInstance
(
)
->
emit
(
"notifyError"
,
$
this
)
;
if
(
$
this
->
getErrorProperty
(
"id"
,
0x00
)
!=
0x00
)
{
if
(
$
permid
=
$
this
->
getErrorProperty
(
"failed_permid"
)
)
{
try
{
$
suffix
=
" (failed on "
.
$
this
->
con
->
permissionGetNameById
(
$
permid
)
.
")"
;
}
catch
(
Exception
$
e
)
{
$
suffix
=
" (failed on "
.
$
this
->
cmd
->
section
(
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
SEPARATOR_CELL
)
.
" "
.
$
permid
.
"/0x"
.
strtoupper
(
dechex
(
$
permid
)
)
.
")"
;
}
}
elseif
(
$
details
=
$
this
->
getErrorProperty
(
"extra_msg"
)
)
{
$
suffix
=
" ("
.
$
details
.
")"
;
}
else
{
$
suffix
=
""
;
}
throw
new
Exception
(
$
this
->
getErrorProperty
(
"msg"
)
.
$
suffix
,
$
this
->
getErrorProperty
(
"id"
)
)
;
}
}

Parses a ServerQuery error and throws a TeamSpeak3_Adapter_ServerQuery_Exception object if
there's an error.

@param  string $err
@throws Exception
@return void


protected function fetchReply($rpl)
  {
    foreach($rpl as $key => $val)
    {
      if($val->startsWith(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::GREET))
      {
        unset($rpl[$key]);
      }
      elseif($val->startsWith(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::EVENT))
      {
        $this->evt[] = new Event($rpl[$key], $this->con);
        unset($rpl[$key]);
      }
    }

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

protected function fetchReply ( $ rpl ) { foreach ( $ rpl as $ key => $ val ) { if ( $ val -> startsWith ( \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: GREET ) ) { unset ( $ rpl [ $ key ] ) ; } elseif ( $ val -> startsWith ( \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: EVENT ) ) { $ this -> evt [ ] = new Event ( $ rpl [ $ key ] , $ this -> con ) ; unset ( $ rpl [ $ key ] ) ; } } $ this -> rpl = new \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ Helper \ String ( implode ( \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: SEPARATOR_LIST , $ rpl ) ) ; }

Parses a ServerQuery reply and creates a \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String object.

@param  string $rpl
@return void

Parses a ServerQuery reply and creates a \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ Helper \ String object .


public function getIdentity()
    {
        if ($this->identity instanceof User) {
            return $this->identity;
        }

        $identity = parent::getIdentity();

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

            return;
        }

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

            return;
        }

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

            return;
        }

        $this->identity = $identity;

        return $identity;
    }

public function getIdentity ( ) { if ( $ this -> identity instanceof User ) { return $ this -> identity ; } $ identity = parent :: getIdentity ( ) ; if ( empty ( $ identity ) ) { $ this -> clearIdentity ( ) ; return ; } $ identity = $ this -> tableGateway -> selectByPrimary ( $ identity ) ; if ( ! ( $ identity instanceof User ) ) { $ this -> clearIdentity ( ) ; return ; } if ( ! \ in_array ( $ identity -> getStatus ( ) , [ User :: STATUS_ACTIVE ] ) ) { $ this -> clearIdentity ( ) ; return ; } $ this -> identity = $ identity ; return $ identity ; }

Returns the authenticated identity or null if no identity is available

@return User|null


public function hasIdentity()
    {
        $storageCheck = !$this->getStorage()->isEmpty();
        if (!$storageCheck) {
            return false;
        }

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

public function hasIdentity ( ) { $ storageCheck = ! $ this -> getStorage ( ) -> isEmpty ( ) ; if ( ! $ storageCheck ) { return false ; } return $ this -> getIdentity ( ) instanceof User ; }

Returns true if and only if an identity is available

@return bool


public function restore()
    {
        /** @var ActiveRecord $this */
        if (((boolean) $this->{$this->isDeletedAttribute}) !== false) {
            $this->{$this->isDeletedAttribute} = false;
            return $this->save(true, [$this->isDeletedAttribute]);
        }
        return true;
    }

public
function
restore
(
)
{
/** @var ActiveRecord $this */
if
(
(
(
boolean
)
$
this
->
{
$
this
->
isDeletedAttribute
}
)
!==
false
)
{
$
this
->
{
$
this
->
isDeletedAttribute
}
=
false
;
return
$
this
->
save
(
true
,
[
$
this
->
isDeletedAttribute
]
)
;
}
return
true
;
}

Restore a record after soft deleting.
@return bool


public function getUser($userId)
    {
        $response = $this->getClient()->get(self::ENDPOINT.$userId);
        $data = $this->jsonResponse($response);

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

public function getUser ( $ userId ) { $ response = $ this -> getClient ( ) -> get ( self :: ENDPOINT . $ userId ) ; $ data = $ this -> jsonResponse ( $ response ) ; return $ this -> getFactory ( ) -> createEntity ( $ data ) ; }

Get user.

@param string $userId

@return User


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

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

Get user followed games.

@param string $userId
@param array  $params

@return GameList


public static function get_notices($context = null)
    {
        // fallback to the CMS as the context - this is required to be consistent with the original behaviour.
        if ($context == null) {
            $context = 'CMS';
        }

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

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

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

         return $notices;
    }

Gets any notices relevant to the present time, context and current users

@param string $context (default: CMS)
@return ArrayList

Gets any notices relevant to the present time context and current users


public function getChannel($channelId)
    {
        $response = $this->getClient()->get(self::ENDPOINT.$channelId);
        $data = $this->jsonResponse($response);

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

public function getChannel ( $ channelId ) { $ response = $ this -> getClient ( ) -> get ( self :: ENDPOINT . $ channelId ) ; $ data = $ this -> jsonResponse ( $ response ) ; return $ this -> getFactory ( ) -> createEntity ( $ data ) ; }

Get channel.

@param string $channelId

@return Channel


public function escape()
  {
    foreach(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::getEscapePatterns() as $search => $replace)
    {
      $this->string = str_replace($search, $replace, $this->string);
    }

    return $this;
  }

public function escape ( ) { foreach ( \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: getEscapePatterns ( ) as $ search => $ replace ) { $ this -> string = str_replace ( $ search , $ replace , $ this -> string ) ; } return $ this ; }

Escapes a string using the TeamSpeak 3 escape patterns.

@return String

Escapes a string using the TeamSpeak 3 escape patterns .


public function unescape()
  {
    $this->string = strtr($this->string, array_flip(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::getEscapePatterns()));

    return $this;
  }

public function unescape ( ) { $ this -> string = strtr ( $ this -> string , array_flip ( \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: getEscapePatterns ( ) ) ) ; return $ this ; }

Unescapes a string using the TeamSpeak 3 escape patterns.

@return String

Unescapes a string using the TeamSpeak 3 escape patterns .


public function getTeam($teamId)
    {
        $response = $this->getClient()->get(self::ENDPOINT.$teamId);
        $data = $this->jsonResponse($response);

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

public function getTeam ( $ teamId ) { $ response = $ this -> getClient ( ) -> get ( self :: ENDPOINT . $ teamId ) ; $ data = $ this -> jsonResponse ( $ response ) ; return $ this -> getFactory ( ) -> createEntity ( $ data ) ; }

Get team.

@param string $teamId

@return Team


public function addResult(ResultInterface $result, string $name = null): ContainerResult
    {
        $this->valid = $this->isValid() && $result->isValid();

        if (is_string($name) === true) {
            $this->results[$name] = $result;
        } else {
            $this->results[] = $result;
        }

        return $this;
    }

public function addResult ( ResultInterface $ result , string $ name = null ) : ContainerResult { $ this -> valid = $ this -> isValid ( ) && $ result -> isValid ( ) ; if ( is_string ( $ name ) === true ) { $ this -> results [ $ name ] = $ result ; } else { $ this -> results [ ] = $ result ; } return $ this ; }

Add result to container.

@param ResultInterface $result
@param string|null     $name
@return ContainerResult


public function getStream($channelId)
    {
        $response = $this->getClient()->get(self::ENDPOINT.$channelId);
        $data = $this->jsonResponse($response);
        $data = null !== $data['stream'] ? $data['stream'] : [];

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

public function getStream ( $ channelId ) { $ response = $ this -> getClient ( ) -> get ( self :: ENDPOINT . $ channelId ) ; $ data = $ this -> jsonResponse ( $ response ) ; $ data = null !== $ data [ 'stream' ] ? $ data [ 'stream' ] : [ ] ; return $ this -> getFactory ( ) -> createEntity ( $ data ) ; }

Get stream.

@param string $channelId

@return Stream


public function getStreams($params = array())
    {
        $params = 0 < count($params) ? '?'.http_build_query($params) : '';
        $response = $this->getClient()->get(self::ENDPOINT.$params);
        $data = $this->jsonResponse($response);

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

public function getStreams ( $ params = array ( ) ) { $ params = 0 < count ( $ params ) ? '?' . http_build_query ( $ params ) : '' ; $ response = $ this -> getClient ( ) -> get ( self :: ENDPOINT . $ params ) ; $ data = $ this -> jsonResponse ( $ response ) ; return $ this -> getFactory ( ) -> createList ( $ data ) ; }

Get streams.

@param array $params

@return StreamList


public function getFeaturedStreams($params = array())
    {
        $params = 0 < count($params) ? '?'.http_build_query($params) : '';
        $response = $this->getClient()->get(self::ENDPOINT.'featured'.$params);
        $data = $this->jsonResponse($response);

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

public function getFeaturedStreams ( $ params = array ( ) ) { $ params = 0 < count ( $ params ) ? '?' . http_build_query ( $ params ) : '' ; $ response = $ this -> getClient ( ) -> get ( self :: ENDPOINT . 'featured' . $ params ) ; $ data = $ this -> jsonResponse ( $ response ) ; return $ this -> getFactory ( ) -> createFeatured ( $ data ) ; }

Get featured streams.

@param array $params

@return StreamList


public function getFollowedStreams($accessToken, $params = array())
    {
        if (empty($accessToken)) {
            throw new \InvalidArgumentException('Empty access token provided', 1);
        }
        $params = 0 < count($params) ? '?'.http_build_query($params) : '';
        $response = $this->getClient()->get(self::ENDPOINT.'followed'.$params, array('Authorization' => 'OAuth '.$accessToken));
        $data = $this->jsonResponse($response);

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

public
function
getFollowedStreams
(
$
accessToken
,
$
params
=
array
(
)
)
{
if
(
empty
(
$
accessToken
)
)
{
throw
new
\
InvalidArgumentException
(
'Empty access token provided'
,
1
)
;
}
$
params
=
0
<
count
(
$
params
)
'?'
.
http_build_query
(
$
params
)
:
''
;
$
response
=
$
this
->
getClient
(
)
->
get
(
self
::
ENDPOINT
.
'followed'
.
$
params
,
array
(
'Authorization'
=>
'OAuth '
.
$
accessToken
)
)
;
$
data
=
$
this
->
jsonResponse
(
$
response
)
;
return
$
this
->
getFactory
(
)
->
createList
(
$
data
)
;
}

Get authenticated user streams.

@param string $accessToken
@param array  $params

@return StreamList


public function getStreamsSummary($params = array())
    {
        $params = 0 < count($params) ? '?'.http_build_query($params) : '';
        $response = $this->getClient()->get(self::ENDPOINT.'summary'.$params);
        $data = $this->jsonResponse($response);

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

public function getStreamsSummary ( $ params = array ( ) ) { $ params = 0 < count ( $ params ) ? '?' . http_build_query ( $ params ) : '' ; $ response = $ this -> getClient ( ) -> get ( self :: ENDPOINT . 'summary' . $ params ) ; $ data = $ this -> jsonResponse ( $ response ) ; return $ this -> setFactory ( ( new RankFactory ( ) ) ) -> getFactory ( ) -> createEntity ( $ data ) ; }

Get streams summary.

@param array $params

@return Rank


public function getTop($params = array())
    {
        $params = 0 < count($params) ? '?'.http_build_query($params) : '';
        $response = $this->getClient()->get(self::ENDPOINT.'/top'.$params);
        $data = $this->jsonResponse($response);

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

public function getTop ( $ params = array ( ) ) { $ params = 0 < count ( $ params ) ? '?' . http_build_query ( $ params ) : '' ; $ response = $ this -> getClient ( ) -> get ( self :: ENDPOINT . '/top' . $ params ) ; $ data = $ this -> jsonResponse ( $ response ) ; return $ this -> getFactory ( ) -> createTop ( $ data ) ; }

Get gameList games.

@param array $params

@return array


public function getValue()
    {
        if ($this->element) {
            $this->value = $this->element->GetValue();
        }

        return $this->value;
    }

public function getValue ( ) { if ( $ this -> element ) { $ this -> value = $ this -> element -> GetValue ( ) ; } return $ this -> value ; }

Get the value of the text box

@return void


public function resolve($tsdns)
  {
    $this->getTransport()->sendLine($tsdns);
    $repl = $this->getTransport()->readLine();
    $this->getTransport()->disconnect();

    if($repl->section(":", 0)->toInt() == 404)
    {
      throw new TSDNS\Exception("unable to resolve TSDNS hostname (" . $tsdns . ")");
    }

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("tsdnsResolved", $tsdns, $repl);

    return $repl;
  }

public
function
resolve
(
$
tsdns
)
{
$
this
->
getTransport
(
)
->
sendLine
(
$
tsdns
)
;
$
repl
=
$
this
->
getTransport
(
)
->
readLine
(
)
;
$
this
->
getTransport
(
)
->
disconnect
(
)
;
if
(
$
repl
->
section
(
":"
,
0
)
->
toInt
(
)
==
404
)
{
throw
new
TSDNS
\
Exception
(
"unable to resolve TSDNS hostname ("
.
$
tsdns
.
")"
)
;
}
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Helper
\
Signal
::
getInstance
(
)
->
emit
(
"tsdnsResolved"
,
$
tsdns
,
$
repl
)
;
return
$
repl
;
}

Queries the TSDNS server for a specified virtual hostname and returns the result.

@param  string $tsdns
@throws TSDNS\Exception
@return TeamSpeak3_Helper_String

Queries the TSDNS server for a specified virtual hostname and returns the result .


protected function getConfigurables($ignoreCache = false)
    {
        if (count($this->_configurables) === 0 || true === $ignoreCache) {
            $this->_configurables = ExtensionsHelper::getConfigurables();
        }
    }

protected function getConfigurables ( $ ignoreCache = false ) { if ( count ( $ this -> _configurables ) === 0 || true === $ ignoreCache ) { $ this -> _configurables = ExtensionsHelper :: getConfigurables ( ) ; } }

Returns configurables sections.
Loads them from files if not loaded.
@param bool $ignoreCache

Returns configurables sections . Loads them from files if not loaded .


public function message($msg)
  {
    $this->execute("sendtextmessage", array("msg" => $msg, "target" => $this->getId(), "targetmode" => \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::TEXTMSG_CLIENT));
  }

public function message ( $ msg ) { $ this -> execute ( "sendtextmessage" , array ( "msg" => $ msg , "target" => $ this -> getId ( ) , "targetmode" => \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: TEXTMSG_CLIENT ) ) ; }

Sends a text message to the client.

@param  string $msg
@return void


public function kick($reasonid = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::KICK_CHANNEL, $reasonmsg = null)
  {
    return $this->getParent()->clientKick($this->getId(), $reasonid, $reasonmsg);
  }

public function kick ( $ reasonid = \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: KICK_CHANNEL , $ reasonmsg = null ) { return $ this -> getParent ( ) -> clientKick ( $ this -> getId ( ) , $ reasonid , $ reasonmsg ) ; }

Kicks the client from his currently joined channel or from the server.

@param  integer $reasonid
@param  string   $reasonmsg
@return void

Kicks the client from his currently joined channel or from the server .


public function avatarDownload()
  {
    if($this["client_flag_avatar"] == 0) return;

    $download = $this->getParent()->transferInitDownload(rand(0x0000, 0xFFFF), 0, $this->avatarGetName());
    $transfer = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::factory("filetransfer://" . $download["host"] . ":" . $download["port"]);

    return $transfer->download($download["ftkey"], $download["size"]);
  }

public function avatarDownload ( ) { if ( $ this [ "client_flag_avatar" ] == 0 ) return ; $ download = $ this -> getParent ( ) -> transferInitDownload ( rand ( 0x0000 , 0xFFFF ) , 0 , $ this -> avatarGetName ( ) ) ; $ transfer = \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ TeamSpeak3 :: factory ( "filetransfer://" . $ download [ "host" ] . ":" . $ download [ "port" ] ) ; return $ transfer -> download ( $ download [ "ftkey" ] , $ download [ "size" ] ) ; }

Downloads and returns the clients avatar file content.

@return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String

Downloads and returns the clients avatar file content .


protected function bindEvents()
    {
        $callback = new ClosureCallback(function($method) {
            $controller = $this->collection->getController();
            $args = array_slice(func_get_args(), 1);

            return call_user_func_array([$controller, $method], $args);
        });

        foreach ($this->events as $event => $constant) {
            if ( ! array_key_exists($event, $this->attributes)) continue;

            $this->connectEvent($constant, [$callback, $this->$event]);
        }
    }

protected function bindEvents ( ) { $ callback = new ClosureCallback ( function ( $ method ) { $ controller = $ this -> collection -> getController ( ) ; $ args = array_slice ( func_get_args ( ) , 1 ) ; return call_user_func_array ( [ $ controller , $ method ] , $ args ) ; } ) ; foreach ( $ this -> events as $ event => $ constant ) { if ( ! array_key_exists ( $ event , $ this -> attributes ) ) continue ; $ this -> connectEvent ( $ constant , [ $ callback , $ this -> $ event ] ) ; } }

Bind this elements events to the wxPHP event handler

@return void


protected function connectEvent($constant, callable $callback)
    {
        if ( ! method_exists($this->element, 'GetId')) {
            return $this->element->Connect($constant, $callback);
        }

        $id = $this->element->GetId();

        $this->collection
            ->getTopLevelWindow()
            ->getRaw()
            ->Connect($id, $constant, $callback);
    }

protected function connectEvent ( $ constant , callable $ callback ) { if ( ! method_exists ( $ this -> element , 'GetId' ) ) { return $ this -> element -> Connect ( $ constant , $ callback ) ; } $ id = $ this -> element -> GetId ( ) ; $ this -> collection -> getTopLevelWindow ( ) -> getRaw ( ) -> Connect ( $ id , $ constant , $ callback ) ; }

Connect the event to the top-level window

@param  integer   $constant
@param  callable $callback
@return void

Connect the event to the top - level window


public function getQueryVar($key, $default = null)
  {
    if(!$this->hasQuery()) return $default;

    parse_str($this->query, $queryArray);

    if(array_key_exists($key, $queryArray))
    {
      $val = $queryArray[$key];

      if(ctype_digit($val))
      {
        return intval($val);
      }
      elseif(is_string($val))
      {
        return new String($val);
      }
      else
      {
        return $val;
      }
    }

    return $default;
  }

public function getQueryVar ( $ key , $ default = null ) { if ( ! $ this -> hasQuery ( ) ) return $ default ; parse_str ( $ this -> query , $ queryArray ) ; if ( array_key_exists ( $ key , $ queryArray ) ) { $ val = $ queryArray [ $ key ] ; if ( ctype_digit ( $ val ) ) { return intval ( $ val ) ; } elseif ( is_string ( $ val ) ) { return new String ( $ val ) ; } else { return $ val ; } } return $ default ; }

Returns a single variable from the query string.

@param  string $key
@param  mixed  $default
@return mixed

Returns a single variable from the query string .


public static function getBaseUri()
  {
    $scriptPath = new String(dirname(self::getHostParam("SCRIPT_NAME")));

    return self::getHostUri()->append(($scriptPath == DIRECTORY_SEPARATOR ? "" : $scriptPath) . "/");
  }

public static function getBaseUri ( ) { $ scriptPath = new String ( dirname ( self :: getHostParam ( "SCRIPT_NAME" ) ) ) ; return self :: getHostUri ( ) -> append ( ( $ scriptPath == DIRECTORY_SEPARATOR ? "" : $ scriptPath ) . "/" ) ; }

Returns the applications base address.

@return string


public function request($cmd)
  {
    $query = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String::factory($cmd)->section(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_CELL);

    if(strstr($cmd, "\r") || strstr($cmd, "\n"))
    {
      throw new Exception("illegal characters in command '" . $query . "'");
    }
    elseif(in_array($query, $this->block))
    {
      throw new ServerQuery\Exception("command not found", 0x100);
    }

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

    $this->getProfiler()->start();
    $this->getTransport()->sendLine($cmd);
    $this->timer = time();
    $this->count++;

    $rpl = array();

    do {
      $str = $this->getTransport()->readLine();
      $rpl[] = $str;
    } while($str instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String && $str->section(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_CELL) != \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::ERROR);

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

    $reply = new ServerQuery\Reply($rpl, $cmd, $this->getHost());

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit("serverqueryCommandFinished", $cmd, $reply);

    return $reply;
  }

public
function
request
(
$
cmd
)
{
$
query
=
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Helper
\
String
::
factory
(
$
cmd
)
->
section
(
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
SEPARATOR_CELL
)
;
if
(
strstr
(
$
cmd
,
"\r"
)
||
strstr
(
$
cmd
,
"\n"
)
)
{
throw
new
Exception
(
"illegal characters in command '"
.
$
query
.
"'"
)
;
}
elseif
(
in_array
(
$
query
,
$
this
->
block
)
)
{
throw
new
ServerQuery
\
Exception
(
"command not found"
,
0x100
)
;
}
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Helper
\
Signal
::
getInstance
(
)
->
emit
(
"serverqueryCommandStarted"
,
$
cmd
)
;
$
this
->
getProfiler
(
)
->
start
(
)
;
$
this
->
getTransport
(
)
->
sendLine
(
$
cmd
)
;
$
this
->
timer
=
time
(
)
;
$
this
->
count
++
;
$
rpl
=
array
(
)
;
do
{
$
str
=
$
this
->
getTransport
(
)
->
readLine
(
)
;
$
rpl
[
]
=
$
str
;
}
while
(
$
str
instanceof
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Helper
\
String
&&
$
str
->
section
(
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
SEPARATOR_CELL
)
!=
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
ERROR
)
;
$
this
->
getProfiler
(
)
->
stop
(
)
;
$
reply
=
new
ServerQuery
\
Reply
(
$
rpl
,
$
cmd
,
$
this
->
getHost
(
)
)
;
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Helper
\
Signal
::
getInstance
(
)
->
emit
(
"serverqueryCommandFinished"
,
$
cmd
,
$
reply
)
;
return
$
reply
;
}

Sends a prepared command to the server and returns the result.

@param  string $cmd
@throws Exception
@return ServerQuery\Reply

Sends a prepared command to the server and returns the result .


public function wait()
  {
    if($this->getTransport()->getConfig("blocking"))
    {
      throw new Exception("only available in non-blocking mode");
    }

    do {
      $evt = $this->getTransport()->readLine();
    } while($evt instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String && !$evt->section(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_CELL)->startsWith(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::EVENT));

    return new ServerQuery\Event($evt, $this->getHost());
  }

public
function
wait
(
)
{
if
(
$
this
->
getTransport
(
)
->
getConfig
(
"blocking"
)
)
{
throw
new
Exception
(
"only available in non-blocking mode"
)
;
}
do
{
$
evt
=
$
this
->
getTransport
(
)
->
readLine
(
)
;
}
while
(
$
evt
instanceof
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Helper
\
String
&&
!
$
evt
->
section
(
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
SEPARATOR_CELL
)
->
startsWith
(
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
EVENT
)
)
;
return
new
ServerQuery
\
Event
(
$
evt
,
$
this
->
getHost
(
)
)
;
}

Waits for the server to send a notification message and returns the result.

@throws Exception
@return ServerQuery\Event

Waits for the server to send a notification message and returns the result .


public function prepare($cmd, array $params = array())
  {
    $args = array();
    $cells = array();

    foreach($params as $ident => $value)
    {
      $ident = is_numeric($ident) ? "" : strtolower($ident) . \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_PAIR;

      if(is_array($value))
      {
        $value = array_values($value);

        for($i = 0; $i < count($value); $i++)
        {
          if($value[$i] === null) continue;
          elseif($value[$i] === FALSE) $value[$i] = 0x00;
          elseif($value[$i] === TRUE) $value[$i] = 0x01;
          elseif($value[$i] instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\AbstractNode) $value[$i] = $value[$i]->getId();

          $cells[$i][] = $ident . \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String::factory($value[$i])->escape();//->toUtf8();
        }
      }
      else
      {
        if($value === null) continue;
        elseif($value === FALSE) $value = 0x00;
        elseif($value === TRUE) $value = 0x01;
        elseif($value instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\AbstractNode) $value = $value->getId();

        $args[] = $ident . \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String::factory($value)->escape();//->toUtf8();
      }
    }

    foreach(array_keys($cells) as $ident) $cells[$ident] = implode(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_CELL, $cells[$ident]);

    if(count($args)) $cmd .= " " . implode(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_CELL, $args);
    if(count($cells)) $cmd .= " " . implode(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_LIST, $cells);

    return trim($cmd);
  }

public
function
prepare
(
$
cmd
,
array
$
params
=
array
(
)
)
{
$
args
=
array
(
)
;
$
cells
=
array
(
)
;
foreach
(
$
params
as
$
ident
=>
$
value
)
{
$
ident
=
is_numeric
(
$
ident
)
""
:
strtolower
(
$
ident
)
.
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
SEPARATOR_PAIR
;
if
(
is_array
(
$
value
)
)
{
$
value
=
array_values
(
$
value
)
;
for
(
$
i
=
0
;
$
i
<
count
(
$
value
)
;
$
i
++
)
{
if
(
$
value
[
$
i
]
===
)
continue
;
elseif
(
$
value
[
$
i
]
===
FALSE
)
$
value
[
$
i
]
=
0x00
;
elseif
(
$
value
[
$
i
]
===
TRUE
)
$
value
[
$
i
]
=
0x01
;
elseif
(
$
value
[
$
i
]
instanceof
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Node
\
AbstractNode
)
$
value
[
$
i
]
=
$
value
[
$
i
]
->
getId
(
)
;
$
cells
[
$
i
]
[
]
=
$
ident
.
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Helper
\
String
::
factory
(
$
value
[
$
i
]
)
->
escape
(
)
;
//->toUtf8();
}
}
else
{
if
(
$
value
===
)
continue
;
elseif
(
$
value
===
FALSE
)
$
value
=
0x00
;
elseif
(
$
value
===
TRUE
)
$
value
=
0x01
;
elseif
(
$
value
instanceof
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Node
\
AbstractNode
)
$
value
=
$
value
->
getId
(
)
;
$
args
[
]
=
$
ident
.
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
Helper
\
String
::
factory
(
$
value
)
->
escape
(
)
;
//->toUtf8();
}
}
foreach
(
array_keys
(
$
cells
)
as
$
ident
)
$
cells
[
$
ident
]
=
implode
(
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
SEPARATOR_CELL
,
$
cells
[
$
ident
]
)
;
if
(
count
(
$
args
)
)
$
cmd
.=
" "
.
implode
(
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
SEPARATOR_CELL
,
$
args
)
;
if
(
count
(
$
cells
)
)
$
cmd
.=
" "
.
implode
(
\
ManiaLivePlugins
\
Standard
\
TeamSpeak
\
TeamSpeak3
\
TeamSpeak3
::
SEPARATOR_LIST
,
$
cells
)
;
return
trim
(
$
cmd
)
;
}

Uses given parameters and returns a prepared ServerQuery command.

@param  string $cmd
@param  array  $params
@return string

Uses given parameters and returns a prepared ServerQuery command .


public function getHost()
  {
    if($this->host === null)
    {
      $this->host = new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Host($this);
    }

    return $this->host;
  }

public function getHost ( ) { if ( $ this -> host === null ) { $ this -> host = new \ ManiaLivePlugins \ Standard \ TeamSpeak \ TeamSpeak3 \ Node \ Host ( $ this ) ; } return $ this -> host ; }

Returns the TeamSpeak3_Node_Host object of the current connection.

@return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Host

Returns the TeamSpeak3_Node_Host object of the current connection .


public function actionList($sort = true)
    {
        $sort = (bool) $sort;
        if ($sort) {
            ksort($this->extensions);
        }
        foreach ($this->extensions as $name => $extension) {
            if ($extension['is_active']) {
                $this->stdout('[active] ', Console::FG_GREEN);
            } else {
                $this->stdout('         ', Console::FG_RED);
            }
            $this->stdout(str_pad($name, 50, ' '));
            $this->stdout(' - ');
            $color = Console::FG_BLACK;
            switch ($extension['composer_type']) {
                case 'yii2-extension':
                    $color = Console::FG_BLUE;
                    break;
                case 'dotplant-extension':
                    $color = Console::FG_GREEN;
                    break;
            }
            $this->stdout($extension['composer_type'] . PHP_EOL, $color);
        }
        return 0;
    }

public
function
actionList
(
$
sort
=
true
)
{
$
sort
=
(
bool
)
$
sort
;
if
(
$
sort
)
{
ksort
(
$
this
->
extensions
)
;
}
foreach
(
$
this
->
extensions
as
$
name
=>
$
extension
)
{
if
(
$
extension
[
'is_active'
]
)
{
$
this
->
stdout
(
'[active] '
,
Console
::
FG_GREEN
)
;
}
else
{
$
this
->
stdout
(
'         '
,
Console
::
FG_RED
)
;
}
$
this
->
stdout
(
str_pad
(
$
name
,
50
,
' '
)
)
;
$
this
->
stdout
(
' - '
)
;
$
color
=
Console
::
FG_BLACK
;
switch
(
$
extension
[
'composer_type'
]
)
{
case
'yii2-extension'
:
$
color
=
Console
::
FG_BLUE
;
break
;
case
'dotplant-extension'
:
$
color
=
Console
::
FG_GREEN
;
break
;
}
$
this
->
stdout
(
$
extension
[
'composer_type'
]
.
PHP_EOL
,
$
color
)
;
}
return
0
;
}

Lists installed extensions
@param bool $sort Sort extensions alphabetically
@return int


private function writeConfig()
    {
        $fileName = Yii::getAlias($this->module->extensionsStorage);
        $writer = new ApplicationConfigWriter([
            'filename' => $fileName,
        ]);
        $writer->addValues($this->extensions);

        if (true === $writer->commit()) {
            $this->stdout('Extensions configuration successfully updated.' . PHP_EOL);
            if (true === $this->module->configurationUpdater->updateConfiguration(false)) {
                $this->stdout('Application configuration successfully updated.' . PHP_EOL);
                return true;
            } else {
                $this->stdout('Application configuration update error.' . PHP_EOL);
                return false;
            }
        } else {
            $this->stdout('There was an error while updating extensions configuration file.' . PHP_EOL);
        }
        return false;
    }


public function setParent(ElementInterface $parent)
    {
        $this->parent = $parent;

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

public function setParent ( ElementInterface $ parent ) { $ this -> parent = $ parent ; $ parent -> getRaw ( ) -> SetMenuBar ( $ this -> element ) ; }

Set the parent element

@param ElementInterface $parent


public function columns($table)
    {
        try {
            $columns = $this->driver->columns($table);

            return $columns;
        } catch (\PDOException $error) {
            $text = (string) $error->getMessage();

            throw new TableNotFoundException($text);
        }
    }

public function columns ( $ table ) { try { $ columns = $ this -> driver -> columns ( $ table ) ; return $ columns ; } catch ( \ PDOException $ error ) { $ text = ( string ) $ error -> getMessage ( ) ; throw new TableNotFoundException ( $ text ) ; } }

Returns an array of Column instances from a table.

@param  string $table
@return \Rougin\Describe\Column[]

@throws \Rougin\Describe\Exceptions\TableNotFoundException

Returns an array of Column instances from a table .


private function createTranscoder() {
        if ($this->transcoder === null) {
            $this->transcoder = Transcoder::create();
        }

        return $this->transcoder;
    }

private function createTranscoder ( ) { if ( $ this -> transcoder === null ) { $ this -> transcoder = Transcoder :: create ( ) ; } return $ this -> transcoder ; }

Returns a transcoder instance.

@return Transcoder


private static function getByCaseInsensitiveKey(array $words, $key) {
        foreach ($words as $headerWord => $value) {
            if (strcasecmp($headerWord, $key) === 0) {
                return $value;
            }
        }

        return null;
    }

private static function getByCaseInsensitiveKey ( array $ words , $ key ) { foreach ( $ words as $ headerWord => $ value ) { if ( strcasecmp ( $ headerWord , $ key ) === 0 ) { return $ value ; } } return null ; }

Gets array item by case-insensitive key.

@param array $words
@param $key

@return ?mixed

Gets array item by case - insensitive key .


private static function setByCaseInsensitiveKey(array $words, $key, $newValue) {
        foreach ($words as $headerWord => $value) {
            if (strcasecmp($headerWord, $key) === 0) {
                $key = $headerWord;

                break;
            }
        }

        $words[$key] = $newValue;

        return $words;
    }

private static function setByCaseInsensitiveKey ( array $ words , $ key , $ newValue ) { foreach ( $ words as $ headerWord => $ value ) { if ( strcasecmp ( $ headerWord , $ key ) === 0 ) { $ key = $ headerWord ; break ; } } $ words [ $ key ] = $ newValue ; return $ words ; }

Sets array item by case-insensitive key.

@param array $words
@param string $key
@param $newValue

@return array

Sets array item by case - insensitive key .


public function notices($context = null)
    {
         $notices = [];

        // fallback to the CMS as the context - this is required to be consistent with the original behaviour.
        if ($context == null || $context instanceof HTTPRequest) {
            $context = 'CMS';
        }

        // We want to deliver notices only if a user is logged in.
        // This way we ensure, that a potential attacker can't read notices for CMS users.
        if (Member::currentUser()) {
            $notices = TimedNotice::get_notices($context)->toNestedArray();
        }

        return Convert::array2json($notices);
    }

Gets any notices relevant to the present time and current users

@return JSON


public function actionIndex()
    {
        $extensions = ExtensionsManager::module()->getExtensions();
        return $this->render(
            'index',
            [
                'dataProvider' => new ArrayDataProvider([
                    'allModels' => $extensions,
                    'sort' => [
                        'attributes' => ['composer_name', 'composer_type', 'is_active'],
                    ],
                    'pagination' => [
                        'defaultPageSize' => 10,
                        'pageSize' => ExtensionsManager::module()->extensionsPerPage,
                    ],
                ]),
            ]
        );
    }

public function actionIndex ( ) { $ extensions = ExtensionsManager :: module ( ) -> getExtensions ( ) ; return $ this -> render ( 'index' , [ 'dataProvider' => new ArrayDataProvider ( [ 'allModels' => $ extensions , 'sort' => [ 'attributes' => [ 'composer_name' , 'composer_type' , 'is_active' ] , ] , 'pagination' => [ 'defaultPageSize' => 10 , 'pageSize' => ExtensionsManager :: module ( ) -> extensionsPerPage , ] , ] ) , ] ) ; }


private static function doRequest($url, $headers = [])
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $response = curl_exec($ch);
        if (0 !== $errno = curl_errno($ch)) {
            $errorMessage = curl_strerror($errno);
            Yii::$app->session->setFlash("cURL error ({$errno}):\n {$errorMessage}");
        }
        curl_close($ch);
        return $response;
    }

Process API requests to github and packagist

@param $url
@param array $headers
@return mixed


public function actionRunTask()
    {
        if (false === Yii::$app->request->isAjax) {
            throw new NotFoundHttpException('Page not found');
        }
        $module = ExtensionsManager::module();
        $packageName = Yii::$app->request->post('packageName');
        $extension = $module->getExtensions($packageName);
        $taskType = Yii::$app->request->post('taskType');
        if (true === empty($extension) && $taskType != ExtensionsManager::INSTALL_DEFERRED_TASK) {
            return self::runTask(
                [
                    realpath(Yii::getAlias('@app') . '/yii'),
                    'extension/dummy',
                    'Undefined extension: ' . $packageName,
                ],
                ExtensionsManager::EXTENSION_DUMMY_DEFERRED_GROUP
            );
        }
        if ($module->extensionIsCore($packageName)
            && !Yii::$app->user->can('extensions-manager-access-to-core-extension')
        ) {
            throw new ForbiddenHttpException;
        }
        $chain = new ReportingChain();
        switch ($taskType) {
            case ExtensionsManager::INSTALL_DEFERRED_TASK :
                if ($module->extensionIsCore($packageName)
                    || !Yii::$app->user->can('extensions-manager-install-extension')
                ) {
                    throw new ForbiddenHttpException;
                }
                return self::runTask(
                    [
                        $module->composerPath,
                        'require',
                        $packageName,
                        '--no-interaction',
                        '--no-ansi',
                        "--working-dir={$module->getLocalExtensionsPath()}",
                        '--prefer-dist',
                        '-o',
                        $module->verbose == 1 ? '-vvv' : '',
                    ],
                    ExtensionsManager::COMPOSER_INSTALL_DEFERRED_GROUP
                );
            case ExtensionsManager::UNINSTALL_DEFERRED_TASK :
                if ($module->extensionIsCore($packageName)
                    || !Yii::$app->user->can('extensions-manager-uninstall-extension')
                ) {
                    throw new ForbiddenHttpException;
                }
                self::uninstall($extension, $chain);
                break;
            case ExtensionsManager::ACTIVATE_DEFERRED_TASK :
                if (!Yii::$app->user->can('extensions-manager-activate-extension')) {
                    throw new ForbiddenHttpException;
                }
                self::activate($extension, $chain);
                break;
            case ExtensionsManager::DEACTIVATE_DEFERRED_TASK :
                if (!Yii::$app->user->can('extensions-manager-deactivate-extension')) {
                    throw new ForbiddenHttpException;
                }
                self::deactivate($extension, $chain);
                break;
            default:
                return self::runTask(
                    [
                        realpath(Yii::getAlias('@app') . '/yii'),
                        'extension/dummy',
                        'Unrecognized task!',
                    ],
                    ExtensionsManager::EXTENSION_DUMMY_DEFERRED_GROUP
                );
        }
        if (null !== $firstTaskId = $chain->registerChain()) {
            DeferredHelper::runImmediateTask($firstTaskId);
            Yii::$app->response->format = Response::FORMAT_JSON;
            return [
                'queueItemId' => $firstTaskId,
            ];
        } else {
            throw new ServerErrorHttpException("Unable to start chain");
        }
    }

Common method to access from web via ajax requests. Builds a ReportingChain and immediately fires it.

@return array
@throws NotFoundHttpException
@throws ServerErrorHttpException
@throws InvalidParamException

Common method to access from web via ajax requests . Builds a ReportingChain and immediately fires it .


private static function deactivate($extension, ReportingChain $chain)
    {
        if ($extension['is_active'] == 1) {
            ExtensionDataHelper::prepareMigrationTask(
                $extension,
                $chain,
                ExtensionsManager::MIGRATE_TYPE_DOWN,
                ExtensionsManager::EXTENSION_DEACTIVATE_DEFERRED_GROUP
            );
            $deactivationTask = ExtensionDataHelper::buildTask(
                [
                    realpath(Yii::getAlias('@app') . '/yii'),
                    'extension/deactivate',
                    $extension['composer_name'],
                ],
                ExtensionsManager::EXTENSION_DEACTIVATE_DEFERRED_GROUP
            );
            $chain->addTask($deactivationTask);
        } else {
            $dummyTask = ExtensionDataHelper::buildTask(
                [
                    realpath(Yii::getAlias('@app') . '/yii'),
                    'extension/dummy',
                    'Extension already deactivated!',
                ],
                ExtensionsManager::EXTENSION_DUMMY_DEFERRED_GROUP
            );
            $chain->addTask($dummyTask);
        }
    }

private
static
function
deactivate
(
$
extension
,
ReportingChain
$
chain
)
{
if
(
$
extension
[
'is_active'
]
==
1
)
{
ExtensionDataHelper
::
prepareMigrationTask
(
$
extension
,
$
chain
,
ExtensionsManager
::
MIGRATE_TYPE_DOWN
,
ExtensionsManager
::
EXTENSION_DEACTIVATE_DEFERRED_GROUP
)
;
$
deactivationTask
=
ExtensionDataHelper
::
buildTask
(
[
realpath
(
Yii
::
getAlias
(
'@app'
)
.
'/yii'
)
,
'extension/deactivate'
,
$
extension
[
'composer_name'
]
,
]
,
ExtensionsManager
::
EXTENSION_DEACTIVATE_DEFERRED_GROUP
)
;
$
chain
->
addTask
(
$
deactivationTask
)
;
}
else
{
$
dummyTask
=
ExtensionDataHelper
::
buildTask
(
[
realpath
(
Yii
::
getAlias
(
'@app'
)
.
'/yii'
)
,
'extension/dummy'
,
'Extension already deactivated!'
,
]
,
ExtensionsManager
::
EXTENSION_DUMMY_DEFERRED_GROUP
)
;
$
chain
->
addTask
(
$
dummyTask
)
;
}
}

Adds deactivation task into ReportingChain if Extension is active

@param array $extension
@param ReportingChain $chain