_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q264500 | Host.whoamiSet | test | public function whoamiSet($ident, $value = null)
{
$this->whoami();
$this->whoami[$ident] = (is_numeric($value)) ? intval($value) : \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String::factory($value);
} | php | {
"resource": ""
} |
q264501 | ValidatorFactory.getValidator | test | protected function getValidator(ServiceLocatorInterface $serviceLocator, string $name, array $options): object
{
return $serviceLocator->getService($name, $options);
} | php | {
"resource": ""
} |
q264502 | PageFetcher.setCurlContent | test | 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));
} | php | {
"resource": ""
} |
q264503 | PageFetcher.parseResult | test | 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;
} | php | {
"resource": ""
} |
q264504 | ExtensionsConfiguration.commonApplicationAttributes | test | 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,
]
],
];
} | php | {
"resource": ""
} |
q264505 | Options.getOption | test | protected function getOption($option)
{
return in_array($option, $this->getOptions())
? $this->getOptions()[$option]
: null;
} | php | {
"resource": ""
} |
q264506 | Options.buildOptions | test | 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;
} | php | {
"resource": ""
} |
q264507 | Securepass.user | test | 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);
} | php | {
"resource": ""
} |
q264508 | Securepass.ping | test | public function ping()
{
$command = $this->client->getCommand('Ping');
$res = $this->execute($command);
return $res;
} | php | {
"resource": ""
} |
q264509 | BoxSizer.setAttribute | test | public function setAttribute($key, $value)
{
switch ($key) {
case 'orientation':
$this->attributes[$key] =
$value == 'horizontal' ?
wxHORIZONTAL :
wxVERTICAL
;
default:
$this->attributes[$key] = $value;
break;
}
} | php | {
"resource": ""
} |
q264510 | Money.format | test | 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);
} | php | {
"resource": ""
} |
q264511 | Money.formatForAccounting | test | 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;
} | php | {
"resource": ""
} |
q264512 | Money.getRoundedAmount | test | 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;
} | php | {
"resource": ""
} |
q264513 | Money.split | test | 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;
} | php | {
"resource": ""
} |
q264514 | Factory.prepareAndInjectElements | test | protected function prepareAndInjectElements($elements, FieldsetInterface $fieldset, $method)
{
$elements = $this->validateSpecification($elements, $method);
foreach ($elements as $elementSpecification) {
if (null === $elementSpecification) {
continue;
}
$fieldset->add($elementSpecification);
}
} | php | {
"resource": ""
} |
q264515 | MeRepository.getMe | test | public function getMe($accessToken)
{
if (empty($accessToken)) {
throw new \InvalidArgumentException('Empty access token provided', 1);
}
$response = $this->getClient()->get(self::ENDPOINT, array('Authorization' => 'OAuth '.$accessToken));
$data = $this->jsonResponse($response);
return $this->getFactory()->createEntity($data);
} | php | {
"resource": ""
} |
q264516 | Router.run | test | 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]);
} | php | {
"resource": ""
} |
q264517 | Router.searchRouter | test | 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;
} | php | {
"resource": ""
} |
q264518 | Router.requestMethod | test | private function requestMethod()
{
if (php_sapi_name() === 'cli') {
return 'CLI';
}
// Take the method as found in $_SERVER
$method = $_SERVER['REQUEST_METHOD'];
if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
ob_start();
$method = 'GET';
} // If it's a POST request, check for a method override header
elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
$headers = $this->requestHeaders();
if (isset($headers['X-HTTP-Method-Override']) && in_array($headers['X-HTTP-Method-Override'], array('PUT', 'DELETE', 'PATCH'))) {
$method = $headers['X-HTTP-Method-Override'];
}
}
return $method;
} | php | {
"resource": ""
} |
q264519 | LogTruck.getLogs | test | 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;
} | php | {
"resource": ""
} |
q264520 | LogTruck.deathByCamels | test | private function deathByCamels($string)
{
$this->index = 0;
return implode('', array_map(function($el) {
$this->index++;
return $this->index === 1 ? $el : ucfirst($el);
}, explode(' ', str_replace('_', ' ', $string))));
} | php | {
"resource": ""
} |
q264521 | Convert.bytes | test | 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";
} | php | {
"resource": ""
} |
q264522 | Convert.codec | test | 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";
} | php | {
"resource": ""
} |
q264523 | Convert.groupType | test | 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";
} | php | {
"resource": ""
} |
q264524 | Convert.permissionType | test | 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";
} | php | {
"resource": ""
} |
q264525 | Convert.logLevel | test | 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;
}
} | php | {
"resource": ""
} |
q264526 | Convert.logEntry | test | 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;
} | php | {
"resource": ""
} |
q264527 | TimedNoticeAdmin.getList | test | public function getList()
{
$list = parent::getList();
$r = $this->getRequest();
if ($q = $r->requestVar('q')) {
if (isset($q['Status'])) {
$status = $q['Status'];
$now = date('Y-m-d H:i:s');
if ($status == 'Future') {
return $list->where("StartTime > '$now'");
} else if ($status == 'Expired') {
return $list->where("EndTime < $now");
} else if ($status == 'Current') {
return $list->where("
StartTime < '$now' AND
(EndTime > '$now' OR EndTime IS NULL)
");
}
}
}
return $list;
} | php | {
"resource": ""
} |
q264528 | EntityTrait.getTraits | test | 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];
} | php | {
"resource": ""
} |
q264529 | EntityTrait.callTraitMethod | test | protected function callTraitMethod($traitName, $methodName)
{
return method_exists($this, $traitName . $methodName)
? $this->{$traitName . $methodName}()
: null;
} | php | {
"resource": ""
} |
q264530 | EntityTrait.callEvents | test | protected function callEvents($eventName)
{
foreach (static::getTraits() as $name) {
if ($name === 'EntityTrait') {
continue;
}
$this->callTraitMethod($name, $eventName);
}
} | php | {
"resource": ""
} |
q264531 | EntityTrait.attributeLabels | test | 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];
} | php | {
"resource": ""
} |
q264532 | EntityTrait.attributeHints | test | 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];
} | php | {
"resource": ""
} |
q264533 | Reply.toArray | test | 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;
} | php | {
"resource": ""
} |
q264534 | Reply.fetchError | test | 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"));
}
} | php | {
"resource": ""
} |
q264535 | Reply.fetchReply | test | protected function fetchReply($rpl)
{
foreach($rpl as $key => $val)
{
if($val->startsWith(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::GREET))
{
unset($rpl[$key]);
}
elseif($val->startsWith(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::EVENT))
{
$this->evt[] = new Event($rpl[$key], $this->con);
unset($rpl[$key]);
}
}
$this->rpl = new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String(implode(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::SEPARATOR_LIST, $rpl));
} | php | {
"resource": ""
} |
q264536 | AuthenticationService.getIdentity | test | 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;
} | php | {
"resource": ""
} |
q264537 | AuthenticationService.hasIdentity | test | public function hasIdentity()
{
$storageCheck = !$this->getStorage()->isEmpty();
if (!$storageCheck) {
return false;
}
return $this->getIdentity() instanceof User;
} | php | {
"resource": ""
} |
q264538 | SoftDeleteTrait.restore | test | public function restore()
{
/** @var ActiveRecord $this */
if (((boolean) $this->{$this->isDeletedAttribute}) !== false) {
$this->{$this->isDeletedAttribute} = false;
return $this->save(true, [$this->isDeletedAttribute]);
}
return true;
} | php | {
"resource": ""
} |
q264539 | UserRepository.getUser | test | public function getUser($userId)
{
$response = $this->getClient()->get(self::ENDPOINT.$userId);
$data = $this->jsonResponse($response);
return $this->getFactory()->createEntity($data);
} | php | {
"resource": ""
} |
q264540 | UserRepository.getUserFollowedGames | test | public function getUserFollowedGames($userId, $params = array())
{
$params = 0 < count($params) ? '?'.http_build_query($params) : '';
// need old api version to get user's followed games
$client = $this->getClient()->setUrl(Client::URL_PROTOCOL.'://'.Client::URL_HOST.'/'.Client::URL_OLD_VERSION.'/');
$response = $this->setClient($client)->getClient()->get(self::ENDPOINT.$userId.'/follows/games/live/'.$params);
// reset api endpoint to current version
$client = $this->getClient()->setUrl(Client::URL_PROTOCOL.'://'.Client::URL_HOST.'/'.Client::URL_VERSION.'/');
$this->setClient($client);
$data = $this->jsonResponse($response);
return $this->setFactory(new FollowFactory())->getFactory()->createGameList($data);
} | php | {
"resource": ""
} |
q264541 | TimedNotice.get_notices | test | 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;
} | php | {
"resource": ""
} |
q264542 | ChannelRepository.getChannel | test | public function getChannel($channelId)
{
$response = $this->getClient()->get(self::ENDPOINT.$channelId);
$data = $this->jsonResponse($response);
return $this->getFactory()->createEntity($data);
} | php | {
"resource": ""
} |
q264543 | String.escape | test | public function escape()
{
foreach(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::getEscapePatterns() as $search => $replace)
{
$this->string = str_replace($search, $replace, $this->string);
}
return $this;
} | php | {
"resource": ""
} |
q264544 | String.unescape | test | public function unescape()
{
$this->string = strtr($this->string, array_flip(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::getEscapePatterns()));
return $this;
} | php | {
"resource": ""
} |
q264545 | TeamRepository.getTeam | test | public function getTeam($teamId)
{
$response = $this->getClient()->get(self::ENDPOINT.$teamId);
$data = $this->jsonResponse($response);
return $this->getFactory()->createEntity($data);
} | php | {
"resource": ""
} |
q264546 | ContainerResult.addResult | test | 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;
} | php | {
"resource": ""
} |
q264547 | StreamRepository.getStream | test | 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);
} | php | {
"resource": ""
} |
q264548 | StreamRepository.getStreams | test | 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);
} | php | {
"resource": ""
} |
q264549 | StreamRepository.getFeaturedStreams | test | 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);
} | php | {
"resource": ""
} |
q264550 | StreamRepository.getFollowedStreams | test | 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);
} | php | {
"resource": ""
} |
q264551 | StreamRepository.getStreamsSummary | test | 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);
} | php | {
"resource": ""
} |
q264552 | GameRepository.getTop | test | 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);
} | php | {
"resource": ""
} |
q264553 | TextBox.getValue | test | public function getValue()
{
if ($this->element) {
$this->value = $this->element->GetValue();
}
return $this->value;
} | php | {
"resource": ""
} |
q264554 | TSDNS.resolve | test | 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;
} | php | {
"resource": ""
} |
q264555 | ConfigurationUpdater.getConfigurables | test | protected function getConfigurables($ignoreCache = false)
{
if (count($this->_configurables) === 0 || true === $ignoreCache) {
$this->_configurables = ExtensionsHelper::getConfigurables();
}
} | php | {
"resource": ""
} |
q264556 | Client.message | test | public function message($msg)
{
$this->execute("sendtextmessage", array("msg" => $msg, "target" => $this->getId(), "targetmode" => \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::TEXTMSG_CLIENT));
} | php | {
"resource": ""
} |
q264557 | Client.kick | test | public function kick($reasonid = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::KICK_CHANNEL, $reasonmsg = null)
{
return $this->getParent()->clientKick($this->getId(), $reasonid, $reasonmsg);
} | php | {
"resource": ""
} |
q264558 | Client.avatarDownload | test | 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"]);
} | php | {
"resource": ""
} |
q264559 | Events.bindEvents | test | 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]);
}
} | php | {
"resource": ""
} |
q264560 | Events.connectEvent | test | 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);
} | php | {
"resource": ""
} |
q264561 | Uri.getQueryVar | test | 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;
} | php | {
"resource": ""
} |
q264562 | Uri.getBaseUri | test | public static function getBaseUri()
{
$scriptPath = new String(dirname(self::getHostParam("SCRIPT_NAME")));
return self::getHostUri()->append(($scriptPath == DIRECTORY_SEPARATOR ? "" : $scriptPath) . "/");
} | php | {
"resource": ""
} |
q264563 | ServerQuery.request | test | 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;
} | php | {
"resource": ""
} |
q264564 | ServerQuery.wait | test | 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());
} | php | {
"resource": ""
} |
q264565 | ServerQuery.prepare | test | 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);
} | php | {
"resource": ""
} |
q264566 | ServerQuery.getHost | test | public function getHost()
{
if($this->host === null)
{
$this->host = new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Node\Host($this);
}
return $this->host;
} | php | {
"resource": ""
} |
q264567 | ExtensionController.actionList | test | 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;
} | php | {
"resource": ""
} |
q264568 | ExtensionController.writeConfig | test | 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;
} | php | {
"resource": ""
} |
q264569 | MenuBar.setParent | test | public function setParent(ElementInterface $parent)
{
$this->parent = $parent;
$parent->getRaw()->SetMenuBar($this->element);
} | php | {
"resource": ""
} |
q264570 | Describe.columns | test | public function columns($table)
{
try {
$columns = $this->driver->columns($table);
return $columns;
} catch (\PDOException $error) {
$text = (string) $error->getMessage();
throw new TableNotFoundException($text);
}
} | php | {
"resource": ""
} |
q264571 | GuzzleTranscoder.createTranscoder | test | private function createTranscoder() {
if ($this->transcoder === null) {
$this->transcoder = Transcoder::create();
}
return $this->transcoder;
} | php | {
"resource": ""
} |
q264572 | GuzzleTranscoder.getByCaseInsensitiveKey | test | private static function getByCaseInsensitiveKey(array $words, $key) {
foreach ($words as $headerWord => $value) {
if (strcasecmp($headerWord, $key) === 0) {
return $value;
}
}
return null;
} | php | {
"resource": ""
} |
q264573 | GuzzleTranscoder.setByCaseInsensitiveKey | test | 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;
} | php | {
"resource": ""
} |
q264574 | TimedNoticeController.notices | test | 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);
} | php | {
"resource": ""
} |
q264575 | ExtensionsController.actionIndex | test | 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,
],
]),
]
);
} | php | {
"resource": ""
} |
q264576 | ExtensionsController.doRequest | test | 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;
} | php | {
"resource": ""
} |
q264577 | ExtensionsController.actionRunTask | test | 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");
}
} | php | {
"resource": ""
} |
q264578 | ExtensionsController.deactivate | test | 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);
}
} | php | {
"resource": ""
} |
q264579 | ExtensionsController.activate | test | private static function activate($extension, ReportingChain $chain)
{
if ($extension['is_active'] == 0) {
ExtensionDataHelper::prepareMigrationTask(
$extension,
$chain,
ExtensionsManager::MIGRATE_TYPE_UP,
ExtensionsManager::EXTENSION_ACTIVATE_DEFERRED_GROUP
);
$activationTask = ExtensionDataHelper::buildTask(
[
realpath(Yii::getAlias('@app') . '/yii'),
'extension/activate',
$extension['composer_name'],
],
ExtensionsManager::EXTENSION_ACTIVATE_DEFERRED_GROUP
);
$chain->addTask($activationTask);
} else {
$dummyTask = ExtensionDataHelper::buildTask(
[
realpath(Yii::getAlias('@app') . '/yii'),
'extension/dummy',
'Extension already activated!',
],
ExtensionsManager::EXTENSION_DUMMY_DEFERRED_GROUP
);
$chain->addTask($dummyTask);
}
} | php | {
"resource": ""
} |
q264580 | ExtensionsController.uninstall | test | private static function uninstall($extension, ReportingChain $chain)
{
$module = ExtensionsManager::module();
if (true === $module->extensionIsCore($extension['composer_name'])) {
$dummyTask = ExtensionDataHelper::buildTask(
[
realpath(Yii::getAlias('@app') . '/yii'),
'extension/dummy',
'--no-interaction',
'-o',
'You are unable to uninstall core extensions!',
],
ExtensionsManager::EXTENSION_DUMMY_DEFERRED_GROUP
);
$chain->addTask($dummyTask);
} else {
self::deactivate($extension, $chain);
$uninstallTask = ExtensionDataHelper::buildTask(
[
$module->composerPath,
'remove',
$extension['composer_name'],
'--no-ansi',
'--no-interaction',
"--working-dir={$module->getLocalExtensionsPath()}",
$module->verbose == 1 ? '-vvv' : '',
],
ExtensionsManager::COMPOSER_UNINSTALL_DEFERRED_GROUP
);
$chain->addTask($uninstallTask);
}
} | php | {
"resource": ""
} |
q264581 | ExtensionsController.runTask | test | private static function runTask($command, $groupName)
{
$task = ExtensionDataHelper::buildTask($command, $groupName);
if ($task->registerTask()) {
DeferredHelper::runImmediateTask($task->model()->id);
Yii::$app->response->format = Response::FORMAT_JSON;
return [
'queueItemId' => $task->model()->id,
];
} else {
throw new ServerErrorHttpException("Unable to start task");
}
} | php | {
"resource": ""
} |
q264582 | Channel.clientGetByName | test | public function clientGetByName($name)
{
foreach($this->clientList() as $client)
{
if($client["client_nickname"] == $name) return $client;
}
throw new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception("invalid clientID", 0x200);
} | php | {
"resource": ""
} |
q264583 | Channel.iconDownload | test | public function iconDownload()
{
if($this->iconIsLocal("channel_icon_id") || $this["channel_icon_id"] == 0) return;
$download = $this->getParent()->transferInitDownload(rand(0x0000, 0xFFFF), 0, $this->iconGetName("channel_icon_id"));
$transfer = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::factory("filetransfer://" . $download["host"] . ":" . $download["port"]);
return $transfer->download($download["ftkey"], $download["size"]);
} | php | {
"resource": ""
} |
q264584 | Channel.message | test | public function message($msg, $cpw = null)
{
if($this->getId() != $this->getParent()->whoamiGet("client_channel_id"))
{
$this->getParent()->clientMove($this->getParent()->whoamiGet("client_id"), $this->getId(), $cpw);
}
$this->execute("sendtextmessage", array("msg" => $msg, "target" => $this->getId(), "targetmode" => \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::TEXTMSG_CHANNEL));
} | php | {
"resource": ""
} |
q264585 | Channel.delete | test | public function delete($force = FALSE)
{
$this->getParent()->channelDelete($this->getId(), $force);
unset($this);
} | php | {
"resource": ""
} |
q264586 | JWT.encode | test | public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null)
{
$header = array('typ' => 'JWT', 'alg' => $alg);
if ($keyId !== null) {
$header['kid'] = $keyId;
}
if ( isset($head) && is_array($head) ) {
$header = array_merge($head, $header);
}
$segments = array();
$segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header));
$segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload));
$signing_input = implode('.', $segments);
$signature = JWT::sign($signing_input, $key, $alg);
$segments[] = JWT::urlsafeB64Encode($signature);
return implode('.', $segments);
} | php | {
"resource": ""
} |
q264587 | JWT.sign | test | public static function sign($msg, $key, $alg = 'HS256')
{
if (empty(self::$supported_algs[$alg])) {
throw new DomainException('Algorithm not supported');
}
list($function, $algorithm) = self::$supported_algs[$alg];
switch($function) {
case 'hash_hmac':
return hash_hmac($algorithm, $msg, $key, true);
case 'openssl':
$signature = '';
$success = openssl_sign($msg, $signature, $key, $algorithm);
if (!$success) {
throw new DomainException("OpenSSL unable to sign data");
} else {
return $signature;
}
}
} | php | {
"resource": ""
} |
q264588 | JWT.jsonDecode | test | public static function jsonDecode($input)
{
if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
/** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you
* to specify that large ints (like Steam Transaction IDs) should be treated as
* strings, rather than the PHP default behaviour of converting them to floats.
*/
$obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
} else {
/** Not all servers will support that, however, so for older versions we must
* manually detect large ints in the JSON string and quote them (thus converting
*them to strings) before decoding, hence the preg_replace() call.
*/
$max_int_length = strlen((string) PHP_INT_MAX) - 1;
$json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
$obj = json_decode($json_without_bigints);
}
if (function_exists('json_last_error') && $errno = json_last_error()) {
JWT::handleJsonError($errno);
} elseif ($obj === null && $input !== 'null') {
throw new DomainException('Null result with non-null input');
}
return $obj;
} | php | {
"resource": ""
} |
q264589 | ApplicationConfigWriter.commit | test | public function commit()
{
$data = <<<PHP
<?php
/*
* ! WARNING !
*
* This file is auto-generated.
* Please don't modify it by-hand or all your changes can be lost.
*/
{$this->append}
return
PHP;
$data .= VarDumper::export($this->configuration);
$data .= ";\n\n";
$result = file_put_contents($this->filename, $data, LOCK_EX) !== false;
if ($result) {
if (function_exists('opcache_invalidate')) {
opcache_invalidate($this->filename, true);
}
if (function_exists('apc_delete_file')) {
@apc_delete_file($this->filename);
}
}
return $result;
} | php | {
"resource": ""
} |
q264590 | Bootstrap.bootstrap | test | public function bootstrap($app)
{
$app->i18n->translations['extensions-manager'] = [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => __DIR__ . DIRECTORY_SEPARATOR . 'messages',
];
DeferredQueueEvent::on(
DeferredController::className(),
DeferredController::EVENT_DEFERRED_QUEUE_COMPLETE,
[DeferredQueueCompleteHandler::className(), 'handleEvent']
);
if ($app instanceof \yii\console\Application) {
$app->controllerMap['extension'] = ExtensionController::className();
$app->on(Application::EVENT_BEFORE_ACTION, function () {
$module = ExtensionsManager::module();
if ($module->autoDiscoverMigrations === true) {
if (isset(Yii::$app->params['yii.migrations']) === false) {
Yii::$app->params['yii.migrations'] = [];
}
/** @var array $extensions */
$extensions = $module->getExtensions();
foreach ($extensions as $name => $ext) {
if ($ext['composer_type'] === Extension::TYPE_DOTPLANT
&& $module->discoverDotPlantMigrations === false
) {
continue;
}
$extData = ComposerInstalledSet::get()->getInstalled($ext['composer_name']);
$packageMigrations = ExtensionDataHelper::getInstalledExtraData(
$extData,
'migrationPath',
true
);
$packagePath = '@vendor/' . $ext['composer_name'];
foreach ($packageMigrations as $migrationPath) {
Yii::$app->params['yii.migrations'][] = "$packagePath/$migrationPath";
}
}
}
});
}
} | php | {
"resource": ""
} |
q264591 | Channelgroup.copy | test | public function copy($name = null, $tcgid = 0, $type = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::GROUP_DBTYPE_REGULAR)
{
return $this->getParent()->channelGroupCopy($this->getId(), $name, $tcgid, $type);
} | php | {
"resource": ""
} |
q264592 | Channelgroup.message | test | public function message($msg)
{
foreach($this as $client)
{
try
{
$this->execute("sendtextmessage", array("msg" => $msg, "target" => $client, "targetmode" => \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3::TEXTMSG_CLIENT));
}
catch(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception $e)
{
/* ERROR_client_invalid_id */
if($e->getCode() != 0x0200) throw $e;
}
}
} | php | {
"resource": ""
} |
q264593 | ApiController.formClassName | test | protected function formClassName(): string
{
if ($this->formClassName)
{
return $this->formClassName;
}
$entityClassName = $this->entityClassName();
$this->formClassName = substr(str_replace('/Form/', '/Entity/', $entityClassName), 0, -4);
return $this->formClassName;
} | php | {
"resource": ""
} |
q264594 | ApiController.getAction | test | public function getAction(int $id)
{
try {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository($this->entityClassName())->find($id);
if ($entity) {
return $entity;
}
return FOSView::create('Not Found', Response::HTTP_NO_CONTENT);
} catch (\Exception $e) {
return FOSView::create($e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}
} | php | {
"resource": ""
} |
q264595 | ApiController.cgetAction | test | public function cgetAction(ParamFetcherInterface $paramFetcher)
{
try {
$offset = $paramFetcher->get('offset');
$limit = $paramFetcher->get('limit');
$order_by = $paramFetcher->get('order_by');
$filters = !is_null($paramFetcher->get('filters')) ? $paramFetcher->get('filters') : array();
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository($this->entityClassName())
->findBy($filters, $order_by, $limit, $offset);
if ($entities) {
return $entities;
}
return FOSView::create('Not Found', Response::HTTP_NO_CONTENT);
} catch (\Exception $e) {
return FOSView::create($e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}
} | php | {
"resource": ""
} |
q264596 | ApiController.postAction | test | public function postAction(Request $request)
{
/**
* @var $em ApiEntityManager
*/
$em = $this->getDoctrine()->getManager();
$data = json_decode($request->getContent(), true);
$entity = $em->createEntity($this->entityClassName());
$form = $this->createForm($this->formClassName(), $entity, [
"method" => $request->getMethod(),
]);
$form->submit($data);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $entity;
}
return FOSView::create([
'errors' => $form->getErrors()
], Response::HTTP_INTERNAL_SERVER_ERROR);
} | php | {
"resource": ""
} |
q264597 | ApiController.putAction | test | public function putAction(Request $request, int $id)
{
try {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository($this->entityClassName())->find($id);
$data = json_decode($request->getContent(), true);
$request->setMethod('PATCH'); //Treat all PUTs as PATCH
$form = $this->createForm($this->formClassName(), $entity, [
"method" => $request->getMethod(),
]);
$form->submit($data);
if ($form->isValid()) {
$em->flush();
return $entity;
}
return FOSView::create(array('errors' => $form->getErrors()), Response::HTTP_INTERNAL_SERVER_ERROR);
} catch (\Exception $e) {
return FOSView::create($e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}
} | php | {
"resource": ""
} |
q264598 | ApiController.deleteAction | test | public function deleteAction(Request $request, int $id)
{
try {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository($this->entityClassName())->find($id);
$em->remove($entity);
$em->flush();
return null;
} catch (\Exception $e) {
return FOSView::create($e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}
} | php | {
"resource": ""
} |
q264599 | JsonDecodeFile.readFile | test | protected static function readFile($path)
{
// Workaround for https://github.com/kherge-php/file-manager/pull/2
$error = null;
set_error_handler(function ($severity, $message, $filename, $lineno) use (&$error) {
$error = new \ErrorException($message, 0, $severity, $filename, $lineno);
}, E_WARNING);
try {
$file = new File($path, 'r');
} finally {
restore_error_handler();
}
if ($error) {
// @codeCoverageIgnoreStart
throw new ResourceException(
"The file \"$path\" could not be opened.",
$error
);
// @codeCoverageIgnoreEnd
}
return $file->read();
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.