_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q7200
UserCredentialSmsTokenLoginService.authenticate
train
public function authenticate() { $currentStage = $this->_multiFactorStages['current']; //set stage as inactive if ($currentStage == 1) { $this->_multiFactorStages[1]['statuss'] = parent::authenticate(); //stage one sucessfull, bootstrap stage 2 if ($this->_multiFactorStages[1]['statuss'] === true ) { $this->_multiFactorStages[2] = array ( 'enc_key' => \openssl_random_pseudo_bytes($this->getEncKeyLength()), 'statuss' => false ); } return $this->_multiFactorStages; } elseif ($currentStage != 2) { throw new UserCredentialException('The current stage of the multi factor auth process is in an unknown state', 2101); } //authenticate stage 2 $totpTimestamp = $this->userTotpProfile['totp_timestamp']; $totpTimelimit = $this->userTotpProfile['totp_timelimit']; $currDateTime = new \DateTime(); $totpTimeElapsed = $currDateTime->getTimestamp() - $totpTimestamp->getTimestamp(); $encKey = $this->userTotpProfile['enc_key']; $verificationHash = $this->getVerificationHash(); $comparisonHash = \crypt($this->getCurrentPassword(), $encKey); $currentOneTimeToken = $this->getCurrentOneTimeToken(); $oneTimeToken = $this->oneTimeToken; //initialize verification - comparison $verificationEqualsComparison = false; //verify if verification hash equals comparison hash. Use hash_equals function if exists if (!\function_exists('hash_equals')) { if ($verificationHash === $comparisonHash) { $verificationEqualsComparison = true; } } else { if (\hash_equals($verificationHash, $comparisonHash)) { $verificationEqualsComparison = true; } } if ( !($totpTimeElapsed < $totpTimelimit) || !($verificationEqualsComparison === true) || !(\password_verify($oneTimeToken,$currentOneTimeToken)) ) { return false; } else { return true; } }
php
{ "resource": "" }
q7201
UserCredentialSmsTokenLoginService.setEncKeyLength
train
public function setEncKeyLength($keyLength) { $keyLengthCast = (int) $keyLength; if (!($keyLengthCast > 0)) { throw new UserCredentialException('The encryption key length must be an integer', 2105); } $this->keyLength = $keyLengthCast; }
php
{ "resource": "" }
q7202
UserCredentialSmsTokenLoginService.getOneTimeToken
train
public function getOneTimeToken($unhashed = false) { if ((bool) $unhashed === true) { return $this->oneTimeToken; } else { return \password_hash($this->oneTimeToken, \PASSWORD_DEFAULT); } }
php
{ "resource": "" }
q7203
Mailer.push
train
public function push($view, array $data = [], $callback = null, ?string $queue = null): ReceiptContract { $method = $this->shouldBeQueued() ? 'queue' : 'send'; return $this->{$method}($view, $data, $callback, $queue); }
php
{ "resource": "" }
q7204
Mailer.send
train
public function send($view, array $data = [], $callback = null): ReceiptContract { $mailer = $this->getMailer(); if ($view instanceof MailableContract) { $this->updateFromOnMailable($view)->send($mailer); } else { $mailer->send($view, $data, $callback); } return new Receipt($mailer, false); }
php
{ "resource": "" }
q7205
Mailer.queue
train
public function queue($view, array $data = [], $callback = null, ?string $queue = null): ReceiptContract { $mailer = $this->getMailer(); if ($view instanceof MailableContract) { $this->updateFromOnMailable($view)->queue($this->queue); } else { $callback = $this->buildQueueCallable($callback); $with = \compact('view', 'data', 'callback'); $this->queue->push('orchestra.mail@handleQueuedMessage', $with, $queue); } return new Receipt($mailer, true); }
php
{ "resource": "" }
q7206
Mailer.updateFromOnMailable
train
protected function updateFromOnMailable(MailableContract $message): MailableContract { if (! empty($this->from['address'])) { $message->from($this->from['address'], $this->from['name']); } return $message; }
php
{ "resource": "" }
q7207
Mailer.configureIlluminateMailer
train
public function configureIlluminateMailer(MailerContract $mailer): MailerContract { $from = $this->memory->get('email.from'); // If a "from" address is set, we will set it on the mailer so that // all mail messages sent by the applications will utilize the same // "from" address on each one, which makes the developer's life a // lot more convenient. if (\is_array($from) && ! empty($from['address'])) { $this->from = $from; $mailer->alwaysFrom($from['address'], $from['name']); } if ($this->queue instanceof QueueContract) { $mailer->setQueue($this->queue); } $mailer->setSwiftMailer(new Swift_Mailer($this->transport->driver())); return $mailer; }
php
{ "resource": "" }
q7208
App.getServices
train
public function getServices(): ServiceContainer { if (is_null($this->services)) { $this->services = new ServiceContainer(); $this->services->setConstraints(['caching' => '\Psr\SimpleCache\CacheInterface', 'events' => '\Psr\EventManager\EventManagerInterface', 'flashbag' => '\Berlioz\Core\Services\FlashBag', 'logging' => '\Psr\Log\LoggerInterface', 'routing' => '\Berlioz\Core\Services\Routing\RouterInterface', 'templating' => '\Berlioz\Core\Services\Template\TemplateInterface']); $this->services->registerServices(['events' => ['class' => '\Berlioz\Core\Services\Events\EventManager'], 'flashbag' => ['class' => '\Berlioz\Core\Services\FlashBag'], 'logging' => ['class' => '\Berlioz\Core\Services\Logger'], 'routing' => ['class' => '\Berlioz\Core\Services\Routing\Router'], 'templating' => ['class' => '\Berlioz\Core\Services\Template\DefaultEngine']]); $this->services->registerServices($this->getConfig()->get('app.services')); $this->services->register('app', $this); } return $this->services; }
php
{ "resource": "" }
q7209
App.addExtension
train
public function addExtension(ExtensionInterface $extension): App { try { if (!$extension->isInitialized()) { $extension->init($this); } } catch (\Exception $e) { throw new RuntimeException(sprintf('Unable to load extension "%s"', get_class($extension))); } return $this; }
php
{ "resource": "" }
q7210
AnnotationService.registerController
train
private function registerController(string $controllerClassName) { $controllerAnnotation = $this->getControllerAnnotation($controllerClassName); if ($controllerAnnotation instanceof Controller) { $controllerName = trim($controllerClassName, "\\"); $this->app["$controllerName"] = function (Application $app) use ($controllerName) { return new $controllerName($app); }; $this->processClassAnnotation($controllerAnnotation); } }
php
{ "resource": "" }
q7211
Server.getDatalistValue
train
protected function getDatalistValue(array $names = array()) { $services = \hypeJunction\Integration::getServiceProvider(); foreach ($names as $name) { $values[$name] = $services->datalist->get($name); } return $values; }
php
{ "resource": "" }
q7212
Action.setup
train
public function setup() { $input_keys = array_keys((array) elgg_get_config('input')); $request_keys = array_keys((array) $_REQUEST); $keys = array_unique(array_merge($input_keys, $request_keys)); foreach ($keys as $key) { if ($key) { $this->params->$key = get_input($key); } } }
php
{ "resource": "" }
q7213
Order.getReportedShippingCollections
train
public function getReportedShippingCollections() { try { return $this->encoder->decode($this->getData(self::FIELD_REPORTED_SHIPPING_COLLECTIONS)) ?: []; } catch (\InvalidArgumentException $e) { $this->_logger->error($e->getMessage()); return []; } }
php
{ "resource": "" }
q7214
Http.authenticateOnServer
train
protected function authenticateOnServer($authUrl, $username, $password) { $response = $this->sendDigestAuthentication($authUrl, $username, $password); $httpCode = $response->getHttpCode(); // If status code is not 200, something went wrong if (200 !== $httpCode) { throw new \Exception('Response with Status Code [' . $httpCode . '].', 500); } }
php
{ "resource": "" }
q7215
Http.getRights
train
public function getRights() { $rights = array( 'graphUpdate' => false, 'tripleQuerying' => false, 'tripleUpdate' => false ); // generate a unique graph URI which we will use later on for our tests. $graph = 'http://saft/'. hash('sha1', rand(0, time()) . microtime(true)) .'/'; /* * check if we can create and drop graphs */ try { $this->query('CREATE GRAPH <'. $graph .'>'); $this->query('DROP GRAPH <'. $graph .'>'); $rights['graphUpdate'] = true; } catch (\Exception $e) { // ignore exception here and assume we could not create or drop the graph. } /* * check if we can query triples */ try { $this->query('SELECT ?g { GRAPH ?g {?s ?p ?o} } LIMIT 1'); $rights['tripleQuerying'] = true; } catch (\Exception $e) { // ignore exception here and assume we could not query anything. } /* * check if we can create and update queries. */ try { if ($rights['graphUpdate']) { // create graph $this->query('CREATE GRAPH <'. $graph .'>'); // create a simple triple $this->query('INSERT DATA { GRAPH <'. $graph .'> { <'. $graph .'1> <'. $graph .'2> "42" } }'); // remove all triples $this->query('WITH <'. $graph .'> DELETE { ?s ?p ?o }'); // drop graph $this->query('DROP GRAPH <'. $graph .'>'); $rights['tripleUpdate'] = true; } } catch (\Exception $e) { // ignore exception here and assume we could not update a triple. // whatever happens, try to remove the fresh graph. try { $this->query('DROP GRAPH <'. $graph .'>'); } catch (\Exception $e) { } } return $rights; }
php
{ "resource": "" }
q7216
Http.isGraphAvailable
train
public function isGraphAvailable(Node $graph) { $graphs = $this->getGraphs(); return isset($graphs[$graph->getUri()]); }
php
{ "resource": "" }
q7217
Http.openConnection
train
public function openConnection() { if (null == $this->httpClient) { return false; } $configuration = array_merge(array( 'authUrl' => '', 'password' => '', 'queryUrl' => '', 'username' => '' ), $this->configuration); // authenticate only if an authUrl was given. if ($this->RdfHelpers->simpleCheckURI($configuration['authUrl'])) { $this->authenticateOnServer( $configuration['authUrl'], $configuration['username'], $configuration['password'] ); } // check query URL if (false === $this->RdfHelpers->simpleCheckURI($configuration['queryUrl'])) { throw new \Exception('Parameter queryUrl is not an URI or empty: '. $configuration['queryUrl']); } }
php
{ "resource": "" }
q7218
Http.sendDigestAuthentication
train
public function sendDigestAuthentication($url, $username, $password = null) { $this->httpClient->setDigestAuthentication($username, $password); return $this->httpClient->get($url); }
php
{ "resource": "" }
q7219
Http.sendSparqlSelectQuery
train
public function sendSparqlSelectQuery($url, $query) { // because you can't just fire multiple requests with the same CURL class instance // we have to be creative and re-create the class everytime a request is to be send. // FYI: https://github.com/php-curl-class/php-curl-class/issues/326 $class = get_class($this->httpClient); $phpVersionToOld = version_compare(phpversion(), '5.5.11', '<='); // only reinstance the class if its not mocked if ($phpVersionToOld && false === strpos($class, 'Mockery')) { $this->httpClient = new $class(); } $this->httpClient->setHeader('Accept', 'application/sparql-results+json'); $this->httpClient->setHeader('Content-Type', 'application/x-www-form-urlencoded'); return $this->httpClient->post($url, array('query' => $query)); }
php
{ "resource": "" }
q7220
Http.sendSparqlUpdateQuery
train
public function sendSparqlUpdateQuery($url, $query) { // because you can't just fire multiple requests with the same CURL class instance // we have to be creative and re-create the class everytime a request is to be send. // FYI: https://github.com/php-curl-class/php-curl-class/issues/326 $class = get_class($this->httpClient); $phpVersionToOld = version_compare(phpversion(), '5.5.11', '<='); // only reinstance the class if its not mocked if ($phpVersionToOld && false === strpos($class, 'Mockery')) { $this->httpClient = new $class; } // TODO extend Accept headers to further formats $this->httpClient->setHeader('Accept', 'application/sparql-results+json'); $this->httpClient->setHeader('Content-Type', 'application/sparql-update'); return $this->httpClient->get($url, array('query' => $query)); }
php
{ "resource": "" }
q7221
Http.transformResultToArray
train
public function transformResultToArray($receivedResult) { // transform object to array if (is_object($receivedResult)) { return json_decode(json_encode($receivedResult), true); // transform json string to array } else { return json_decode($receivedResult, true); } }
php
{ "resource": "" }
q7222
Retriever.getProductTaxClasses
train
public function getProductTaxClasses() { /** @var \Magento\Tax\Model\ResourceModel\TaxClass\Collection $taxCollection */ $classes = []; $taxCollection = $this->taxClass->getCollection(); $taxCollection->setClassTypeFilter(ClassModel::TAX_CLASS_TYPE_PRODUCT); /** @var ClassModel $tax */ foreach ($taxCollection as $tax) { $classes[] = [ 'id' => $tax->getId(), 'key' => $tax->getClassName() ]; } return $classes; }
php
{ "resource": "" }
q7223
Retriever.getCustomerTaxClasses
train
public function getCustomerTaxClasses() { /** @var \Magento\Tax\Model\ResourceModel\TaxClass\Collection $taxCollection */ $classes = []; $defaultTaxId = $this->customerGroup->getNotLoggedInGroup()->getTaxClassId(); $taxCollection = $this->taxClass->getCollection(); $taxCollection->setClassTypeFilter(ClassModel::TAX_CLASS_TYPE_CUSTOMER); /** @var ClassModel $tax */ foreach ($taxCollection as $tax) { $classes[] = [ 'id' => $tax->getId(), 'key' => $tax->getClassName(), 'is_default' => intval($defaultTaxId == $tax->getId()), ]; } return $classes; }
php
{ "resource": "" }
q7224
Retriever.getTaxRates
train
public function getTaxRates() { $rates = []; /** @var \Magento\Tax\Model\Calculation\Rate $rate */ foreach ($this->taxRates as $rate) { $zipCodeType = self::ZIP_CODE_TYPE_ALL; $zipCodePattern = ''; $zipCodeRangeFrom = ''; $zipCodeRangeTo = ''; if ($rate->getZipIsRange()) { $zipCodeType = self::ZIP_CODE_TYPE_RANGE; $zipCodeRangeFrom = $rate->getZipFrom(); $zipCodeRangeTo = $rate->getZipTo(); } elseif ($rate->getTaxPostcode() && $rate->getTaxPostcode() != '*') { $zipCodeType = self::ZIP_CODE_TYPE_PATTERN; $zipCodePattern = $rate->getTaxPostcode(); } $state = ''; $regionId = $rate->getTaxRegionId(); if ($regionId) { /** @var \Magento\Directory\Model\Region $region */ $region = $this->regionCollection->getItemById($regionId); $state = $this->regionHelper->getIsoStateByMagentoRegion( new DataObject( [ 'region_code' => $region->getCode(), 'country_id' => $rate->getTaxCountryId() ] ) ); } $rates[] = [ 'id' => $rate->getId(), 'key' => $rate->getId(), 'display_name' => $rate->getCode(), 'tax_percent' => round($rate->getRate(), 4), 'country' => $rate->getTaxCountryId(), 'state' => $state, 'zipcode_type' => $zipCodeType, 'zipcode_pattern' => $zipCodePattern, 'zipcode_range_from' => $zipCodeRangeFrom, 'zipcode_range_to' => $zipCodeRangeTo ]; } return $rates; }
php
{ "resource": "" }
q7225
Retriever.getTaxRules
train
public function getTaxRules() { $rules = []; /* @var \Magento\Tax\Model\Calculation\Rule $rule */ foreach ($this->taxRules as $rule) { $_rule = [ 'id' => $rule->getId(), 'name' => $rule->getCode(), 'priority' => $rule->getPriority(), 'product_tax_classes' => [], 'customer_tax_classes' => [], 'tax_rates' => [], ]; foreach (array_unique($rule->getProductTaxClasses()) as $taxClass) { $_rule['product_tax_classes'][] = [ 'id' => $taxClass, 'key' => $taxClass ]; } foreach (array_unique($rule->getCustomerTaxClasses()) as $taxClass) { $_rule['customer_tax_classes'][] = [ 'id' => $taxClass, 'key' => $taxClass ]; } foreach (array_unique($rule->getRates()) as $taxRates) { $_rule['tax_rates'][] = [ 'id' => $taxRates, 'key' => $taxRates ]; } $rules[] = $_rule; } return $rules; }
php
{ "resource": "" }
q7226
FileContentHelper._returnHash
train
private function _returnHash(string $hash, int $length) { try { return substr($hash, 0, $length); } catch (\Exception $e) { } return false; }
php
{ "resource": "" }
q7227
FileContentHelper.pathHash
train
public function pathHash(string $path, int $length = 8) { return $this->_returnHash( sha1_file($this->_generalizeResource($path)), $length ); }
php
{ "resource": "" }
q7228
FileContentHelper.resourceHash
train
public function resourceHash($resource, int $length = 8): string { return $this->_returnHash($resource->getResource()->getSha1(), $length); }
php
{ "resource": "" }
q7229
UploadHandler.makeFiles
train
public function makeFiles($input, array $attributes = array(), array $config = array()) { $files = array(); $uploads = hypeApps()->uploader->handle($input, $attributes, $config); foreach ($uploads as $upload) { if ($upload->file instanceof \ElggEntity) { $files[] = $upload->file; } } return $files; }
php
{ "resource": "" }
q7230
UploadHandler.handle
train
public static function handle($input, array $attributes = array(), array $config = array()) { return hypeApps()->uploader->handle($input, $attributes, $config); }
php
{ "resource": "" }
q7231
AbstractFTPClient.newFTPException
train
protected function newFTPException($message) { return new FTPException(sprintf("%s://%s:%s@%s:%d " . $message, $this->authenticator->getScheme(), $this->authenticator->getPasswordAuthentication()->getUsername(), $this->authenticator->getPasswordAuthentication()->getPassword(), $this->authenticator->getHost(), $this->authenticator->getPort())); }
php
{ "resource": "" }
q7232
Multiotp.ResetCacheArray
train
function ResetCacheArray() { // First, we reset all values (we know the key based on the schema) reset($this->_sql_tables_schema['cache']); while(list($valid_key, $valid_format) = @each($this->_sql_tables_schema['cache'])) { $pos = mb_strpos(mb_strtoupper($valid_format), 'DEFAULT'); $value = ""; if ($pos !== FALSE) { $value = trim(substr($valid_format, $pos + strlen("DEFAULT"))); if (("'" == substr($value,0,1)) && ("'" == substr($value,-1))) { $value = substr($value,1,-1); } } $this->_cache_data[$valid_key] = $value; } }
php
{ "resource": "" }
q7233
Multiotp.ResetConfigArray
train
function ResetConfigArray($array_to_reset = '') { if (!is_array($array_to_reset)) { $array_to_reset = $this->_sql_tables_schema['config']; } // First, we reset all values (we know the key based on the schema) reset($array_to_reset); while(list($valid_key, $valid_format) = @each($array_to_reset)) { $pos = mb_strpos(mb_strtoupper($valid_format), 'DEFAULT'); $value = ""; if ($pos !== FALSE) { $value = trim(substr($valid_format, $pos + strlen("DEFAULT"))); if (("'" == substr($value,0,1)) && ("'" == substr($value,-1))) { $value = substr($value,1,-1); } } $this->_config_data[$valid_key] = $value; } }
php
{ "resource": "" }
q7234
Multiotp.ResetTempUserArray
train
function ResetTempUserArray() { $temp_user_array = array(); // First, we reset all values (we know the key based on the schema) reset($this->_sql_tables_schema['users']); while(list($valid_key, $valid_format) = @each($this->_sql_tables_schema['users'])) { $pos = mb_strpos(mb_strtoupper($valid_format), 'DEFAULT'); $value = ""; if ($pos !== FALSE) { $value = trim(substr($valid_format, $pos + strlen("DEFAULT"))); if (("'" == substr($value,0,1)) && ("'" == substr($value,-1))) { $value = substr($value,1,-1); } } $temp_user_array[$valid_key] = $value; } // Request the pin as a prefix of the returned token value $temp_user_array['request_prefix_pin'] = $this->GetDefaultRequestPrefixPin(); return $temp_user_array; }
php
{ "resource": "" }
q7235
Multiotp.ResetUserArray
train
function ResetUserArray() { $this->_user_data = array(); $this->_user_data = $this->ResetTempUserArray(); // The user data array is not read actually $this->SetUserDataReadFlag(false); }
php
{ "resource": "" }
q7236
Multiotp.GetDetailedUsersArray
train
function GetDetailedUsersArray() { $users_array = array(); $result = $this->GetNextUserArray(TRUE); if (isset($result['user'])) { $users_array[$result['user']] = $result; } do { if ($result = $this->GetNextUserArray()) { if (isset($result['user'])) { $users_array[$result['user']] = $result; } } } while (FALSE !== $result); return $users_array; }
php
{ "resource": "" }
q7237
Multiotp.ImportTokensFile
train
function ImportTokensFile( $file, $original_name = '', $cipher_password = '', $key_mac = "" ) { if (!file_exists($file)) { $result = FALSE; } else { $data1000 = @file_get_contents($file, FALSE, NULL, 0, 1000); $file_name = ('' != $original_name)?$original_name:$file; if (FALSE !== mb_strpos(mb_strtolower($data1000), mb_strtolower('"urn:ietf:params:xml:ns:keyprov:pskc"'))) { $result = $this->ImportTokensFromPskc($file, $cipher_password, $key_mac); } elseif (FALSE !== mb_strpos(mb_strtolower($data1000), mb_strtolower('LOGGING START'))) { $result = $this->ImportYubikeyTraditional($file); } elseif ((FALSE !== mb_strpos(mb_strtolower($data1000), mb_strtolower('AUTHENEXDB'))) && ('.sql' == mb_strtolower(substr($file_name, -4)))) { $result = $this->ImportTokensFromAuthenexSql($file); } elseif ((FALSE !== mb_strpos(mb_strtolower($data1000), mb_strtolower('SafeWord Authenticator Records'))) && ('.dat' == mb_strtolower(substr($file_name, -4)))) { $result = $this->ImportTokensFromAlpineDat($file); } elseif (FALSE !== mb_strpos(mb_strtolower($data1000), mb_strtolower('<ProductName>eTPass'))) { // elseif (('.xml' == mb_strtolower(substr($file_name, -4))) && (FALSE !== mb_strpos(mb_strtolower($file_name), 'alpine'))) $result = $this->ImportTokensFromAlpineXml($file); } elseif ('.xml' == mb_strtolower(substr($file_name, -4))) { $result = $this->ImportTokensFromXml($file); } else { $result = $this->ImportTokensFromCsv($file); } } return $result; }
php
{ "resource": "" }
q7238
Multiotp.qrcode
train
function qrcode( $data = '', $file_name = '', $image_type = "P", $ecc_level = "Q", $module_size = 4, $version = 0, $structure_m = 0, $structure_n = 0, $parity = 0, $original_data = '' ) { $result = ''; $qrcode_folder = $this->GetQrCodeFolder(); $path = $qrcode_folder.'data'; $image_path = $qrcode_folder.'image'; if (!(file_exists($path) && file_exists($image_path))) { $this->WriteLog("Error: QRcode files or folders are not available", FALSE, FALSE, 39, 'System', '', 3); } else { $result = MultiotpQrcode($data, $file_name, $image_type, $ecc_level, $module_size, $version, $structure_m, $structure_n, $parity, $original_data, $path, $image_path); $output_name = NULL; ob_start(); if (('' != trim($file_name)) && ('binary' != trim($file_name)) && ('' != $this->GetLinuxFileMode())) { if (file_exists($file_name)) { @chmod($file_name, octdec($this->GetLinuxFileMode())); } } } return $result; }
php
{ "resource": "" }
q7239
MultiotpAdLdap.authenticate
train
function authenticate($username,$password,$prevent_rebind=false){ if ($username==NULL || $password==NULL){ return (false); } //prevent null binding //bind as the user $this->_bind = @ldap_bind($this->_conn,$username.$this->_account_suffix,$password); $this->_bind_paged = @ldap_bind($this->_conn_paged,$username.$this->_account_suffix,$password); if (!$this->_bind){ return (false); } //once we've checked their details, kick back into admin mode if we have it if ($this->_ad_username!=NULL && !$prevent_rebind){ $this->_bind = @ldap_bind($this->_conn,$this->_ad_username.$this->_account_suffix,$this->_ad_password); $this->_bind_paged = @ldap_bind($this->_conn_paged,$this->_ad_username.$this->_account_suffix,$this->_ad_password); if (!$this->_bind){ // Modified by SysCo/al $this->_error = TRUE; $this->_error_message = 'FATAL: AD rebind failed.'; exit(); } //this should never happen in theory } return (true); }
php
{ "resource": "" }
q7240
MultiotpAdLdap.group_add_group
train
function group_add_group($parent,$child){ //find the parent group's dn $parent_group=$this->group_info($parent,array("cn")); if ($parent_group[0]["dn"]==NULL){ return (false); } $parent_dn=$parent_group[0]["dn"]; //find the child group's dn $child_group=$this->group_info($child,array("cn")); if ($child_group[0]["dn"]==NULL){ return (false); } $child_dn=$child_group[0]["dn"]; $add=array(); $add["member"] = $child_dn; $result=@ldap_mod_add($this->_conn,$parent_dn,$add); if ($result==false){ return (false); } return (true); }
php
{ "resource": "" }
q7241
MultiotpAdLdap.group_add_user
train
function group_add_user($group,$user){ //adding a user is a bit fiddly, we need to get the full DN of the user //and add it using the full DN of the group //find the user's dn $user_info=$this->user_info($user,array("cn")); if ($user_info[0]["dn"]==NULL){ return (false); } $user_dn=$user_info[0]["dn"]; //find the group's dn $group_info=$this->group_info($group,array("cn")); if ($group_info[0]["dn"]==NULL){ return (false); } $group_dn=$group_info[0]["dn"]; $add=array(); $add["member"] = $user_dn; $result=@ldap_mod_add($this->_conn,$group_dn,$add); if ($result==false){ return (false); } return (true); }
php
{ "resource": "" }
q7242
MultiotpAdLdap.group_del_group
train
function group_del_group($parent,$child){ //find the parent dn $parent_group=$this->group_info($parent,array("cn")); if ($parent_group[0]["dn"]==NULL){ return (false); } $parent_dn=$parent_group[0]["dn"]; //find the child dn $child_group=$this->group_info($child,array("cn")); if ($child_group[0]["dn"]==NULL){ return (false); } $child_dn=$child_group[0]["dn"]; $del=array(); $del["member"] = $child_dn; $result=@ldap_mod_del($this->_conn,$parent_dn,$del); if ($result==false){ return (false); } return (true); }
php
{ "resource": "" }
q7243
MultiotpAdLdap.group_del_user
train
function group_del_user($group,$user){ //find the parent dn $group_info=$this->group_info($group,array("cn")); if ($group_info[0]["dn"]==NULL){ return (false); } $group_dn=$group_info[0]["dn"]; //find the child dn $user_info=$this->user_info($user,array("cn")); if ($user_info[0]["dn"]==NULL){ return (false); } $user_dn=$user_info[0]["dn"]; $del=array(); $del["member"] = $user_dn; $result=@ldap_mod_del($this->_conn,$group_dn,$del); if ($result==false){ return (false); } return (true); }
php
{ "resource": "" }
q7244
MultiotpAdLdap.group_info
train
function group_info($group_name,$fields=NULL){ if ($group_name==NULL){ return (false); } if (!$this->_bind){ return (false); } $filter="(&(objectCategory=group)(".$this->_group_cn_identifier."=".$this->ldap_search_encode($group_name)."))"; if ($fields==NULL){ $fields=array("member",$this->_group_attribute,"cn","description","distinguishedname","objectcategory",$this->_group_cn_identifier); } $sr=@ldap_search($this->_conn,$this->_base_dn,$filter,$fields); if (FALSE === $sr) { $this->_warning_message = "group_info: ldap_search error ".ldap_errno($this->_conn).": ".ldap_error($this->_conn); echo "DEBUG: ".$this->_warning_message."\n"; } // Search: (&(objectCategory=group)(cn=gr10000)) // (&(objectCategory=group)(cn=gr10)) // PHP Warning: ldap_search(): Search: Critical extension is unavailable in // C:\data\projects\multiotp\core\contrib\MultiotpAdLdap.php on line 591 // Search: (&(objectCategory=group)(cn=gr10)) $entries = $this->ldap_get_entries_raw($sr); // DEBUG if (0 == count($entries)) { $this->_warning_message = "group_info: No entry for the specified filter $filter"; echo "DEBUG: ".$this->_warning_message."\n"; } return ($entries); }
php
{ "resource": "" }
q7245
MultiotpAdLdap.group_users
train
function group_users($group_name=NUL){ $result = array(); if ($group_name==NULL){ return (false); } if (!$this->_bind){ return (false); } $filter="(&(|(objectClass=posixGroup)(objectClass=groupofNames))(".$this->_group_cn_identifier."=".$this->ldap_search_encode($group_name)."))"; $fields=array("member","memberuid"); $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); $entries = $this->ldap_get_entries_raw($sr); // DEBUG if (0 == count($entries)) { $this->_warning_message = "group_users: No entry for the specified filter $filter"; echo "DEBUG: ".$this->_warning_message; } if (isset($entries[0]["member"][0])) { $result = $this->nice_names($entries[0]["member"]); /* for ($i=0; $i++; $i < $entries[0]["member"][count]) { $result[] == ($entries[0]["member"][$i]); } */ } elseif (isset($entries[0]["memberuid"][0])) { $result = $this->nice_names($entries[0]["memberuid"]); } else { $result = array(); } return ($result); }
php
{ "resource": "" }
q7246
MultiotpAdLdap.user_groups
train
function user_groups($username,$recursive=NULL){ if ($username==NULL){ return (false); } if ($recursive==NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it if (!$this->_bind){ return (false); } //search the directory for their information $info=@$this->user_info($username,array($this->_group_attribute,"member","primarygroupid")); $groups=$this->nice_names($info[0][$this->_group_attribute]); //presuming the entry returned is our guy (unique usernames) if ($recursive){ foreach ($groups as $id => $group_name){ $extra_groups=$this->recursive_groups($group_name); $groups=array_merge($groups,$extra_groups); } } return ($groups); }
php
{ "resource": "" }
q7247
MultiotpAdLdap.user_all_groups
train
function user_all_groups($username, $groups_filtering = '') { if ($username==NULL){ return (false); } if (!$this->_bind){ return (false); } $filter = "(&(objectCategory=group)(member:1.2.840.113556.1.4.1941:=".$username.")".$groups_filtering.")"; // $fields = array($this->_group_cn_identifier,$this->_group_attribute,"distinguishedname"); $fields = array("cn"); $sr = ldap_search($this->_conn,$this->_base_dn,$filter, $fields); $group_entries = $this->rCountRemover(ldap_get_entries($this->_conn, $sr)); //echo "DEBUG: info group_entries\n"; //print_r($group_entries); $group_array = array(); foreach ($group_entries as $group_entry) { $group_array[] = $group_entry['cn'][0]; } //echo "DEBUG: group_array\n"; //print_r($group_array); return ($group_array); }
php
{ "resource": "" }
q7248
MultiotpAdLdap.users_info
train
function users_info($username=NULL, $fields=NULL, $groups_filtering = '') { $entries = array(); $entries['count'] = 0; // To be compatible with the old data organisation (counter at the beginning) $i = 0; if ($result = $this->one_user_info(TRUE, $username, $fields, FALSE, $groups_filtering)) { do { $entries[$i] = $result; $i++; } while ($result = $this->one_user_info()); } $entries['count'] = $i; // and not count($entries) because of the ['count'] argument return ($entries); }
php
{ "resource": "" }
q7249
MultiotpAdLdap.user_ingroup
train
function user_ingroup($username,$group,$recursive=NULL){ if ($username==NULL){ return (false); } if ($group==NULL){ return (false); } if (!$this->_bind){ return (false); } if ($recursive==NULL){ $recursive=$this->_recursive_groups; } //use the default option if they haven't set it //get a list of the groups $groups=$this->user_groups($username,array($this->_group_attribute),$recursive); //return true if the specified group is in the group list if (in_array($group,$groups)){ return (true); } return (false); }
php
{ "resource": "" }
q7250
MultiotpAdLdap.user_modify
train
function user_modify($username,$attributes){ if ($username==NULL){ return ("Missing compulsory field [username]"); } if (array_key_exists("password",$attributes) && !$this->_use_ssl){ echo ("FATAL: SSL must be configured on your webserver and enabled in the class to set passwords."); exit(); } //if (array_key_exists("container",$attributes)){ //if (!is_array($attributes["container"])){ return ("Container attribute must be an array."); } //$attributes["container"]=array_reverse($attributes["container"]); //} //find the dn of the user $user=$this->user_info($username,array("cn")); if ($user[0]["dn"]==NULL){ return (false); } $user_dn=$user[0]["dn"]; //translate the update to the LDAP schema $mod=$this->adldap_schema($attributes); if (!$mod){ return (false); } //set the account control attribute (only if specified) if (array_key_exists("enabled",$attributes)){ if ($attributes["enabled"]){ $control_options=array("NORMAL_ACCOUNT"); } else { $control_options=array("NORMAL_ACCOUNT","ACCOUNTDISABLE"); } $mod["userAccountControl"][0]=$this->account_control($control_options); } //do the update $result=ldap_modify($this->_conn,$user_dn,$mod); if ($result==false){ return (false); } return (true); }
php
{ "resource": "" }
q7251
MultiotpAdLdap.user_password
train
function user_password($username,$password){ if ($username==NULL){ return (false); } if ($password==NULL){ return (false); } if (!$this->_bind){ return (false); } if (!$this->_use_ssl){ echo ("FATAL: SSL must be configured on your webserver and enabled in the class to set passwords."); exit(); } $user=$this->user_info($username,array("cn")); if ($user[0]["dn"]==NULL){ return (false); } $user_dn=$user[0]["dn"]; $add=array(); $add["unicodePwd"][0]=$this->encode_password($password); $result=ldap_mod_replace($this->_conn,$user_dn,$add); if ($result==false){ return (false); } return (true); }
php
{ "resource": "" }
q7252
MultiotpAdLdap.computer_info
train
function computer_info($computer_name,$fields=NULL){ if ($computer_name==NULL){ return (false); } if (!$this->_bind){ return (false); } $filter="(&(objectClass=computer)(cn=".$computer_name."))"; if ($fields==NULL){ $fields=array($this->_group_attribute,"cn","displayname","dnshostname","distinguishedname","objectcategory","operatingsystem","operatingsystemservicepack","operatingsystemversion"); } $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); $entries = $this->ldap_get_entries_raw($sr); return ($entries); }
php
{ "resource": "" }
q7253
MultiotpAdLdap.all_users
train
function all_users($include_desc = false, $search = "*", $sorted = true){ if (!$this->_bind){ return (false); } //perform the search and grab all their details $filter = "(&(objectClass=user)(samaccounttype=". ADLDAP_NORMAL_ACCOUNT .")(objectCategory=person)(cn=".$search."))"; $fields=array($this->_cn_identifier,"displayname"); $sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields); $entries = $this->ldap_get_entries_raw($sr); $users_array = array(); for ($i=0; $i<$entries["count"]; $i++){ if ($include_desc && strlen($entries[$i]["displayname"][0])>0){ $users_array[ $entries[$i][$this->_cn_identifier][0] ] = $entries[$i]["displayname"][0]; } elseif ($include_desc){ $users_array[ $entries[$i][$this->_cn_identifier][0] ] = $entries[$i][$this->_cn_identifier][0]; } else { array_push($users_array, $entries[$i][$this->_cn_identifier][0]); } } if ($sorted){ asort($users_array); } return ($users_array); }
php
{ "resource": "" }
q7254
MultiotpAdLdap.encode_password
train
function encode_password($password){ $password="\"".$password."\""; $encoded=""; for ($i=0; $i <strlen($password); $i++){ $encoded.="{$password{$i}}\000"; } return ($encoded); }
php
{ "resource": "" }
q7255
MultiotpAdLdap.ldap_slashes
train
function ldap_slashes($str){ $illegal=array("(",")","#"); // the + character has problems too, but it's an illegal character $legal=array(); foreach ($illegal as $id => $char){ $legal[$id]="\\".$char; } //make up the array of legal chars $str=str_replace($illegal,$legal,$str); //replace them return ($str); }
php
{ "resource": "" }
q7256
ShopgateOrder.getValueSelectOptions
train
public function getValueSelectOptions() { if (!$this->hasData('value_select_options')) { $this->setData( 'value_select_options', $this->sourceYesno->toOptionArray() ); } return $this->getData('value_select_options'); }
php
{ "resource": "" }
q7257
ShopgateOrder.validate
train
public function validate(\Magento\Framework\Model\AbstractModel $model) { $isShopgateOrder = (int) in_array($model->getData(self::CLIENT_ATTRIBUTE), self::APP_CLIENTS); // TODO add validation for web checkout $model->setData(self::IS_SHOPGATE_ORDER, $isShopgateOrder); return parent::validate($model); }
php
{ "resource": "" }
q7258
ModelCustomFields.getCustomFields
train
public static function getCustomFields($findResults, $getById = false) { if (is_array($findResults)) { if (count($findResults) == 1 && $getById) { $findResults = [$findResults]; } } $results = []; $classReflection = (new \ReflectionClass($findResults[0])); $className = $classReflection->getShortName(); $classNamespace = $classReflection->getNamespaceName(); $module = Modules::findFirstByName($className); if ($module) { $model = $classNamespace . '\\' . ucfirst($module->name) . 'CustomFields'; $modelId = strtolower($module->name) . '_id'; $customFields = CustomFields::findByModulesId($module->id); if (is_array($findResults)) { $findResults[0] = $findResults[0]->toArray(); } else { $findResults = $findResults->toArray(); } foreach ($findResults as $result) { foreach ($customFields as $customField) { $result['custom_fields'][$customField->name] = ''; $values = []; $moduleValues = $model::find([ $modelId . ' = ?0 AND custom_fields_id = ?1', 'bind' => [$result['id'], $customField->id] ]); if ($moduleValues->count()) { $result['custom_fields'][$customField->name] = $moduleValues[0]->value; } } $results[] = $result; } return $getById ? $results[0] : $results; } return $getById ? $findResults[0]->toArray() : $findResults; }
php
{ "resource": "" }
q7259
ModelCustomFields.getAllCustomFields
train
public function getAllCustomFields(array $fields = []) { if (!$models = Modules::findFirstByName($this->getSource())) { return; } $conditions = []; $fieldsIn = null; if (!empty($fields)) { $fieldsIn = " and name in ('" . implode("','", $fields) . ')'; } $conditions = 'modules_id = ? ' . $fieldsIn; $bind = [$this->getId(), $models->getId()]; $customFieldsValueTable = $this->getSource() . '_custom_fields'; $result = $this->getReadConnection()->prepare("SELECT l.{$this->getSource()}_id, c.id as field_id, c.name, l.value , c.users_id, l.created_at, l.updated_at FROM {$customFieldsValueTable} l, custom_fields c WHERE c.id = l.custom_fields_id AND l.leads_id = ? AND c.modules_id = ? "); $result->execute($bind); // $listOfCustomFields = $result->fetchAll(); $listOfCustomFields = []; while ($row = $result->fetch(\PDO::FETCH_OBJ)) { $listOfCustomFields[$row->name] = $row->value; } return $listOfCustomFields; }
php
{ "resource": "" }
q7260
ModelCustomFields.saveCustomFields
train
protected function saveCustomFields(): bool { //find the custom field module if (!$module = Modules::findFirstByName($this->getSource())) { return false; } //we need a new instane to avoid overwrite $reflector = new \ReflectionClass($this); $classNameWithNameSpace = $reflector->getNamespaceName() . '\\' . $reflector->getShortName() . 'CustomFields'; //if all is good now lets get the custom fields and save them foreach ($this->customFields as $key => $value) { //create a new obj per itration to se can save new info $customModel = new $classNameWithNameSpace(); //validate the custome field by it model if ($customField = CustomFields::findFirst(['conditions' => 'name = ?0 and modules_id = ?1', 'bind' => [$key, $module->id]])) { //throw new Exception("this custom field doesnt exist"); $customModel->setCustomId($this->getId()); $customModel->custom_fields_id = $customField->id; $customModel->value = $value; $customModel->created_at = date('Y-m-d H:i:s'); if (!$customModel->save()) { throw new Exception('Custome ' . $key . ' - ' . $this->customModel->getMessages()[0]); } } } //clean unset($this->customFields); return true; }
php
{ "resource": "" }
q7261
ModelCustomFields.cleanCustomFields
train
public function cleanCustomFields(int $id): bool { $reflector = new \ReflectionClass($this); $classNameWithNameSpace = $reflector->getNamespaceName() . '\\' . $reflector->getShortName() . 'CustomFields'; $customModel = new $classNameWithNameSpace(); //return $customModel->find(['conditions' => $this->getSource() . '_id = ?0', 'bind' => [$id]])->delete(); //we need to run the query since we dont have primary key $result = $this->getReadConnection()->prepare("DELETE FROM {$customModel->getSource()} WHERE " . $this->getSource() . '_id = ?'); return $result->execute([$id]); }
php
{ "resource": "" }
q7262
ModelCustomFields.afterUpdate
train
public function afterUpdate() { //only clean and change custom fields if they are been sent if (!empty($this->customFields)) { //replace old custom with new $allCustomFields = $this->getAllCustomFields(); if (is_array($allCustomFields)) { foreach ($this->customFields as $key => $value) { $allCustomFields[$key] = $value; } } //set $this->setCustomFields($allCustomFields); //clean old $this->cleanCustomFields($this->getId()); //save new $this->saveCustomFields(); } }
php
{ "resource": "" }
q7263
AlphabeticalTreeSort.compare
train
protected function compare(AlphabeticalTreeNodeInterface $a, AlphabeticalTreeNodeInterface $b) { // Get the paths. $pathA = AlphabeticalTreeNodeHelper::getPath($a); $pathB = AlphabeticalTreeNodeHelper::getPath($b); // Count the path. $count = count($pathA); // Handle each path. for ($i = 0; $i < $count; ++$i) { // Get the items. $itemA = $pathA[$i]; $itemB = true === isset($pathB[$i]) ? $pathB[$i] : null; // Compare the items. if ($itemA !== $itemB) { return null !== $itemB ? strcasecmp($itemA->getAlphabeticalTreeNodeLabel(), $itemB->getAlphabeticalTreeNodeLabel()) : 1; } } // Return. return 0; }
php
{ "resource": "" }
q7264
Session.flash
train
public function flash($key, $value = true) { if (is_array($key)) $this->flashMany($key); else $this->session->flash($key, $value); }
php
{ "resource": "" }
q7265
AbstractDatabase.getConnection
train
public function getConnection() { if (null === $this->connection) { $this->connection = $this->connect(); } return $this->connection; }
php
{ "resource": "" }
q7266
AbstractDatabase.prepareBinding
train
public function prepareBinding(array $fields) { $output = []; foreach ($fields as $current) { $output[$current] = ":" . $current; } return $output; }
php
{ "resource": "" }
q7267
AbstractDatabase.prepareInsert
train
public function prepareInsert($table, array $values) { // Initialize the query. $query = []; $query[] = "INSERT INTO "; $query[] = $table; $query[] = " (`"; $query[] = implode("`, `", array_keys($values)); $query[] = "`) VALUES ("; $query[] = implode(", ", array_values($values)); $query[] = ")"; // Return the query. return implode("", $query); }
php
{ "resource": "" }
q7268
AbstractDatabase.prepareUpdate
train
public function prepareUpdate($table, array $values) { // Initialize the SET. $set = []; foreach ($values as $k => $v) { $set[] = "`" . $k . "` = " . $v; } // Initialize the query. $query = []; $query[] = "UPDATE "; $query[] = $table; $query[] = " SET "; $query[] = implode(", ", $set); // Return the query. return implode("", $query); }
php
{ "resource": "" }
q7269
UserParser.parseEntity
train
public function parseEntity(User $entity) { $output = [ $this->encodeInteger($entity->getUserNumber(), 9), $this->encodeInteger($entity->getCustomerNumber(), 9), $this->encodeString($entity->getTitle(), 10), $this->encodeString($entity->getSurname(), 25), $this->encodeString($entity->getFirstname(), 25), $this->encodeDate($entity->getDateBirth()), $this->encodeString($entity->getParkingSpace(), 5), $this->encodeString($entity->getRemarks(), 50), $this->encodeDateTime($entity->getDatetimeLastModification()), $this->encodeBoolean($entity->getDeletedRecord()), $this->encodeString($entity->getIdentificationNumber(), 20), $this->encodeBoolean($entity->getCheckLicensePlate()), $this->encodeBoolean($entity->getPassageLicensePlatePermitted()), $this->encodeBoolean($entity->getExcessTimesCreditCard()), $this->encodeString($entity->getCreditCardNumber(), 20), $this->encodeDate($entity->getExpiryDate()), $this->encodeString($entity->getRemarks2(), 50), $this->encodeString($entity->getRemarks3(), 50), $this->encodeString($entity->getDivision(), 50), $this->encodeString($entity->getEmail(), 120), $this->encodeBoolean($entity->getGroupCounting()), $this->encodeInteger($entity->getETicketTypeP(), 1), $this->encodeString($entity->getETicketEmailTelephone(), 120), $this->encodeInteger($entity->getETicketAuthentication(), 1), $this->encodeInteger($entity->getETicketServiceTyp(), 1), $this->encodeInteger($entity->getETicketServiceArt(), 1), ]; return implode(";", $output); }
php
{ "resource": "" }
q7270
CssInliner.handle
train
public function handle(MessageSending $sending): void { $message = $sending->message; $converter = new CssToInlineStyles(); if ($message->getContentType() === 'text/html' || ($message->getContentType() === 'multipart/alternative' && $message->getBody()) ) { $message->setBody($converter->convert($message->getBody())); } foreach ($message->getChildren() as $part) { if (Str::contains($part->getContentType(), 'text/html')) { $part->setBody($converter->convert($part->getBody())); } } }
php
{ "resource": "" }
q7271
CodeStringBuffer.append
train
public function append($lines, $newline = true, $indentOffset = 0) { $this->_buffer[] = trim($lines) ? ($this->_getIndentationString($indentOffset) . $lines) : $lines; if ($newline) { $this->_buffer[] = $this->newLineStr; } return $this; }
php
{ "resource": "" }
q7272
Type.getType
train
public function getType($item) { switch ($this->getProductType($item)) { case Bundle::TYPE_CODE: return $this->bundle->create()->setItem($item); case Grouped::TYPE_CODE: return $this->grouped->create()->setItem($item); case Configurable::TYPE_CODE: return $this->configurable->create()->setItem($item); default: return $this->generic->create()->setItem($item); } }
php
{ "resource": "" }
q7273
Upload.save
train
public function save(array $attributes = array(), $prefix = self::DEFAULT_FILESTORE_PREFIX) { $this->error_code = $this->error; $this->error = $this->getError(); $this->filesize = $this->size; $this->path = $this->tmp_name; $this->mimetype = $this->detectMimeType(); $this->simpletype = $this->parseSimpleType(); if (!$this->isSuccessful()) { return $this; } $prefix = trim($prefix, '/'); if (!$prefix) { $prefix = self::DEFAULT_FILESTORE_PREFIX; } $id = elgg_strtolower(time() . $this->name); $filename = implode('/', array($prefix, $id)); $type = elgg_extract('type', $attributes, 'object'); $subtype = elgg_extract('subtype', $attributes, 'file'); $class = get_subtype_class($type, $subtype); if (!$class) { $class = '\\ElggFile'; } try { $filehandler = new $class(); foreach ($attributes as $key => $value) { $filehandler->$key = $value; } $filehandler->setFilename($filename); $filehandler->title = $this->name; $filehandler->originalfilename = $this->name; $filehandler->filesize = $this->size; $filehandler->mimetype = $this->mimetype; $filehandler->simpletype = $this->simpletype; $filehandler->open("write"); $filehandler->close(); if ($this->simpletype == 'image') { $img = new \hypeJunction\Files\Image($this->tmp_name); $img->save($filehandler->getFilenameOnFilestore(), hypeApps()->config->getSrcCompressionOpts()); } else { move_uploaded_file($this->tmp_name, $filehandler->getFilenameOnFilestore()); } if ($filehandler->save()) { $this->guid = $filehandler->getGUID(); $this->file = $filehandler; } } catch (\Exception $ex) { elgg_log($ex->getMessage(), 'ERROR'); $this->error = elgg_echo('upload:error:unknown'); } return $this; }
php
{ "resource": "" }
q7274
Upload.getError
train
public function getError() { switch ($this->error_code) { case UPLOAD_ERR_OK: return false; case UPLOAD_ERR_NO_FILE: $error = 'upload:error:no_file'; case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $error = 'upload:error:file_size'; default: $error = 'upload:error:unknown'; } return elgg_echo($error); }
php
{ "resource": "" }
q7275
Upload.parseSimpleType
train
public function parseSimpleType() { if (is_callable('elgg_get_file_simple_type')) { return elgg_get_file_simple_type($this->detectMimeType()); } $mime_type = $this->detectMimeType(); switch ($mime_type) { case "application/msword": case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": case "application/pdf": return "document"; case "application/ogg": return "audio"; } if (preg_match('~^(audio|image|video)/~', $mime_type, $m)) { return $m[1]; } if (0 === strpos($mime_type, 'text/') || false !== strpos($mime_type, 'opendocument')) { return "document"; } // unrecognized MIME return "general"; }
php
{ "resource": "" }
q7276
CMySQLSyntaxBuilder.describeStorage
train
public function describeStorage($name, $schema = false) { if (!$schema) { $schema = $this->connector->getSchema(); } return $this->describeTable($name, $schema); }
php
{ "resource": "" }
q7277
CMySQLSyntaxBuilder.describeTable
train
private function describeTable($name, $schema) { $data = $this->connector->getQueryAsSingleRow( 'SELECT t.table_schema AS table_schema, t.table_name AS table_name, t.engine AS engine, t.auto_increment AS auto_increment, t.table_collation AS table_collation, t.table_comment AS table_comment, cs.character_set_name AS table_charset, t.create_options AS create_options FROM information_schema.tables t, information_schema.character_sets cs WHERE t.table_schema=\'%schema$s\' AND t.table_name = \'%table$s\' AND t.table_collation = cs.default_collate_name', array( 'schema' => $schema, 'table' => $name ) ); if (is_array($data)) { $fields = $this->describeTableFields($name, $schema); $table['schema'] = $data['table_schema']; $table['name'] = $data['table_name']; $table['engine'] = $data['engine']; $table['type'] = CMySQLConnector::TYPE_TABLE; $table['autoincrement'] = $this->validateAutoIncrement($data['auto_increment'], $fields); $table['charset'] = $data['table_charset']; $table['collation'] = $data['table_collation']; $table['create_options'] = $data['create_options']; $table['comment'] = $data['table_comment']; $table['fields'] = $fields; $table['constraints'] = $this->describeTableConstraints($name, $table['fields'], $schema); $descriptor = new CMySQLDescriptor($this->connector, $table); } else { $descriptor = null; } return $descriptor; }
php
{ "resource": "" }
q7278
ObjectHelper.getHooks
train
public static function getHooks($classpath, $namespace, $classname = null, $extends = null, $method = null) { // $hooks = []; // Get the filenames. $filenames = FileHelper::getFileNames($classpath, ".php"); // Handle each filenames. foreach ($filenames as $filename) { // Check the class name. if (null !== $classname && 0 === preg_match($classname, $filename)) { continue; } // Import the class. try { require_once $classpath . "/" . $filename; } catch (Error $ex) { throw new SyntaxErrorException($classpath . "/" . $filename); } // Init. the complete class name. $completeClassname = $namespace . basename($filename, ".php"); try { $rc = new ReflectionClass($completeClassname); } catch (Exception $ex) { throw new ClassNotFoundException($completeClassname, $ex); } // Check the extends. if (false === (null === $extends || true === $rc->isSubclassOf($extends))) { continue; } // Initialize the hook. $hook = []; $hook["classpath"] = $classpath; $hook["namespace"] = $namespace; $hook["filename"] = $filename; $hook["class"] = $rc; $hook["method"] = null; $hooks[] = $hook; // Check the method. if (null === $method) { continue; } try { $rm = $rc->getMethod($method); $hooks[count($hooks) - 1]["method"] = $rm; } catch (ReflectionException $ex) { throw new MethodNotFoundException($method, $ex); } } // Returns the hooks. return $hooks; }
php
{ "resource": "" }
q7279
ObjectHelper.urlEncodeShortName
train
public static function urlEncodeShortName($object) { $classname = static::getShortName($object); $explode = preg_replace("/([a-z]{1})([A-Z]{1})/", "$1-$2", $classname); return strtolower($explode); }
php
{ "resource": "" }
q7280
ContextIORequest.put
train
public function put($account, $action, $parameters = null, $httpHeadersToSet = array()) { return $this->sendRequest('PUT', $account, $action, $parameters, null, null, $httpHeadersToSet); }
php
{ "resource": "" }
q7281
ContextIORequest.delete
train
public function delete($account, $action = '', $parameters = null) { return $this->sendRequest('DELETE', $account, $action, $parameters); }
php
{ "resource": "" }
q7282
PaginateHelper.getPageOffsetAndLimit
train
public static function getPageOffsetAndLimit($pageNumber, $divider, $total = -1) { if ($pageNumber < 0 || $divider < 0) { return -1; } $offset = $pageNumber * $divider; $limit = $divider; if (0 <= $total && ($total < $offset || $total < ($offset + $limit))) { $offset = (static::getPagesCount($total, $divider) - 1) * $divider; $limit = $total - $offset; } return [$offset, $limit]; }
php
{ "resource": "" }
q7283
PaginateHelper.getPagesCount
train
public static function getPagesCount($linesNumber, $divider) { if ($linesNumber < 0 || $divider < 0) { return -1; } $pagesCount = intval($linesNumber / $divider); if (0 < ($linesNumber % $divider)) { ++$pagesCount; } return $pagesCount; }
php
{ "resource": "" }
q7284
OrderRepository.createAndSave
train
public function createAndSave($mageOrderId) { $order = $this->orderFactory->create() ->setOrderId($mageOrderId) ->setStoreId($this->config->getStoreViewId()) ->setShopgateOrderNumber($this->sgOrder->getOrderNumber()) ->setIsShippingBlocked($this->sgOrder->getIsShippingBlocked()) ->setIsPaid($this->sgOrder->getIsPaid()) ->setIsTest($this->sgOrder->getIsTest()) ->setIsCustomerInvoiceBlocked($this->sgOrder->getIsCustomerInvoiceBlocked()); try { $order->setReceivedData(\Zend_Json_Encoder::encode($this->sgOrder->toArray())); } catch (\InvalidArgumentException $exception) { $this->sgLogger->error($exception->getMessage()); } $order->save(); }
php
{ "resource": "" }
q7285
OrderRepository.update
train
public function update(Order $order) { if ($this->sgOrder->getUpdatePayment()) { $order->setIsPaid($this->sgOrder->getIsPaid()); } if ($this->sgOrder->getUpdateShipping()) { $order->setIsShippingBlocked($this->sgOrder->getIsShippingBlocked()); } }
php
{ "resource": "" }
q7286
DefaultController.actionJson
train
public function actionJson() { /** @var \yii\web\Response */ $response = \Yii::$app->getResponse(); if (!is_readable($this->module->swaggerPath)) { throw new NotFoundHttpException(); } // Read source json file $json = file_get_contents($this->module->swaggerPath); // Do replacements if (is_array($this->module->swaggerReplace)) { foreach ($this->module->swaggerReplace as $find => $replace) { if (is_callable($replace)) { $replaceText = call_user_func($replace); } else { $replaceText = (string) $replace; } $json = mb_ereg_replace((string)$find, $replaceText, $json); } } // Override default response formatters // To avvoid json format modification $response->format = Response::FORMAT_RAW; $response->getHeaders()->set('Content-Type', 'application/json; charset=UTF-8'); // Trigger events $event = new BeforeJsonEvent; $event->responseText = $json; $this->module->trigger(self::EVENT_BEFORE_JSON, $event); return $event->responseText; }
php
{ "resource": "" }
q7287
AlphabeticalTreeNodeHelper.createChoices
train
public static function createChoices(array $choices) { // Initialize the output. $output = []; // Sort the nodes. $sorter = new AlphabeticalTreeSort($choices); $sorter->sort(); // Handle each node. foreach ($sorter->getNodes() as $current) { // Get and check the path. $path = static::getPath($current); if (false === array_key_exists($path[0]->getAlphabeticalTreeNodeLabel(), $output)) { $output[$current->getAlphabeticalTreeNodeLabel()] = []; } if (1 === count($path)) { continue; } // Add the node. $output[$path[0]->getAlphabeticalTreeNodeLabel()][] = $current; } // Return the output. return $output; }
php
{ "resource": "" }
q7288
AlphabeticalTreeNodeHelper.removeOrphan
train
public static function removeOrphan(array &$nodes = []) { do { $found = false; foreach ($nodes as $k => $v) { if (false === ($v instanceof AlphabeticalTreeNodeInterface) || null === $v->getAlphabeticalTreeNodeParent() || true === in_array($v->getAlphabeticalTreeNodeParent(), $nodes)) { continue; } unset($nodes[$k]); $found = true; } } while (true === $found); }
php
{ "resource": "" }
q7289
DefaultEngine.getTwig
train
public function getTwig(): \Twig_Environment { if (is_null($this->twig)) { // Init Twig $this->twigLoader = new \Twig_Loader_Filesystem(); $this->twig = new \Twig_Environment($this->twigLoader); } return $this->twig; }
php
{ "resource": "" }
q7290
Config.all
train
public function all() { if (!isset($this->settings)) { $this->settings = array_merge($this->getDefaults(), $this->plugin->getAllSettings()); } return $this->settings; }
php
{ "resource": "" }
q7291
OAuthServer.fetchRequestToken
train
public function fetchRequestToken(&$request) { $this->getVersion($request); $consumer = $this->getConsumer($request); // no token required for the initial token request $token = null; $this->checkSignature($request, $consumer, $token); // Rev A change $callback = $request->getParameter('oauth_callback'); $new_token = $this->data_store->newRequestToken($consumer, $callback); return $new_token; }
php
{ "resource": "" }
q7292
OAuthServer.fetchAccessToken
train
public function fetchAccessToken(&$request) { $this->getVersion($request); $consumer = $this->getConsumer($request); // requires authorized request token $token = $this->getToken($request, $consumer, "request"); $this->checkSignature($request, $consumer, $token); // Rev A change $verifier = $request->getParameter('oauth_verifier'); $new_token = $this->data_store->newAccessToken($token, $consumer, $verifier); return $new_token; }
php
{ "resource": "" }
q7293
OAuthServer.getSignatureMethod
train
protected function getSignatureMethod(&$request) { $signature_method = @$request->getParameter("oauth_signature_method"); if (!$signature_method) { // According to chapter 7 ("Accessing Protected Ressources") the signature-method // parameter is required, and we can't just fallback to PLAINTEXT throw new OAuthException('No signature method parameter. This parameter is required'); } if (!in_array($signature_method, array_keys($this->signature_methods)) ) { throw new OAuthException( "Signature method '$signature_method' not supported " . "try one of the following: " . implode(", ", array_keys($this->signature_methods)) ); } return $this->signature_methods[ $signature_method ]; }
php
{ "resource": "" }
q7294
OAuthServer.getConsumer
train
protected function getConsumer(&$request) { $consumer_key = @$request->getParameter("oauth_consumer_key"); if (!$consumer_key) { throw new OAuthException("Invalid consumer key"); } $consumer = $this->data_store->lookupConsumer($consumer_key); if (!$consumer) { throw new OAuthException("Invalid consumer"); } return $consumer; }
php
{ "resource": "" }
q7295
OAuthServer.getToken
train
protected function getToken(&$request, $consumer, $token_type = "access") { $token_field = @$request->getParameter('oauth_token'); $token = $this->data_store->lookupToken( $consumer, $token_type, $token_field ); if (!$token) { throw new OAuthException("Invalid $token_type token: $token_field"); } return $token; }
php
{ "resource": "" }
q7296
OAuthServer.checkNonce
train
protected function checkNonce($consumer, $token, $nonce, $timestamp) { if (!$nonce) { throw new OAuthException( 'Missing nonce parameter. The parameter is required' ); } // verify that the nonce is uniqueish $found = $this->data_store->lookupNonce( $consumer, $token, $nonce, $timestamp ); if ($found) { throw new OAuthException("Nonce already used: $nonce"); } }
php
{ "resource": "" }
q7297
Date.convert_to_date_time
train
protected function convert_to_date_time( $value ) { if ( $value instanceof \DateTimeInterface ) { return $value; } switch ( gettype( $value ) ) { case 'string' : return $this->convert_string( $value ); case 'integer' : return $this->convert_integer( $value ); case 'double' : return $this->convert_double( $value ); case 'array' : return $this->convert_array( $value ); } $this->error_code = Error\ErrorLoggerInterface::INVALID_TYPE_NON_DATE; return FALSE; }
php
{ "resource": "" }
q7298
Date.convert_string
train
protected function convert_string( $value ) { $format = $this->input_data[ 'format' ]; $date = \DateTime::createFromFormat( $format, $value ); // Invalid dates can show up as warnings (ie. "2007-02-99") and still return a DateTime object. $errors = \DateTime::getLastErrors(); if ( $errors[ 'warning_count' ] > 0 ) { $this->error_code = Error\ErrorLoggerInterface::INVALID_DATE_FORMAT; return FALSE; } return $date; }
php
{ "resource": "" }
q7299
DiagramUML.getStereoType
train
public function getStereoType(\DOMElement $diaObject) { $xpath = $diaObject->getNodePath() . '/dia:attribute[@name="stereotype"]/dia:string'; $nodeList = $this->engine->query($xpath); if ($nodeList->length == 1) { $stereoType = str_replace('#', '', $nodeList->item(0)->nodeValue); return $stereoType; } return false; }
php
{ "resource": "" }