_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q259500
LDAPGateway.move
test
public function move($fromDn, $toDn, $recursively = false) { $this->ldap->move($fromDn, $toDn, $recursively); }
php
{ "resource": "" }
q259501
LDAPAuthenticator.authenticate
test
public static function authenticate($data, Form $form = null) { $service = Injector::inst()->get('LDAPService'); $login = trim($data['Login']); if (Email::validEmailAddress($login)) { if (Config::inst()->get('LDAPAuthenticator', 'allow_email_login')!='yes') { $form->sessionMessage( _t( 'LDAPAuthenticator.PLEASEUSEUSERNAME', 'Please enter your username instead of your email to log in.' ), 'bad' ); return; } $username = $service->getUsernameByEmail($login); // No user found with this email. if (!$username) { if (Config::inst()->get('LDAPAuthenticator', 'fallback_authenticator') === 'yes') { $fallbackMember = self::fallback_authenticate($data, $form); if ($fallbackMember) { return $fallbackMember; } } $form->sessionMessage(_t('LDAPAuthenticator.INVALIDCREDENTIALS', 'Invalid credentials'), 'bad'); return; } } else { $username = $login; } $result = $service->authenticate($username, $data['Password']); $success = $result['success'] === true; if (!$success) { if (Config::inst()->get('LDAPAuthenticator', 'fallback_authenticator') === 'yes') { $fallbackMember = self::fallback_authenticate($data, $form); if ($fallbackMember) { return $fallbackMember; } } if ($form) { $form->sessionMessage($result['message'], 'bad'); } return; } $data = $service->getUserByUsername($result['identity']); if (!$data) { if ($form) { $form->sessionMessage( _t('LDAPAuthenticator.PROBLEMFINDINGDATA', 'There was a problem retrieving your user data'), 'bad' ); } return; } // LDAPMemberExtension::memberLoggedIn() will update any other AD attributes mapped to Member fields $member = Member::get()->filter('GUID', $data['objectguid'])->limit(1)->first(); if (!($member && $member->exists())) { $member = new Member(); $member->GUID = $data['objectguid']; } // Update the users from LDAP so we are sure that the email is correct. // This will also write the Member record. $service->updateMemberFromLDAP($member); Session::clear('BackURL'); return $member; }
php
{ "resource": "" }
q259502
LDAPAuthenticator.fallback_authenticate
test
protected static function fallback_authenticate($data, Form $form = null) { return call_user_func( [Config::inst()->get('LDAPAuthenticator', 'fallback_authenticator_class'), 'authenticate'], array_merge($data, ['Email' => $data['Login']]), $form ); }
php
{ "resource": "" }
q259503
SAMLController.acs
test
public function acs() { $auth = Injector::inst()->get('SAMLHelper')->getSAMLAuth(); $auth->processResponse(); $error = $auth->getLastErrorReason(); if (!empty($error)) { SS_Log::log($error, SS_Log::ERR); Form::messageForForm("SAMLLoginForm_LoginForm", "Authentication error: '{$error}'", 'bad'); Session::save(); return $this->getRedirect(); } if (!$auth->isAuthenticated()) { Form::messageForForm("SAMLLoginForm_LoginForm", _t('Member.ERRORWRONGCRED'), 'bad'); Session::save(); return $this->getRedirect(); } $decodedNameId = base64_decode($auth->getNameId()); // check that the NameID is a binary string (which signals that it is a guid if (ctype_print($decodedNameId)) { Form::messageForForm("SAMLLoginForm_LoginForm", "Name ID provided by IdP is not a binary GUID.", 'bad'); Session::save(); return $this->getRedirect(); } // transform the NameId to guid $guid = LDAPUtil::bin_to_str_guid($decodedNameId); if (!LDAPUtil::validGuid($guid)) { $errorMessage = "Not a valid GUID '{$guid}' recieved from server."; SS_Log::log($errorMessage, SS_Log::ERR); Form::messageForForm("SAMLLoginForm_LoginForm", $errorMessage, 'bad'); Session::save(); return $this->getRedirect(); } // Write a rudimentary member with basic fields on every login, so that we at least have something // if LDAP synchronisation fails. $member = Member::get()->filter('GUID', $guid)->limit(1)->first(); if (!($member && $member->exists())) { $member = new Member(); $member->GUID = $guid; } $attributes = $auth->getAttributes(); foreach ($member->config()->claims_field_mappings as $claim => $field) { if (!isset($attributes[$claim][0])) { SS_Log::log( sprintf( 'Claim rule \'%s\' configured in LDAPMember.claims_field_mappings, but wasn\'t passed through. Please check IdP claim rules.', $claim ), SS_Log::WARN ); continue; } if(count($attributes[$claim]) > 1) { $member->$field = $attributes[$claim]; } else { $member->$field = $attributes[$claim][0]; } } $member->SAMLSessionIndex = $auth->getSessionIndex(); // This will trigger LDAP update through LDAPMemberExtension::memberLoggedIn. // The LDAP update will also write the Member record. We shouldn't write before // calling this, as any onAfterWrite hooks that attempt to update LDAP won't // have the Username field available yet for new Member records, and fail. // Both SAML and LDAP identify Members by the GUID field. $member->logIn(); return $this->getRedirect(); }
php
{ "resource": "" }
q259504
SAMLController.metadata
test
public function metadata() { try { $auth = Injector::inst()->get('SAMLHelper')->getSAMLAuth(); $settings = $auth->getSettings(); $metadata = $settings->getSPMetadata(); $errors = $settings->validateMetadata($metadata); if (empty($errors)) { header('Content-Type: text/xml'); echo $metadata; } else { throw new \OneLogin_Saml2_Error( 'Invalid SP metadata: ' . implode(', ', $errors), \OneLogin_Saml2_Error::METADATA_SP_INVALID ); } } catch (Exception $e) { SS_Log::log($e->getMessage(), SS_Log::ERR); echo $e->getMessage(); } }
php
{ "resource": "" }
q259505
LDAPUtil.little_endian
test
public static function little_endian($hex) { $result = ''; for ($x = strlen($hex) - 2; $x >= 0; $x = $x - 2) { $result .= substr($hex, $x, 2); } return $result; }
php
{ "resource": "" }
q259506
ReadHandler.selectCallback
test
public function selectCallback($ret) { if ($ret instanceof ErrorMessage) { return $ret; } $result = array(); foreach ($ret as $row) { $result[] = array_combine($this->fields, $row); } return $result; }
php
{ "resource": "" }
q259507
ReadHandler.select
test
public function select($compare, $keys, $limit = 1, $begin = 0) { $sk = $this->keys; if (is_array($keys)) { foreach ($sk as &$value) { if (!isset($keys[$value])) { break; } $value = $keys[$value]; } array_slice($sk, 0, count($keys)); } else { $sk = array($keys); } $this->io->select($this->indexId, $compare, $sk, $limit, $begin); $ret = $this->io->registerCallback(array($this, 'selectCallback')); if ($ret instanceof ErrorMessage) { throw $ret; } return $ret; }
php
{ "resource": "" }
q259508
XenforoPassword.splitHash
test
protected function splitHash($hash) { $parts = @unserialize($hash); if (!is_array($parts)) { $result = ['', '', '']; } else { $parts = array_merge(['hash' => '', 'hashFunc' => '', 'salt' => ''], $parts); if (!$parts['hashFunc']) { switch (strlen($parts['hash'])) { case 32: $parts['hashFunc'] = 'md5'; break; case 40: $parts['hashFunc'] = 'sha1'; break; } } $result = [$parts['hash'], $parts['hashFunc'], $parts['salt']]; } return $result; }
php
{ "resource": "" }
q259509
Db.create
test
public static function create($config) { $driver = val('driver', $config); if (!$driver) { throw new \Exception('You must specify a driver.', 500); } if (strpos($driver, '\\') === false) { $class = '\Garden\Db\\'.$driver; } else { // TODO: Check against a white list of db drivers. $class = $driver; } if (!class_exists($class)) { throw new \Exception("Class $class does not exist.", 500); } $db = new $class($config); return $db; }
php
{ "resource": "" }
q259510
Db.getTableDef
test
public function getTableDef($tablename) { $ltablename = strtolower($tablename); // Check to see if the table isn't in the cache first. if ($this->allTablesFetched & Db::FETCH_TABLENAMES && !isset($this->tables[$ltablename])) { return null; } if ( isset($this->tables[$ltablename]) && is_array($this->tables[$ltablename]) && isset($this->tables[$ltablename]['columns'], $this->tables[$ltablename]['indexes']) ) { return $this->tables[$ltablename]; } return []; }
php
{ "resource": "" }
q259511
Db.getAllTables
test
public function getAllTables($withDefs = false) { if ($withDefs && ($this->allTablesFetched & Db::FETCH_COLUMNS)) { return $this->tables; } elseif (!$withDefs && ($this->allTablesFetched & Db::FETCH_TABLENAMES)) { return array_keys($this->tables); } else { return null; } }
php
{ "resource": "" }
q259512
Db.fixIndexes
test
protected function fixIndexes($tablename, array &$tableDef, $curTableDef = null) { // Loop through the columns and add get the primary key index. $primaryColumns = []; foreach ($tableDef['columns'] as $cname => $cdef) { if (val('primary', $cdef)) { $primaryColumns[] = $cname; } } // Massage the primary key index. $primaryFound = false; array_touch('indexes', $tableDef, []); foreach ($tableDef['indexes'] as &$indexDef) { array_touch('name', $indexDef, $this->buildIndexName($tablename, $indexDef)); if (val('type', $indexDef) === Db::INDEX_PK) { $primaryFound = true; if (empty($primaryColumns)) { foreach ($indexDef['columns'] as $cname) { $tableDef['columns'][$cname]['primary'] = true; } } elseif (array_diff($primaryColumns, $indexDef['columns'])) { throw new \Exception("There is a mismatch in the primary key index and primary key columns.", 500); } } elseif (isset($curTableDef['indexes'])) { $curIndexDef = array_usearch($indexDef, $curTableDef['indexes'], [$this, 'indexCompare']); if ($curIndexDef && isset($curIndexDef['name'])) { $indexDef['name'] = $curIndexDef['name']; } } } if (!$primaryFound && !empty($primaryColumns)) { $tableDef['indexes'][db::INDEX_PK] = [ 'columns' => $primaryColumns, 'type' => Db::INDEX_PK ]; } }
php
{ "resource": "" }
q259513
Db.indexCompare
test
public function indexCompare(array $a, array $b) { if ($a['columns'] > $b['columns']) { return 1; } elseif ($a['columns'] < $b['columns']) { return -1; } return strcmp(val('type', $a, ''), val('type', $b, '')); }
php
{ "resource": "" }
q259514
Db.getOne
test
public function getOne($tablename, array $where, array $options = []) { $options['limit'] = 1; $rows = $this->get($tablename, $where, $options); return array_shift($rows); }
php
{ "resource": "" }
q259515
Db.buildIndexName
test
protected function buildIndexName($tablename, array $indexDef) { $type = val('type', $indexDef, Db::INDEX_IX); if ($type === Db::INDEX_PK) { return 'primary'; } $px = val($type, [Db::INDEX_IX => 'ix_', Db::INDEX_UNIQUE => 'ux_'], 'ix_'); $sx = val('suffix', $indexDef); $result = $px.$tablename.'_'.($sx ?: implode('', $indexDef['columns'])); return $result; }
php
{ "resource": "" }
q259516
SecureString.encode
test
public function encode($data, array $spec, $throw = false) { $str = json_encode($data, JSON_UNESCAPED_SLASHES); $first = true; foreach ($spec as $name => $password) { if ($name === self::STRICT) { // Strict is just an option so continue. continue; } $supported = $this->supportedInfo($name, $throw); if ($supported === null) { return null; } list($encode,, $method, $encodeFirst) = $supported; if ($first) { if ($encodeFirst) { $str = static::base64urlEncode($str); } $this->pushString($str, self::EOS); } switch ($encode) { case 'encrypt': $str = $this->encrypt($str, $method, $password, '', $throw); break; case 'hmac': $str = $this->hmac($str, $method, $password, 0, $throw); break; default: return $this->exception($throw, "Invalid method $encode.", 500); } // Return on error. if (!$str) { return null; } $this->pushString($str, $name); $first = false; } return $str; }
php
{ "resource": "" }
q259517
SecureString.generateRandomKey
test
public static function generateRandomKey($len = 32) { $bytes = ceil($len * 3 / 4); return substr(self::base64urlEncode(openssl_random_pseudo_bytes($bytes)), 0, $len); }
php
{ "resource": "" }
q259518
SecureString.supportedInfo
test
protected function supportedInfo($name, $throw = false) { switch ($name) { case 'aes128': case 'aes256': $cipher = 'aes-'.substr($name, 3).'-cbc'; return ['encrypt', 'decrypt', $cipher, false]; case 'hsha1': case 'hsha256': $hash = substr($name, 1); return ['hmac', 'verifyHmac', $hash, true]; } return $this->exception($throw, "Spec $name not supported.", 400); }
php
{ "resource": "" }
q259519
SecureString.hmac
test
protected function hmac($str, $method, $password, $timestamp = 0, $throw = false) { if ($timestamp === 0) { $timestamp = time(); } // Add the timestamp to the string. static::pushString($str, $timestamp); // Sign the string. $signature = hash_hmac($method, $str, $password, true); if ($signature === false) { return $this->exception($throw, "Invalid hash method $method.", 400); } // Add the signature to the string. static::pushString($str, static::base64urlEncode($signature)); return $str; }
php
{ "resource": "" }
q259520
SecureString.verifyHmac
test
protected function verifyHmac($str, $method, $password, $throw = false) { // Grab the signature from the string. $signature = $this->popString($str); if (!$signature) { return $this->exception($throw, "The signature is missing.", 403); } $signature = static::base64urlDecode($signature); // Recalculate the signature to compare. $calcSignature = hash_hmac($method, $str, $password, true); if (strlen($signature) !== strlen($calcSignature)) { return $this->exception($throw, "The signature is invalid.", 403); } // Do a double hmac comparison to prevent timing attacks. // https://www.isecpartners.com/blog/2011/february/double-hmac-verification.aspx $dblSignature = hash_hmac($method, $signature, $password, true); $dblCalcSignature = hash_hmac($method, $calcSignature, $password, true); if ($dblSignature !== $dblCalcSignature) { return $this->exception($throw, "The signature is invalid.", 403); } // Grab the timestamp and verify it. $timestamp = $this->popString($str); if (!$this->verifyTimestamp($timestamp, $throw)) { return null; } return $str; }
php
{ "resource": "" }
q259521
SecureString.verifyTimestamp
test
protected function verifyTimestamp($timestamp, $throw = false) { if (!is_numeric($timestamp)) { return (bool)$this->exception($throw, "Invalid timestamp.", 403); } $intTimestamp = (int)$timestamp; $now = time(); if ($intTimestamp + $this->timestampExpiry <= $now) { return (bool)$this->exception($throw, "The timestamp has expired.", 403); } return true; }
php
{ "resource": "" }
q259522
SecureString.popString
test
protected function popString(&$str) { if ($str === '') { return null; } $pos = strrpos($str, '.'); if ($pos !== false) { $result = substr($str, $pos + 1); $str = substr($str, 0, $pos); } else { $result = $str; $str = ''; } return $result; }
php
{ "resource": "" }
q259523
SecureString.pushString
test
protected function pushString(&$str, $item) { if ($str) { $str .= static::SEP; } $str .= implode(static::SEP, (array)$item); }
php
{ "resource": "" }
q259524
SecureString.twiddle
test
public function twiddle($string, $index, $value, $encode = false) { $parts = explode(static::SEP, $string); if ($encode) { $value = static::base64urlEncode($value); } $parts[$index] = $value; return implode(static::SEP, $parts); }
php
{ "resource": "" }
q259525
Validation.errorMessage
test
public static function errorMessage(array $error) { if (isset($error['message'])) { return $error['message']; } else { $field = val('field', $error, '*'); if (is_array($field)) { $field = implode(', ', $field); } return sprintft($error['code'].': %s.', $field); } }
php
{ "resource": "" }
q259526
Validation.addError
test
public function addError($messageCode, $field = '*', $options = []) { $error = []; if (substr($messageCode, 0, 1) === '@') { $error['message'] = substr($messageCode, 1); } else { $error['code'] = $messageCode; } if (is_array($field)) { $fieldname = array_select(['path', 'name'], $field); if ($fieldname) { // This is a full field object. $fieldKey = $fieldname; $error['field'] = $fieldKey; } else { $fieldKey = '*'; $error['field'] = $field; } } else { $fieldKey = $field; if ($field !== '*') { $error['field'] = $field; } } if (is_array($options)) { $error += $options; } else if (is_int($options)) { $error['status'] = $options; } $this->errors[$fieldKey][] = $error; return $this; }
php
{ "resource": "" }
q259527
Validation.mainMessage
test
public function mainMessage($value = null) { if ($value !== null) { $this->mainMessage = $value; return $this; } return $this->mainMessage; }
php
{ "resource": "" }
q259528
Validation.status
test
public function status($value = null) { if ($value !== null) { $this->status = $value; return $this; } if ($this->status) { return $this->status; } // There was no status so loop through the errors and look for the highest one. $maxStatus = 400; foreach ($this->errors as $field => $errors) { foreach ($errors as $error) { if (isset($error['status']) && $error['status'] > $maxStatus) { $maxStatus = $error['status']; } } } return $maxStatus; }
php
{ "resource": "" }
q259529
Validation.getMessage
test
public function getMessage() { if ($this->mainMessage) { return $this->mainMessage; } // Generate the message by concatenating all of the errors together. $messages = []; foreach ($this->errors as $errors) { foreach ($errors as $error) { $field = val('field', $error, '*'); if (is_array($field)) { $field = implode(', ', $field); } if (isset($error['message'])) { $message = $error['message']; } elseif (strpos($error['code'], '%s') === false) { $message = sprintft($error['code'].': %s.', $field); } else { $message = sprintft($error['code'], $field); } $messages[] = $message; } } return implode(' ', $messages); }
php
{ "resource": "" }
q259530
Validation.getErrorsFlat
test
public function getErrorsFlat() { $result = []; foreach ($this->errors as $errors) { foreach ($errors as $error) { $result[] = $error; } } return $result; }
php
{ "resource": "" }
q259531
Validation.fieldValid
test
public function fieldValid($field) { $result = !isset($this->errors[$field]) || count($this->errors[$field]) === 0; return $result; }
php
{ "resource": "" }
q259532
Schema.parseSchema
test
public static function parseSchema(array $arr) { $result = []; foreach ($arr as $key => $value) { if (is_int($key)) { if (is_string($value)) { // This is a short param value. $param = static::parseShortParam($value); $name = $param['name']; $result[$name] = $param; } else { throw new \InvalidArgumentException("Schema at position $key is not a valid param.", 500); } } else { // The parameter is defined in the key. $param = static::parseShortParam($key, $value); $name = $param['name']; if (is_array($value)) { // The value describes a bit more about the schema. switch ($param['type']) { case 'array': if (isset($value['items'])) { // The value includes array schema information. $param = array_replace($param, $value); } elseif (isset($value['type'])) { // The value is a long-form schema. $param['items'] = $value; } else { // The value is another shorthand schema. $param['items'] = [ 'type' => 'object', 'required' => true, 'properties' => static::parseSchema($value) ]; } break; case 'object': // The value is a schema of the object. if (isset($value['properties'])) { $param['properties'] = static::parseSchema($value['properties']); } else { $param['properties'] = static::parseSchema($value); } break; default: $param = array_replace($param, $value); break; } } elseif (is_string($value)) { if ($param['type'] === 'array') { // Check to see if the value is the item type in the array. if (isset(self::$types[$value])) { $arrType = self::$types[$value]; } elseif (($index = array_search($value, self::$types)) !== false) { $arrType = self::$types[$index]; } if (isset($arrType)) { $param['items'] = ['type' => $arrType, 'required' => true]; } else { $param['description'] = $value; } } else { // The value is the schema description. $param['description'] = $value; } } $result[$name] = $param; } } return $result; }
php
{ "resource": "" }
q259533
Schema.requireOneOf
test
public function requireOneOf(array $fieldnames, $count = 1) { $result = $this->addValidator('*', function ($data, Validation $validation) use ($fieldnames, $count) { $hasCount = 0; $flattened = []; foreach ($fieldnames as $name) { $flattened = array_merge($flattened, (array)$name); if (is_array($name)) { // This is an array of required names. They all must match. $hasCountInner = 0; foreach ($name as $nameInner) { if (isset($data[$nameInner]) && $data[$nameInner]) { $hasCountInner++; } else { break; } } if ($hasCountInner >= count($name)) { $hasCount++; } } elseif (isset($data[$name]) && $data[$name]) { $hasCount++; } if ($hasCount >= $count) { return true; } } $messageFields = array_map(function ($v) { if (is_array($v)) { return '('.implode(', ', $v).')'; } return $v; }, $fieldnames); if ($count === 1) { $message = sprintft('One of %s are required.', implode(', ', $messageFields)); } else { $message = sprintft('%1$s of %2$s are required.', $count, implode(', ', $messageFields)); } $validation->addError('missing_field', $flattened, [ 'message' => $message ]); return false; }); return $result; }
php
{ "resource": "" }
q259534
Schema.validate
test
public function validate(array &$data, Validation &$validation = null) { if (!$this->isValidInternal($data, $this->schema, $validation, '')) { if ($validation === null) { // Although this should never be null, scrutinizer complains that it might be. $validation = new Validation(); } throw new ValidationException($validation); } return $this; }
php
{ "resource": "" }
q259535
Schema.validateField
test
protected function validateField(&$value, array $field, Validation $validation) { $path = array_select(['path', 'name'], $field); $type = val('type', $field, ''); $valid = true; // Check required first. // A value that isn't passed should fail the required test, but short circuit the other ones. $validRequired = $this->validateRequired($value, $field, $validation); if ($validRequired !== null) { return $validRequired; } // Validate the field's type. $validType = true; switch ($type) { case 'boolean': $validType &= $this->validateBoolean($value, $field, $validation); break; case 'integer': $validType &= $this->validateInteger($value, $field, $validation); break; case 'float': $validType &= $this->validateFloat($value, $field, $validation); break; case 'string': $validType &= $this->validateString($value, $field, $validation); break; case 'timestamp': $validType &= $this->validateTimestamp($value, $field, $validation); break; case 'datetime': $validType &= $this->validateDatetime($value, $field, $validation); break; case 'base64': $validType &= $this->validateBase64($value, $field, $validation); break; case 'array': $validType &= $this->validateArray($value, $field, $validation); break; case 'object': $validType &= $this->validateObject($value, $field, $validation); break; case '': // No type was specified so we are valid. $validType = true; break; default: throw new \InvalidArgumentException("Unrecognized type $type.", 500); } if (!$validType) { $valid = false; $validation->addError( 'invalid_type', $path, [ 'type' => $type, 'message' => sprintft('%1$s is not a valid %2$s.', $path, $type), 'status' => 422 ] ); } // Validate a custom field validator. $validatorName = val('validatorName', $field, $path); if (isset($this->validators[$validatorName])) { foreach ($this->validators[$validatorName] as $callback) { call_user_func_array($callback, [&$value, $field, $validation]); } } return $valid; }
php
{ "resource": "" }
q259536
Schema.validateArray
test
protected function validateArray(&$value, array $field, Validation $validation) { $validType = true; if (!is_array($value) || (count($value) > 0 && !array_key_exists(0, $value))) { $validType = false; } else { // Cast the items into a proper numeric array. $value = array_values($value); if (isset($field['items'])) { // Validate each of the types. $path = array_select(['path', 'name'], $field); $itemField = $field['items']; $itemField['validatorName'] = array_select(['validatorName', 'path', 'name'], $field).'.items'; foreach ($value as $i => &$item) { $itemField['path'] = "$path.$i"; $this->validateField($item, $itemField, $validation); } } } return $validType; }
php
{ "resource": "" }
q259537
Schema.validateBase64
test
protected function validateBase64(&$value, array $field, Validation $validation) { if (!is_string($value)) { $validType = false; } else { if (!preg_match('`^[a-zA-Z0-9/+]*={0,2}$`', $value)) { $validType = false; } else { $decoded = @base64_decode($value); if ($decoded === false) { $validType = false; } else { $value = $decoded; $validType = true; } } } return $validType; }
php
{ "resource": "" }
q259538
Schema.validateBoolean
test
protected function validateBoolean(&$value, array $field, Validation $validation) { if (is_bool($value)) { $validType = true; } else { $bools = [ '0' => false, 'false' => false, 'no' => false, 'off' => false, '1' => true, 'true' => true, 'yes' => true, 'on' => true ]; if ((is_string($value) || is_numeric($value)) && isset($bools[$value])) { $value = $bools[$value]; $validType = true; } else { $validType = false; } } return $validType; }
php
{ "resource": "" }
q259539
Schema.validateDatetime
test
protected function validateDatetime(&$value, array $field, Validation $validation) { $validType = true; if ($value instanceof \DateTime) { $validType = true; } elseif (is_string($value)) { try { $dt = new \DateTime($value); if ($dt) { $value = $dt; } else { $validType = false; } } catch (\Exception $ex) { $validType = false; } } elseif (is_numeric($value) && $value > 0) { $value = new \DateTime('@'.(string)round($value)); $validType = true; } else { $validType = false; } return $validType; }
php
{ "resource": "" }
q259540
Schema.validateFloat
test
protected function validateFloat(&$value, array $field, Validation $validation) { if (is_float($value)) { $validType = true; } elseif (is_numeric($value)) { $value = (float)$value; $validType = true; } else { $validType = false; } return $validType; }
php
{ "resource": "" }
q259541
Schema.validateInteger
test
protected function validateInteger(&$value, array $field, Validation $validation) { if (is_int($value)) { $validType = true; } elseif (is_numeric($value)) { $value = (int)$value; $validType = true; } else { $validType = false; } return $validType; }
php
{ "resource": "" }
q259542
Schema.validateObject
test
protected function validateObject(&$value, array $field, Validation $validation) { if (!is_array($value) || isset($value[0])) { return false; } elseif (isset($field['properties'])) { $path = array_select(['path', 'name'], $field); // Validate the data against the internal schema. $this->isValidInternal($value, $field['properties'], $validation, $path.'.'); } return true; }
php
{ "resource": "" }
q259543
Schema.validateRequired
test
protected function validateRequired(&$value, array $field, Validation $validation) { $required = val('required', $field, false); $type = $field['type']; if ($value === '' || $value === null) { if (!$required) { $value = null; return true; } switch ($type) { case 'boolean': $value = false; return true; case 'string': if (val('minLength', $field, 1) == 0) { $value = ''; return true; } } $validation->addError('missing_field', $field); return false; } return null; }
php
{ "resource": "" }
q259544
Schema.validateString
test
protected function validateString(&$value, array $field, Validation $validation) { if (is_string($value)) { $validType = true; } elseif (is_numeric($value)) { $value = (string)$value; $validType = true; } else { $validType = false; } return $validType; }
php
{ "resource": "" }
q259545
Schema.validateTimestamp
test
protected function validateTimestamp(&$value, array $field, Validation $validation) { $validType = true; if (is_numeric($value)) { $value = (int)$value; } elseif (is_string($value) && $ts = strtotime($value)) { $value = $ts; } else { $validType = false; } return $validType; }
php
{ "resource": "" }
q259546
Addons.all
test
public static function all($addon_key = null, $key = null) { if (self::$all === null) { self::$all = static::cacheGet('addons-all', array(get_class(), 'scanAddons')); } // The array should be built now return the addon. if ($addon_key === null) { return self::$all; } else { $addon = val(strtolower($addon_key), self::$all); if ($addon && $key) { return val($key, $addon); } elseif ($addon) { return $addon; } else { return null; } } }
php
{ "resource": "" }
q259547
Addons.bootstrap
test
public static function bootstrap($enabled_addons = null) { // Load the addons from the config if they aren't passed in. if (!is_array($enabled_addons)) { $enabled_addons = config('addons', array()); } // Reformat the enabled array into the form: array('addon_key' => 'addon_key') $enabled_keys = array_keys(array_change_key_case(array_filter($enabled_addons))); $enabled_keys = array_combine($enabled_keys, $enabled_keys); self::$enabledKeys = $enabled_keys; self::$classMap = null; // invalidate so it will rebuild // Enable the addon autoloader. spl_autoload_register(array(get_class(), 'autoload'), true, true); // Bind all of the addon plugin events now. foreach (self::enabled() as $addon) { if (!isset($addon[self::K_CLASSES])) { continue; } foreach ($addon[self::K_CLASSES] as $class_name => $class_path) { if (str_ends($class_name, 'plugin')) { Event::bindClass($class_name); } elseif (str_ends($class_name, 'hooks')) { // Vanilla 2 used hooks files for themes and applications. $basename = ucfirst(rtrim_substr($class_name, 'hooks')); deprecated($basename.'Hooks', $basename.'Plugin'); Event::bindClass($class_name); } } } Event::bind('bootstrap', function () { // Start each of the enabled addons. foreach (self::enabled() as $key => $value) { static::startAddon($key); } }); }
php
{ "resource": "" }
q259548
Addons.cacheGet
test
protected static function cacheGet($key, callable $cache_cb) { // Salt the cache with the root path so that it will invalidate if the app is moved. $salt = substr(md5(static::baseDir()), 0, 10); $cache_path = PATH_ROOT."/cache/$key-$salt.json.php"; if (file_exists($cache_path)) { $result = array_load($cache_path); return $result; } else { $result = $cache_cb(); array_save($result, $cache_path); } return $result; }
php
{ "resource": "" }
q259549
Addons.classMap
test
public static function classMap($classname = null) { if (self::$classMap === null) { // Loop through the enabled addons and grab their classes. $class_map = array(); foreach (static::enabled() as $addon) { if (isset($addon[self::K_CLASSES])) { $class_map = array_replace($class_map, $addon[self::K_CLASSES]); } } self::$classMap = $class_map; } // Now that the class map has been built return the result. if ($classname !== null) { if (strpos($classname, '\\') === false) { $basename = strtolower($classname); } else { $basename = strtolower(trim(strrchr($classname, '\\'), '\\')); } $row = val($basename, self::$classMap); if ($row === null) { return ['', '']; } elseif (is_string($row)) { return [$classname, $row]; } elseif (is_array($row)) { return $row; } else { return ['', '']; } } else { return self::$classMap; } }
php
{ "resource": "" }
q259550
Addons.enabled
test
public static function enabled($addon_key = null, $key = null) { // Lazy build the enabled array. if (self::$enabled === null) { // Make sure the enabled addons have been added first. if (self::$enabledKeys === null) { throw new \Exception("Addons::boostrap() must be called before Addons::enabled() can be called.", 500); } if (self::$all !== null || self::$sharedEnvironment) { // Build the enabled array by filtering the all array. self::$enabled = array(); foreach (self::all() as $key => $row) { if (isset($key, self::$enabledKeys)) { self::$enabled[$key] = $row; } } } else { // Build the enabled array by walking the addons. self::$enabled = static::cacheGet('addons-enabled', function () { return static::scanAddons(null, self::$enabledKeys); }); } } // The array should be built now return the addon. if ($addon_key === null) { return self::$enabled; } else { $addon = val(strtolower($addon_key), self::$enabled); if ($addon && $key) { return val($key, $addon); } elseif ($addon) { return $addon; } else { return null; } } }
php
{ "resource": "" }
q259551
Addons.info
test
public static function info($addon_key) { $addon_key = strtolower($addon_key); // Check the enabled array first so that we don't load all addons if we don't have to. if (isset(self::$enabledKeys[$addon_key])) { return static::enabled($addon_key, self::K_INFO); } else { return static::all($addon_key, self::K_INFO); } }
php
{ "resource": "" }
q259552
Addons.scanAddonRecursive
test
protected static function scanAddonRecursive($dir, &$addons, $enabled = null) { $dir = rtrim($dir, '/'); $addonKey = strtolower(basename($dir)); // Scan the addon if it is enabled. if ($enabled === null || in_array($addonKey, $enabled)) { list($addonKey, $addon) = static::scanAddon($dir); } else { $addon = null; } // Add the addon to the collection array if one was supplied. if ($addon !== null) { $addons[$addonKey] = $addon; } // Recurse. $addon_subdirs = array('/addons'); foreach ($addon_subdirs as $addon_subdir) { if (is_dir($dir.$addon_subdir)) { static::scanAddons($dir.$addon_subdir, $enabled, $addons); } } return array($addonKey, $addon); }
php
{ "resource": "" }
q259553
Addons.scanAddon
test
protected static function scanAddon($dir) { $dir = rtrim($dir, '/'); $addon_key = strtolower(basename($dir)); // Look for the addon info array. $info_path = $dir.'/addon.json'; $info = false; if (file_exists($info_path)) { $info = json_decode(file_get_contents($info_path), true); } if (!$info) { $info = array(); } array_touch('name', $info, $addon_key); array_touch('version', $info, '0.0'); // Look for the bootstrap. $bootstrap = $dir.'/bootstrap.php'; if (!file_exists($dir.'/bootstrap.php')) { $bootstrap = null; } // Scan the appropriate subdirectories for classes. $subdirs = array('', '/library', '/controllers', '/models', '/modules', '/settings'); $classes = array(); foreach ($subdirs as $subdir) { // Get all of the php files in the subdirectory. $paths = glob($dir.$subdir.'/*.php'); foreach ($paths as $path) { $decls = static::scanFile($path); foreach ($decls as $namespace_row) { if (isset($namespace_row['namespace']) && $namespace_row) { $namespace = rtrim($namespace_row['namespace'], '\\').'\\'; $namespace_classes = $namespace_row['classes']; } else { $namespace = ''; $namespace_classes = $namespace_row; } foreach ($namespace_classes as $class_row) { $classes[strtolower($class_row['name'])] = [$namespace.$class_row['name'], $path]; } } } } $addon = array( self::K_BOOTSTRAP => $bootstrap, self::K_CLASSES => $classes, self::K_DIR => $dir, self::K_INFO => $info ); return array($addon_key, $addon); }
php
{ "resource": "" }
q259554
Addons.scanAddons
test
protected static function scanAddons($dir = null, $enabled = null, &$addons = null) { if (!$dir) { $dir = static::$baseDir; } if ($addons === null) { $addons = array(); } /* @var \DirectoryIterator */ foreach (new \DirectoryIterator($dir) as $subdir) { if ($subdir->isDir() && !$subdir->isDot()) { // echo $subdir->getPathname().$subdir->isDir().$subdir->isDot().'<br />'; static::scanAddonRecursive($subdir->getPathname(), $addons, $enabled); } } return $addons; }
php
{ "resource": "" }
q259555
Addons.startAddon
test
public static function startAddon($addon_key) { $addon = static::enabled($addon_key); if (!$addon) { return false; } // Run the class' bootstrap. if ($bootstrap_path = val(self::K_BOOTSTRAP, $addon)) { include_once $bootstrap_path; } return true; }
php
{ "resource": "" }
q259556
ClientException.getHeaders
test
public function getHeaders() { $result = []; foreach ($this->context as $key => $value) { if (stripos($key, 'http_') === 0) { $key = Response::normalizeHeader(ltrim_substr($key, 'http_')); $result[$key] = $value; } } return $result; }
php
{ "resource": "" }
q259557
Event.callUserFuncArray
test
public static function callUserFuncArray($callback, $args = []) { // Figure out the event name from the callback. $event_name = static::getEventname($callback); if (!$event_name) { return call_user_func_array($callback, $args); } // The events could have different args because the event handler can take the object as the first parameter. $event_args = $args; // If the callback is an object then it gets passed as the first argument. if (is_array($callback) && is_object($callback[0])) { array_unshift($event_args, $callback[0]); } // Fire before events. self::fireArray($event_name.'_before', $event_args); // Call the function. if (static::hasHandler($event_name)) { // The callback was overridden so fire it. $result = static::fireArray($event_name, $event_args); } else { // The callback was not overridden so just call the passed callback. $result = call_user_func_array($callback, $args); } // Fire after events. self::fireArray($event_name.'_after', $event_args); return $result; }
php
{ "resource": "" }
q259558
Event.bind
test
public static function bind($event, $callback, $priority = Event::PRIORITY_NORMAL) { $event = strtolower($event); self::$handlers[$event][$priority][] = $callback; self::$toSort[$event] = true; }
php
{ "resource": "" }
q259559
Event.bindClass
test
public static function bindClass($class, $priority = Event::PRIORITY_NORMAL) { $method_names = get_class_methods($class); // Grab an instance of the class so there is something to bind to. if (is_string($class)) { if (method_exists($class, 'instance')) { // TODO: Make the instance lazy load. $instance = call_user_func(array($class, 'instance')); } else { throw new \InvalidArgumentException('Event::bindClass(): The class for argument #1 must have an instance() method or be passed as an object.', 422); } } else { $instance = $class; } foreach ($method_names as $method_name) { if (strpos($method_name, '_') === false) { continue; } $parts = explode('_', strtolower($method_name)); switch (end($parts)) { case 'handler': case 'create': case 'override': array_pop($parts); $event_name = implode('_', $parts); break; case 'before': case 'after': default: $event_name = implode('_', $parts); break; } // Bind the event if we have one. if ($event_name) { static::bind($event_name, array($instance, $method_name), $priority); } } }
php
{ "resource": "" }
q259560
Event.dumpHandlers
test
public static function dumpHandlers() { $result = []; foreach (self::$handlers as $event_name => $nested) { $handlers = call_user_func_array('array_merge', static::getHandlers($event_name)); $result[$event_name] = array_map('format_callback', $handlers); } return $result; }
php
{ "resource": "" }
q259561
Event.fire
test
public static function fire($event) { $handlers = self::getHandlers($event); if (!$handlers) { return null; } // Grab the handlers and call them. $args = array_slice(func_get_args(), 1); $result = null; foreach ($handlers as $callbacks) { foreach ($callbacks as $callback) { $result = call_user_func_array($callback, $args); } } return $result; }
php
{ "resource": "" }
q259562
Event.fireArray
test
public static function fireArray($event, $args = []) { $handlers = self::getHandlers($event); if (!$handlers) { return null; } // Grab the handlers and call them. $result = null; foreach ($handlers as $callbacks) { foreach ($callbacks as $callback) { $result = call_user_func_array($callback, $args); } } return $result; }
php
{ "resource": "" }
q259563
Event.fireFilter
test
public static function fireFilter($event, $value) { $handlers = self::getHandlers($event); if (!$handlers) { return $value; } $args = array_slice(func_get_args(), 1); foreach ($handlers as $callbacks) { foreach ($callbacks as $callback) { $value = call_user_func_array($callback, $args); $args[0] = $value; } } return $value; }
php
{ "resource": "" }
q259564
Event.functionExists
test
public static function functionExists($function_name, $only_events = false) { if (!$only_events && function_exists($function_name)) { return true; } else { return static::hasHandler($function_name); } }
php
{ "resource": "" }
q259565
Event.getEventname
test
protected static function getEventname($callback) { if (is_string($callback)) { return strtolower($callback); } elseif (is_array($callback)) { if (is_string($callback[0])) { $classname = $callback[0]; } else { $classname = get_class($callback[0]); } $eventclass = trim(strrchr($classname, '\\'), '\\'); if (!$eventclass) { $eventclass = $classname; } return strtolower($eventclass.'_'.$callback[1]); } return ''; }
php
{ "resource": "" }
q259566
Event.getHandlers
test
public static function getHandlers($name) { $name = strtolower($name); if (!isset(self::$handlers[$name])) { return []; } // See if the handlers need to be sorted. if (isset(self::$toSort[$name])) { ksort(self::$handlers[$name]); unset(self::$toSort[$name]); } return self::$handlers[$name]; }
php
{ "resource": "" }
q259567
Event.hasHandler
test
public static function hasHandler($event) { $event = strtolower($event); return array_key_exists($event, self::$handlers) && !empty(self::$handlers[$event]); }
php
{ "resource": "" }
q259568
Event.methodExists
test
public static function methodExists($object, $method_name, $only_events = false) { if (!$only_events && method_exists($object, $method_name)) { return true; } else { // Check to see if there is an event bound to the method. $event_name = self::getEventname([$object, $method_name]); return static::hasHandler($event_name); } }
php
{ "resource": "" }
q259569
Literal.getValue
test
public function getValue($driver = 'default') { $driver = $this->normalizeKey($driver); if (isset($this->driverValues[$driver])) { return $this->driverValues[$driver]; } elseif (isset($this->driverValues['default'])) { return $this->driverValues['default']; } else { return 'null'; } }
php
{ "resource": "" }
q259570
Literal.setValue
test
public function setValue($value, $driver = 'default') { $driver = $this->normalizeKey($driver); $this->driverValues[$driver] = $value; return $this; }
php
{ "resource": "" }
q259571
VbulletinPassword.splitSalt
test
public function splitSalt($hash) { // The hash is in the form: <32 char hash><salt>. $salt_length = strlen($hash) - 32; $salt = trim(substr($hash, -$salt_length, $salt_length)); $stored_hash = substr($hash, 0, strlen($hash) - $salt_length); return [$stored_hash, $salt]; }
php
{ "resource": "" }
q259572
Config.defaultPath
test
public static function defaultPath($value = '') { if ($value) { self::$defaultPath = $value; } elseif (!self::$defaultPath) { self::$defaultPath = PATH_ROOT.'/conf/config.json.php'; } return self::$defaultPath; }
php
{ "resource": "" }
q259573
Config.get
test
public static function get($key, $default = null) { if (array_key_exists($key, self::$data)) { return self::$data[$key]; } else { return $default; } }
php
{ "resource": "" }
q259574
Config.load
test
public static function load($path = '', $underlay = false, $php_var = 'config') { if (!$path) { $path = self::$defaultPath; } $loaded = array_load($path, $php_var); if (empty($loaded)) { return; } if (!is_array(self::$data)) { self::$data = []; } if ($underlay) { self::$data = array_replace($loaded, self::$data); } else { self::$data = array_replace(self::$data, $loaded); } }
php
{ "resource": "" }
q259575
Config.save
test
public static function save($data, $path = null, $php_var = 'config') { if (!is_array($data)) { throw new \InvalidArgumentException('Config::save(): Argument #1 is not an array.', 400); } if (!$path) { $path = static::defaultPath(); } // Load the current config information so we know what to replace. $config = array_load($path, $php_var); // Merge the new config into the current config. $config = array_replace($config, $data); // Remove null config values. $config = array_filter($config, function ($value) { return $value !== null; }); ksort($config, SORT_NATURAL | SORT_FLAG_CASE); $result = array_save($config, $path, $php_var); return $result; }
php
{ "resource": "" }
q259576
Application.matchRoutes
test
public function matchRoutes(Request $request) { $result = array(); foreach ($this->routes as $route) { $matches = $route->matches($request, $this); if ($matches) { $result[] = array($route, $matches); } } return $result; }
php
{ "resource": "" }
q259577
Application.route
test
public function route($pathOrRoute, $callback = null) { if (is_object($pathOrRoute) && $pathOrRoute instanceof Route) { $route = $pathOrRoute; } elseif (is_string($pathOrRoute) && $callback !== null) { $route = Route::create($pathOrRoute, $callback); } else { throw new \InvalidArgumentException("Argument #1 must be either a Garden\\Route or a string.", 500); } $this->routes[] = $route; return $route; }
php
{ "resource": "" }
q259578
Application.finalize
test
protected function finalize($result) { $response = Response::create($result); $response->meta(['request' => $this->request], true); $response->contentTypeFromAccept($this->request->getEnv('HTTP_ACCEPT')); $response->contentAsset($this->request->getEnv('HTTP_X_ASSET')); $contentType = $response->contentType(); if ($this->request->getMethod() === Request::METHOD_HEAD) { $response->flushHeaders(); return null; } // Check for known response types. switch ($contentType) { case 'application/internal': if ($result instanceof \Exception) { throw $result; } if ($response->contentAsset() === 'response') { return $response; } else { return $response->jsonSerialize(); } // No break because everything returns. case 'application/json': $response->flushHeaders(); echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); break; default: $data = $response->data(); if (is_string($data)) { $response->flushHeaders(); echo $data; } else { $response->status(415); $response->flushHeaders(); echo "Unsupported response type: $contentType"; } break; } return null; }
php
{ "resource": "" }
q259579
ResourceRoute.actionExists
test
protected function actionExists($object, $action, $method = '', $special = false) { if ($special && in_array($action, self::$specialActions)) { return ''; } // Short circuit on a badly named action. if (!$this->isIdentifier($action)) { return ''; } if ($method && $method !== $action) { $calledAction = $method.$action; if (Event::methodExists($object, $calledAction)) { return $calledAction; } } $calledAction = $action; if (Event::methodExists($object, $calledAction)) { return $calledAction; } return ''; }
php
{ "resource": "" }
q259580
ResourceRoute.allowedMethods
test
protected function allowedMethods($object, $action) { $allMethods = [ Request::METHOD_GET, Request::METHOD_POST, Request::METHOD_DELETE, Request::METHOD_PATCH, Request::METHOD_PUT, Request::METHOD_HEAD, Request::METHOD_OPTIONS ]; // Special actions should not be considered. if (in_array($action, self::$specialActions)) { return []; } if (Event::methodExists($object, $action)) { // The controller has the named action and thus supports all methods. return $allMethods; } // Loop through all the methods and check to see if they exist in the form $method.$action. $allowed = []; foreach ($allMethods as $method) { if (Event::methodExists($object, $method.$action)) { $allowed[] = $method; } } return $allowed; }
php
{ "resource": "" }
q259581
ResourceRoute.matches
test
public function matches(Request $request, Application $app) { if (!$this->matchesMethods($request)) { return null; } if ($this->getMatchFullPath()) { $path = $request->getFullPath(); } else { $path = $request->getPath(); } // If this route is off of a root then check that first. if ($root = $this->pattern()) { if (stripos($path, $root) === 0) { // Strip the root off the path that we are examining. $path = substr($path, strlen($root)); } else { return null; } } $pathParts = explode('/', trim($path, '/')); $controller = array_shift($pathParts); if (!$controller) { return null; } // Check to see if a class exists with the desired controller name. // If a controller is found then it is responsible for the route, regardless of any other parameters. $basename = sprintf($this->controllerPattern, ucfirst($controller)); if (class_exists('\Garden\Addons', false)) { list($classname) = Addons::classMap($basename); // TODO: Optimize this second check. if (!$classname && class_exists($basename)) { $classname = $basename; } } elseif (class_exists($basename)) { $classname = $basename; } else { $classname = ''; } if (!$classname) { return null; } $result = array( 'controller' => $classname, 'method' => $request->getMethod(), 'path' => $path, 'pathArgs' => $pathParts, 'query' => $request->getQuery() ); return $result; }
php
{ "resource": "" }
q259582
ResourceRoute.failsCondition
test
protected function failsCondition($name, $value) { $name = strtolower($name); if (isset($this->conditions[$name])) { $regex = $this->conditions[$name]; return !preg_match("`^$regex$`", $value); } if (isset(self::$globalConditions[$name])) { $regex = self::$globalConditions[$name]; return !preg_match("`^$regex$`", $value); } return null; }
php
{ "resource": "" }
q259583
Response.current
test
public static function current(Response $response = null) { if ($response !== null) { self::$current = $response; } elseif (self::$current === null) { self::$current = new Response(); } return self::$current; }
php
{ "resource": "" }
q259584
Response.create
test
public static function create($result) { if ($result instanceof Response) { return $result; } elseif ($result instanceof Exception\ResponseException) { /* @var Exception\ResponseException $result */ return $result->getResponse(); } $response = new Response(); if ($result instanceof Exception\ClientException) { /* @var Exception\ClientException $cex */ $cex = $result; $response->status($cex->getCode()); $response->headers($cex->getHeaders()); $response->data($cex->jsonSerialize()); } elseif ($result instanceof \Exception) { /* @var \Exception $ex */ $ex = $result; $response->status($ex->getCode()); $response->data([ 'exception' => $ex->getMessage(), 'code' => $ex->getCode() ]); } elseif (is_array($result)) { if (count($result) === 3 && isset($result[0], $result[1], $result[2])) { // This is a rack style response in the form [code, headers, body]. $response->status($result[0]); $response->headers($result[1]); $response->data($result[2]); } elseif (array_key_exists('response', $result)) { $resultResponse = $result['response']; if (!$resultResponse) { $response->data($result['body']); } else { // This is a dispatched response. $response = static::create($resultResponse); } // Set the rest of the result to the response context. unset($result['response']); $response->meta($result, true); } else { $response->data($result); } } else { $response->status(422); $response->data([ 'exception' => "Unknown result type for response.", 'code' => $response->status() ]); } return $response; }
php
{ "resource": "" }
q259585
Response.contentType
test
public function contentType($value = null) { if ($value === null) { return $this->headers('Content-Type'); } return $this->headers('Content-Type', $value); }
php
{ "resource": "" }
q259586
Response.contentAsset
test
public function contentAsset($asset = null) { if ($asset !== null) { $this->contentAsset = $asset; return $this; } return $this->contentAsset; }
php
{ "resource": "" }
q259587
Response.contentTypeFromAccept
test
public function contentTypeFromAccept($accept) { if (!empty($this->headers['Content-Type'])) { return; } $accept = strtolower($accept); if (strpos($accept, ',') === false) { list($contentType) = explode(';', $accept); } elseif (strpos($accept, 'text/html') !== false) { $contentType = 'text/html'; } elseif (strpos($accept, 'application/rss+xml' !== false)) { $contentType = 'application/rss+xml'; } elseif (strpos($accept, 'text/plain')) { $contentType = 'text/plain'; } else { $contentType = 'text/html'; } $this->contentType($contentType); return $this; }
php
{ "resource": "" }
q259588
Response.statusMessage
test
public static function statusMessage($statusCode, $header = false) { $message = val($statusCode, self::$messages, 'Unknown'); if ($header) { return "HTTP/1.1 $statusCode $message"; } else { return $message; } }
php
{ "resource": "" }
q259589
Response.cookies
test
public function cookies($name, $value = false, $expires = 0, $path = null, $domain = null, $secure = false, $httponly = false) { if ($value === false) { return val($name, $this->cookies); } $this->cookies[$name] = [$value, $expires, $path, $domain, $secure, $httponly]; return $this; }
php
{ "resource": "" }
q259590
Response.globalCookies
test
public static function globalCookies($name = null, $value = false, $expires = 0, $path = null, $domain = null, $secure = false, $httponly = false) { if (self::$globalCookies === null) { self::$globalCookies = []; } if ($name === null) { return self::$globalCookies; } if ($value === false) { return val($name, self::$globalCookies); } self::$globalCookies[$name] = [$value, $expires, $path, $domain, $secure, $httponly]; return null; }
php
{ "resource": "" }
q259591
Response.meta
test
public function meta($meta = null, $merge = false) { if ($meta !== null) { if ($merge) { $this->meta = array_merge($this->meta, $meta); } else { $this->meta = $meta; } return $this; } else { return $this->meta; } }
php
{ "resource": "" }
q259592
Response.data
test
public function data($data = null, $merge = false) { if ($data !== null) { if ($merge) { $this->data = array_merge($this->data, $data); } else { $this->data = $data; } return $this; } else { return $this->data; } }
php
{ "resource": "" }
q259593
Response.headers
test
public function headers($name, $value = null, $replace = true) { $headers = static::splitHeaders($name, $value); if (is_string($headers)) { return val($headers, $this->headers); } foreach ($headers as $name => $value) { if ($replace || !isset($this->headers[$name])) { $this->headers[$name] = $value; } else { $this->headers[$name] = array_merge((array)$this->headers, [$value]); } } return $this; }
php
{ "resource": "" }
q259594
Response.globalHeaders
test
public static function globalHeaders($name = null, $value = null, $replace = true) { if (self::$globalHeaders === null) { self::$globalHeaders = [ 'P3P' => 'CP="CAO PSA OUR"' ]; } if ($name === null) { return self::$globalHeaders; } $headers = static::splitHeaders($name, $value); if (is_string($headers)) { return val($headers, self::$globalHeaders); } foreach ($headers as $name => $value) { if ($replace || !isset(self::$globalHeaders[$name])) { self::$globalHeaders[$name] = $value; } else { self::$globalHeaders[$name] = array_merge((array)self::$globalHeaders, [$value]); } } return null; }
php
{ "resource": "" }
q259595
Response.normalizeHeader
test
public static function normalizeHeader($name) { static $special = [ 'etag' => 'ETag', 'p3p' => 'P3P', 'www-authenticate' => 'WWW-Authenticate', 'x-ua-compatible' => 'X-UA-Compatible' ]; $name = str_replace(['-', '_'], ' ', strtolower($name)); if (isset($special[$name])) { $name = $special[$name]; } else { $name = str_replace(' ', '-', ucwords($name)); } return $name; }
php
{ "resource": "" }
q259596
Response.flushHeaders
test
public function flushHeaders($global = true) { if (headers_sent()) { return; } if ($global) { $cookies = array_replace(static::globalCookies(), $this->cookies); $headers = array_replace(static::globalHeaders(), $this->headers); } else { $cookies = $this->cookies; $headers = $this->headers; } // Set the cookies first. foreach ($cookies as $name => $value) { setcookie( $name, $value[0], $value[1], $value[2] !== null ? $value[2] : $this->defaultCookiePath, $value[3] !== null ? $value[3] : $this->defaultCookieDomain, $value[4], $value[5] ); } // Set the response code. header(static::statusMessage($this->status, true), true, $this->status); $headers = array_filter($headers); // The content type is a special case. if (isset($headers['Content-Type'])) { $contentType = (array)$headers['Content-Type']; header('Content-Type: '.reset($contentType).'; charset=utf8', true); unset($headers['Content-Type']); } // Flush the rest of the headers. foreach ($headers as $name => $value) { foreach ((array)$value as $hvalue) { header("$name: $hvalue", false); } } }
php
{ "resource": "" }
q259597
SqliteDb.alterTableMigrate
test
protected function alterTableMigrate($tablename, array $alterDef, array $options = []) { $currentDef = $this->getTableDef($tablename); // Merge the table definitions if we aren't dropping stuff. if (!val(Db::OPTION_DROP, $options)) { $tableDef = $this->mergeTableDefs($currentDef, $alterDef); } else { $tableDef = $alterDef['def']; } // Drop all of the indexes on the current table. foreach (val('indexes', $currentDef, []) as $indexDef) { if (val('type', $indexDef, Db::INDEX_IX) === Db::INDEX_IX) { $this->dropIndex($indexDef['name']); } } $tmpTablename = $tablename.'_'.time(); // Rename the current table. $this->renameTable($tablename, $tmpTablename); // Create the new table. $this->createTable($tablename, $tableDef, $options); // Figure out the columns that we can insert. $columns = array_keys(array_intersect_key($tableDef['columns'], $currentDef['columns'])); // Build the insert/select statement. $sql = 'insert into '.$this->backtick($this->px.$tablename)."\n". $this->bracketList($columns, '`')."\n". $this->buildSelect($tmpTablename, [], ['columns' => $columns]); $this->query($sql, Db::QUERY_WRITE); // Drop the temp table. $this->dropTable($tmpTablename); }
php
{ "resource": "" }
q259598
SqliteDb.renameTable
test
protected function renameTable($oldname, $newname) { $renameSql = 'alter table '. $this->backtick($this->px.$oldname). ' rename to '. $this->backtick($this->px.$newname); $this->query($renameSql, Db::QUERY_WRITE); }
php
{ "resource": "" }
q259599
SqliteDb.dropIndex
test
protected function dropIndex($indexName) { $sql = 'drop index if exists '. $this->backtick($indexName); $this->query($sql, Db::QUERY_DEFINE); }
php
{ "resource": "" }