_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q250100 | ThemeAssetsInstallCommand._hardCopy | validation | private function _hardCopy(string $originDir, string $targetDir): string
{
$this->filesystem->mkdir($targetDir, 0777);
// We use a custom iterator to ignore VCS files
$this->filesystem->mirror($originDir, $targetDir, Finder::create()->ignoreDotFiles(false)->in($originDir));
return AssetsInstallCommand::METHOD_COPY;
} | php | {
"resource": ""
} |
q250101 | BlogPost.onBeforePublish | validation | public function onBeforePublish() {
if ($this->dbObject('PublishDate')->InPast() && !$this->isPublished()) {
$this->setCastedField("PublishDate", time());
$this->write();
}
} | php | {
"resource": ""
} |
q250102 | BlogPost.canView | validation | public function canView($member = null) {
if(!parent::canView($member)) return false;
if($this->PublishDate) {
$publishDate = $this->dbObject("PublishDate");
if($publishDate->InFuture() && !Permission::checkMember($member, "VIEW_DRAFT_CONTENT")) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q250103 | BlogPost.getYearlyArchiveLink | validation | public function getYearlyArchiveLink() {
$date = $this->dbObject("PublishDate");
return Controller::join_links($this->Parent()->Link("archive"), $date->format("Y"));
} | php | {
"resource": ""
} |
q250104 | GridFieldAddByDBField.getHTMLFragments | validation | public function getHTMLFragments($gridField) {
$dataClass = $gridField->getList()->dataClass();
$obj = singleton($dataClass);
if(!$obj->canCreate()) return "";
$dbField = $this->getDataObjectField();
$textField = TextField::create(
"gridfieldaddbydbfield[" . $obj->ClassName . "][" . Convert::raw2htmlatt($dbField) . "]"
)->setAttribute("placeholder", $obj->fieldLabel($dbField))
->addExtraClass("no-change-track");
$addAction = new GridField_FormAction($gridField,
'add',
_t('GridFieldAddByDBField.Add',
"Add {name}", "Add button text",
array("name" => $obj->i18n_singular_name())
),
'add',
'add'
);
$addAction->setAttribute('data-icon', 'add');
// Start thinking about rending this back to the GF
$forTemplate = new ArrayData(array());
$forTemplate->Fields = new ArrayList();
$forTemplate->Fields->push($textField);
$forTemplate->Fields->push($addAction);
return array(
$this->targetFragment => $forTemplate->renderWith("GridFieldAddByDBField")
);
} | php | {
"resource": ""
} |
q250105 | BlogPostFilter.augmentSQL | validation | public function augmentSQL(SQLQuery &$query) {
$stage = Versioned::current_stage();
if($stage == 'Live' || !Permission::check("VIEW_DRAFT_CONTENT")) {
$query->addWhere("PublishDate < '" . Convert::raw2sql(SS_Datetime::now()) . "'");
}
} | php | {
"resource": ""
} |
q250106 | Runner.run | validation | public function run(PayloadInterface $payload)
{
$tasks = $this->getTaskCollection()->getTasks();
$tasksCount = $tasks->count();
if (0 === $tasksCount) {
throw new LogicException('Can\'t invoke task run. Empty task collection set.');
}
$this->log(LogLevel::INFO, sprintf('Starting runner with %s tasks ready for execution.', $tasksCount));
$this->dispatch('runner.start', null, $payload);
foreach ($tasks as $task) {
try {
/** @var TaskInterface $task */
$task->setPayload($payload);
$this->runTask($task, $payload);
} catch (\Exception $e) {
$this->logTask(
$task,
LogLevel::ERROR,
sprintf('An exception was thrown. Message: %s', $e->getMessage())
);
$this->dispatch('runner.failure', null, null, null, $e);
throw new RunFailedException(
'Complete run failed: ' . $e->getMessage(),
$e->getCode(),
$e
);
}
}
$this->log(LogLevel::INFO, 'All tasks were processed.');
$this->log(LogLevel::INFO, 'Calling attached runners.');
$this->notify($payload);
$this->log(LogLevel::INFO, 'Execution successful.');
$this->dispatch('runner.success', null, $payload);
return $payload;
} | php | {
"resource": ""
} |
q250107 | Runner.runTask | validation | private function runTask(TaskInterface $task, PayloadInterface $payload)
{
$this->logTask($task, LogLevel::INFO, 'Starting execution.');
try {
if (!$task->unless()) {
$this->dispatch('runner.task.unless', $task, $payload);
$this->logTask($task, LogLevel::INFO, 'Skipping because unless() returned boolean false.');
return;
}
$this->dispatch('runner.task.start', $task, $payload);
$task->setUp();
$exitCode = (int)$task->run($payload) ?: 0;
$task->tearDown();
if ($task->isFailOnError() && $exitCode !== 0) {
throw new FailException(
sprintf(
'Task: %s failed with exit code %s',
get_class($task),
$exitCode
)
);
}
$message = sprintf('Task exited with status code %s', $exitCode);
if ($exitCode === 0) {
$this->logTask($task, LogLevel::INFO, $message);
} else {
$this->logTask($task, LogLevel::WARNING, $message);
}
$this->dispatch('runner.task.success', $task, $payload, $exitCode);
$task->markAsSuccessfullyExecuted();
} catch (SkipException $e) {
$this->logTask($task, LogLevel::INFO, 'Skipping.');
$this->dispatch('runner.task.skip', $task, $payload);
} catch (RetryException $e) {
$this->logTask($task, LogLevel::NOTICE, 'Retry thrown. Starting again.');
$this->dispatch('runner.task.retry', $task, $payload);
if (!$task->getMaxRetries()) {
throw new LogicException('A retry exception was thrown, but no retries instance was set.');
}
$task->getMaxRetries()->increase();
$this->runTask($task, $payload);
return;
} catch (FailException $e) {
$this->logTask(
$task,
LogLevel::WARNING,
sprintf(
'Failure thrown. Given message: %s',
$e->getMessage()
)
);
$exitCode = $e->getCode();
if (is_int($exitCode)) {
$this->dispatch('runner.task.failure', $task, $payload, $exitCode);
} else {
$this->dispatch('runner.task.failure', $task, $payload);
}
throw $e;
}
$this->logTask($task, LogLevel::INFO, 'Execution successful.');
} | php | {
"resource": ""
} |
q250108 | Runner.logTask | validation | protected function logTask(TaskInterface $task, $level, $message, array $context = array())
{
$class = get_class($task);
$message = sprintf('Task: %s. ', $class) . $message;
$this->log($level, $message, $context);
} | php | {
"resource": ""
} |
q250109 | Runner.notify | validation | public function notify(PayloadInterface $payload)
{
foreach ($this->runners as $runner) {
/** @var Runner $runner */
$runner->run($payload);
}
return $this;
} | php | {
"resource": ""
} |
q250110 | Runner.attach | validation | public function attach(Runner $runner)
{
if ($this->runners->contains($runner)) {
throw new LogicException('Can\'t attach already attached runner.');
}
$this->runners->attach($runner);
return $this;
} | php | {
"resource": ""
} |
q250111 | Runner.detach | validation | public function detach(Runner $runner)
{
if (!$this->runners->contains($runner)) {
throw new LogicException('Can\'t detach not attached runner.');
}
$this->runners->detach($runner);
return $this;
} | php | {
"resource": ""
} |
q250112 | Runner.on | validation | public function on($eventName, callable $callable)
{
\Assert\that($eventName)->string()->notEmpty();
$this->eventDispatcher->addListener($eventName, $callable);
return $this;
} | php | {
"resource": ""
} |
q250113 | Mail.buildAttachmentPart | validation | private function buildAttachmentPart() {
if (count($this->attachments) > 0) {
$attachment_part = '';
foreach ($this->attachments as $attachment) {
$file_str = chunk_split(base64_encode(file_get_contents($attachment)));
$attachment_part .= "--MIME_BOUNDRY\nContent-Type: ".$this->getMimeType($attachment)."; name=".basename($attachment)."\nContent-disposition: attachment\nContent-Transfer-Encoding: base64\n\n{$file_str}\n\n";
}
return $attachment_part;
}
} | php | {
"resource": ""
} |
q250114 | Mail.buildHeaders | validation | private function buildHeaders($required_headers = []) {
$build_headers = array_merge($this->headers, $required_headers);
$headers = [];
foreach ($build_headers as $name => $value) {
$headers[] = "{$name}: {$value}";
}
return implode("\r\n", $headers)."\nThis is a multi-part message in MIME format.\n";
} | php | {
"resource": ""
} |
q250115 | Mail.addAttachment | validation | public function addAttachment($attachment) {
if (!file_exists($attachment)) {
pines_error('Invalid attachment.');
return false;
}
$this->attachments[] = $attachment;
return true;
} | php | {
"resource": ""
} |
q250116 | Mail.getMimeType | validation | public function getMimeType($attachment) {
$attachment = explode('.', basename($attachment));
if (!isset($this->mimeTypes[strtolower($attachment[count($attachment) - 1])])) {
pines_error('MIME Type not found.');
return null;
}
return $this->mimeTypes[strtolower($attachment[count($attachment) - 1])];
} | php | {
"resource": ""
} |
q250117 | Mail.send | validation | public function send() {
// First verify values.
if (!preg_match('/^.+@.+$/', $this->sender)) {
return false;
}
if (!preg_match('/^.+@.+$/', $this->recipient)) {
return false;
}
if (!$this->subject || strlen($this->subject) > 255) {
return false;
}
// Headers that must be in the sent message.
$required_headers = [];
// Are we in testing mode?
if (Mail::$config['testing_mode']) {
// If the testing email is empty, just return true.
if (empty(Mail::$config['testing_email'])) {
return true;
}
// The testing email isn't empty, so replace stuff now.
// Save the original to, cc, and bcc in additional headers.
$required_headers['X-Testing-Original-To'] = $this->recipient;
foreach ($this->headers as $name => $value) {
switch (strtolower($name)) {
case 'cc':
$this->headers['X-Testing-Original-Cc'] = $value;
$required_headers[$name] = '';
break;
case 'bcc':
$this->headers['X-Testing-Original-Bcc'] = $value;
$required_headers[$name] = '';
break;
}
}
$to = Mail::$config['testing_email'];
$subject = '*Test* '.$this->subject;
} else {
$to = $this->recipient;
$subject = $this->subject;
}
// Add from headers.
$required_headers['From'] = $this->sender;
$required_headers['Return-Path'] = $this->sender;
$required_headers['Reply-To'] = $this->sender;
$required_headers['X-Sender'] = $this->sender;
$headers = $this->buildHeaders($required_headers);
$message = $this->buildTextPart().$this->buildAttachmentPart()."--MIME_BOUNDRY--\n";
// Now send the mail.
return mail($to, $subject, $message, $headers, Mail::$config['additional_parameters']);
} | php | {
"resource": ""
} |
q250118 | Mail.formatDate | validation | public static function formatDate($timestamp, $type = 'full_sort', $format = '', $timezone = null) {
// Determine the format to use.
switch ($type) {
case 'date_sort':
$format = 'Y-m-d';
break;
case 'date_long':
$format = 'l, F j, Y';
break;
case 'date_med':
$format = 'j M Y';
break;
case 'date_short':
$format = 'n/d/Y';
break;
case 'time_sort':
$format = 'H:i T';
break;
case 'time_long':
$format = 'g:i:s A T';
break;
case 'time_med':
$format = 'g:i:s A';
break;
case 'time_short':
$format = 'g:i A';
break;
case 'full_sort':
$format = 'Y-m-d H:i T';
break;
case 'full_long':
$format = 'l, F j, Y g:i A T';
break;
case 'full_med':
$format = 'j M Y g:i A T';
break;
case 'full_short':
$format = 'n/d/Y g:i A T';
break;
case 'custom':
default:
break;
}
// Create a date object from the timestamp.
try {
$date = new \DateTime(gmdate('c', (int) $timestamp));
if (isset($timezone)) {
if (!is_object($timezone)) {
$timezone = new \DateTimeZone($timezone);
}
$date->setTimezone($timezone);
} else {
$date->setTimezone(new \DateTimeZone(date_default_timezone_get()));
}
} catch (\Exception $e) {
throw new \Exception("Error formatting date: $e");
}
return $date->format($format);
} | php | {
"resource": ""
} |
q250119 | UnixEnvironment.safeSendSignal | validation | private function safeSendSignal($process, string $signal, int $mappedSignal): void
{
if (true !== proc_terminate($process, $mappedSignal)) {
throw new CommandExecutionException(
'Call to proc_terminate with signal "' . $signal . '" failed for unknown reason.'
);
}
} | php | {
"resource": ""
} |
q250120 | UnixEnvironment.isValidHomeDirectory | validation | private function isValidHomeDirectory(string $path): bool
{
$valid = false;
if ('~/' === substr($path, 0, 2)) {
$valid = $this->isValidFullPath(
$this->expandHomeDirectory($path)
);
}
return $valid;
} | php | {
"resource": ""
} |
q250121 | UnixEnvironment.isValidFullPath | validation | private function isValidFullPath(string $path): bool
{
$valid = false;
if ('/' === substr($path, 0, 1) && is_executable($path)) {
$valid = true;
}
return $valid;
} | php | {
"resource": ""
} |
q250122 | UnixEnvironment.isValidRelativePath | validation | private function isValidRelativePath(string $relativePath, string $cwd): bool
{
$valid = false;
if ('./' === substr($relativePath, 0, 2)) {
$tmpPath = $cwd . DIRECTORY_SEPARATOR . substr($relativePath, 2, strlen($relativePath));
$valid = $this->isValidFullPath($tmpPath);
}
return $valid;
} | php | {
"resource": ""
} |
q250123 | UnixEnvironment.isValidGlobalCommand | validation | private function isValidGlobalCommand(string $command): bool
{
$valid = false;
if (strlen($command)) {
// Check for command in path list
foreach ($this->paths as $pathDir) {
$tmpPath = $pathDir . DIRECTORY_SEPARATOR . $command;
if ($this->isValidFullPath($tmpPath)) {
$valid = true;
break;
}
}
}
return $valid;
} | php | {
"resource": ""
} |
q250124 | Ups.getQuote | validation | public function getQuote($credentials, $options)
{
// Load the credentials
$this->loadCredentials($credentials);
// Run the options array through the default check
$options = $this->checkDefaults($options);
$residential_flag = ($this->commercial_rates) ? '' : '<ResidentialAddressIndicator/>';
$negotiated_flag = ($this->negotiated_rates) ? '<RateInformation><NegotiatedRatesIndicator/></RateInformation>' : '';
$this->xml = '<?xml version="1.0"?>
<AccessRequest xml:lang="en-US">
<AccessLicenseNumber>' . $this->access_key . '</AccessLicenseNumber>
<UserId>' . $this->username . '</UserId>
<Password>' . $this->password . '</Password>
</AccessRequest>
<?xml version="1.0"?>
<RatingServiceSelectionRequest xml:lang="en-US">
<Request>
<TransactionReference>
<CustomerContext>Rate Request</CustomerContext>
<XpciVersion>1.0001</XpciVersion>
</TransactionReference>
<RequestAction>Rate</RequestAction>
<RequestOption>' . $options['request_option'] . '</RequestOption>
</Request>
<PickupType>
<Code>01</Code>
</PickupType>
<Shipment>
<Shipper>
<ShipperNumber>' . $this->account_number . '</ShipperNumber>
<Address>
<PostalCode>' . $options['from_zip'] . '</PostalCode>
<StateProvinceCode>' . $options['from_state'] . '</StateProvinceCode>
<CountryCode>' . $options['from_country'] . '</CountryCode>
</Address>
</Shipper>
<ShipTo>
<Address>
<PostalCode>' . $options['to_zip'] . '</PostalCode>
<StateProvinceCode>' . $options['to_state'] . '</StateProvinceCode>
<CountryCode>' . $options['to_country'] . '</CountryCode>
' . $residential_flag .'
</Address>
</ShipTo>
<Service>
<Code>' . $options['service_type'] . '</Code>
<Description>Package</Description>
</Service>
<ShipmentServiceOptions/>
' . $this->buildPackages($options['packages'], $options['weight'], $options['measurement']) . $negotiated_flag . '
</Shipment>
</RatingServiceSelectionRequest>';
return $this->send();
} | php | {
"resource": ""
} |
q250125 | Ups.buildPackages | validation | private function buildPackages($number, $weight, $measurement = 'LBS')
{
$packages = array();
if($number > 1)
{
$individual_weight = $weight / $number;
for($i = 0; $i < $number; $i++)
{
$packages[] = '<Package>
<PackagingType>
<Code>02</Code>
</PackagingType>
<PackageWeight>
<UnitOfMeasurement>
<Code>' . $measurement . '</Code>
</UnitOfMeasurement>
<Weight>' . $individual_weight . '</Weight>
</PackageWeight>
</Package>';
}
}
else
{
$packages[] = '<Package>
<PackagingType>
<Code>02</Code>
</PackagingType>
<PackageWeight>
<UnitOfMeasurement>
<Code>' . $measurement . '</Code>
</UnitOfMeasurement>
<Weight>' . $weight . '</Weight>
</PackageWeight>
</Package>';
}
return implode('', $packages);
} | php | {
"resource": ""
} |
q250126 | Ups.send | validation | private function send()
{
$ch = curl_init($this->url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->xml);
$result = curl_exec($ch);
$this->xml = strstr($result, '<?');
$this->xml_result = new \SimpleXMLElement($this->xml);
return $this->parseResult();
} | php | {
"resource": ""
} |
q250127 | Ups.parseResult | validation | private function parseResult()
{
if($this->xml_result->Response->ResponseStatusCode != '1')
{
return array(
'Error' => array(
'ErrorSeverity' => "{$this->xml_result->Response->Error->ErrorSeverity}",
'ErrorCode' => "{$this->xml_result->Response->Error->ErrorCode}",
'ErrorDescription' => "{$this->xml_result->Response->Error->ErrorDescription}"
)
);
return $this->xml_result;
}
$simplified = array();
$shipping_choices = array();
foreach($this->xml_result->RatedShipment as $service)
{
$simplified[] = '{' . $service->TotalCharges->MonetaryValue . '}';
}
foreach($simplified as $key => $value)
{
$service = $this->xml_result->RatedShipment[$key]->children();
if($this->negotiated_rates && $service->NegotiatedRates->NetSummaryCharges->GrandTotal->MonetaryValue)
{
$rate = number_format((double)($service->NegotiatedRates->NetSummaryCharges->GrandTotal->MonetaryValue), 2);
}
else
{
$rate = number_format((double)($service->TransportationCharges->MonetaryValue), 2);
}
$shipping_choices["{$service->Service->Code}"] = array(
'service' => $this->shipperCodes("{$service->Service->Code}"),
'rate' => "{$rate}"
);
}
return $shipping_choices;
} | php | {
"resource": ""
} |
q250128 | Ups.checkDefaults | validation | private function checkDefaults($options)
{
if(!isset($options['request_option']))
{
$options['request_option'] = 'Shop';
}
if(!isset($options['from_country']))
{
$options['from_country'] = 'US';
}
if(!isset($options['to_country']))
{
$options['to_country'] = 'US';
}
if(!isset($options['service_type']))
{
$options['service_type'] = '03';
}
if(!isset($options['from_state']))
{
$options['from_state'] = '';
}
if(!isset($options['to_state']))
{
$options['to_state'] = '';
}
$this->commercial_rates = (isset($options['commercial']) && $options['commercial']) ? true : false;
$this->negotiated_rates = (isset($options['negotiated_rates']) && $options['negotiated_rates']) ? true : false;
return $options;
} | php | {
"resource": ""
} |
q250129 | Routerunner.process | validation | public function process(ServerRequestInterface $request, RequestHandlerInterface $requestHandler): ResponseInterface
{
$this->container->set(ServerRequestInterface::class, $request);
$result = $this->dispatch($this->route($request));
if ($result instanceof ResponseInterface) {
return $result;
}
return $response = (new Response())
->withProtocolVersion('1.1')
->withBody(\GuzzleHttp\Psr7\stream_for($result));
} | php | {
"resource": ""
} |
q250130 | Container.set | validation | public function set($key, $value)
{
if (is_callable($value)) {
$this->registerFactory($key, $value, false);
} else {
$this->sm->setService($key, $value);
}
} | php | {
"resource": ""
} |
q250131 | Container.get | validation | public function get($key, $default = null)
{
return $this->has($key) ? $this->sm->get($key) : $default;
} | php | {
"resource": ""
} |
q250132 | Container.singleton | validation | public function singleton($key, $value)
{
if (is_callable($value)) {
$this->registerFactory($key, $value);
} else {
$this->sm->setService($key, $value);
}
} | php | {
"resource": ""
} |
q250133 | Container.consumeSlimContainer | validation | public function consumeSlimContainer(Set $container)
{
foreach ($container as $key => $value) {
if ($value instanceof \Closure) {
// Try to determin if this belongs to a singleton or not
$refFunc = new \ReflectionFunction($value);
// Slim singletons have a static 'object' variable
$shared = in_array('object', $refFunc->getStaticVariables());
$this->registerFactory($key, $value, $shared);
} elseif (is_callable($value)) {
// Register as non-shared factories any other callable
$this->registerFactory($key, $value, false);
} else {
$this->sm->setService($key, $value);
}
}
} | php | {
"resource": ""
} |
q250134 | Container.registerFactory | validation | protected function registerFactory($key, callable $callable, $shared = true)
{
$this->sm->setFactory($key, new CallbackWrapper($this, $callable));
$this->sm->setShared($key, $shared);
} | php | {
"resource": ""
} |
q250135 | CI_Base_Model._initialize_schema | validation | protected function _initialize_schema()
{
$this->set_database($this->_database_group);
$this->_fetch_table();
$this->_fetch_primary_key();
if($this->primary_key == null && $this->is_base_model_instance()) {
return;
}
$this->_fields = $this->get_fields();
$this->_guess_is_soft_deletable();
$this->_guess_is_blamable();
$this->_guess_is_timestampable();
} | php | {
"resource": ""
} |
q250136 | CI_Base_Model._initialize_event_listeners | validation | protected function _initialize_event_listeners()
{
foreach($this->event_listeners as $event_listener => $e)
{
if(isset($this->$event_listener) && !empty($this->$event_listener)){
foreach($this->$event_listener as $event){
$this->subscribe($event_listener, $event);
}
}
}
$this->subscribe('before_update', 'protect_attributes', TRUE);
} | php | {
"resource": ""
} |
q250137 | CI_Base_Model.get_many_by | validation | public function get_many_by()
{
$where = func_get_args();
$this->apply_soft_delete_filter();
$this->_set_where($where);
return $this->get_all();
} | php | {
"resource": ""
} |
q250138 | CI_Base_Model.insert_many | validation | public function insert_many($data, $insert_individual = false)
{
if($insert_individual){
return $this->_insert_individual($data);
}
return $this->_insert_batch($data);
} | php | {
"resource": ""
} |
q250139 | CI_Base_Model.update | validation | public function update($primary_value, $data)
{
$data = $this->_do_pre_update($data);
if ($data !== FALSE)
{
$result = $this->_database->where($this->primary_key, $primary_value)
->set($data)
->update($this->_table);
$this->trigger('after_update', array($data, $result));
return $result;
}
else
{
return FALSE;
}
} | php | {
"resource": ""
} |
q250140 | CI_Base_Model.update_many | validation | public function update_many($primary_values, $data)
{
$data = $this->_do_pre_update($data);
if ($data !== FALSE)
{
$result = $this->_database->where_in($this->primary_key, $primary_values)
->set($data)
->update($this->_table);
$this->trigger('after_update', array($data, $result));
return $result;
}
return FALSE;
} | php | {
"resource": ""
} |
q250141 | CI_Base_Model.update_by | validation | public function update_by()
{
$args = func_get_args();
$data = array_pop($args);
$data = $this->_do_pre_update($data);
if ($data !== FALSE)
{
$this->_set_where($args);
return $this->_update($data);
}
return FALSE;
} | php | {
"resource": ""
} |
q250142 | CI_Base_Model.update_batch | validation | public function update_batch($data, $where_key)
{
$_data = array();
foreach ($data as $key => $row) {
if (false !== $row = $this->_do_pre_update($row)) {
$_data[$key] = $row;
}
}
return $this->_database->update_batch($this->_table, $_data, $where_key);
} | php | {
"resource": ""
} |
q250143 | CI_Base_Model.delete | validation | public function delete($id, $time = 'NOW()')
{
$this->_database->where($this->primary_key, $id);
return $this->_delete($id, $time);
} | php | {
"resource": ""
} |
q250144 | CI_Base_Model.delete_by_at | validation | public function delete_by_at($condition, $time)
{
$this->prevent_if_not_soft_deletable();
$this->_set_where($condition);
return $this->_delete($condition, $time);
} | php | {
"resource": ""
} |
q250145 | CI_Base_Model.delete_many | validation | public function delete_many($primary_values, $time='NOW()')
{
$this->_database->where_in($this->primary_key, $primary_values);
return $this->_delete($primary_values, $time);
} | php | {
"resource": ""
} |
q250146 | CI_Base_Model.dropdown | validation | function dropdown()
{
$args = func_get_args();
if(count($args) == 2)
{
list($key, $value) = $args;
}
else
{
$key = $this->primary_key;
$value = $args[0];
}
$this->trigger('before_dropdown', array( $key, $value ));
$this->apply_soft_delete_filter();
$result = $this->_database->select(array($key, $value))
->get($this->_table)
->result();
$options = array();
foreach ($result as $row)
{
$options[$row->{$key}] = $row->{$value};
}
$options = $this->trigger('after_dropdown', $options);
return $options;
} | php | {
"resource": ""
} |
q250147 | CI_Base_Model.count_by | validation | public function count_by()
{
$where = func_get_args();
$this->_set_where($where);
$this->apply_soft_delete_filter();
return $this->_database->count_all_results($this->_table);
} | php | {
"resource": ""
} |
q250148 | CI_Base_Model.get_next_id | validation | public function get_next_id()
{
return (int) $this->_database->select('AUTO_INCREMENT')
->from('information_schema.TABLES')
->where('TABLE_NAME', $this->_database->dbprefix($this->get_table()))
->where('TABLE_SCHEMA', $this->_database->database)->get()->row()->AUTO_INCREMENT;
} | php | {
"resource": ""
} |
q250149 | CI_Base_Model.created_at | validation | public function created_at($row)
{
if (is_object($row))
{
$row->{$this->created_at_key} = date('Y-m-d H:i:s');
}
else
{
$row[$this->created_at_key] = date('Y-m-d H:i:s');
}
return $row;
} | php | {
"resource": ""
} |
q250150 | CI_Base_Model.serialize_row | validation | public function serialize_row($row)
{
foreach ($this->callback_parameters as $column)
{
$row[$column] = serialize($row[$column]);
}
return $row;
} | php | {
"resource": ""
} |
q250151 | CI_Base_Model.getCallableFunction | validation | private function getCallableFunction($method)
{
if (is_callable($method)) {
return $method;
}
if (is_string($method) && is_callable(array($this, $method))) {
return array($this, $method);
}
return FALSE;
} | php | {
"resource": ""
} |
q250152 | CI_Base_Model.apply_soft_delete_filter | validation | protected function apply_soft_delete_filter()
{
if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE) {
if($this->_temporary_only_deleted)
{
$where = "`{$this->deleted_at_key}` <= NOW()";
}
else
{
$where = sprintf('(%1$s > NOW() OR %1$s IS NULL OR %1$s = \'0000-00-00 00:00:00\')', $this->deleted_at_key);
}
$this->_database->where($where);
}
} | php | {
"resource": ""
} |
q250153 | CI_Base_Model._fetch_primary_key | validation | protected function _fetch_primary_key()
{
if($this->is_base_model_instance()) {
return;
}
if ($this->primary_key == NULL && $this->_database) {
$this->primary_key = $this->execute_query("SHOW KEYS FROM `" . $this->_database->dbprefix($this->_table) . "` WHERE Key_name = 'PRIMARY'")->row()->Column_name;
}
} | php | {
"resource": ""
} |
q250154 | CI_Base_Model._set_where | validation | protected function _set_where($params)
{
if (count($params) == 1)
{
$this->_database->where($params[0]);
}
else if(count($params) == 2)
{
$this->_database->where($params[0], $params[1]);
}
else if(count($params) == 3)
{
$this->_database->where($params[0], $params[1], $params[2]);
}
else
{
$this->_database->where($params);
}
} | php | {
"resource": ""
} |
q250155 | Base62.decode | validation | public function decode($value, $b = 62)
{
$limit = strlen($value);
$result = strpos($this->base, $value[0]);
for ($i = 1; $i < $limit; $i++) {
$result = $b * $result + strpos($this->base, $value[$i]);
}
return $result;
} | php | {
"resource": ""
} |
q250156 | Base62.encode | validation | public function encode($value, $b = 62)
{
$r = (int) $value % $b;
$result = $this->base[$r];
$q = floor((int) $value / $b);
while ($q) {
$r = $q % $b;
$q = floor($q / $b);
$result = $this->base[$r].$result;
}
return $result;
} | php | {
"resource": ""
} |
q250157 | BibliographicRecord.parseSubjectAddedEntry | validation | public function parseSubjectAddedEntry(QuiteSimpleXmlElement &$node)
{
$out = array('term' => '', 'vocabulary' => null);
$vocabularies = array(
'0' => 'lcsh',
'1' => 'lccsh', // LC subject headings for children's literature
'2' => 'mesh', // Medical Subject Headings
'3' => 'atg', // National Agricultural Library subject authority file (?)
// 4 : unknown
'5' => 'cash', // Canadian Subject Headings
'6' => 'rvm', // Répertoire de vedettes-matière
// 7: Source specified in subfield $2
);
$ind2 = $node->attr('ind2');
$id = $node->text('marc:subfield[@code="0"]');
$out['id'] = empty($id) ? null : $id;
if (isset($vocabularies[$ind2])) {
$out['vocabulary'] = $vocabularies[$ind2];
} elseif ($ind2 == '7') {
$vocab = $node->text('marc:subfield[@code="2"]');
if (!empty($vocab)) {
$out['vocabulary'] = $vocab;
}
} elseif ($ind2 == '4') {
$this->parseAuthority($node->text('marc:subfield[@code="0"]'), $out);
}
$out['parts'] = array();
$subdivtypes = array(
'v' => 'form',
'x' => 'general',
'y' => 'chronologic',
'z' => 'geographic',
);
foreach ($node->all('marc:subfield') as $subdiv) {
$code = $subdiv->attr('code');
if (in_array($code, array_keys($subdivtypes))) {
$subdiv = trim($subdiv, '.');
$out['parts'][] = array('value' => $subdiv, 'type' => $subdivtypes[$code]);
$out['term'] .= self::$subfieldSeparator . $subdiv;
}
}
return $out;
} | php | {
"resource": ""
} |
q250158 | SemaphoreClient.message | validation | public function message( $messageId )
{
$params = [
'query' => [
'apikey' => $this->apikey,
]
];
$response = $this->client->get( 'messages/' . $messageId, $params );
return $response->getBody();
} | php | {
"resource": ""
} |
q250159 | SemaphoreClient.messages | validation | public function messages( $options )
{
$params = [
'query' => [
'apikey' => $this->apikey,
'limit' => 100,
'page' => 1
]
];
//Set optional parameters
if( array_key_exists( 'limit', $options ) )
{
$params['query']['limit'] = $options['limit'];
}
if( array_key_exists( 'page', $options ) )
{
$params['query']['page'] = $options['page'];
}
if( array_key_exists( 'startDate', $options ) )
{
$params['query']['startDate'] = $options['startDate'];
}
if( array_key_exists( 'endDate', $options ) )
{
$params['query']['endDate'] = $options['endDate'];
}
if( array_key_exists( 'status', $options ) )
{
$params['query']['status'] = $options['status'];
}
if( array_key_exists( 'network', $options ) )
{
$params['query']['network'] = $options['network'];
}
if( array_key_exists( 'sendername', $options ) )
{
$params['query']['sendername'] = $options['sendername'];
}
$response = $this->client->get( 'messages', $params );
return $response->getBody();
} | php | {
"resource": ""
} |
q250160 | Record.parseAuthority | validation | protected function parseAuthority($authority, &$out)
{
if (!empty($authority)) {
$out['id'] = $authority;
if (preg_match('/\((.*?)\)(.*)/', $authority, $matches)) {
// As used by at least OCLC and Bibsys
$out['vocabulary'] = $matches[1];
$out['id'] = $matches[2];
}
}
} | php | {
"resource": ""
} |
q250161 | Record.parseRelator | validation | protected function parseRelator(&$node, &$out, $default = null)
{
$relterm = $node->text('marc:subfield[@code="e"]');
$relcode = $node->text('marc:subfield[@code="4"]');
if (!empty($relcode)) {
$out['role'] = $relcode;
} elseif (!empty($relterm)) {
$out['role'] = $relterm;
} elseif (!is_null($default)) {
$out['role'] = $default;
}
} | php | {
"resource": ""
} |
q250162 | Record.parseRelationship | validation | protected function parseRelationship($node)
{
$rel = array();
$x = preg_replace('/\(.*?\)/', '', $node->text('marc:subfield[@code="w"]'));
if (!empty($x)) {
$rel['id'] = $x;
}
$x = $node->text('marc:subfield[@code="t"]');
if (!empty($x)) {
$rel['title'] = $x;
}
$x = $node->text('marc:subfield[@code="g"]');
if (!empty($x)) {
$rel['parts'] = $x;
}
$x = $node->text('marc:subfield[@code="x"]');
if (!empty($x)) {
$rel['issn'] = $x;
}
$x = $node->text('marc:subfield[@code="z"]');
if (!empty($x)) {
$rel['isbn'] = $x;
}
return $rel;
} | php | {
"resource": ""
} |
q250163 | Patch.apply | validation | public function apply($targetDocument, $patchDocument)
{
if ($targetDocument === null || !is_object($targetDocument) || is_array($targetDocument)) {
$targetDocument = new \stdClass();
}
if ($patchDocument === null || !is_object($patchDocument) || is_array($patchDocument)) {
return $patchDocument;
}
foreach ($patchDocument as $key => $value) {
if ($value === null) {
unset($targetDocument->$key);
} else {
if (!isset($targetDocument->$key)) {
$targetDocument->$key = null;
}
$targetDocument->$key = $this->apply(
$targetDocument->$key,
$value
);
}
}
return $targetDocument;
} | php | {
"resource": ""
} |
q250164 | Patch.generate | validation | public function generate($sourceDocument, $targetDocument)
{
if ($sourceDocument === null || $targetDocument === null) {
return $targetDocument;
}
if ($sourceDocument == new \stdClass()) {
return null;
}
if (is_array($sourceDocument)) {
if ($sourceDocument !== $targetDocument) {
return $targetDocument;
}
return null;
}
$patchDocument = new \stdClass();
$sourceDocumentVars = get_object_vars($sourceDocument);
$targetDocumentVars = get_object_vars($targetDocument);
foreach ($targetDocumentVars as $var => $value) {
if (!in_array($var, array_keys($sourceDocumentVars))
|| !in_array($value, array_values($sourceDocumentVars))
) {
$patchDocument->$var = $value;
}
}
foreach ($sourceDocumentVars as $var => $value) {
if ($targetDocumentVars === []) {
$patchDocument->$var = null;
break;
}
if (is_object($value)) {
if ($sourceDocument->$var !== null && is_object($sourceDocument->$var)) {
$subPatch = $this->generate($sourceDocument->$var, $targetDocument->$var);
if ($subPatch !== null) {
$patchDocument->$var = $subPatch;
}
}
} elseif (!in_array($var, array_keys($targetDocumentVars))
|| !in_array($value, array_values($targetDocumentVars))) {
$sourceDocument->$var = null;
if (!in_array($var, array_keys($targetDocumentVars))) {
$patchDocument->$var = null;
}
}
}
if (count(get_object_vars($patchDocument)) > 0) {
return $patchDocument;
}
return null;
} | php | {
"resource": ""
} |
q250165 | Patch.merge | validation | public function merge($patchDocument1, $patchDocument2)
{
if ($patchDocument1 === null || $patchDocument2 === null
|| !is_object($patchDocument1) || !is_object($patchDocument2)
) {
return $patchDocument2;
}
$patchDocument = $patchDocument1;
$patchDocument1Vars = get_object_vars($patchDocument1);
$patchDocument2Vars = get_object_vars($patchDocument2);
foreach ($patchDocument2Vars as $var => $value) {
if (isset($patchDocument1Vars[$var])) {
$patchDocument->$var = $this->merge(
$patchDocument1->$var,
$patchDocument2->$var
);
} else {
$patchDocument->$var = $patchDocument2->$var;
}
}
return $patchDocument;
} | php | {
"resource": ""
} |
q250166 | ObjectMapper.mapJson | validation | public function mapJson($json, $targetClass)
{
// Check if the JSON is valid
if (!is_array($data = json_decode($json, true))) {
throw new InvalidJsonException();
}
// Pre initialize the result
$result = null;
// Check if the target object is a collection of type X
if (substr($targetClass, -2) == '[]') {
$result = [];
foreach ($data as $key => $entryData) {
// Map the data recursive
$result[] = $this->mapDataToObject($entryData, substr($targetClass, 0, -2));
}
} else {
// Map the data recursive
$result = $this->mapDataToObject($data, $targetClass);
}
return $result;
} | php | {
"resource": ""
} |
q250167 | ConfigService.fetch | validation | public static function fetch($dir = false)
{
if (false === $dir) {
$dir = getcwd();
}
$config = [];
$files = glob($dir.'/config/*.config.php', GLOB_BRACE);
foreach ($files as $file) {
$config = array_merge($config, (require $file));
}
return $config;
} | php | {
"resource": ""
} |
q250168 | GeneratorFactory.fetch | validation | public function fetch($name)
{
$generator = false;
if (array_key_exists($name, $this->generators)) {
$generator = $this->generators[$name];
}
return $generator;
} | php | {
"resource": ""
} |
q250169 | GeneratorFactory.add | validation | public function add($name, GeneratorInterface $class)
{
if (array_key_exists($name, $this->generators)) {
throw new \InvalidArgumentException('Generator already exists.');
}
$this->generators[$name] = $class;
} | php | {
"resource": ""
} |
q250170 | FontAwesome.stack | validation | public function stack($icons)
{
if (count($icons) !== 2)
{
throw new \InvalidArgumentException('Expecting exactly 2 icons in the stack');
}
$contents = [];
$index = 2;
foreach ($icons as $key => $value)
{
$contents[] = $this->getStackIconElement($key, $value, $index);
--$index;
}
return $this->html->span($contents)->addClass('fa-stack');
} | php | {
"resource": ""
} |
q250171 | FontAwesome.getStackIconElement | validation | protected function getStackIconElement($key, $value, $index)
{
$element = $value;
if (is_string($key))
{
$element = $this->icon($key)->addClass($value);
}
else if (is_string($value))
{
$element = $this->icon($value);
}
if ( !is_a($element, FontAwesomeIcon::class))
{
throw new \InvalidArgumentException('Invalid icon passed to stack');
}
return $element->addClass("fa-stack-{$index}x");
} | php | {
"resource": ""
} |
q250172 | RouteService.addRoute | validation | private function addRoute($method)
{
switch ($method) {
case 'index':
$methodMap = ['GET'];
$realRoute = '$route';
$controllerCallable = $this->controllerLocation.':indexAction';
break;
case 'get':
$methodMap = ['GET'];
$realRoute = '$route/{id}';
$controllerCallable = $this->controllerLocation.':getAction';
break;
case 'post':
$methodMap = ['POST'];
$realRoute = '$route';
$controllerCallable = $this->controllerLocation.':postAction';
break;
case 'put':
$methodMap = ['POST', 'PUT'];
$realRoute = '$route/{id}';
$controllerCallable = $this->controllerLocation.':putAction';
break;
case 'delete':
$methodMap = ['DELETE'];
$realRoute = '$route/{id}';
$controllerCallable = $this->controllerLocation.':deleteAction';
break;
default:
throw new \Exception('Invalid method.'.$method);
break;
}
$methodMap = "['".implode("', '", $methodMap)."']";
$command = strtr($this->template, ['$methodMap' => $methodMap, '$route' => $realRoute, '$controllerCallable' => $controllerCallable]);
// $app->map(['GET'], '/trails', 'EarlyBird\Controllers\TrailsController:index');
// $app->map(['GET'], '/texts/{stage}', 'EarlyBird\Controllers\TrailsController:get');
// $app->map(['POST'], '/trails', 'EarlyBird\Controllers\TrailsController:post');
// $app->map(['POST', 'PUT'], '/trails/{id}', 'EarlyBird\Controllers\TrailsController:put');
$this->commands[] = $command;
} | php | {
"resource": ""
} |
q250173 | Module.loadDependencies | validation | public function loadDependencies()
{
// load the apis config
$config = ConfigService::fetch(dirname(__DIR__));
// load the app config
$config = array_merge($config, ConfigService::fetch());
$moduleService = new ModuleService;
if (! array_key_exists('slim-api', $config)) {
$config['slim-api'] = [
'modules' => [
'SlimApi\Phinx', //provides migrations
'SlimApi\Mvc' //provides structure
]
];
} else {
// load the target autoloader
require 'vendor/autoload.php';
}
foreach ($config['slim-api']['modules'] as $moduleNamespace) {
$config = array_merge($config, $moduleService->load($moduleNamespace));
}
return $config;
} | php | {
"resource": ""
} |
q250174 | DependencyService.addDependency | validation | private function addDependency($name, $template)
{
$this->commands[] = strtr($template, ['$namespace' => $this->namespaceRoot, '$name' => $name]);
} | php | {
"resource": ""
} |
q250175 | DependencyService.fetch | validation | public function fetch($name)
{
$template = false;
if (array_key_exists($name, $this->templates)) {
$template = $this->templates[$name];
}
return $template;
} | php | {
"resource": ""
} |
q250176 | DependencyService.add | validation | public function add($name, $template)
{
if (array_key_exists($name, $this->templates)) {
throw new \InvalidArgumentException('Template already exists.');
}
$this->templates[$name] = $template;
} | php | {
"resource": ""
} |
q250177 | Changesets.createChangeset | validation | public function createChangeset($changesets=array())
{
$token = $this->oauth->getToken();
// Set parameters.
$parameters = array(
'oauth_token' => $token['key'],
'oauth_token_secret' => $token['secret'],
);
// Set the API base
$base = 'changeset/create';
// Build the request path.
$path = $this->getOption('api.url') . $base;
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="JoomlaOpenStreetMap">';
if (!empty($changesets))
{
// Create Changeset element for every changeset
foreach ($changesets as $tags)
{
$xml .= '<changeset>';
if (!empty($tags))
{
// Create a list of tags for each changeset
foreach ($tags as $key => $value)
{
$xml .= '<tag k="' . $key . '" v="' . $value . '"/>';
}
}
$xml .= '</changeset>';
}
}
$xml .= '</osm>';
$header['Content-Type'] = 'text/xml';
// Send the request.
$response = $this->oauth->oauthRequest($path, 'PUT', $parameters, $xml, $header);
return $response->body;
} | php | {
"resource": ""
} |
q250178 | Changesets.readChangeset | validation | public function readChangeset($id)
{
// Set the API base
$base = 'changeset/' . $id;
// Build the request path.
$path = $this->getOption('api.url') . $base;
// Send the request.
$xmlString = $this->sendRequest($path);
return $xmlString->changeset;
} | php | {
"resource": ""
} |
q250179 | Changesets.updateChangeset | validation | public function updateChangeset($id, $tags = array())
{
$token = $this->oauth->getToken();
// Set parameters.
$parameters = array(
'oauth_token' => $token['key'],
);
// Set the API base
$base = 'changeset/' . $id;
// Build the request path.
$path = $this->getOption('api.url') . $base;
// Create a list of tags to update changeset
$tagList = '';
if (!empty($tags))
{
foreach ($tags as $key => $value)
{
$tagList .= '<tag k="' . $key . '" v="' . $value . '"/>';
}
}
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="JoomlaOpenStreetMap">
<changeset>'
. $tagList .
'</changeset>
</osm>';
$header['Content-Type'] = 'text/xml';
// Send the request.
$response = $this->oauth->oauthRequest($path, 'PUT', $parameters, $xml, $header);
$xmlString = simplexml_load_string($response->body);
return $xmlString->changeset;
} | php | {
"resource": ""
} |
q250180 | Changesets.closeChangeset | validation | public function closeChangeset($id)
{
$token = $this->oauth->getToken();
// Set parameters.
$parameters = array(
'oauth_token' => $token['key'],
);
// Set the API base
$base = 'changeset/' . $id . '/close';
// Build the request path.
$path = $this->getOption('api.url') . $base;
$header['format'] = 'text/xml';
// Send the request.
$this->oauth->oauthRequest($path, 'PUT', $parameters, $header);
} | php | {
"resource": ""
} |
q250181 | Changesets.downloadChangeset | validation | public function downloadChangeset($id)
{
// Set the API base
$base = 'changeset/' . $id . '/download';
// Build the request path.
$path = $this->getOption('api.url') . $base;
// Send the request.
$xmlString = $this->sendRequest($path);
return $xmlString->create;
} | php | {
"resource": ""
} |
q250182 | Changesets.expandBBoxChangeset | validation | public function expandBBoxChangeset($id, $nodes)
{
$token = $this->oauth->getToken();
// Set parameters.
$parameters = array(
'oauth_token' => $token['key'],
);
// Set the API base
$base = 'changeset/' . $id . '/expand_bbox';
// Build the request path.
$path = $this->getOption('api.url') . $base;
// Create a list of tags to update changeset
$nodeList = '';
if (!empty($nodes))
{
foreach ($nodes as $node)
{
$nodeList .= '<node lat="' . $node[0] . '" lon="' . $node[1] . '"/>';
}
}
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="JoomlaOpenStreetMap">
<changeset>'
. $nodeList .
'</changeset>
</osm>';
$header['Content-Type'] = 'text/xml';
// Send the request.
$response = $this->oauth->oauthRequest($path, 'POST', $parameters, $xml, $header);
$xmlString = simplexml_load_string($response->body);
return $xmlString->changeset;
} | php | {
"resource": ""
} |
q250183 | Changesets.queryChangeset | validation | public function queryChangeset($param)
{
// Set the API base
$base = 'changesets/' . $param;
// Build the request path.
$path = $this->getOption('api.url') . $base;
// Send the request.
$xmlString = $this->sendRequest($path);
return $xmlString->osm;
} | php | {
"resource": ""
} |
q250184 | Changesets.diffUploadChangeset | validation | public function diffUploadChangeset($xml, $id)
{
$token = $this->oauth->getToken();
// Set parameters.
$parameters = array(
'oauth_token' => $token['key'],
);
// Set the API base
$base = 'changeset/' . $id . '/upload';
// Build the request path.
$path = $this->getOption('api.url') . $base;
$header['Content-Type'] = 'text/xml';
// Send the request.
$response = $this->oauth->oauthRequest($path, 'POST', $parameters, $xml, $header);
$xmlString = simplexml_load_string($response->body);
return $xmlString->diffResult;
} | php | {
"resource": ""
} |
q250185 | User.getDetails | validation | public function getDetails()
{
$token = $this->oauth->getToken();
// Set parameters.
$parameters = array(
'oauth_token' => $token['key'],
);
// Set the API base
$base = 'user/details';
// Build the request path.
$path = $this->getOption('api.url') . $base;
// Send the request.
$response = $this->oauth->oauthRequest($path, 'GET', $parameters);
return $response->body;
} | php | {
"resource": ""
} |
q250186 | User.replacePreferences | validation | public function replacePreferences($preferences)
{
$token = $this->oauth->getToken();
// Set parameters.
$parameters = array(
'oauth_token' => $token['key'],
);
// Set the API base
$base = 'user/preferences';
// Build the request path.
$path = $this->getOption('api.url') . $base;
// Create a list of preferences
$preferenceList = '';
if (!empty($preferences))
{
foreach ($preferences as $key => $value)
{
$preferenceList .= '<preference k="' . $key . '" v="' . $value . '"/>';
}
}
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="JoomlaOpenStreetMap">
<preferences>'
. $preferenceList .
'</preferences>
</osm>';
$header['Content-Type'] = 'text/xml';
// Send the request.
$response = $this->oauth->oauthRequest($path, 'PUT', $parameters, $xml, $header);
return $response->body;
} | php | {
"resource": ""
} |
q250187 | User.changePreference | validation | public function changePreference($key, $preference)
{
$token = $this->oauth->getToken();
// Set parameters.
$parameters = array(
'oauth_token' => $token['key'],
);
// Set the API base
$base = 'user/preferences/' . $key;
// Build the request path.
$path = $this->getOption('api.url') . $base;
// Send the request.
$response = $this->oauth->oauthRequest($path, 'PUT', $parameters, $preference);
return $response->body;
} | php | {
"resource": ""
} |
q250188 | Gps.uploadTrace | validation | public function uploadTrace($file, $description, $tags, $public, $visibility, $username, $password)
{
// Set parameters.
$parameters = array(
'file' => $file,
'description' => $description,
'tags' => $tags,
'public' => $public,
'visibility' => $visibility,
);
// Set the API base
$base = 'gpx/create';
// Build the request path.
$path = $this->getOption('api.url') . $base;
$header['Content-Type'] = 'multipart/form-data';
$header = array_merge($header, $parameters);
$header = array_merge($header, array('Authorization' => 'Basic ' . base64_encode($username . ':' . $password)));
// Send the request.
return $this->sendRequest($path, 'POST', $header, array());
} | php | {
"resource": ""
} |
q250189 | Gps.downloadTraceMetadetails | validation | public function downloadTraceMetadetails($id, $username, $password)
{
// Set the API base
$base = 'gpx/' . $id . '/details';
// Build the request path.
$path = $this->getOption('api.url') . $base;
// Send the request.
return $this->sendRequest($path, 'GET', array('Authorization' => 'Basic ' . base64_encode($username . ':' . $password)));
} | php | {
"resource": ""
} |
q250190 | RouteMock.constructUrl | validation | function constructUrl(Request $appRequest, Nette\Http\Url $refUrl)
{
return $this->getRouter()->constructUrl($appRequest, $refUrl);
} | php | {
"resource": ""
} |
q250191 | ModulesExtension.addRouters | validation | private function addRouters()
{
$builder = $this->getContainerBuilder();
// Get application router
$router = $builder->getDefinition('router');
// Init collections
$routerFactories = array();
foreach ($builder->findByTag(self::TAG_ROUTER) as $serviceName => $priority) {
// Priority is not defined...
if (is_bool($priority)) {
// ...use default value
$priority = 100;
}
$routerFactories[$priority][$serviceName] = $serviceName;
}
// Sort routes by priority
if (!empty($routerFactories)) {
krsort($routerFactories, SORT_NUMERIC);
foreach ($routerFactories as $priority => $items) {
$routerFactories[$priority] = $items;
}
// Process all routes services by priority...
foreach ($routerFactories as $priority => $items) {
// ...and by service name...
foreach($items as $serviceName) {
$factory = new Nette\DI\Statement(array('@' . $serviceName, 'createRouter'));
$router->addSetup('offsetSet', array(NULL, $factory));
}
}
}
} | php | {
"resource": ""
} |
q250192 | Info.getCapabilities | validation | public function getCapabilities()
{
// Set the API base
$base = 'capabilities';
// Build the request path.
$path = $this->getOption('api.url') . $base;
// Send the request.
$response = $this->oauth->oauthRequest($path, 'GET', array());
return simplexml_load_string($response->body);
} | php | {
"resource": ""
} |
q250193 | Info.retrieveMapData | validation | public function retrieveMapData($left, $bottom, $right, $top)
{
// Set the API base
$base = 'map?bbox=' . $left . ',' . $bottom . ',' . $right . ',' . $top;
// Build the request path.
$path = $this->getOption('api.url') . $base;
// Send the request.
$response = $this->oauth->oauthRequest($path, 'GET', array());
return simplexml_load_string($response->body);
} | php | {
"resource": ""
} |
q250194 | Elements.createNode | validation | public function createNode($changeset, $latitude, $longitude, $tags)
{
$token = $this->oauth->getToken();
// Set parameters.
$parameters = array(
'oauth_token' => $token['key'],
);
// Set the API base
$base = 'node/create';
// Build the request path.
$path = $this->getOption('api.url') . $base;
$tagList = '';
// Create XML node
if (!empty($tags))
{
foreach ($tags as $key => $value)
{
$tagList .= '<tag k="' . $key . '" v="' . $value . '"/>';
}
}
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="JoomlaOpenStreetMap">
<node changeset="' . $changeset . '" lat="' . $latitude . '" lon="' . $longitude . '">'
. $tagList .
'</node>
</osm>';
$header['Content-Type'] = 'text/xml';
// Send the request.
$response = $this->oauth->oauthRequest($path, 'PUT', $parameters, $xml, $header);
return $response->body;
} | php | {
"resource": ""
} |
q250195 | Elements.createWay | validation | public function createWay($changeset, $tags, $nds)
{
$token = $this->oauth->getToken();
// Set parameters.
$parameters = array(
'oauth_token' => $token['key'],
);
// Set the API base
$base = 'way/create';
// Build the request path.
$path = $this->getOption('api.url') . $base;
$tagList = '';
// Create XML node
if (!empty($tags))
{
foreach ($tags as $key => $value)
{
$tagList .= '<tag k="' . $key . '" v="' . $value . '"/>';
}
}
$ndList = '';
if (!empty($nds))
{
foreach ($nds as $value)
{
$ndList .= '<nd ref="' . $value . '"/>';
}
}
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="JoomlaOpenStreetMap">
<way changeset="' . $changeset . '">'
. $tagList
. $ndList .
'</way>
</osm>';
$header['Content-Type'] = 'text/xml';
// Send the request.
$response = $this->oauth->oauthRequest($path, 'PUT', $parameters, $xml, $header);
return $response->body;
} | php | {
"resource": ""
} |
q250196 | Elements.createRelation | validation | public function createRelation($changeset, $tags, $members)
{
$token = $this->oauth->getToken();
// Set parameters.
$parameters = array(
'oauth_token' => $token['key'],
);
// Set the API base
$base = 'relation/create';
// Build the request path.
$path = $this->getOption('api.url') . $base;
$tagList = '';
// Create XML node
if (!empty($tags))
{
foreach ($tags as $key => $value)
{
$tagList .= '<tag k="' . $key . '" v="' . $value . '"/>';
}
}
// Members
$memberList = '';
if (!empty($members))
{
foreach ($members as $member)
{
if ($member['type'] == 'node')
{
$memberList .= '<member type="' . $member['type'] . '" role="' . $member['role'] . '" ref="' . $member['ref'] . '"/>';
}
elseif ($member['type'] == 'way')
{
$memberList .= '<member type="' . $member['type'] . '" ref="' . $member['ref'] . '"/>';
}
}
}
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="JoomlaOpenStreetMap">
<relation relation="' . $changeset . '" >'
. $tagList
. $memberList .
'</relation>
</osm>';
$header['Content-Type'] = 'text/xml';
// Send the request.
$response = $this->oauth->oauthRequest($path, 'PUT', $parameters, $xml, $header);
return $response->body;
} | php | {
"resource": ""
} |
q250197 | Elements.waysForNode | validation | public function waysForNode($id)
{
// Set the API base
$base = 'node/' . $id . '/ways';
// Build the request path.
$path = $this->getOption('api.url') . $base;
// Send the request.
$xmlString = $this->sendRequest($path);
return $xmlString->way;
} | php | {
"resource": ""
} |
q250198 | Elements.redaction | validation | public function redaction($element, $id, $version, $redactionId)
{
if ($element != 'node' && $element != 'way' && $element != 'relation')
{
throw new \DomainException('Element should be a node, a way or a relation');
}
$token = $this->oauth->getToken();
// Set parameters.
$parameters = array(
'oauth_token' => $token['key'],
);
// Set the API base
$base = $element . '/' . $id . '/' . $version . '/redact?redaction=' . $redactionId;
// Build the request path.
$path = $this->getOption('api.url') . $base;
// Send the request.
$response = $this->oauth->oauthRequest($path, 'PUT', $parameters);
return simplexml_load_string($response->body);
} | php | {
"resource": ""
} |
q250199 | OAuth.validateResponse | validation | public function validateResponse($url, $response)
{
if ($response->code != 200)
{
$error = htmlspecialchars($response->body);
throw new \DomainException($error, $response->code);
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.