_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q4600
Db.query
train
protected function query(string $sql, array $params = [], array $options = []): \PDOStatement { $options += [ Db::OPTION_FETCH_MODE => $this->getFetchArgs() ]; $stm = $this->getPDO()->prepare($sql); if ($options[Db::OPTION_FETCH_MODE]) { $stm->setFetchMode(...(array)$options[Db::OPTION_FETCH_MODE]); } $r = $stm->execute($params); // This is a kludge for those that don't have errors turning into exceptions. if ($r === false) { list($state, $code, $msg) = $stm->errorInfo(); throw new \PDOException($msg, $code); } return $stm; }
php
{ "resource": "" }
q4601
Db.queryModify
train
protected function queryModify(string $sql, array $params = [], array $options = []): int { $options += [Db::OPTION_FETCH_MODE => 0]; $stm = $this->query($sql, $params, $options); return $stm->rowCount(); }
php
{ "resource": "" }
q4602
Db.queryID
train
protected function queryID(string $sql, array $params = [], array $options = []) { $options += [Db::OPTION_FETCH_MODE => 0]; $this->query($sql, $params, $options); $r = $this->getPDO()->lastInsertId(); return is_numeric($r) ? (int)$r : $r; }
php
{ "resource": "" }
q4603
Db.queryDefine
train
protected function queryDefine(string $sql, array $options = []) { $options += [Db::OPTION_FETCH_MODE => 0]; $this->query($sql, [], $options); }
php
{ "resource": "" }
q4604
Db.escape
train
public function escape($identifier): string { if ($identifier instanceof Literal) { return $identifier->getValue($this); } return '`'.str_replace('`', '``', $identifier).'`'; }
php
{ "resource": "" }
q4605
Db.prefixTable
train
protected function prefixTable($table, bool $escape = true): string { if ($table instanceof Identifier) { return $escape ? $table->escape($this) : (string)$table; } else { $table = $this->px.$table; return $escape ? $this->escape($table) : $table; } }
php
{ "resource": "" }
q4606
Db.stripPrefix
train
protected function stripPrefix(string $table): string { $len = strlen($this->px); if (strcasecmp(substr($table, 0, $len), $this->px) === 0) { $table = substr($table, $len); } return $table; }
php
{ "resource": "" }
q4607
ThemeHandle.getThemesFromDir
train
public function getThemesFromDir() { $themeList = array(); $themePath = Yii::getPathOfAlias('webroot.themes'); $themes = scandir($themePath); foreach($themes as $theme) { $themeName = $this->urlTitle($theme); $themeFile = $themePath.'/'.$theme.'/'.$themeName.'.yaml'; if(file_exists($themeFile)) { if(!in_array($themeName, $this->getIgnoreTheme())) { $themeList[] = $theme; } } } if(count($themeList) > 0) return $themeList; else return false; }
php
{ "resource": "" }
q4608
ThemeHandle.cacheThemeConfig
train
public function cacheThemeConfig($return=false) { $themes = $this->getThemesFromDb(); $arrayTheme = array(); foreach($themes as $theme) { if(!in_array($theme->folder, $arrayTheme)) $arrayTheme[] = $theme->folder; } if($return == false) { $filePath = Yii::getPathOfAlias('application.config'); $fileHandle = fopen($filePath.'/cache_theme.php', 'w'); fwrite($fileHandle, implode("\n", $arrayTheme)); fclose($fileHandle); } else return $arrayTheme; }
php
{ "resource": "" }
q4609
ThemeHandle.getThemeConfig
train
public function getThemeConfig($theme) { Yii::import('mustangostang.spyc.Spyc'); define('DS', DIRECTORY_SEPARATOR); $themeName = $this->urlTitle($theme); $configPath = Yii::getPathOfAlias('webroot.themes.'.$theme).DS.$themeName.'.yaml'; if(file_exists($configPath)) return Spyc::YAMLLoad($configPath); else return null; }
php
{ "resource": "" }
q4610
ThemeHandle.deleteThemeDb
train
public function deleteThemeDb($theme) { if($theme != null) { $model = OmmuThemes::model()->findByAttributes(array('folder'=>$theme)); if($model != null) $model->delete(); else return false; } else return false; }
php
{ "resource": "" }
q4611
ThemeHandle.setThemes
train
public function setThemes() { $installedTheme = $this->getThemesFromDir(); $cacheTheme = file(Yii::getPathOfAlias('application.config').'/cache_theme.php'); $toBeInstalled = array(); $caches = array(); foreach($cacheTheme as $val) { $caches[] = $val; } if(!$installedTheme) $installedTheme = array(); foreach($caches as $cache) { $cache = trim($cache); if(!in_array($cache, array_map("trim", $installedTheme))) { $this->deleteTheme($cache, true); } } $themeDb = $this->cacheThemeConfig(true); foreach($installedTheme as $theme) { if(!in_array(trim($theme), array_map("trim", $themeDb))) { $config = $this->getThemeConfig($theme); $themeName = $this->urlTitle($theme); if($config && $themeName == $config['folder']) { $model=new OmmuThemes; $model->group_page = $config['group_page']; $model->folder = $theme; $model->layout = $config['layout']; $model->name = $config['name']; $model->thumbnail = $config['thumbnail']; $model->save(); } } } }
php
{ "resource": "" }
q4612
PhotosAlbumsTable.afterSave
train
public function afterSave(Event $event, Entity $entity, ArrayObject $options) { //Creates the folder (new Folder($entity->path, true, 0777)); parent::afterSave($event, $entity, $options); }
php
{ "resource": "" }
q4613
CreateAdminCommand.execute
train
public function execute(Arguments $args, ConsoleIo $io) { $command = new AddUserCommand; return $command->run(['--group', 1] + $args->getOptions(), $io); }
php
{ "resource": "" }
q4614
ReqAttr.getReferrer
train
public static function getReferrer(ServerRequestInterface $request) { if ($referrer = $request->getAttribute(self::REFERRER)) { return $referrer; } if ($referrer = Respond::session()->get(self::REFERRER)) { return $referrer; } $info = $request->getServerParams(); return array_key_exists('HTTP_REFERER', $info) ? $info['HTTP_REFERER'] : ''; }
php
{ "resource": "" }
q4615
ReqAttr.withBasePath
train
public static function withBasePath(ServerRequestInterface $request, $basePath, $pathInfo = null) { $path = $request->getUri()->getPath(); if (strpos($path, $basePath) !== 0) { throw new \InvalidArgumentException; } $pathInfo = is_null($pathInfo) ? substr($path, strlen($basePath)) : $pathInfo; return $request ->withAttribute(self::BASE_PATH, $basePath) ->withAttribute(self::PATH_INFO, $pathInfo); }
php
{ "resource": "" }
q4616
ReqAttr.getPathInfo
train
public static function getPathInfo(ServerRequestInterface $request) { return $request->getAttribute(self::PATH_INFO, null) ?: $request->getUri()->getPath(); }
php
{ "resource": "" }
q4617
QueueManager.run
train
public function run($eventname, $count) { $queueEvents = $this->loadQueue($eventname, $count); if ($queueEvents->numRows) { while ($queueEvents->next()) { if ($this->checkInterval($queueEvents)) { $this->setStartTime($queueEvents->id); $jobEvent = $this->dispatch($queueEvents); $this->setEndTime($queueEvents->id, $queueEvents->intervaltorun); $this->saveJobResult($queueEvents->id, $jobEvent); } } } else { $this->response($eventname, 'noActiveJobs', 'INFO'); } }
php
{ "resource": "" }
q4618
QueueManager.setError
train
protected function setError($id) { $queueEvent = new QueueSetErrorEvent(); $queueEvent->setId($id); $this->dispatcher->dispatch($queueEvent::NAME, $queueEvent); }
php
{ "resource": "" }
q4619
QueueManager.saveJobResult
train
protected function saveJobResult($id, $jobEvent) { if ($jobEvent) { $queueEvent = new QueueSaveJobResultEvent(); $queueEvent->setId($id); $queueEvent->setData($jobEvent); $this->dispatcher->dispatch($queueEvent::NAME, $queueEvent); } }
php
{ "resource": "" }
q4620
QueueManager.dispatch
train
protected function dispatch($queueEvent) { $event = urldecode($queueEvent->data); $event = unserialize($event); if ($event) { $this->dispatcher->dispatch($event::NAME, $event); if ($event->getHasError()) { $this->setError($queueEvent->id); $this->response($event::NAME, $event->getError(), 'ERROR', $event->getParam()); } else { $this->response($event::NAME, $event->getReturnMessages(), 'NOTICE', $event->getParam()); } return $event; } }
php
{ "resource": "" }
q4621
MessageMapper.markAsRead
train
public function markAsRead(int $messageId) { $this->sql = 'update message set is_read = \'Y\' where id = ?'; $this->bindValues[] = $messageId; return $this->execute(); }
php
{ "resource": "" }
q4622
MessageMapper.markAsUnread
train
public function markAsUnread(int $messageId) { $this->sql = 'update message set is_read = \'N\' where id = ?'; $this->bindValues[] = $messageId; return $this->execute(); }
php
{ "resource": "" }
q4623
DateInterval.fromSpecification
train
public static function fromSpecification(string $specification) : self { $microseconds = 0; // Parse the microsecond component. if (false !== ($position = stripos($specification, 'U'))) { // Step backwards consuming digits until we hit a duration designator. // Note that we always expect at least the duration designator (P), but for loop safety we break if // the first character in the specification is reached too. $microseconds = ''; while ($position > 0) { $char = $specification[--$position]; if (!is_numeric($char)) { break; } $microseconds = $char . $microseconds; } // Remove the microsecond designator from the specification. $specification = substr($specification, 0, -1 - strlen($microseconds)); } // If the specification is just the duration designator it means that only microseconds were specified. // In that case we create an empty interval for convenience. if ('P' === $specification || 'PT' === $specification) { $specification = 'P0Y'; } return new static(new \DateInterval($specification), (int)$microseconds); }
php
{ "resource": "" }
q4624
DateInterval.diff
train
public static function diff(DateTime $a, DateTime $b, bool $absolute = false) : self { $microseconds = $b->microsecond() - $a->microsecond(); if ($absolute) { $microseconds = abs($microseconds); } $diff = $a->toInternalDateTime()->diff($b->toInternalDateTime(), $absolute); return new static($diff, $microseconds); }
php
{ "resource": "" }
q4625
DateInterval.fromComponents
train
public static function fromComponents( int $years = null, int $months = null, int $weeks = null, int $days = null, int $hours = null, int $minutes = null, int $seconds = null, int $microseconds = null ) : self { if (!($years || $months || $weeks || $days || $hours || $minutes || $seconds || $microseconds)) { throw new \InvalidArgumentException('At least one component is required.'); } $years = $years ?: 0; $months = $months ?: 0; $weeks = $weeks ?: 0; $days = $days ?: 0; $hours = $hours ?: 0; $minutes = $minutes ?: 0; $seconds = $seconds ?: 0; $microseconds = $microseconds ?: 0; $specification = 'P'; if ($years) { $specification .= $years . 'Y'; } if ($months) { $specification .= $months . 'M'; } if ($weeks) { $specification .= $weeks . 'W'; } if ($days) { $specification .= $days . 'D'; } if ($hours || $minutes || $seconds) { $specification .= 'T'; if ($hours) { $specification .= $hours . 'H'; } if ($minutes) { $specification .= $minutes . 'M'; } if ($seconds) { $specification .= $seconds . 'M'; } } return new static(new \DateInterval($specification), $microseconds); }
php
{ "resource": "" }
q4626
DateInterval.format
train
public function format(string $format) : string { // Replace microseconds first so they become literals. // Ignore any escaped microsecond identifiers. $format = preg_replace_callback( // Starting at the start of the string or the first non % character, // consume pairs of % characters (effectively consuming all escaped %s) // and finally match the string %u. '/((?:^|[^%])(?:%{2})*)(%u)/', function (array $matches) { return $matches[1] . $this->microseconds; }, $format ); $format = $this->wrapped->format($format); return $format; }
php
{ "resource": "" }
q4627
DateInterval.totalMicroseconds
train
public function totalMicroseconds() : int { if (null === $this->totalMicroseconds) { $reference = DateTime::now(); $end = $reference->add($this); $this->totalMicroseconds = $end->timestampWithMicrosecond() - $reference->timestampWithMicrosecond(); } return $this->totalMicroseconds; }
php
{ "resource": "" }
q4628
DateInterval.clone
train
private static function clone(\DateInterval $interval) { $specification = $interval->format('P%yY%mM%dDT%hH%iM%sS'); $clone = new \DateInterval($specification); $clone->days = $interval->days; $clone->invert = $interval->invert; return $clone; }
php
{ "resource": "" }
q4629
PostsCategoriesController.view
train
public function view($slug = null) { //The category can be passed as query string, from a widget if ($this->request->getQuery('q')) { return $this->redirect([$this->request->getQuery('q')]); } $page = $this->request->getQuery('page', 1); //Sets the cache name $cache = sprintf('category_%s_limit_%s_page_%s', md5($slug), $this->paginate['limit'], $page); //Tries to get data from the cache list($posts, $paging) = array_values(Cache::readMany( [$cache, sprintf('%s_paging', $cache)], $this->PostsCategories->getCacheName() )); //If the data are not available from the cache if (empty($posts) || empty($paging)) { $query = $this->PostsCategories->Posts->find('active') ->find('forIndex') ->where([sprintf('%s.slug', $this->PostsCategories->getAlias()) => $slug]); is_true_or_fail(!$query->isEmpty(), I18N_NOT_FOUND, RecordNotFoundException::class); $posts = $this->paginate($query); //Writes on cache Cache::writeMany([ $cache => $posts, sprintf('%s_paging', $cache) => $this->request->getParam('paging'), ], $this->PostsCategories->getCacheName()); //Else, sets the paging parameter } else { $this->request = $this->request->withParam('paging', $paging); } $this->set('category', $posts->extract('category')->first()); $this->set(compact('posts')); }
php
{ "resource": "" }
q4630
LogsController.getPath
train
protected function getPath($filename, $serialized) { if ($serialized) { $filename = pathinfo($filename, PATHINFO_FILENAME) . '_serialized.log'; } return LOGS . $filename; }
php
{ "resource": "" }
q4631
LogsController.read
train
protected function read($filename, $serialized) { $log = $this->getPath($filename, $serialized); is_readable_or_fail($log); $log = file_get_contents($log); return $serialized ? @unserialize($log) : trim($log); }
php
{ "resource": "" }
q4632
LogsController.view
train
public function view($filename) { $serialized = false; if ($this->request->getQuery('as') === 'serialized') { $serialized = true; $this->viewBuilder()->setTemplate('view_as_serialized'); } $content = $this->read($filename, $serialized); $this->set(compact('content', 'filename')); }
php
{ "resource": "" }
q4633
LogsController.download
train
public function download($filename) { return $this->response->withFile($this->getPath($filename, false), ['download' => true]); }
php
{ "resource": "" }
q4634
LogsController.delete
train
public function delete($filename) { $this->request->allowMethod(['post', 'delete']); $success = (new File($this->getPath($filename, false)))->delete(); $serialized = $this->getPath($filename, true); //Deletes the serialized log copy, if it exists if (file_exists($serialized)) { $successSerialized = (new File($serialized))->delete(); } if ($success && $successSerialized) { $this->Flash->success(I18N_OPERATION_OK); } else { $this->Flash->error(I18N_OPERATION_NOT_OK); } return $this->redirect(['action' => 'index']); }
php
{ "resource": "" }
q4635
PhotosController.view
train
public function view($slug = null, $id = null) { //This allows backward compatibility for URLs like `/photo/11` if (empty($slug)) { $slug = $this->Photos->findById($id) ->contain([$this->Photos->Albums->getAlias() => ['fields' => ['slug']]]) ->extract('album.slug') ->first(); return $this->redirect(compact('id', 'slug'), 301); } $photo = $this->Photos->findActiveById($id) ->select(['id', 'album_id', 'filename', 'active', 'modified']) ->contain([$this->Photos->Albums->getAlias() => ['fields' => ['id', 'title', 'slug']]]) ->cache(sprintf('view_%s', md5($id)), $this->Photos->getCacheName()) ->firstOrFail(); $this->set(compact('photo')); }
php
{ "resource": "" }
q4636
PhotosController.preview
train
public function preview($id = null) { $photo = $this->Photos->findPendingById($id) ->select(['id', 'album_id', 'filename']) ->contain([$this->Photos->Albums->getAlias() => ['fields' => ['id', 'title', 'slug']]]) ->firstOrFail(); $this->set(compact('photo')); $this->render('view'); }
php
{ "resource": "" }
q4637
MultiCurrencyBank.checkCurrencies
train
protected function checkCurrencies($currencies) { foreach ((array) $currencies as $currency) { if (!$this->hasCurrency($currency)) { throw new InvalidCurrencyException(sprintf('"%s" is an unknown currency code.', $currency)); } } }
php
{ "resource": "" }
q4638
MultiCurrencyBank.getRate
train
public function getRate($fromCurrency, $toCurrency = null) { if (null === $toCurrency) { $toCurrency = $this->getBaseCurrency(); } $this->checkCurrencies(array($fromCurrency, $toCurrency)); return $this->exchanger->getRate($fromCurrency, $toCurrency); }
php
{ "resource": "" }
q4639
MultiCurrencyBank.reduce
train
public function reduce(MoneyInterface $source, $toCurrency = null) { if (null === $toCurrency) { $toCurrency = $this->getBaseCurrency(); } $this->checkCurrencies($toCurrency); return $source->reduce($this, $toCurrency); }
php
{ "resource": "" }
q4640
MultiCurrencyBank.createMoney
train
public function createMoney($amount, $currency = null) { if (null === $currency) { $currency = $this->getBaseCurrency(); } $this->checkCurrencies($currency); $class = $this->moneyClass; return new $class($amount, $currency); }
php
{ "resource": "" }
q4641
Auth.verifyCredentials
train
public function verifyCredentials($sIdentifier, $sPassword) { // Look up the user, how we do so depends on the login mode that the app is using $oUserModel = Factory::model('User', 'nails/module-auth'); $oPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); $oUser = $oUserModel->getByIdentifier($sIdentifier); return !empty($oUser) ? $oPasswordModel->isCorrect($oUser->id, $sPassword) : false; }
php
{ "resource": "" }
q4642
Auth.logout
train
public function logout() { $oUserModel = Factory::model('User', 'nails/module-auth'); $oUserModel->clearRememberCookie(); // -------------------------------------------------------------------------- // null the remember_code so that auto-logins stop $oDb = Factory::service('Database'); $oDb->set('remember_code', null); $oDb->where('id', activeUser('id')); $oDb->update(NAILS_DB_PREFIX . 'user'); // -------------------------------------------------------------------------- // Destroy key parts of the session (enough for user_model to report user as logged out) $oUserModel->clearLoginData(); // -------------------------------------------------------------------------- // Destroy CI session $oSession = Factory::service('Session', 'nails/module-auth'); $oSession->destroy(); // -------------------------------------------------------------------------- // Destroy PHP session if it exists if (session_id()) { session_destroy(); } // -------------------------------------------------------------------------- return true; }
php
{ "resource": "" }
q4643
Auth.mfaTokenGenerate
train
public function mfaTokenGenerate($iUserId) { $oPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); $oNow = Factory::factory('DateTime'); $oInput = Factory::service('Input'); $oDb = Factory::service('Database'); $sSalt = $oPasswordModel->salt(); $sIp = $oInput->ipAddress(); $sCreated = $oNow->format('Y-m-d H:i:s'); $sExpires = $oNow->add(new \DateInterval('PT10M'))->format('Y-m-d H:i:s'); $aToken = [ 'token' => sha1(sha1(APP_PRIVATE_KEY . $iUserId . $sCreated . $sExpires . $sIp) . $sSalt), 'salt' => md5($sSalt), ]; // Add this to the DB $oDb->set('user_id', $iUserId); $oDb->set('token', $aToken['token']); $oDb->set('salt', $aToken['salt']); $oDb->set('created', $sCreated); $oDb->set('expires', $sExpires); $oDb->set('ip', $sIp); if ($oDb->insert(NAILS_DB_PREFIX . 'user_auth_two_factor_token')) { $aToken['id'] = $oDb->insert_id(); return $aToken; } else { $error = lang('auth_twofactor_token_could_not_generate'); $this->setError($error); return false; } }
php
{ "resource": "" }
q4644
Auth.mfaTokenValidate
train
public function mfaTokenValidate($iUserId, $sSalt, $sToken, $sIp) { $oDb = Factory::service('Database'); $oDb->where('user_id', $iUserId); $oDb->where('salt', $sSalt); $oDb->where('token', $sToken); $oToken = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_token')->row(); $bReturn = true; if (!$oToken) { $this->setError(lang('auth_twofactor_token_invalid')); return false; } elseif (strtotime($oToken->expires) <= time()) { $this->setError(lang('auth_twofactor_token_expired')); $bReturn = false; } elseif ($oToken->ip != $sIp) { $this->setError(lang('auth_twofactor_token_bad_ip')); $bReturn = false; } // Delete the token $this->mfaTokenDelete($oToken->id); return $bReturn; }
php
{ "resource": "" }
q4645
Auth.mfaTokenDelete
train
public function mfaTokenDelete($iTokenId) { $oDb = Factory::service('Database'); $oDb->where('id', $iTokenId); $oDb->delete(NAILS_DB_PREFIX . 'user_auth_two_factor_token'); return (bool) $oDb->affected_rows(); }
php
{ "resource": "" }
q4646
Auth.mfaQuestionGet
train
public function mfaQuestionGet($iUserId) { $oDb = Factory::service('Database'); $oInput = Factory::service('Input'); $oDb->where('user_id', $iUserId); $oDb->order_by('last_requested', 'DESC'); $aQuestions = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_question')->result(); if (!$aQuestions) { $this->setError('No security questions available for this user.'); return false; } // -------------------------------------------------------------------------- // Choose a question to return if (count($aQuestions) == 1) { // No choice, just return the lonely question $oOut = reset($aQuestions); } elseif (count($aQuestions) > 1) { /** * Has the most recently asked question been asked in the last 10 minutes? * If so, return that one again (to make harvesting all the user's questions * a little more time consuming). If not randomly choose one. */ $oOut = reset($aQuestions); if (strtotime($oOut->last_requested) < strtotime('-10 MINS')) { $oOut = $aQuestions[array_rand($aQuestions)]; } } else { $this->setError('Could not determine security question.'); return false; } // Decode the question $oEncrypt = Factory::service('Encrypt'); $oOut->question = $oEncrypt->decode($oOut->question, APP_PRIVATE_KEY . $oOut->salt); // Update the last requested details $oDb->set('last_requested', 'NOW()', false); $oDb->set('last_requested_ip', $oInput->ipAddress()); $oDb->where('id', $oOut->id); $oDb->update(NAILS_DB_PREFIX . 'user_auth_two_factor_question'); return $oOut; }
php
{ "resource": "" }
q4647
Auth.mfaQuestionValidate
train
public function mfaQuestionValidate($iQuestionId, $iUserId, $answer) { $oDb = Factory::service('Database'); $oDb->select('answer, salt'); $oDb->where('id', $iQuestionId); $oDb->where('user_id', $iUserId); $oQuestion = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_question')->row(); if (!$oQuestion) { return false; } $hash = sha1(sha1(strtolower($answer)) . APP_PRIVATE_KEY . $oQuestion->salt); return $hash === $oQuestion->answer; }
php
{ "resource": "" }
q4648
Auth.mfaQuestionSet
train
public function mfaQuestionSet($iUserId, $aData, $bClearOld = true) { // Check input foreach ($aData as $oDatum) { if (empty($oDatum->question) || empty($oDatum->answer)) { $this->setError('Malformed question/answer data.'); return false; } } // Begin transaction $oDb = Factory::service('Database'); $oDb->trans_begin(); // Delete old questions? if ($bClearOld) { $oDb->where('user_id', $iUserId); $oDb->delete(NAILS_DB_PREFIX . 'user_auth_two_factor_question'); } $oPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); $oEncrypt = Factory::service('Encrypt'); $aQuestionData = []; $iCounter = 0; $oNow = Factory::factory('DateTime'); $sDateTime = $oNow->format('Y-m-d H:i:s'); foreach ($aData as $oDatum) { $sSalt = $oPasswordModel->salt(); $aQuestionData[$iCounter] = [ 'user_id' => $iUserId, 'salt' => $sSalt, 'question' => $oEncrypt->encode($oDatum->question, APP_PRIVATE_KEY . $sSalt), 'answer' => sha1(sha1(strtolower($oDatum->answer)) . APP_PRIVATE_KEY . $sSalt), 'created' => $sDateTime, 'last_requested' => null, ]; $iCounter++; } if ($aQuestionData) { $oDb->insert_batch(NAILS_DB_PREFIX . 'user_auth_two_factor_question', $aQuestionData); if ($oDb->trans_status() !== false) { $oDb->trans_commit(); return true; } else { $oDb->trans_rollback(); return false; } } else { $oDb->trans_rollback(); $this->setError('No data to save.'); return false; } }
php
{ "resource": "" }
q4649
Auth.mfaDeviceSecretGet
train
public function mfaDeviceSecretGet($iUserId) { $oDb = Factory::service('Database'); $oEncrypt = Factory::service('Encrypt'); $oDb->where('user_id', $iUserId); $oDb->limit(1); $aResult = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_device_secret')->result(); if (empty($aResult)) { return false; } $oReturn = reset($aResult); $oReturn->secret = $oEncrypt->decode($oReturn->secret, APP_PRIVATE_KEY); return $oReturn; }
php
{ "resource": "" }
q4650
Auth.mfaDeviceSecretGenerate
train
public function mfaDeviceSecretGenerate($iUserId, $sExistingSecret = null) { // Get an identifier for the user $oUserModel = Factory::model('User', 'nails/module-auth'); $oUser = $oUserModel->getById($iUserId); if (!$oUser) { $this->setError('User does not exist.'); return false; } $oGoogleAuth = new GoogleAuthenticator(); // Generate the secret if (empty($sExistingSecret)) { $sSecret = $oGoogleAuth->generateSecret(); } else { $sSecret = $sExistingSecret; } // Get the hostname $sHostname = Functions::getDomainFromUrl(BASE_URL); // User identifier $sUsername = $oUser->username; $sUsername = empty($sUsername) ? preg_replace('/[^a-z]/', '', strtolower($oUser->first_name . $oUser->last_name)) : $sUsername; $sUsername = empty($sUsername) ? preg_replace('/[^a-z]/', '', strtolower($oUser->email)) : $sUsername; return [ 'secret' => $sSecret, 'url' => $oGoogleAuth->getUrl($sUsername, $sHostname, $sSecret), ]; }
php
{ "resource": "" }
q4651
Auth.mfaDeviceSecretValidate
train
public function mfaDeviceSecretValidate($iUserId, $sSecret, $iCode) { // Tidy up codes so that they only contain digits $sCode = preg_replace('/[^\d]/', '', $iCode); // New instance of the authenticator $oGoogleAuth = new GoogleAuthenticator(); if ($oGoogleAuth->checkCode($sSecret, $sCode)) { $oDb = Factory::service('Database'); $oEncrypt = Factory::service('Encrypt'); $oDb->set('user_id', $iUserId); $oDb->set('secret', $oEncrypt->encode($sSecret, APP_PRIVATE_KEY)); $oDb->set('created', 'NOW()', false); if ($oDb->insert(NAILS_DB_PREFIX . 'user_auth_two_factor_device_secret')) { $iSecretId = $oDb->insert_id(); $oNow = Factory::factory('DateTime'); $oDb->set('secret_id', $iSecretId); $oDb->set('code', $sCode); $oDb->set('used', $oNow->format('Y-m-d H:i:s')); $oDb->insert(NAILS_DB_PREFIX . 'user_auth_two_factor_device_code'); return true; } else { $this->setError('Could not save secret.'); return false; } } else { $this->setError('Codes did not validate.'); return false; } }
php
{ "resource": "" }
q4652
Auth.mfaDeviceCodeValidate
train
public function mfaDeviceCodeValidate($iUserId, $sCode) { // Get the user's secret $oSecret = $this->mfaDeviceSecretGet($iUserId); if (!$oSecret) { $this->setError('Invalid User'); return false; } // Has the code been used before? $oDb = Factory::service('Database'); $oDb->where('secret_id', $oSecret->id); $oDb->where('code', $sCode); if ($oDb->count_all_results(NAILS_DB_PREFIX . 'user_auth_two_factor_device_code')) { $this->setError('Code has already been used.'); return false; } // Tidy up codes so that they only contain digits $sCode = preg_replace('/[^\d]/', '', $sCode); // New instance of the authenticator $oGoogleAuth = new GoogleAuthenticator(); $checkCode = $oGoogleAuth->checkCode($oSecret->secret, $sCode); if ($checkCode) { // Log the code so it can't be used again $oDb->set('secret_id', $oSecret->id); $oDb->set('code', $sCode); $oDb->set('used', 'NOW()', false); $oDb->insert(NAILS_DB_PREFIX . 'user_auth_two_factor_device_code'); return true; } else { return false; } }
php
{ "resource": "" }
q4653
Referrer.saveReferrer
train
private function saveReferrer(ServerRequestInterface $request) { Respond::session()->set(self::REFERRER, $request->getUri()->__toString()); }
php
{ "resource": "" }
q4654
ViewData.setMessage
train
public function setMessage($type, $message) { if (!is_null($message)) { $this->messages[] = [ 'message' => $message, 'type' => $type, ]; } return $this; }
php
{ "resource": "" }
q4655
Apache.modules
train
public function modules() { $modules = []; foreach ($this->modulesToCheck as $module) { $modules[$module] = in_array('mod_' . $module, apache_get_modules()); } return $modules; }
php
{ "resource": "" }
q4656
App.brokenLinksColumnSorting
train
public function brokenLinksColumnSorting() { add_filter('posts_fields', function ($fields, $query) { if ($query->get('orderby') !== 'broken-links') { return $fields; } global $wpdb; $fields .= ", ( SELECT COUNT(*) FROM " . self::$dbTable . " WHERE post_id = {$wpdb->posts}.ID ) AS broken_links_count"; return $fields; }, 10, 2); add_filter('posts_orderby', function ($orderby, $query) { if ($query->get('orderby') !== 'broken-links') { return $orderby; } $orderby = "broken_links_count {$query->get('order')}, " . $orderby; return $orderby; }, 10, 2); }
php
{ "resource": "" }
q4657
App.addListTablePage
train
public function addListTablePage() { add_submenu_page( 'options-general.php', 'Broken links', 'Broken links', 'edit_posts', 'broken-links-detector', function () { \BrokenLinkDetector\App::checkInstall(); $listTable = new \BrokenLinkDetector\ListTable(); $offset = get_option('gmt_offset'); if ($offset > -1) { $offset = '+' . $offset; } else { $offset = '-' . (1 * abs($offset)); } $nextRun = date('Y-m-d H:i', strtotime($offset . ' hours', wp_next_scheduled('broken-links-detector-external'))); include BROKENLINKDETECTOR_TEMPLATE_PATH . 'list-table.php'; } ); }
php
{ "resource": "" }
q4658
App.checkSavedPost
train
public function checkSavedPost($data, $postarr) { remove_action('wp_insert_post_data', array($this, 'checkSavedPost'), 10, 2); $detector = new \BrokenLinkDetector\InternalDetector($data, $postarr); return $data; }
php
{ "resource": "" }
q4659
App.deleteBrokenLinks
train
public function deleteBrokenLinks($postId) { global $wpdb; $tableName = self::$dbTable; $wpdb->delete($tableName, array('post_id' => $postId), array('%d')); }
php
{ "resource": "" }
q4660
UsersTable.findAuth
train
public function findAuth(Query $query, array $options) { return $query->contain('Groups', function (Query $q) { return $q->select(['name']); }); }
php
{ "resource": "" }
q4661
UsersTable.findBanned
train
public function findBanned(Query $query, array $options) { return $query->where([sprintf('%s.banned', $this->getAlias()) => true]); }
php
{ "resource": "" }
q4662
UsersTable.findPending
train
public function findPending(Query $query, array $options) { return $query->where([ sprintf('%s.active', $this->getAlias()) => false, sprintf('%s.banned', $this->getAlias()) => false, ]); }
php
{ "resource": "" }
q4663
UsersTable.getActiveList
train
public function getActiveList() { return $this->find() ->select(['id', 'first_name', 'last_name']) ->where([sprintf('%s.active', $this->getAlias()) => true]) ->order(['username' => 'ASC']) ->formatResults(function (ResultSet $results) { return $results->indexBy('id')->map(function (User $user) { return $user->first_name . ' ' . $user->last_name; }); }) ->cache(sprintf('active_%s_list', $this->getTable()), $this->getCacheName()); }
php
{ "resource": "" }
q4664
UsersTable.validationDoNotRequirePresence
train
public function validationDoNotRequirePresence(UserValidator $validator) { //No field is required foreach ($validator->getIterator() as $field => $rules) { $validator->requirePresence($field, false); } return $validator; }
php
{ "resource": "" }
q4665
PostsTagsWidgetsCell.getFontSizes
train
protected function getFontSizes(array $style = []) { //Maximum and minimun font sizes we want to use $maxFont = empty($style['maxFont']) ? 40 : $style['maxFont']; $minFont = empty($style['minFont']) ? 12 : $style['minFont']; is_true_or_fail($maxFont > $minFont, __d('me_cms', 'Invalid values'), InvalidArgumentException::class); return [$maxFont, $minFont]; }
php
{ "resource": "" }
q4666
PostsTagsWidgetsCell.popular
train
public function popular( $limit = 10, $prefix = '#', $render = 'cloud', $shuffle = true, $style = ['maxFont' => 40, 'minFont' => 12] ) { $this->viewBuilder()->setTemplate(sprintf('popular_as_%s', $render)); //Returns on tags index if ($this->request->isUrl(['_name' => 'postsTags'])) { return; } //Sets default maximum and minimun font sizes we want to use $maxFont = $minFont = 0; //Sets the initial cache name $cache = sprintf('widget_tags_popular_%s', $limit); if ($style && is_array($style)) { //Updates maximum and minimun font sizes we want to use list($maxFont, $minFont) = $this->getFontSizes($style); //Updates the cache name $cache = sprintf('%s_max_%s_min_%s', $cache, $maxFont, $minFont); } $tags = $this->Tags->find() ->select(['tag', 'post_count']) ->limit($limit) ->order([ sprintf('%s.post_count', $this->Tags->getAlias()) => 'DESC', sprintf('%s.tag', $this->Tags->getAlias()) => 'ASC', ]) ->formatResults(function (ResultSet $results) use ($style, $maxFont, $minFont) { $results = $results->indexBy('slug'); if (!$results->count() || !$style || !$maxFont || !$minFont) { return $results; } //Highest and lowest numbers of occurrences and their difference $minCount = $results->last()->post_count; $diffCount = $results->first()->post_count - $minCount; $diffFont = $maxFont - $minFont; return $results->map(function (Tag $tag) use ($minCount, $diffCount, $maxFont, $minFont, $diffFont) { $tag->size = $diffCount ? round((($tag->post_count - $minCount) / $diffCount * $diffFont) + $minFont) : $maxFont; return $tag; }); }) ->cache($cache, $this->Tags->getCacheName()) ->all(); if ($shuffle) { $tags = $tags->shuffle(); } $this->set(compact('prefix', 'tags')); }
php
{ "resource": "" }
q4667
ComposerListener.registerPackage
train
public static function registerPackage(Event $event) { $installedPackage = $event->getOperation()->getPackage(); if (!self::isBundle($installedPackage)) { return; } self::enablePackage($installedPackage); }
php
{ "resource": "" }
q4668
Redirect.toPath
train
public function toPath($path) { $uri = $this->request->getUri()->withPath($path); return $this->toAbsoluteUri($uri); }
php
{ "resource": "" }
q4669
PostsWidgetsCell.months
train
public function months($render = 'form') { $this->viewBuilder()->setTemplate(sprintf('months_as_%s', $render)); //Returns on posts index if ($this->request->isUrl(['_name' => 'posts'])) { return; } $query = $this->Posts->find('active'); $time = $query->func()->date_format(['created' => 'identifier', "'%Y/%m'" => 'literal']); $months = $query->select([ 'month' => $time, 'post_count' => $query->func()->count($time), ]) ->distinct(['month']) ->formatResults(function (ResultSet $results) { return $results->indexBy('month') ->map(function (Post $post) { list($year, $month) = explode('/', $post->month); $post->month = (new FrozenDate())->day(1)->month($month)->year($year); return $post; }); }) ->order(['month' => 'DESC']) ->cache('widget_months', $this->Posts->getCacheName()) ->all(); $this->set(compact('months')); }
php
{ "resource": "" }
q4670
DisableElementsCapableFormSettings.filterArrayStrings
train
protected function filterArrayStrings($array, $search, $replace) { $return = array(); foreach ((array)$array as $key => $value) { $key = str_replace($search, $replace, $key); $value = is_array($value) ? $this->filterArrayStrings($value, $search, $replace) : str_replace($search, $replace, $value); $return[$key] = $value; } return $return; }
php
{ "resource": "" }
q4671
Escaper.escapeCharacterClass
train
public function escapeCharacterClass($char) { return (isset($this->inCharacterClass[$char])) ? $this->inCharacterClass[$char] : $char; }
php
{ "resource": "" }
q4672
Escaper.escapeLiteral
train
public function escapeLiteral($char) { return (isset($this->inLiteral[$char])) ? $this->inLiteral[$char] : $char; }
php
{ "resource": "" }
q4673
RedisService.add
train
public function add($id, $data = 1) { try { return $this->resource->hSet(static::CACHE_KEY, $id, $data); } catch (ConnectionException $e) { return false; } }
php
{ "resource": "" }
q4674
RedisService.exists
train
public function exists($id) { try { return !!$this->resource->hExists(static::CACHE_KEY, $id); } catch (ConnectionException $e) { return false; } }
php
{ "resource": "" }
q4675
RedisService.remove
train
public function remove($id) { try { return $this->resource->hDel(static::CACHE_KEY, $id); } catch (ConnectionException $e) { return false; } }
php
{ "resource": "" }
q4676
MergeSuffix.hasMatchingSuffix
train
protected function hasMatchingSuffix(array $strings) { $suffix = end($strings[1]); foreach ($strings as $string) { if (end($string) !== $suffix) { return false; } } return ($suffix !== false); }
php
{ "resource": "" }
q4677
MergeSuffix.pop
train
protected function pop(array $strings) { $cnt = count($strings); $i = $cnt; while (--$i >= 0) { array_pop($strings[$i]); } // Remove empty elements then prepend one back at the start of the array if applicable $strings = array_filter($strings); if (count($strings) < $cnt) { array_unshift($strings, []); } return $strings; }
php
{ "resource": "" }
q4678
User.getSearch
train
public function getSearch($aData = []) { if (!userHasPermission('admin:auth:accounts:browse')) { $oHttpCodes = Factory::service('HttpCodes'); throw new ApiException( 'You are not authorised to search users', $oHttpCodes::STATUS_UNAUTHORIZED ); } return parent::getSearch($aData); }
php
{ "resource": "" }
q4679
User.getEmail
train
public function getEmail() { $oHttpCodes = Factory::service('HttpCodes'); if (!userHasPermission('admin:auth:accounts:browse')) { throw new ApiException( 'You are not authorised to browse users', $oHttpCodes::STATUS_UNAUTHORIZED ); } $oInput = Factory::service('Input'); $sEmail = $oInput->get('email'); if (!valid_email($sEmail)) { throw new ApiException( '"' . $sEmail . '" is not a valid email', $oHttpCodes::STATUS_BAD_REQUEST ); } $oUserModel = Factory::model(static::CONFIG_MODEL_NAME, static::CONFIG_MODEL_PROVIDER); $oUser = $oUserModel->getByEmail($sEmail); if (empty($oUser)) { throw new ApiException( 'No user found for email "' . $sEmail . '"', $oHttpCodes::STATUS_NOT_FOUND ); } return Factory::factory('ApiResponse', 'nails/module-api') ->setData($this->formatObject($oUser)); }
php
{ "resource": "" }
q4680
User.postRemap
train
public function postRemap() { $oUri = Factory::service('Uri'); $iItemId = (int) $oUri->segment(4); if ($iItemId && $iItemId != activeUSer('id') && !userHasPermission('admin:auth:accounts:editothers')) { return [ 'status' => 401, 'error' => 'You do not have permission to update this resource', ]; } elseif (!$iItemId && !userHasPermission('admin:auth:accounts:create')) { return [ 'status' => 401, 'error' => 'You do not have permission to create this type of resource', ]; } return parent::postRemap(); }
php
{ "resource": "" }
q4681
User.formatObject
train
public function formatObject($oObj) { return [ 'id' => $oObj->id, 'first_name' => $oObj->first_name, 'last_name' => $oObj->last_name, 'email' => $oObj->email, ]; }
php
{ "resource": "" }
q4682
FileUploadHandler.upload
train
public function upload(string $fileKey) { if (!isset($this->uploadedFiles[$fileKey])) { throw new Exception('PitonCMS: File upload key does not exist'); } $file = $this->uploadedFiles[$fileKey]; if ($file->getError() === UPLOAD_ERR_OK) { // Get file name and extension $uploadFileName = $file->getClientFilename(); $ext = strtolower(pathinfo($uploadFileName, PATHINFO_EXTENSION)); // Create new file name and directory and ensure it is unique do { $name = $this->generateName(); $path = $this->getFilePath($name); $exists = $this->makeFileDirectory($path); } while (!$exists); $this->fileName = "$name.$ext"; $file->moveTo("{$this->publicRoot}{$path}{$this->fileName}"); unset($file); return true; } // Save error code $this->error = $file->getError(); return false; }
php
{ "resource": "" }
q4683
FileUploadHandler.getErrorMessage
train
public function getErrorMessage() { switch ($this->error) { case UPLOAD_ERR_INI_SIZE: $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; break; case UPLOAD_ERR_FORM_SIZE: $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; break; case UPLOAD_ERR_PARTIAL: $message = "The uploaded file was only partially uploaded"; break; case UPLOAD_ERR_NO_FILE: $message = "No file was uploaded"; break; case UPLOAD_ERR_NO_TMP_DIR: $message = "Missing a temporary folder"; break; case UPLOAD_ERR_CANT_WRITE: $message = "Failed to write file to disk"; break; case UPLOAD_ERR_EXTENSION: $message = "File upload stopped by extension"; break; default: $message = "Unknown upload error"; } return $message; }
php
{ "resource": "" }
q4684
FileUploadHandler.makeFileDirectory
train
protected function makeFileDirectory($directoryPath) { $filePath = $this->publicRoot . $directoryPath; // Create the path if the directory does not exist if (!is_dir($filePath)) { try { mkdir($filePath, 0775, true); return true; } catch (Exception $e) { throw new Exception('PitonCMS: Failed to create file upload directory'); } } // The directory already exists return false; }
php
{ "resource": "" }
q4685
Utf8.charsToCodepointsWithSurrogates
train
protected function charsToCodepointsWithSurrogates(array $chars) { $codepoints = []; foreach ($chars as $char) { $cp = $this->cp($char); if ($cp < 0x10000) { $codepoints[] = $cp; } else { $codepoints[] = 0xD7C0 + ($cp >> 10); $codepoints[] = 0xDC00 + ($cp & 0x3FF); } } return $codepoints; }
php
{ "resource": "" }
q4686
Utf8.cp
train
protected function cp($char) { $cp = ord($char[0]); if ($cp >= 0xF0) { $cp = ($cp << 18) + (ord($char[1]) << 12) + (ord($char[2]) << 6) + ord($char[3]) - 0x3C82080; } elseif ($cp >= 0xE0) { $cp = ($cp << 12) + (ord($char[1]) << 6) + ord($char[2]) - 0xE2080; } elseif ($cp >= 0xC0) { $cp = ($cp << 6) + ord($char[1]) - 0x3080; } return $cp; }
php
{ "resource": "" }
q4687
Page.getPublishedStatus
train
public function getPublishedStatus() { $today = date('Y-m-d'); if (empty($this->published_date)) { return 'draft'; } elseif ($this->published_date > $today) { return 'pending'; } elseif ($this->published_date <= $today) { return 'published'; } return null; }
php
{ "resource": "" }
q4688
AttachmentAwareTrait.addAttachment
train
public function addAttachment($attachment, $group = 'contents') { if (!$attachment instanceof AttachableInterface && !$attachment instanceof ModelInterface) { return false; } $join = $this->modelFactory()->create(Join::class); $objId = $this->id(); $objType = $this->objType(); $attId = $attachment->id(); $join->setAttachmentId($attId); $join->setObjectId($objId); $join->setGroup($group); $join->setObjectType($objType); $join->save(); return $this; }
php
{ "resource": "" }
q4689
AttachmentAwareTrait.removeAttachmentJoins
train
public function removeAttachmentJoins() { $joinProto = $this->modelFactory()->get(Join::class); $loader = $this->collectionLoader(); $loader ->setModel($joinProto) ->addFilter('object_type', $this->objType()) ->addFilter('object_id', $this->id()); $collection = $loader->load(); foreach ($collection as $obj) { $obj->delete(); } return true; }
php
{ "resource": "" }
q4690
Pager.generateLinksCenter
train
public function generateLinksCenter(string $page = null, string $ignoredKeys = null, $linksClassName = null): string { // only one page? $totalPages = $this->totalPages; if ($totalPages == 1) { return $this->template(['<a class="current" href="#">1</a>'], $linksClassName, true); } $links = (array) $this->linksCenter; if ($links != null) { return $this->template($links, $linksClassName, true); } $linksTemplate = $this->linksTemplate; $s = $this->startKey; $query = $this->prepareQuery($ignoredKeys); $start = max(1, ($this->start / $this->stop) + 1); // add first & prev links $prev = $start - 1; if ($prev >= 1) { $links[] = sprintf('<a class="first" rel="first" href="%s%s=1">%s</a>', $query, $s, $linksTemplate['first']); $links[] = sprintf('<a class="prev" rel="prev" href="%s%s=%s">%s</a>', $query, $s, $prev, $linksTemplate['prev']); } $links[] = sprintf('<a class="current" href="#">%s %s</a>', $page ?? $linksTemplate['page'], $start); // add next & last link $next = $start + 1; if ($start < $totalPages) { $links[] = sprintf('<a class="next" rel="next" href="%s%s=%s">%s</a>', $query, $s, $next, $linksTemplate['next']); $links[] = sprintf('<a class="last" rel="last" href="%s%s=%s">%s</a>', $query, $s, $totalPages, $linksTemplate['last']); } // store $this->linksCenter = $links; return $this->template($links, $linksClassName, true); }
php
{ "resource": "" }
q4691
GetStartAndEndDateTrait.getStartAndEndDate
train
protected function getStartAndEndDate($date) { $year = $month = $day = null; //Sets the start date if (in_array($date, ['today', 'yesterday'])) { $start = Time::parse($date); } else { list($year, $month, $day) = array_replace([null, null, null], explode('/', $date)); $start = Time::now()->setDate($year, $month ?: 1, $day ?: 1); } $start = $start->setTime(0, 0, 0); $end = Time::parse($start); if (($year && $month && $day) || in_array($date, ['today', 'yesterday'])) { $end = $end->addDay(1); } else { $end = $year && $month ? $end->addMonth(1) : $end->addYear(1); } return [$start, $end]; }
php
{ "resource": "" }
q4692
User.addTeams
train
public function addTeams(ArrayCollection $teams) { foreach ($teams as $team) { $team->addUser($this); $this->teams->add($team); } }
php
{ "resource": "" }
q4693
User.removeTeams
train
public function removeTeams(ArrayCollection $teams) { foreach ($teams as $team) { $team->removeUser($this); $this->teams->removeElement($team); } }
php
{ "resource": "" }
q4694
XMLTransformer.transform
train
public static function transform($xslFileName, DOMDocument $xml) { $xsl = new DOMDocument; $xsl->load(__DIR__.'/../../xslt/'.$xslFileName.'.xsl'); $proc = new XSLTProcessor; $proc->importStyleSheet($xsl); libxml_use_internal_errors(true); $result = $proc->transformToXML($xml); foreach (libxml_get_errors() as $error) { //throw new \Exception($error->message); } return $result; }
php
{ "resource": "" }
q4695
PostsCategoriesController.delete
train
public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $category = $this->PostsCategories->get($id); //Before deleting, it checks if the category has some posts if (!$category->post_count) { $this->PostsCategories->deleteOrFail($category); $this->Flash->success(I18N_OPERATION_OK); } else { $this->Flash->alert(I18N_BEFORE_DELETE); } return $this->redirect(['action' => 'index']); }
php
{ "resource": "" }
q4696
TableQuery.setOption
train
protected function setOption($name, $value, $reset = false) { $changed = !isset($this->options[$name]) || $this->options[$name] !== $value; if ($changed && $reset) { $this->data = null; } $this->options[$name] = $value; return $this; }
php
{ "resource": "" }
q4697
SessionStorage.forge
train
public static function forge($name, $cookie = null) { $factory = new SessionFactory(); $cookie = $cookie ?: $_COOKIE; $session = $factory->newInstance($cookie); $self = new self($session); $self->start(); return $self->withStorage($name); }
php
{ "resource": "" }
q4698
SessionStorage.withStorage
train
public function withStorage($name) { $self = clone($this); $self->segment = $this->session->getSegment($name); return $self; }
php
{ "resource": "" }
q4699
Login.index
train
public function index() { // If you're logged in you shouldn't be accessing this method if (isLoggedIn()) { redirect($this->data['return_to']); } // -------------------------------------------------------------------------- // If there's POST data attempt to log user in $oInput = Factory::service('Input'); if ($oInput->post()) { // Validate input $oFormValidation = Factory::service('FormValidation'); // The rules vary depending on what login methods are enabled. switch (APP_NATIVE_LOGIN_USING) { case 'EMAIL': $oFormValidation->set_rules('identifier', 'Email', 'required|trim|valid_email'); break; case 'USERNAME': $oFormValidation->set_rules('identifier', 'Username', 'required|trim'); break; default: $oFormValidation->set_rules('identifier', 'Username or Email', 'trim'); break; } // Password is always required, obviously. $oFormValidation->set_rules('password', 'Password', 'required'); $oFormValidation->set_message('required', lang('fv_required')); $oFormValidation->set_message('valid_email', lang('fv_valid_email')); if ($oFormValidation->run()) { // Attempt the log in $sIdentifier = $oInput->post('identifier'); $sPassword = $oInput->post('password'); $bRememberMe = (bool) $oInput->post('remember'); $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oUser = $oAuthModel->login($sIdentifier, $sPassword, $bRememberMe); if ($oUser) { $this->_login($oUser, $bRememberMe); } else { $this->data['error'] = $oAuthModel->lastError(); } } else { $this->data['error'] = lang('fv_there_were_errors'); } } // -------------------------------------------------------------------------- $oSocial = Factory::service('SocialSignOn', 'nails/module-auth'); $this->data['social_signon_enabled'] = $oSocial->isEnabled(); $this->data['social_signon_providers'] = $oSocial->getProviders('ENABLED'); // -------------------------------------------------------------------------- $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/login/form.php'); Factory::service('View') ->load([ 'structure/header/blank', 'auth/login/form', 'structure/footer/blank', ]); }
php
{ "resource": "" }