_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q2700
UserPermission.revoke
train
public function revoke($flag) { if (is_string($flag) && defined('static::' . strtoupper($flag))) { $flag = constant('static::' . strtoupper($flag)); } $this->mask &= ~$flag; return $this; }
php
{ "resource": "" }
q2701
Assets.sort
train
protected function sort($assets) { $original = $assets; $sorted = []; while (count($assets) > 0) { foreach ($assets as $handle => $asset) { // No dependencies anymore, add it to sorted if (!$asset->hasDependency()) { $sorted[$handle] = $asset; unset($assets[$handle]); } else { foreach ($asset->getDependency() as $dep) { // Remove dependency if doesn't exist, if its dependent on itself, // or if the dependent is dependent on it if (!isset($original[$dep]) or $dep === $handle or (isset($assets[$dep]) and $assets[$dep]->hasDependency($handle))) { $assets[$handle]->removeDependency($dep); continue; } // This dependency hasn't been sorted yet if (!isset($sorted[$dep])) { continue; } // This dependency is taken care of, remove from list $assets[$handle]->removeDependency($dep); } } } } return $sorted; }
php
{ "resource": "" }
q2702
CA.createAppCSR
train
public static function createAppCSR($keyPair, $dn) { $privKey = new \Crypt_RSA(); $privKey->loadKey($keyPair['privatekey']); $pubKey = new \Crypt_RSA(); $pubKey->loadKey($keyPair['publickey']); $pubKey->setPublicKey(); $x509 = new \File_X509(); $x509->setPrivateKey($privKey); $x509->setDN($dn); $x509->loadCSR($x509->saveCSR($x509->signCSR(Constants::CERT_SIGNATURE_ALGORITHM))); $x509->setExtension('id-ce-keyUsage', array('keyEncipherment')); $csrData = $x509->signCSR(Constants::CERT_SIGNATURE_ALGORITHM); return $x509->saveCSR($csrData); }
php
{ "resource": "" }
q2703
CA.createCrlDistCSR
train
public static function createCrlDistCSR($keyPair, $dn) { $privKey = new \Crypt_RSA(); $privKey->loadKey($keyPair['privatekey']); $pubKey = new \Crypt_RSA(); $pubKey->loadKey($keyPair['publickey']); $pubKey->setPublicKey(); $csr = new \File_X509(); $csr->setPrivateKey($privKey); $csr->setPublicKey($pubKey); $csr->setDN($dn); $csr->loadCSR($csr->saveCSR($csr->signCSR(Constants::CERT_SIGNATURE_ALGORITHM))); $csr->setExtension('id-ce-keyUsage', array('cRLSign')); $csrData = $csr->signCSR(Constants::CERT_SIGNATURE_ALGORITHM); return $csr->saveCSR($csrData); }
php
{ "resource": "" }
q2704
Util.localDelete
train
public static function localDelete(string $path, string $fileName) : bool { if (is_file($path . $fileName)) { unlink($path . $fileName); } else { return false; } return true; }
php
{ "resource": "" }
q2705
Util.getUUID
train
public static function getUUID() : string { mt_srand((double) microtime() * 10000); $charId = strtolower(md5(uniqid(rand(), true))); $hyphen = chr(45); return substr($charId, 0, 8) . $hyphen . substr($charId, 8, 4) . $hyphen . substr($charId, 12, 4) . $hyphen . substr($charId, 16, 4) . $hyphen . substr($charId, 20, 12); }
php
{ "resource": "" }
q2706
Util.getRandomString
train
public static function getRandomString(int $length = 64) : string { $characters = "01234567890123456789"; $characters .= "abcdefghijklmnopqrstuvwxyz"; $string_generated = ""; while ($length--) { $string_generated .= $characters[mt_rand(0, 45)]; } return $string_generated; }
php
{ "resource": "" }
q2707
Parser.arrayToXml
train
public static function arrayToXml($arr, $num_prefix = "num_") : string { if (!is_array($arr)) return $arr; $result = ''; foreach ($arr as $key => $val) { $key = (is_numeric($key) ? $num_prefix . $key : $key); $result .= '<' . $key . '>' . self::arrayToXml($val, $num_prefix) . '</' . $key . '>'; } return $result; }
php
{ "resource": "" }
q2708
Client.get
train
public function get($apiPath, $queryParams = []) { $response = $this->guzzleClient->get( $this->baseUrl . $apiPath, [ 'query' => $queryParams, 'future' => false, 'auth' => [ $this->id, $this->secret, self::$AUTH_TYPE ], ] ); return $this->resolve($response); }
php
{ "resource": "" }
q2709
AssetsServiceProvider.compiles
train
public static function compiles() { return [ base_path('vendor\kodicms\laravel-assets\src\Contracts\MetaInterface.php'), base_path('vendor\kodicms\laravel-assets\src\Contracts\AssetsInterface.php'), base_path('vendor\kodicms\laravel-assets\src\Contracts\PackageManagerInterface.php'), base_path('vendor\kodicms\laravel-assets\src\Contracts\AssetElementInterface.php'), base_path('vendor\kodicms\laravel-assets\src\Contracts\PackageInterface.php'), base_path('vendor\kodicms\laravel-assets\src\Contracts\SocialMediaTagsInterface.php'), base_path('vendor\kodicms\laravel-assets\src\Traits\Groups.php'), base_path('vendor\kodicms\laravel-assets\src\Traits\Vars.php'), base_path('vendor\kodicms\laravel-assets\src\Traits\Packages.php'), base_path('vendor\kodicms\laravel-assets\src\Traits\Styles.php'), base_path('vendor\kodicms\laravel-assets\src\Traits\Scripts.php'), base_path('vendor\kodicms\laravel-assets\src\AssetElement.php'), base_path('vendor\kodicms\laravel-assets\src\Css.php'), base_path('vendor\kodicms\laravel-assets\src\Javascript.php'), base_path('vendor\kodicms\laravel-assets\src\Html.php'), base_path('vendor\kodicms\laravel-assets\src\Meta.php'), base_path('vendor\kodicms\laravel-assets\src\Package.php'), base_path('vendor\kodicms\laravel-assets\src\PackageManager.php'), base_path('vendor\kodicms\laravel-assets\src\Assets.php'), base_path('vendor\kodicms\laravel-assets\src\Facades\Meta.php'), ]; }
php
{ "resource": "" }
q2710
HttpRequest.setSecurityLevel
train
public function setSecurityLevel($rawData) { switch ($this->securityLevel) { case "low": break; case "normal": $rawData = \str_replace("<", "&lt;", $rawData); $rawData = \str_replace(">", "&gt;", $rawData); $rawData = \str_replace("\"", "&quot;", $rawData); $rawData = \str_replace("'", "&apos;", $rawData); break; case "high": $rawData = \str_replace("<", "", $rawData); $rawData = \str_replace(">", "", $rawData); $rawData = \str_replace("\"", "", $rawData); $rawData = \str_replace("'", "", $rawData); break; } return $rawData; }
php
{ "resource": "" }
q2711
HttpRequest.setGet
train
private function setGet() { if (isset($_GET)) { foreach ($_GET as $k => $v) { $this->log->debug("[ GET Params ]" . $k . ": " . $v, []); $this->get->$k = $this->setSecurityLevel($v); $this->parameters["get"][$k] = $this->setSecurityLevel($v); } unset($_GET); } }
php
{ "resource": "" }
q2712
HttpRequest.setConfig
train
private function setConfig($config) { $this->securityLevel = $config->config['project']['security_level']; if ($config->config['config']) { foreach ($config->config['config'] as $k => $v) { $this->log->debug("[ CONFIG Params ]" . $k . ": " . $v, []); $this->config->$k = $this->setSecurityLevel($v); $this->parameters["config"][$k] = $this->setSecurityLevel($v); } } }
php
{ "resource": "" }
q2713
HttpRequest.setPost
train
private function setPost() { if ($this->parameters['header']["Content-Type"] == "application/x-www-form-urlencoded") { if (isset($_GET)) { foreach ($_GET as $k => $v) { $this->log->debug("[ _POST Params ]" . $k . ": " . $v, []); $this->post->$k = $this->setSecurityLevel($v); $this->parameters["post"][$k] = $this->setSecurityLevel($v); } unset($_GET); } } if (isset($_POST)) { foreach ($_POST as $k => $v) { if (is_array($v) == true) { $this->log->debug("[ _POST Params ]" . $k . ": " . json_encode($v), []); } else { $this->log->debug("[ _POST Params ]" . $k . ": " . $v, []); } $this->post->$k = $this->setSecurityLevel($v); $this->parameters["post"][$k] = $this->setSecurityLevel($v); } $rawData = file_get_contents("php://input"); if (isset($rawData)) { $this->log->debug("[ POST RawData ] : " . $rawData, []); $this->parameters["post"]["raw"] = $rawData; $this->post->raw = $rawData; } unset($_POST); } }
php
{ "resource": "" }
q2714
HttpRequest.setPut
train
private function setPut() { if ($this->parameters['header']["Content-Type"] == "application/x-www-form-urlencoded") { if (isset($_GET)) { foreach ($_GET as $k => $v) { $this->log->debug("[ PUT Params ]" . $k . ": " . $v, []); $this->put->$k = $this->setSecurityLevel($v); $this->parameters["put"][$k] = $this->setSecurityLevel($v); } unset($_GET); } $rawData = file_get_contents("php://input"); parse_str($rawData, $_PUT); foreach ($_PUT as $k => $v) { $this->log->debug("[ PUT Params ]" . $k . ": " . $v, []); $this->put->$k = $this->setSecurityLevel($v); $this->parameters["put"][$k] = $this->setSecurityLevel($v); } if ($rawData) { $this->parameters["put"]['raw'] = $rawData; $this->log->debug("[ PUT RawData ] raw: " . $rawData, []); } } }
php
{ "resource": "" }
q2715
HttpRequest.setDelete
train
private function setDelete() { if ($this->parameters['header']["Content-Type"] == "application/x-www-form-urlencoded") { if (isset($_GET)) { foreach ($_GET as $k => $v) { $this->log->debug("[ DELETE Params ]" . $k . ": " . $v, []); $this->delete->$k = $this->setSecurityLevel($v); $this->parameters["delete"][$k] = $this->setSecurityLevel($v); } unset($_GET); } $rawData = file_get_contents("php://input"); parse_str($rawData, $_DELETE); foreach ($_DELETE as $k => $v) { $this->log->debug("[ DELETE Params ]" . $k . ": " . $v, []); $this->delete->$k = $this->setSecurityLevel($v); $this->parameters["delete"][$k] = $this->setSecurityLevel($v); } if ($rawData) { $this->parameters["delete"]['raw'] = $rawData; $this->log->debug("[ DELETE RawData ] raw: " . $rawData, []); } } }
php
{ "resource": "" }
q2716
HttpRequest.setCookie
train
private function setCookie() { if (isset($_COOKIE)) { foreach ($_COOKIE as $k => $v) { $this->log->debug("[ COOKIE Params ]" . $k . ": " . $v, []); $this->cookie->$k = $this->setSecurityLevel($v); $this->parameters["cookie"][$k] = $this->setSecurityLevel($v); } unset($_COOKIE); } }
php
{ "resource": "" }
q2717
HttpRequest.setHeader
train
private function setHeader() { foreach (getallheaders() as $k => $v) { $this->log->debug("[ HEADER Params ]" . $k . ": " . $v, []); $this->header->$k = $this->setSecurityLevel($v); $this->parameters["header"][$k] = $this->setSecurityLevel($v); } }
php
{ "resource": "" }
q2718
HttpRequest.setServer
train
private function setServer() { if (isset($_SERVER)) { foreach ($_SERVER as $k => $v) { $this->log->debug("[ SERVER Params ]" . $k . ": " . $v, []); $this->server->$k = $v; $this->parameters["server"][$k] = $v; } unset($_SERVER); } }
php
{ "resource": "" }
q2719
HttpRequest.setSession
train
private function setSession() { if (isset($_SESSION)) { foreach ($_SESSION as $k => $v) { $this->log->debug("[ SESSION Params ]" . $k . ": " . $v, []); $this->session->$k = $this->setSecurityLevel($v); $this->parameters["session"][$k] = $this->setSecurityLevel($v); } } }
php
{ "resource": "" }
q2720
Scripts.addJs
train
public function addJs($handle = false, $src = null, $dependency = null, $footer = false) { return $this->scripts[$handle] = new Javascript($handle, $src, $dependency, $footer); }
php
{ "resource": "" }
q2721
Scripts.removeJs
train
public function removeJs($handle = null) { if (is_null($handle)) { return $this->scripts = []; } if (is_bool($handle)) { foreach ($this->scripts as $i => $javaScript) { if ($javaScript->isFooter() === $handle) { unset($this->scripts[$i]); } } return; } unset($this->scripts[$handle]); }
php
{ "resource": "" }
q2722
View.data
train
public static function data($key, $value) { if ($value === null) { unset(self::$shared[$key]); } else { self::$shared[$key] = $value; } }
php
{ "resource": "" }
q2723
View.render
train
public static function render($view, array $data = array()) { if (self::$force || App::state() > 2) { \UtilsSandboxLoader('application/View/' . strtr($view, '.', '/') . '.php', self::$shared + $data); return $data = null; } return array_push(self::$views, array(strtr($view, '.', '/'), $data)) - 1; }
php
{ "resource": "" }
q2724
View.remove
train
public static function remove($index) { if (isset(self::$views[$index])) { self::$views[$index] = null; } }
php
{ "resource": "" }
q2725
Commands.getContainerName
train
protected function getContainerName($container) { $this->validateConfig(); // Project name is defined in a nice, human-readable style, so lowercase it // first. $project_lowercase = strtolower($this->config->get('name')); // Replace all spaces to match the behavior of Docker Compose. Then finally // append container name. return str_replace(' ', '', $project_lowercase) . '_' . $container; }
php
{ "resource": "" }
q2726
Commands.cleanFileName
train
protected function cleanFileName($identifier) { // Convert or strip certain special characters, by convention. $filter = [ ' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '', ]; $identifier = strtr($identifier, $filter); // Valid characters in a clean filename identifier are: // - the hyphen (U+002D) // - the period (U+002E) // - a-z (U+0030 - U+0039) // - A-Z (U+0041 - U+005A) // - the underscore (U+005F) // - 0-9 (U+0061 - U+007A) // - ISO 10646 characters U+00A1 and higher // We strip out any character not in the above list $identifier = preg_replace('/[^\\x{002D}\\x{002E}\\x{0030}-\\x{0039}\\x{0041}-\\x{005A}\\x{005F}\\x{0061}-\\x{007A}\\x{00A1}-\\x{FFFF}]/u', '', $identifier); // Convert everything to lowercase return strtolower($identifier); }
php
{ "resource": "" }
q2727
MessageFactory.createRequest
train
public function createRequest($method, $url, array $options = []) { $request = parent::createRequest($method, $url, $options); $query = $request->getQuery(); $auth = $request->getConfig()->get('auth'); // The 'auth' configuration must be valid if ((!is_array($auth)) || (count($auth) < 3) || ($auth[2] != Client::$AUTH_TYPE)) { throw new RuntimeException("Authorization information not provided"); } $id = $auth[0]; $secret = $auth[1]; // Add API User ID to the query $query->set('api_id', $id); // Add timestamp to the query if (!$query->hasKey('api_ts')) { $query->set('api_ts', time()); } // Add version to the query $query->set('api_ver', '2'); // Add hash to the query $hash = $this->generateMac($request->getUrl(), $request->getQuery()->toArray(), $secret); $query->set('api_mac', $hash); return $request; }
php
{ "resource": "" }
q2728
MessageFactory.generateMac
train
private function generateMac($url, $query, $secret) { // break URL into parts to get the path $urlParts = parse_url($url); // trim double slashes in the path if (substr($urlParts['path'], 0, 2) == '//') { $urlParts['path'] = substr($urlParts['path'], 1); } // build query string from given parameters $queryString = urldecode(http_build_query($query)); // combine strings to build the signing string $signingString = $query['api_id'] . "\n" . $query['api_ts'] . "\n" . $urlParts['path'] . "\n" . $queryString; $mac = hash_hmac('sha1', $signingString, $secret); return $mac; }
php
{ "resource": "" }
q2729
MessageFactory.createResponse
train
public function createResponse( $statusCode, array $headers = [], $body = null, array $options = [] ) { return parent::createResponse($statusCode, $headers, $body, $options); }
php
{ "resource": "" }
q2730
Common.setMaxDepth
train
public function setMaxDepth(int $maxDepth) : void { if ($maxDepth < 0 || $maxDepth >= 0x7fffffff) { // max depth + 1 must not be greater than this limit throw new \InvalidArgumentException('Invalid max depth.'); } $this->maxDepth = $maxDepth; }
php
{ "resource": "" }
q2731
Common.setOption
train
protected function setOption(int $option, bool $bool) : void { if ($bool) { $this->options |= $option; } else { $this->options &= ~ $option; } }
php
{ "resource": "" }
q2732
Sypexgeo.get
train
public function get($ip='') { if (empty($ip)) $this->getIP(); else if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { return false; } else { $this->ip = $ip; $this->ipAsLong = sprintf('%u', ip2long($ip)); } $this->getSypexGeo(); $data = $this->_sypex->getCityFull($this->ip); if (isset($data['city'])) $this->city = $data['city']; if (isset($data['region'])) $this->region = $data['region']; if (isset($data['country'])) $this->country = $data['country']; return empty($data) ? false : $data; }
php
{ "resource": "" }
q2733
Debug.unregister
train
public static function unregister() { $nc = '\\' . get_called_class(); App::off('error', array( $nc, 'renderError' )); App::off('terminate', array( $nc, 'renderPerformance' )); App::off('terminate', array( $nc, 'renderClasses' )); if (false === empty(self::$displayErrors)) { function_exists('init_set') && ini_set('display_errors', self::$displayErrors); self::$displayErrors = null; } }
php
{ "resource": "" }
q2734
Debug.renderError
train
public static function renderError($type, $message, $file, $line) { if (empty(self::$views['error'])) { return null; } elseif (preg_match('#allowed\s+memory\s+size\s+of\s+\d+\s+bytes\s+exhausted\s+\(tried\s+to\s+allocate\s+\d+\s+bytes\)#i', $message)) { die('<br><strong>Fatal error:</strong> ' . $message . ' in <strong>' . $file . '</strong> on line <strong>' . $line . '</strong>'); } $data = self::details($type, $message, $file, $line); if (!headers_sent() && strcasecmp(Request::header('accept'), 'application/json') === 0) { ob_start(); self::unregister(); Response::cache(0); Response::type('application/json'); echo json_encode($data); App::stop(500); } if (in_array($type, self::$fatal)) { View::dispatch(); } self::render(self::$views['error'], $data); }
php
{ "resource": "" }
q2735
Debug.renderPerformance
train
public static function renderPerformance() { if (!empty(self::$views['performance'])) { self::render(self::$views['performance'], self::performance()); } }
php
{ "resource": "" }
q2736
Debug.renderClasses
train
public static function renderClasses() { if (!empty(self::$views['classes'])) { self::render(self::$views['classes'], array( 'classes' => self::classes() )); } }
php
{ "resource": "" }
q2737
Debug.view
train
public static function view($type, $view) { if ($view !== null && View::exists($view) === false) { throw new Exception($view . ' view is not found', 2); } $callRender = array( '\\' . get_called_class(), 'render' . ucfirst($type) ); switch ($type) { case 'error': self::$views[$type] = $view; App::on('error', $callRender); if (empty(self::$displayErrors)) { self::$displayErrors = ini_get('display_errors'); function_exists('ini_set') && ini_set('display_errors', '0'); } break; case 'classes': case 'performance': self::$views[$type] = $view; App::on('terminate', $callRender); break; case 'before': self::$views[$type] = $view; break; default: throw new Exception($type . ' is not valid event', 2); } }
php
{ "resource": "" }
q2738
Debug.classes
train
public static function classes() { $objs = array(); foreach (get_declared_classes() as $value) { $value = ltrim($value, '\\'); $cname = new \ReflectionClass($value); if (false === $cname->isInternal()) { $objs[$value] = $cname->getDefaultProperties(); } $cname = null; } return $objs; }
php
{ "resource": "" }
q2739
Debug.source
train
public static function source($file, $line) { if ($line <= 0 || is_file($file) === false) { return null; } elseif ($line > 5) { $init = $line - 5; $end = $line + 5; $breakpoint = 6; } else { $init = 0; $end = 5; $breakpoint = $line; } return array( 'breakpoint' => $breakpoint, 'preview' => preg_split('#\r\n|\n#', trim( File::portion($file, $init, $end, true), "\r\n") ) ); }
php
{ "resource": "" }
q2740
CsvFileIterator.readCurrent
train
private function readCurrent() : void { $row = $this->readRow(); if ($this->columns === null || $row === null) { $this->current = $row; } else { $this->current = []; foreach ($this->columns as $key => $name) { $this->current[$name] = isset($row[$key]) ? $row[$key] : null; } } }
php
{ "resource": "" }
q2741
ObjectStorage.has
train
public function has($object) : bool { $hash = spl_object_hash($object); return isset($this->objects[$hash]); }
php
{ "resource": "" }
q2742
ObjectStorage.get
train
public function get($object) { $hash = spl_object_hash($object); if (isset($this->data[$hash])) { return $this->data[$hash]; } return null; }
php
{ "resource": "" }
q2743
ObjectStorage.set
train
public function set($object, $data = null) : void { $hash = spl_object_hash($object); $this->objects[$hash] = $object; $this->data[$hash] = $data; }
php
{ "resource": "" }
q2744
ObjectStorage.remove
train
public function remove($object) : void { $hash = spl_object_hash($object); unset($this->objects[$hash]); unset($this->data[$hash]); }
php
{ "resource": "" }
q2745
ObjectStorage.getIterator
train
public function getIterator() : \Traversable { foreach ($this->objects as $hash => $object) { yield $object => $this->data[$hash]; } }
php
{ "resource": "" }
q2746
RegistrationServer.call
train
public function call($reqData) { $respData = $this->createError('Unrecognized entity or action'); if ($reqData['entity'] == 'Cxn' && preg_match('/^[a-zA-Z]+$/', $reqData['action'])) { $func = 'on' . $reqData['entity'] . strtoupper($reqData['action']{0}) . substr($reqData['action'], 1); if (is_callable(array($this, $func))) { $respData = call_user_func(array($this, $func), $reqData['cxn'], $reqData['params']); } } return $respData; }
php
{ "resource": "" }
q2747
RegistrationServer.onCxnRegister
train
public function onCxnRegister($cxn, $params) { $storedCxn = $this->cxnStore->getByCxnId($cxn['cxnId']); if (!$storedCxn || $storedCxn['secret'] == $cxn['secret']) { $this->log->notice('Register cxnId="{cxnId}" siteUrl={siteUrl}: OK', array( 'cxnId' => $cxn['cxnId'], 'siteUrl' => $cxn['siteUrl'], )); $this->cxnStore->add($cxn); return $this->createSuccess(array( 'cxn_id' => $cxn['cxnId'], )); } else { $this->log->warning('Register cxnId="{cxnId}" siteUrl="{siteUrl}": Secret does not match.', array( 'cxnId' => $cxn['cxnId'], 'siteUrl' => $cxn['siteUrl'], )); $this->createError('Secret does not match previous registration.'); } }
php
{ "resource": "" }
q2748
RegistrationServer.onCxnUnregister
train
public function onCxnUnregister($cxn, $params) { $storedCxn = $this->cxnStore->getByCxnId($cxn['cxnId']); if (!$storedCxn) { $this->log->warning('Unregister cxnId="{cxnId} siteUrl="{siteUrl}"": Non-existent', array( 'cxnId' => $cxn['cxnId'], 'siteUrl' => $cxn['siteUrl'], )); return $this->createSuccess(array( 'cxn_id' => $cxn['cxnId'], )); } elseif ($storedCxn['secret'] == $cxn['secret']) { $this->log->notice('Unregister cxnId="{cxnId} siteUrl="{siteUrl}": OK"', array( 'cxnId' => $cxn['cxnId'], 'siteUrl' => $cxn['siteUrl'], )); $this->cxnStore->remove($cxn['cxnId']); return $this->createSuccess(array( 'cxn_id' => $cxn['cxnId'], )); } else { $this->log->warning('Unregister cxnId="{cxnId}" siteUrl="{siteUrl}": Secret does not match.', array( 'cxnId' => $cxn['cxnId'], 'siteUrl' => $cxn['siteUrl'], )); $this->createError('Incorrect cxnId or secret.'); } }
php
{ "resource": "" }
q2749
Builder.addPlugin
train
public function addPlugin(Plugin $plugin): Builder { $this->plugins[] = $plugin; $this->httpClientModified = true; return $this; }
php
{ "resource": "" }
q2750
Route.set
train
public static function set($method, $path, $action) { if (is_array($method)) { foreach ($method as $value) { self::set($value, $path, $action); } } else { if (is_string($action)) { $action = parent::$prefixNS . $action; } elseif ($action !== null && !$action instanceof \Closure) { return null; } $method = strtoupper(trim($method)); $path = parent::$prefixPath . $path; if (!isset(parent::$httpRoutes[$path])) { parent::$httpRoutes[$path] = array(); } parent::$httpRoutes[$path][$method] = $action; } }
php
{ "resource": "" }
q2751
Route.get
train
public static function get() { if (self::$current !== null) { return self::$current; } $resp = 404; $args = array(); $routes = parent::$httpRoutes; $path = \UtilsPath(); $method = $_SERVER['REQUEST_METHOD']; //... if (isset($routes[$path])) { $verbs = $routes[$path]; } else { foreach ($routes as $route => $actions) { if (parent::find($route, $path, $args)) { $verbs = $actions; break; } } } if (isset($verbs[$method])) { $resp = $verbs[$method]; } elseif (isset($verbs['ANY'])) { $resp = $verbs['ANY']; } elseif (isset($verbs)) { $resp = 405; } if (is_numeric($resp)) { self::$current = $resp; } else { self::$current = array( 'callback' => $resp, 'args' => $args ); } $routes = null; return self::$current; }
php
{ "resource": "" }
q2752
ErrorCatcher.run
train
public static function run(callable $function) { set_error_handler(static function($severity, $message, $file, $line) { throw new \ErrorException($message, 0, $severity, $file, $line); }); try { $result = $function(); } finally { restore_error_handler(); } return $result; }
php
{ "resource": "" }
q2753
LoggerService.emergency
train
public static function emergency($message, $context = [], $channel = 'tastphp.logger') { $logger = static::getLoggerByLevelAndChannel(Monolog::ALERT, $channel); $logger->addEmergency($message, $context); }
php
{ "resource": "" }
q2754
Response.dispatch
train
public static function dispatch() { if (empty(self::$headers) === false) { self::$dispatchedHeaders = true; foreach (self::$headers as $value) { self::putHeader($value[0], $value[1], $value[2]); } } }
php
{ "resource": "" }
q2755
Response.status
train
public static function status($code = null, $trigger = true) { if (self::$httpCode === null) { self::$httpCode = \UtilsStatusCode(); } if ($code === null || self::$httpCode === $code) { return self::$httpCode; } elseif (headers_sent() || $code < 100 || $code > 599) { return false; } header('X-PHP-Response-Code: ' . $code, true, $code); $lastCode = self::$httpCode; self::$httpCode = $code; if ($trigger) { App::trigger('changestatus', array($code, null)); } return $lastCode; }
php
{ "resource": "" }
q2756
Response.removeHeader
train
public static function removeHeader($name) { self::$headers = array_filter(self::$headers, function ($header) use ($name) { return strcasecmp($header[0], $name) !== 0; }); }
php
{ "resource": "" }
q2757
Response.download
train
public static function download($name = null, $contentLength = 0) { if ($name) { $name = '; filename="' . strtr($name, '"', '-') . '"'; } else { $name = ''; } self::putHeader('Content-Transfer-Encoding', 'Binary'); self::putHeader('Content-Disposition', 'attachment' . $name); if ($contentLength > 0) { self::putHeader('Content-Length', $contentLength); } }
php
{ "resource": "" }
q2758
ModelView.addViewData
train
public function addViewData($key, $value) { if ($key) { $this->modelVar[$key] = $value; } else { $this->modelVar = $value; } return $this; }
php
{ "resource": "" }
q2759
Shell.inputObserver
train
public function inputObserver($callback, $exitCicle = null) { if (self::isCli() === false || is_callable($callback) === false) { return false; } $this->io = $callback; $this->ec = $exitCicle ? $exitCicle : $this->ec; if ($this->started) { return true; } $this->started = true; $this->fireInputObserver(); return true; }
php
{ "resource": "" }
q2760
Shell.fireInputObserver
train
protected function fireInputObserver() { $response = rtrim(self::input(), PHP_EOL); if (strcasecmp($response, $this->ec) === 0) { return null; } $callback = $this->io; $callback($response); usleep(100); $this->fireInputObserver(); }
php
{ "resource": "" }
q2761
Router.get
train
public function get(string $pattern, callable $callback) { if ($this->requestMethod === "GET") { $this->mapRoute($pattern, $callback); } }
php
{ "resource": "" }
q2762
Router.post
train
public function post(string $pattern, callable $callback) { if ($this->requestMethod === "POST") { $this->mapRoute($pattern, $callback); } }
php
{ "resource": "" }
q2763
Router.getPattern
train
private static function getPattern(string $pattern) { $keywords = preg_split("/\\//", $pattern); $i = '0'; $word = ""; foreach ($keywords as $keyword) { $i++; if (preg_match("/:/i", $keyword)) { $word .= "([a-zA-Z0-9-._]+)"; } else { $word .= $keyword; } if (count($keywords) != $i) { $word .= "/"; } } return $word; }
php
{ "resource": "" }
q2764
Embed.normalizeConfig
train
private function normalizeConfig(array $embedConfig) { $config = $embedConfig; // apply deprecated configuration keys if exists: if (array_key_exists('video_player', $embedConfig)) { $config['video']['player'] = $embedConfig['video_player']; } if (array_key_exists('video_autoplay', $embedConfig)) { $config['video']['autoplay'] = $embedConfig['video_autoplay']; } if (array_key_exists('video_available_speeds', $embedConfig)) { $config['video']['available-speeds'] = $embedConfig['video_available_speeds']; } if (array_key_exists('audio_player', $embedConfig)) { $config['audio']['player'] = $embedConfig['audio_player']; } if (array_key_exists('audio_autoplay', $embedConfig)) { $config['audio']['autoplay'] = $embedConfig['audio_autoplay']; } if (array_key_exists('audio_available_speeds', $embedConfig)) { $config['audio']['available-speeds'] = $embedConfig['audio_available_speeds']; } if (array_key_exists('enable_pdfjs', $embedConfig['document'])) { $config['document']['enable-pdfjs'] = $embedConfig['document']['enable_pdfjs']; } return $config; }
php
{ "resource": "" }
q2765
Groups.group
train
public function group($group, $handle = null, $content = null) { $this->groups[$group][$handle] = $content; return $this; }
php
{ "resource": "" }
q2766
Groups.removeGroup
train
public function removeGroup($group = null, $handle = null) { if (is_null($group)) { return $this->groups = []; } if (is_null($handle)) { unset($this->groups[$group]); return; } unset($this->groups[$group][$handle]); }
php
{ "resource": "" }
q2767
Groups.renderGroup
train
public function renderGroup($group) { if (!isset($this->groups[$group])) { return PHP_EOL; } foreach ($this->groups[$group] as $handle => $data) { $assets[] = $this->getGroup($group, $handle); } return implode(PHP_EOL, $assets); }
php
{ "resource": "" }
q2768
SeoBehavior.saveSeoContent
train
public function saveSeoContent() { $model = $this->getSeoContentModel(); if (!$model->is_global) { $model->title = $this->owner->{$this->titleAttribute}; $model->keywords = $this->owner->{$this->keywordsAttribute}; $model->description = $this->owner->{$this->descriptionAttribute}; $model->save(); } }
php
{ "resource": "" }
q2769
SeoBehavior.deleteSeoContent
train
public function deleteSeoContent() { $model = $this->getSeoContentModel(); if ($model && !$model->getIsNewRecord() && !$model->is_global) { $model->delete(); } }
php
{ "resource": "" }
q2770
Router.find
train
protected static function find($route, $path, array &$matches) { $re = Regex::parse($route); if ($re !== false && preg_match('#^' . $re . '$#', $path, $matches)) { array_shift($matches); return true; } return false; }
php
{ "resource": "" }
q2771
Quick.verbs
train
private static function verbs(array $methods) { $list = array(); $reMatch = '#^(any|get|post|patch|put|head|delete|options|trace|connect)([A-Z0-9]\w+)$#'; foreach ($methods as $value) { $verb = array(); if (preg_match($reMatch, $value, $verb)) { if (strcasecmp('index', $verb[2]) === 0) { $verb[2] = ''; } else { $verb[2] = strtolower(preg_replace('#([a-z])([A-Z])#', '$1-$2', $verb[2])); } $list[] = array(strtoupper($verb[1]), $verb[2], $value); } } return $list; }
php
{ "resource": "" }
q2772
Quick.prepare
train
public function prepare() { if ($this->ready) { return null; } $this->ready = true; $format = $this->format; $controller = $this->controller; foreach ($this->classMethods as $value) { if ($format === self::BOTH || $format === self::SLASH) { $route = '/' . (empty($value[1]) ? '' : ($value[1] . '/')); Route::set($value[0], $route, $controller . ':' . $value[2]); } if ($format === self::BOTH || $format === self::NOSLASH) { $route = empty($value[1]) ? '' : ('/' . $value[1]); Route::set($value[0], $route, $controller . ':' . $value[2]); } } $controller = $classMethods = null; }
php
{ "resource": "" }
q2773
AesHelper.authenticateThenDecrypt
train
public static function authenticateThenDecrypt($secret, $body, $signature) { $keys = self::deriveAesKeys($secret); $localHmac = hash_hmac('sha256', $body, $keys['auth']); if (!self::hash_compare($signature, $localHmac)) { throw new InvalidMessageException("Incorrect hash"); } list ($jsonEnvelope, $jsonEncrypted) = explode(Constants::PROTOCOL_DELIM, $body, 2); if (strlen($jsonEnvelope) > Constants::MAX_ENVELOPE_BYTES) { throw new InvalidMessageException("Oversized envelope"); } $envelope = json_decode($jsonEnvelope, TRUE); if (!$envelope) { throw new InvalidMessageException("Malformed envelope"); } if (!is_numeric($envelope['ttl']) || Time::getTime() > $envelope['ttl']) { throw new InvalidMessageException("Invalid TTL"); } if (!is_string($envelope['iv']) || strlen($envelope['iv']) !== Constants::AES_BYTES * 2 || !preg_match('/^[a-f0-9]+$/', $envelope['iv'])) { // AES_BYTES (32) ==> bin2hex ==> 2 hex digits (4-bit) per byte (8-bit) throw new InvalidMessageException("Malformed initialization vector"); } $jsonPlaintext = UserError::adapt('Civi\Cxn\Rpc\Exception\InvalidMessageException', function () use ($jsonEncrypted, $envelope, $keys) { $cipher = new \Crypt_AES(CRYPT_AES_MODE_CBC); $cipher->setKeyLength(Constants::AES_BYTES); $cipher->setKey($keys['enc']); $cipher->setIV(BinHex::hex2bin($envelope['iv'])); return $cipher->decrypt($jsonEncrypted); }); return $jsonPlaintext; }
php
{ "resource": "" }
q2774
AesHelper.hash_compare
train
private static function hash_compare($a, $b) { if (!is_string($a) || !is_string($b)) { return FALSE; } $len = strlen($a); if ($len !== strlen($b)) { return FALSE; } $status = 0; for ($i = 0; $i < $len; $i++) { $status |= ord($a[$i]) ^ ord($b[$i]); } return $status === 0; }
php
{ "resource": "" }
q2775
File.exists
train
public static function exists($path) { if (file_exists($path) === false) { return false; } $path = preg_replace('#^file:/+([a-z]:/|/)#i', '$1', $path); $pinfo = pathinfo($path); $rpath = strtr(realpath($path), '\\', '/'); if ($pinfo['dirname'] !== '.') { $path = Uri::canonpath($pinfo['dirname']) . '/' . $pinfo['basename']; } $pinfo = null; return $rpath === $path || substr($rpath, strlen($rpath) - strlen($path)) === $path; }
php
{ "resource": "" }
q2776
File.mime
train
public static function mime($path) { $mime = false; if (is_readable($path)) { if (function_exists('finfo_open')) { $buffer = file_get_contents($path, false, null, -1, 5012); $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_buffer($finfo, $buffer); finfo_close($finfo); $buffer = null; } elseif (function_exists('mime_content_type')) { $mime = mime_content_type($path); } } if ($mime !== false && strpos($mime, 'application/') === 0) { $size = filesize($path); $mime = $size >= 0 && $size < 2 ? 'text/plain' : $mime; } return $mime; }
php
{ "resource": "" }
q2777
File.output
train
public static function output($path, $length = 102400, $delay = 0) { if (is_readable($path) === false) { return false; } $buffer = ob_get_level() !== 0; $handle = fopen($path, 'rb'); $length = is_int($length) && $length > 0 ? $length : 102400; while (false === feof($handle)) { echo fread($handle, $length); if ($delay > 0) { usleep($delay); } if ($buffer) { ob_flush(); } flush(); } }
php
{ "resource": "" }
q2778
Message.send
train
public function send() { list ($headers, $blob, $code) = $this->toHttp(); header('Content-Type: ' . Constants::MIME_TYPE); header("X-PHP-Response-Code: $code", TRUE, $code); foreach ($headers as $n => $v) { header("$n: $v"); } echo $blob; }
php
{ "resource": "" }
q2779
Message.toSymfonyResponse
train
public function toSymfonyResponse() { $headers = array_merge( array('Content-Type' => Constants::MIME_TYPE), $this->getHeaders() ); return new \Symfony\Component\HttpFoundation\Response( $this->encode(), $this->code, $headers ); }
php
{ "resource": "" }
q2780
JmsMetadataParser.doParse
train
protected function doParse($className, $visited = array(), array $groups = array()) { $meta = $this->factory->getMetadataForClass($className); if (null === $meta) { throw new \InvalidArgumentException(sprintf('No metadata found for class %s', $className)); } $exclusionStrategies = array(); if ($groups) { $exclusionStrategies[] = new GroupsExclusionStrategy($groups); } $params = array(); // iterate over property metadata foreach ($meta->propertyMetadata as $item) { if (!is_null($item->type)) { $name = $this->namingStrategy->translateName($item); $dataType = $this->processDataType($item); // apply exclusion strategies foreach ($exclusionStrategies as $strategy) { if (true === $strategy->shouldSkipProperty($item, SerializationContext::create())) { continue 2; } } $params[$name] = array( 'dataType' => $dataType['normalized'], 'required' => false, 'readonly' => $item->readOnly, 'sinceVersion' => $item->sinceVersion, 'untilVersion' => $item->untilVersion, ); if (!is_null($dataType['class'])) { $params[$name]['class'] = $dataType['class']; } // if class already parsed, continue, to avoid infinite recursion if (in_array($dataType['class'], $visited)) { continue; } // check for nested classes with JMS metadata if ($dataType['class'] && null !== $this->factory->getMetadataForClass($dataType['class'])) { $visited[] = $dataType['class']; $params[$name]['children'] = $this->doParse($dataType['class'], $visited, $groups); } } } return $params; }
php
{ "resource": "" }
q2781
Request.header
train
public static function header($name = null) { if (self::$reqHeaders === null) { self::generate(); } if (is_string($name)) { $name = strtolower($name); return isset(self::$reqHeadersLower[$name]) ? self::$reqHeadersLower[$name] : false; } return self::$reqHeaders; }
php
{ "resource": "" }
q2782
Request.raw
train
public static function raw($binary = true) { if (is_readable('php://input')) { return false; } $mode = $binary ? 'rb' : 'r'; if (PHP_VERSION_ID >= 50600) { return fopen('php://input', $mode); } $tmp = Storage::temp(); return copy('php://input', $tmp) ? fopen($tmp, $mode) : false; }
php
{ "resource": "" }
q2783
SeoContentHelper.behavior
train
protected static function behavior(Component $model) { foreach ($model->getBehaviors() as $b) { if ($b instanceof SeoBehavior) { return $b; } } throw new InvalidConfigException('Model ' . $model->className() . ' must have SeoBehavior'); }
php
{ "resource": "" }
q2784
SeoContentHelper.registerSeoMetaTag
train
protected static function registerSeoMetaTag(Component $model, string $modelSeoAttributeName, string $metaTagKey) { $value = $model->{$modelSeoAttributeName}; if ($value) Yii::$app->view->registerMetaTag(['name' => $metaTagKey, 'content' => $value], $metaTagKey); }
php
{ "resource": "" }
q2785
SeoContentHelper.registerAllSeoMeta
train
public static function registerAllSeoMeta(Component $model) { self::registerMetaTitle($model); self::registerMetaKeywords($model); self::registerMetaDescription($model); }
php
{ "resource": "" }
q2786
SeoContentHelper.setTitle
train
public static function setTitle(Component $model) { $title = $model->{self::behavior($model)->titleAttribute}; if ($title) Yii::$app->view->title = $title; }
php
{ "resource": "" }
q2787
SeoContentHelper.registerMetaTitle
train
public static function registerMetaTitle(Component $model) { $modelSeoAttributeName = self::behavior($model)->titleAttribute; self::registerSeoMetaTag($model, $modelSeoAttributeName, 'title'); }
php
{ "resource": "" }
q2788
SeoContentHelper.registerMetaKeywords
train
public static function registerMetaKeywords(Component $model) { $modelSeoAttributeName = self::behavior($model)->keywordsAttribute; self::registerSeoMetaTag($model, $modelSeoAttributeName, 'keywords'); }
php
{ "resource": "" }
q2789
SeoContentHelper.registerMetaDescription
train
public static function registerMetaDescription(Component $model) { $modelSeoAttributeName = self::behavior($model)->descriptionAttribute; self::registerSeoMetaTag($model, $modelSeoAttributeName, 'description'); }
php
{ "resource": "" }
q2790
FileStream.gets
train
public function gets(?int $maxLength = null) : string { if ($this->closed) { throw new IoException('The stream is closed.'); } try { $data = ErrorCatcher::run(function() use ($maxLength) { if ($maxLength === null) { return fgets($this->handle); } else { return fgets($this->handle, $maxLength + 1); } }); } catch (\ErrorException $e) { throw new IoException($e->getMessage(), 0, $e); } if ($data === false) { return ''; } return $data; }
php
{ "resource": "" }
q2791
FileStream.lock
train
public function lock(bool $exclusive) : void { if ($this->closed) { throw new IoException('The stream is closed.'); } try { $result = ErrorCatcher::run(function() use ($exclusive) { return flock($this->handle, $exclusive ? LOCK_EX : LOCK_SH); }); } catch (\ErrorException $e) { throw new IoException($e->getMessage(), 0, $e); } if ($result === false) { throw new IoException('Failed to obtain a lock.'); } }
php
{ "resource": "" }
q2792
FileStream.unlock
train
public function unlock() : void { if ($this->closed) { throw new IoException('The stream is closed.'); } try { $result = ErrorCatcher::run(function() { return flock($this->handle, LOCK_UN); }); } catch (\ErrorException $e) { throw new IoException($e->getMessage(), 0, $e); } if ($result === false) { throw new IoException('Failed to release the lock.'); } }
php
{ "resource": "" }
q2793
Uri.withScheme
train
public function withScheme($scheme) { $scheme = strtolower($scheme); $pattern = new UriPattern(); if (strlen($scheme) === 0 || $pattern->matchScheme($scheme)) { return $this->with('scheme', $scheme); } throw new \InvalidArgumentException("Invalid scheme '$scheme'"); }
php
{ "resource": "" }
q2794
Uri.withUserInfo
train
public function withUserInfo($user, $password = null) { $username = rawurlencode($user); if (strlen($username) > 0) { return $this->with('userInfo', $this->constructString([ '%s%s' => $username, '%s:%s' => rawurlencode($password), ])); } return $this->with('userInfo', ''); }
php
{ "resource": "" }
q2795
Uri.withHost
train
public function withHost($host) { $pattern = new UriPattern(); if ($pattern->matchHost($host)) { return $this->with('host', $this->normalize(strtolower($host))); } throw new \InvalidArgumentException("Invalid host '$host'"); }
php
{ "resource": "" }
q2796
Uri.withPort
train
public function withPort($port) { if ($port !== null) { $port = (int) $port; if (max(0, min(65535, $port)) !== $port) { throw new \InvalidArgumentException("Invalid port number '$port'"); } } return $this->with('port', $port); }
php
{ "resource": "" }
q2797
Uri.with
train
private function with($variable, $value) { if ($value === $this->$variable) { return $this; } $uri = clone $this; $uri->$variable = $value; return $uri; }
php
{ "resource": "" }
q2798
Uri.encode
train
private function encode($string, $extra = '') { $pattern = sprintf( '/[^0-9a-zA-Z%s]|%%(?![0-9A-F]{2})/', preg_quote("%-._~!$&'()*+,;=" . $extra, '/') ); return preg_replace_callback($pattern, function ($match) { return sprintf('%%%02X', ord($match[0])); }, $this->normalize($string)); }
php
{ "resource": "" }
q2799
Uri.constructString
train
private function constructString(array $components) { $formats = array_keys($components); $values = array_values($components); $keys = array_keys(array_filter($values, 'strlen')); return array_reduce($keys, function ($string, $key) use ($formats, $values) { return sprintf($formats[$key], $string, $values[$key]); }, ''); }
php
{ "resource": "" }