_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q4900
Password.generate
train
public function generate($iGroupId) { $aPwRules = $this->getRules($iGroupId); $aPwOut = []; // -------------------------------------------------------------------------- /** * We're generating a password, define all the charsets to use, at the very * ;east have the lower_alpha charset. */ $aCharsets = []; $aCharsets[] = $this->aCharset['lower_alpha']; if (!empty($aPwRules['requirements'])) { foreach ($aPwRules['requirements'] as $sRequirement => $bValue) { switch ($sRequirement) { case 'symbol': $aCharsets[] = $this->aCharset['symbol']; break; case 'number': $aCharsets[] = $this->aCharset['number']; break; case 'upper_alpha': $aCharsets[] = $this->aCharset['upper_alpha']; break; } } } // -------------------------------------------------------------------------- // Work out the min length $iMin = getFromArray('min', $aPwRules); if (empty($iMin)) { $iMin = 8; } // Work out the max length $iMax = getFromArray('max', $aPwRules); if (empty($iMax) || $iMin > $iMax) { $iMax = $iMin + count($aCharsets) * 2; } // -------------------------------------------------------------------------- // We now have a max_length and all our chars, generate password! $bPwValid = true; do { do { foreach ($aCharsets as $sCharset) { $sCharacter = rand(0, strlen($sCharset) - 1); $aPwOut[] = $sCharset[$sCharacter]; } } while (count($aPwOut) < $iMax); // Check password isn't a prohibited string if (!empty($aPwRules['banned'])) { foreach ($aPwRules['banned'] as $sString) { if (strtolower(implode('', $aPwOut)) == strtolower($sString)) { $bPwValid = false; break; } } } } while (!$bPwValid); // -------------------------------------------------------------------------- // Shuffle the string and return shuffle($aPwOut); return implode('', $aPwOut); }
php
{ "resource": "" }
q4901
Password.getRules
train
protected function getRules($iGroupId) { $sCacheKey = 'password-rules-' . $iGroupId; $aCacheResult = $this->getCache($sCacheKey); if (!empty($aCacheResult)) { return $aCacheResult; } $oDb = Factory::service('Database'); $oDb->select('password_rules'); $oDb->where('id', $iGroupId); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user_group'); if ($oResult->num_rows() === 0) { return []; } $oPwRules = json_decode($oResult->row()->password_rules); $aOut = []; $aOut['min'] = !empty($oPwRules->min) ? $oPwRules->min : null; $aOut['max'] = !empty($oPwRules->max) ? $oPwRules->max : null; $aOut['expiresAfter'] = !empty($oPwRules->expiresAfter) ? $oPwRules->expiresAfter : null; $aOut['requirements'] = !empty($oPwRules->requirements) ? $oPwRules->requirements : []; $aOut['banned'] = !empty($oPwRules->banned) ? $oPwRules->banned : []; $this->setCache($sCacheKey, $aOut); return $aOut; }
php
{ "resource": "" }
q4902
Password.getRulesAsString
train
public function getRulesAsString($iGroupId) { $aRules = $this->getRulesAsArray($iGroupId); if (empty($aRules)) { return ''; } $sStr = 'Passwords must ' . strtolower(implode(', ', $aRules)) . '.'; return str_lreplace(', ', ' and ', $sStr); }
php
{ "resource": "" }
q4903
Password.getRulesAsArray
train
public function getRulesAsArray($iGroupId) { $aRules = $this->getRules($iGroupId); $aOut = []; if (!empty($aRules['min'])) { $aOut[] = 'Have at least ' . $aRules['min'] . ' characters'; } if (!empty($aRules['max'])) { $aOut[] = 'Have at most ' . $aRules['max'] . ' characters'; } if (!empty($aRules['requirements'])) { foreach ($aRules['requirements'] as $sKey => $bValue) { switch ($sKey) { case 'symbol': $aOut[] = 'Contain a symbol'; break; case 'lower_alpha': $aOut[] = 'Contain a lowercase letter'; break; case 'upper_alpha': $aOut[] = 'Contain an upper case letter'; break; case 'number': $aOut[] = 'Contain a number'; break; } } } return $aOut; }
php
{ "resource": "" }
q4904
Password.setToken
train
public function setToken($sIdentifier) { if (empty($sIdentifier)) { return false; } // -------------------------------------------------------------------------- // Generate code $sKey = sha1(sha1($this->salt()) . $this->salt() . APP_PRIVATE_KEY); $iTtl = time() + 86400; // 24 hours. // -------------------------------------------------------------------------- // Update the user $oUserModel = Factory::model('User', 'nails/module-auth'); $oUser = $oUserModel->getByIdentifier($sIdentifier); if ($oUser) { $aData = [ 'forgotten_password_code' => $iTtl . ':' . $sKey, ]; return $oUserModel->update($oUser->id, $aData); } else { return false; } }
php
{ "resource": "" }
q4905
Password.validateToken
train
public function validateToken($sCode, $bGenerateNewPw) { if (empty($sCode)) { return false; } // -------------------------------------------------------------------------- $oDb = Factory::service('Database'); $oDb->select('id, group_id, forgotten_password_code'); $oDb->like('forgotten_password_code', ':' . $sCode, 'before'); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user'); // -------------------------------------------------------------------------- if ($oResult->num_rows() != 1) { return false; } // -------------------------------------------------------------------------- $oUser = $oResult->row(); $aCode = explode(':', $oUser->forgotten_password_code); // -------------------------------------------------------------------------- // Check that the link is still valid if (time() > $aCode[0]) { return 'EXPIRED'; } else { // Valid hash and hasn't expired. $aOut = []; $aOut['user_id'] = $oUser->id; // Generate a new password? if ($bGenerateNewPw) { $aOut['password'] = $this->generate($oUser->group_id); if (empty($aOut['password'])) { // This should never happen, but just in case. return false; } $oHash = $this->generateHash($oUser->group_id, $aOut['password']); if (!$oHash) { // Again, this should never happen, but just in case. return false; } // -------------------------------------------------------------------------- $aData['password'] = $oHash->password; $aData['password_md5'] = $oHash->password_md5; $aData['password_engine'] = $oHash->engine; $aData['salt'] = $oHash->salt; $aData['temp_pw'] = true; $aData['forgotten_password_code'] = null; $oDb->where('forgotten_password_code', $oUser->forgotten_password_code); $oDb->set($aData); $oDb->update(NAILS_DB_PREFIX . 'user'); } } return $aOut; }
php
{ "resource": "" }
q4906
PageSettingMapper.findPageSettings
train
public function findPageSettings($pageId) { $this->makeSelect(); $this->sql .= ' and page_id = ?'; $this->bindValues[] = $pageId; return $this->find(); }
php
{ "resource": "" }
q4907
WidgetHelper.getAll
train
protected function getAll() { $widgets = getConfig('Widgets.general', []); if ($this->getView()->getRequest()->isUrl(['_name' => 'homepage']) && getConfig('Widgets.homepage')) { $widgets = getConfig('Widgets.homepage'); } return $widgets ? collection($widgets)->map(function ($args, $name) { if (is_string($name) && is_array($args)) { return [$name => $args]; } elseif (is_string($args)) { return [$args => []]; } list($name, $args) = [array_key_first($args), array_value_first($args)]; return is_int($name) && is_string($args) ? [$args => []] : [$name => $args]; })->toList() : []; }
php
{ "resource": "" }
q4908
WidgetHelper.all
train
public function all() { foreach ($this->getAll() as $widget) { foreach ($widget as $name => $args) { $widgets[] = $this->widget($name, $args); } } return empty($widgets) ? null : trim(implode(PHP_EOL, $widgets)); }
php
{ "resource": "" }
q4909
WidgetHelper.widget
train
public function widget($name, array $data = [], array $options = []) { $parts = explode('::', $name); $name = $parts[0] . 'Widgets'; $name = empty($parts[1]) ? $name : sprintf('%s::%s', $name, $parts[1]); return $this->getView()->cell($name, $data, $options); }
php
{ "resource": "" }
q4910
BackupsController.index
train
public function index() { $backups = collection($this->BackupManager->index()) ->map(function (Entity $backup) { return $backup->set('slug', urlencode($backup->filename)); }); $this->set(compact('backups')); }
php
{ "resource": "" }
q4911
BackupsController.add
train
public function add() { $backup = new BackupForm; if ($this->request->is('post')) { //Creates the backup if ($backup->execute($this->request->getData())) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('backup')); }
php
{ "resource": "" }
q4912
BackupsController.delete
train
public function delete($filename) { $this->request->allowMethod(['post', 'delete']); $this->BackupManager->delete($this->getFilename($filename)); $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); }
php
{ "resource": "" }
q4913
BackupsController.deleteAll
train
public function deleteAll() { $this->request->allowMethod(['post', 'delete']); $this->BackupManager->deleteAll(); $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); }
php
{ "resource": "" }
q4914
BackupsController.restore
train
public function restore($filename) { //Imports and clears the cache (new BackupImport)->filename($this->getFilename($filename))->import(); Cache::clearAll(); $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); }
php
{ "resource": "" }
q4915
BackupsController.send
train
public function send($filename) { $this->BackupManager->send($this->getFilename($filename), getConfigOrFail('email.webmaster')); $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); }
php
{ "resource": "" }
q4916
OEmbed.setURL
train
public function setURL($url) { if (!$this->validateURL($url)) { throw new \InvalidArgumentException(sprintf('The URL "%s" is invalid.', $url)); } $this->url = $url; $this->endpoint = null; }
php
{ "resource": "" }
q4917
OEmbed.removeProvider
train
public function removeProvider(Provider $provider) { $index = array_search($provider, $this->providers); if ($index !== false) { unset($this->providers[$index]); } return $this; }
php
{ "resource": "" }
q4918
OEmbed.getObject
train
public function getObject(array $parameters = array()) { if ($this->url === null) { throw new \InvalidArgumentException('Missing URL.'); } if ($this->endpoint === null) { $this->endpoint = $this->discover($this->url); } $sign = '?'; if ($query = parse_url($this->endpoint, PHP_URL_QUERY)) { $sign = '&'; parse_str($query, $parameters); } if (!isset($parameters['url'])) { $parameters['url'] = $this->url; } if (!isset($parameters['format'])) { $parameters['format'] = 'json'; } $client = new Client( sprintf('%s%s%s', $this->endpoint, $sign, http_build_query($parameters)) ); $data = $client->send(); switch ($parameters['format']) { case 'json': $data = json_decode($data); if (!is_object($data)) { throw new \InvalidArgumentException('Could not parse JSON response.'); } break; case 'xml': libxml_use_internal_errors(true); $data = simplexml_load_string($data); if (!$data instanceof \SimpleXMLElement) { $errors = libxml_get_errors(); $error = array_shift($errors); libxml_clear_errors(); libxml_use_internal_errors(false); throw new \InvalidArgumentException($error->message, $error->code); } break; } return Object::factory($data); }
php
{ "resource": "" }
q4919
OEmbed.discover
train
protected function discover($url) { $endpoint = $this->findEndpointFromProviders($url); // if no provider was found, try to discover the endpoint URL if ($this->discovery && !$endpoint) { $discover = new Discoverer(); $endpoint = $discover->getEndpointForUrl($url); } if (!$endpoint) { throw new \InvalidArgumentException('No oEmbed links found.'); } return $endpoint; }
php
{ "resource": "" }
q4920
OEmbed.findEndpointFromProviders
train
protected function findEndpointFromProviders($url) { // try to find a provider matching the supplied URL if no one has been supplied foreach ($this->providers as $provider) { /** @var $provider Provider */ if ($provider->match($url)) { return $provider->getEndpoint(); } } return null; }
php
{ "resource": "" }
q4921
PostsController.indexByDate
train
public function indexByDate($date) { //Data can be passed as query string, from a widget if ($this->request->getQuery('q')) { return $this->redirect([$this->request->getQuery('q')]); } list($start, $end) = $this->getStartAndEndDate($date); $page = $this->request->getQuery('page', 1); //Sets the cache name $cache = sprintf('index_date_%s_limit_%s_page_%s', md5(serialize([$start, $end])), $this->paginate['limit'], $page); //Tries to get data from the cache list($posts, $paging) = array_values(Cache::readMany( [$cache, sprintf('%s_paging', $cache)], $this->Posts->getCacheName() )); //If the data are not available from the cache if (empty($posts) || empty($paging)) { $query = $this->Posts->find('active') ->find('forIndex') ->where([ sprintf('%s.created >=', $this->Posts->getAlias()) => $start, sprintf('%s.created <', $this->Posts->getAlias()) => $end, ]); $posts = $this->paginate($query); //Writes on cache Cache::writeMany([ $cache => $posts, sprintf('%s_paging', $cache) => $this->request->getParam('paging'), ], $this->Posts->getCacheName()); //Else, sets the paging parameter } else { $this->request = $this->request->withParam('paging', $paging); } $this->set(compact('date', 'posts', 'start')); }
php
{ "resource": "" }
q4922
PostsController.rss
train
public function rss() { //This method works only for RSS is_true_or_fail($this->RequestHandler->prefers('rss'), ForbiddenException::class); $posts = $this->Posts->find('active') ->select(['title', 'preview', 'slug', 'text', 'created']) ->limit(getConfigOrFail('default.records_for_rss')) ->order([sprintf('%s.created', $this->Posts->getAlias()) => 'DESC']) ->cache('rss', $this->Posts->getCacheName()); $this->set(compact('posts')); }
php
{ "resource": "" }
q4923
PostsController.preview
train
public function preview($slug = null) { $post = $this->Posts->findPendingBySlug($slug) ->find('forIndex') ->firstOrFail(); $this->set(compact('post')); //Gets related posts if (getConfig('post.related')) { $related = $this->Posts->getRelated($post, getConfigOrFail('post.related.limit'), getConfig('post.related.images')); $this->set(compact('related')); } $this->render('view'); }
php
{ "resource": "" }
q4924
GetPreviewsFromTextTrait.extractImages
train
protected function extractImages($html) { if (empty($html)) { return []; } $libxmlPreviousState = libxml_use_internal_errors(true); $dom = new DOMDocument; $dom->loadHTML($html); libxml_clear_errors(); libxml_use_internal_errors($libxmlPreviousState); $images = []; //Gets all image tags foreach ($dom->getElementsByTagName('img') as $item) { $src = $item->getAttribute('src'); if (in_array(strtolower(pathinfo($src, PATHINFO_EXTENSION)), ['gif', 'jpg', 'jpeg', 'png'])) { $images[] = $src; } } //Gets all Youtube videos if (preg_match_all('/\[youtube](.+?)\[\/youtube]/', $html, $items)) { foreach ($items[1] as $item) { $images[] = Youtube::getPreview($item); } } return $images; }
php
{ "resource": "" }
q4925
GetPreviewsFromTextTrait.getPreviews
train
public function getPreviews($html) { $images = array_map(function ($url) { if ($url && !is_url($url)) { //If is relative path $url = Folder::isAbsolute($url) ? $url : WWW_ROOT . 'img' . DS . $url; if (!file_exists($url)) { return false; } $thumber = new ThumbCreator($url); $thumber->resize(1200, 1200)->save(['format' => 'jpg']); $url = $thumber->getUrl(); } list($width, $height) = $this->getPreviewSize($url); return new Entity(compact('url', 'width', 'height')); }, $this->extractImages($html)); return array_filter($images); }
php
{ "resource": "" }
q4926
Connection.get
train
public function get($resource, $body = null, $params = []) { return $this->send($this->prepare('GET', $resource, $body, $params)); }
php
{ "resource": "" }
q4927
Connection.post
train
public function post($resource, $body = null, $params = []) { return $this->send($this->prepare('POST', $resource, $body, $params)); }
php
{ "resource": "" }
q4928
Connection.send
train
protected function send(Request $request) { try { $response = $this->client->send($request); } catch (ClientException $e) { $response = $e->getResponse(); } catch (ServerException $e) { $response = $e->getResponse(); } return $response; }
php
{ "resource": "" }
q4929
Connection.prepare
train
protected function prepare($method, $resource, $body, $params) { // Append the username parameter to the end of every resource URI. $resource = trim($resource, '/').'/'.$this->username; foreach ($params as $param) { $resource .= '/'.$param; } return new Request($method, $resource, [], $body); }
php
{ "resource": "" }
q4930
PrintableAscii.escapeControlCode
train
protected function escapeControlCode($cp) { $table = [9 => '\\t', 10 => '\\n', 13 => '\\r']; return (isset($table[$cp])) ? $table[$cp] : $this->escapeAscii($cp); }
php
{ "resource": "" }
q4931
BleedingEffect.bleed
train
public function bleed(Bleeding $bleeding, WoundsTable $woundsTable, WoundBoundary $woundBoundary): Wound { // see PPH page 78 right column, Bleeding $effectSize = $bleeding->getAfflictionSize()->getValue() - 6; $woundsFromTable = $woundsTable->toWounds(new WoundsBonus($effectSize, $woundsTable)); $woundSize = new WoundSize($woundsFromTable->getValue()); $woundCausedBleeding = $bleeding->getSeriousWound(); return $woundCausedBleeding->getHealth()->addWound( $woundSize, $woundCausedBleeding->getWoundOriginCode(), $woundBoundary ); }
php
{ "resource": "" }
q4932
ClientRepository.create
train
public function create($params) { $client = new Client; $client->fill($params); $client->save(); // update datacite_symbol $this->generateDataciteSymbol($client); return $client; }
php
{ "resource": "" }
q4933
ClientRepository.generateDataciteSymbol
train
public function generateDataciteSymbol(Client $client) { $prefix = "ANDS."; $id = $client->client_id; // prefix before the if ($id < 100) { $prefix .= "CENTRE"; } if ($id < 10) { $prefix .= "-"; } elseif ($id >= 100) { // prefix before the ID (new form) $prefix .= "C"; } $client->datacite_symbol = $prefix . $id; $client->save(); return $client; }
php
{ "resource": "" }
q4934
Request.postParam
train
public function postParam(string $name, $valueDefault = null) { return $this->params->post($name, $valueDefault); }
php
{ "resource": "" }
q4935
Request.cookieParam
train
public function cookieParam(string $name, $valueDefault = null) { return $this->params->cookie($name, $valueDefault); }
php
{ "resource": "" }
q4936
Request.loadHttpHeaders
train
private function loadHttpHeaders(): array { if (function_exists('getallheaders')) { $headers = getallheaders(); // apache } else { $headers = []; foreach ($_SERVER as $key => $value) { if (stripos(strval($key), 'HTTP_') === 0) { $headers[ // normalize key implode('-', array_map('ucwords', explode('_', strtolower(substr($key, 5))))) ] = $value; } } } // content issues if (isset($_SERVER['CONTENT_TYPE'])) { $headers['Content-Type'] = $_SERVER['CONTENT_TYPE']; } if (isset($_SERVER['CONTENT_LENGTH'])) { $headers['Content-Length'] = $_SERVER['CONTENT_LENGTH']; } if (isset($_SERVER['CONTENT_MD5'])) { $headers['Content-MD5'] = $_SERVER['CONTENT_MD5']; } // authorization issues if (!isset($headers['Authorization'])) { if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { $headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) { $headers['Authorization'] = $_SERVER['PHP_AUTH_DIGEST']; } elseif (isset($_SERVER['PHP_AUTH_USER'])) { $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] .':'. ($_SERVER['PHP_AUTH_PW'] ?? '')); } } return $headers; }
php
{ "resource": "" }
q4937
IPValidator.validate
train
public static function validate($ip, $ip_range) { // first lets get the lists of ip address or ranges separated by commas $ip_ranges = explode(',', $ip_range); foreach ($ip_ranges as $ip_range) { $ip_range = explode('-', $ip_range); if (sizeof($ip_range) > 1) { $target_ip = ip2long($ip); // If exactly 2, then treat the values as the upper and lower bounds of a range for checking // AND the target_ip is valid if (count($ip_range) == 2 && $target_ip) { // convert dotted quad notation to long for numeric comparison $lower_bound = ip2long($ip_range[0]); $upper_bound = ip2long($ip_range[1]); // If the target_ip is valid if ($target_ip >= $lower_bound && $target_ip <= $upper_bound) { return true; } } } else { if (self::ip_match($ip, $ip_range[0])) { return true; } } } return false; }
php
{ "resource": "" }
q4938
IPValidator.ip_match
train
public static function ip_match($ip, $match) { if (ip2long($match)) {//is an actual IP if ($ip == $match) { return true; } } else {//is something weird if (strpos($match, '/')) {//if it's a cidr notation if (self::cidr_match($ip, $match)) { return true; } } else {//is a random string (let's say a host name) $match = gethostbyname($match); if ($ip == $match) { return true; } else { return false; } } } return false; }
php
{ "resource": "" }
q4939
WeightTable.getMalusFromLoad
train
public function getMalusFromLoad(Strength $strength, Weight $cargoWeight): int { $requiredStrength = $cargoWeight->getBonus()->getValue(); $missingStrength = $requiredStrength - $strength->getValue(); $malus = -SumAndRound::half($missingStrength); // see PPH page 113, right column if ($malus > 0) { return 0; } return $malus; }
php
{ "resource": "" }
q4940
OmmuThemes.getThemes
train
public static function getThemes($array=true) { $criteria=new CDbCriteria; $model = self::model()->findAll($criteria); if($array == true) { $items = array(); if($model != null) { foreach($model as $key => $val) { $items[$val->theme_id] = $val->name; } return $items; } else return false; } else return $model; }
php
{ "resource": "" }
q4941
Override.login_as
train
public function login_as() { // Perform lookup of user $oUserModel = Factory::model('User', 'nails/module-auth'); $oUri = Factory::service('Uri'); $sHashId = $oUri->segment(4); $sHashPw = $oUri->segment(5); $oUser = $oUserModel->getByHashes($sHashId, $sHashPw); if (!$oUser) { show404(); } // -------------------------------------------------------------------------- /** * Check sign-in permissions; ignore if recovering. * Users cannot: * - Sign in as themselves * - Sign in as superusers (unless they are a superuser) */ $oSession = Factory::service('Session', 'nails/module-auth'); if (!wasAdmin()) { $bHasPermission = userHasPermission('admin:auth:accounts:loginAs'); $bIsCloning = activeUser('id') == $oUser->id; $bIsSuperuser = !isSuperuser() && isSuperuser($oUser) ? true : false; if (!$bHasPermission || $bIsCloning || $bIsSuperuser) { if (!$bHasPermission) { $oSession->setFlashData('error', lang('auth_override_fail_nopermission')); redirect('admin/dashboard'); } elseif ($bIsCloning) { show404(); } elseif ($bIsSuperuser) { show404(); } } } // -------------------------------------------------------------------------- $oInput = Factory::service('Input'); if (!$oInput->get('returningAdmin') && isAdmin()) { /** * The current user is an admin, we should set our Admin Recovery Data so * that they can come back. */ $oUserModel->setAdminRecoveryData($oUser->id, $oInput->get('return_to')); $sRedirectUrl = $oUser->group_homepage; // A bit of feedback $sStatus = 'success'; $sMessage = lang('auth_override_ok', $oUser->first_name . ' ' . $oUser->last_name); } elseif (wasAdmin()) { /** * This user is a recovering adminaholic. Work out where we're sending * them back to then remove the adminRecovery data. */ $oRecoveryData = getAdminRecoveryData(); $sRedirectUrl = !empty($oRecoveryData->returnTo) ? $oRecoveryData->returnTo : $oUser->group_homepage; unsetAdminRecoveryData(); // Some feedback $sStatus = 'success'; $sMessage = lang('auth_override_return', $oUser->first_name . ' ' . $oUser->last_name); } else { /** * This user is simply logging in as someone else and has passed the hash * verification. */ $sRedirectUrl = $oUser->group_homepage; // Some feedback $sStatus = 'success'; $sMessage = lang('auth_override_ok', $oUser->first_name . ' ' . $oUser->last_name); } // -------------------------------------------------------------------------- // Replace current user's session data $oUserModel->setLoginData($oUser->id); // -------------------------------------------------------------------------- // Any feedback? if (!empty($sMessage)) { $oSession->setFlashData($sStatus, $sMessage); } // -------------------------------------------------------------------------- redirect($sRedirectUrl); }
php
{ "resource": "" }
q4942
DateTime.fromTimestampWithMicroseconds
train
public static function fromTimestampWithMicroseconds(int $timestamp) : self { $seconds = (int)($timestamp / 10 ** 6); $microseconds = $timestamp - ($seconds * 10 ** 6); // Ensure microseconds are right-padded with zeros because values like 012345 will be 12345 when expressed // as an integer, and the concatenation below will therefore shift digits left by one place. $microseconds = str_pad($microseconds, 6, '0', STR_PAD_LEFT); return static::fromFormat('U.u', $seconds . '.' . $microseconds); }
php
{ "resource": "" }
q4943
DateTime.withDateAt
train
public function withDateAt(int $year = null, int $month = null, int $day = null) : self { if (null === $year && null === $month && null === $day) { return $this; } $year = $year === null ? $this->year() : $year; $month = $month ?: $this->month(); $day = $day ?: $this->day(); $instance = clone $this; $instance->date->setDate($year, $month, $day); return $instance; }
php
{ "resource": "" }
q4944
DateTime.withDateAtStartOfYear
train
public function withDateAtStartOfYear() : self { $instance = $this->withTimeAtMidnight(); $instance->date->setDate($instance->format('Y'), 1, 1); return $instance; }
php
{ "resource": "" }
q4945
DateTime.withDateAtEndOfMonth
train
public function withDateAtEndOfMonth() : self { $instance = $this->withDateAtStartOfMonth(); $instance->date->modify('+1 month'); $instance->date->modify('-1 day'); return $instance; }
php
{ "resource": "" }
q4946
DateTime.withDateAtDayOfWeekInMonth
train
public function withDateAtDayOfWeekInMonth(int $dayOfWeek, int $occurrence) : self { self::assertValidDayOfWeek($dayOfWeek); if ($occurrence < -5 || $occurrence === 0 || $occurrence > 5) { throw new \InvalidArgumentException("Invalid occurrence: $occurrence."); } $calendar = $this->createCalendar(); // IntlCalendar uses Sunday as day 1 - convert that to Monday as day 1. if (++$dayOfWeek === 8) { $dayOfWeek = 1; } $calendar->set(\IntlCalendar::FIELD_DAY_OF_WEEK, $dayOfWeek); $calendar->set(\IntlCalendar::FIELD_DAY_OF_WEEK_IN_MONTH, $occurrence); return static::fromIntlCalendar($calendar); }
php
{ "resource": "" }
q4947
DateTime.withTimeAt
train
public function withTimeAt( int $hour = null, int $minute = null, int $second = null, int $microsecond = null ) : self { $instance = clone $this; $hour = $hour === null ? $this->hour() : $hour; $minute = $minute === null ? $this->minute() : $minute; $second = $second === null ? $this->second() : $second; $microsecond = $microsecond === null ? $this->microsecond() : $microsecond; $instance->date->setTime($hour, $minute, $second); // There is no API for setting the microsecond explicitly so a new instance has to be constructed. $format = 'Y-m-d H:i:s'; $value = $instance->format($format) . '.' . substr($microsecond, 0, 6); $instance->date = \DateTime::createFromFormat("$format.u", $value); return $instance; }
php
{ "resource": "" }
q4948
DateTime.withTimeZone
train
public function withTimeZone(\DateTimeZone $timezone) : self { if ($this->timezone()->getName() === $timezone->getName()) { return $this; } $instance = clone $this; $instance->date->setTimezone($timezone); return $instance; }
php
{ "resource": "" }
q4949
DateTime.subtract
train
public function subtract($interval) : self { $instance = clone $this; $instance->date->sub(self::resolveDateInterval($interval)); return $instance; }
php
{ "resource": "" }
q4950
DateTime.add
train
public function add($interval) : self { $instance = clone $this; $instance->date->add(self::resolveDateInterval($interval)); return $instance; }
php
{ "resource": "" }
q4951
DateTime.modify
train
public function modify(string $specification) : self { $instance = clone $this; $instance->date->modify($specification); return $instance; }
php
{ "resource": "" }
q4952
DateRange.contains
train
public function contains(DateTime $dateTime) : bool { return $this->from->isEarlierThanOrEqualTo($dateTime) && $this->until->isLaterThan($dateTime); }
php
{ "resource": "" }
q4953
DateRange.equals
train
public function equals(self $other) : bool { if ($other === $this) { return true; } return $other->from->equals($this->from) && $other->until->equals($this->until); }
php
{ "resource": "" }
q4954
DateRange.dateDiff
train
private function dateDiff() : DateInterval { if (null === $this->dateDiff) { $this->dateDiff = $this->from->withTimeAtMidnight()->diff($this->until->withTimeAtMidnight()); } return $this->dateDiff; }
php
{ "resource": "" }
q4955
DateRange.fullDiff
train
private function fullDiff() : DateInterval { if (null === $this->fullDiff) { $this->fullDiff = $this->from->diff($this->until); } return $this->fullDiff; }
php
{ "resource": "" }
q4956
ObjectAttributeTrait.applyObjectConditions
train
protected function applyObjectConditions() { if ($this->object !== null) { $this->andWhere(Db::parseParam('objectId', $this->object)); } }
php
{ "resource": "" }
q4957
AdminAccessController.requestLoginToken
train
public function requestLoginToken() { // Get dependencies $session = $this->container->sessionHandler; $email = $this->container->emailHandler; $security = $this->container->accessHandler; $userMapper = ($this->container->dataMapper)('UserMapper'); $body = $this->request->getParsedBody(); // Fetch all users $userList = $userMapper->find(); // Clean provided email $providedEmail = strtolower(trim($body['email'])); $foundValidUser = false; foreach ($userList as $user) { if ($user->email === $providedEmail) { $foundValidUser = $user; break; } } // Did we find a match? if (!$foundValidUser) { // No, log and silently redirect to home $this->container->logger->alert('Failed login attempt: ' . $body['email']); return $this->redirect('home'); } // Belt and braces/suspenders double check if ($foundValidUser->email === $providedEmail) { // Get and set token, and user ID $token = $security->generateLoginToken(); $session->setData([ $this->loginTokenKey => $token, $this->loginTokenExpiresKey => time() + 120, 'user_id' => $foundValidUser->id, 'email' => $foundValidUser->email ]); // Get request details to create login link and email to user $scheme = $this->request->getUri()->getScheme(); $host = $this->request->getUri()->getHost(); $link = $scheme . '://' . $host; $link .= $this->container->router->pathFor('adminProcessLoginToken', ['token' => $token]); // Send message $email->setTo($providedEmail, '') ->setSubject('PitonCMS Login') ->setMessage("Click to login\n\n {$link}") ->send(); } // Direct to home page return $this->redirect('home'); }
php
{ "resource": "" }
q4958
AdminAccessController.processLoginToken
train
public function processLoginToken($args) { // Get dependencies $session = $this->container->sessionHandler; $security = $this->container->accessHandler; $savedToken = $session->getData($this->loginTokenKey); $tokenExpires = $session->getData($this->loginTokenExpiresKey); // Checks whether token matches, and if within expires time if ($args['token'] === $savedToken && time() < $tokenExpires) { // Successful, set session $security->startAuthenticatedSession(); // Delete token $session->unsetData($this->loginTokenKey); $session->unsetData($this->loginTokenExpiresKey); // Go to admin dashboard return $this->redirect('adminHome'); } // Not valid, direct home $message = $args['token'] . ' saved: ' . $savedToken . ' time: ' . time() . ' expires: ' . $tokenExpires; $this->container->logger->info('Invalid login token, supplied: ' . $message); return $this->notFound(); }
php
{ "resource": "" }
q4959
AdminSettingController.showSettings
train
public function showSettings() { // Get dependencies $settingMapper = ($this->container->dataMapper)('SettingMapper'); $json = $this->container->json; // Fetch settings from database $allSettings = $settingMapper->findSiteSettings(); // Fetch custom settings $jsonFilePath = ROOT_DIR . "structure/definitions/customSettings.json"; if (null === $customSettings = $json->getJson($jsonFilePath, 'setting')) { $this->setAlert('danger', 'Custom Settings Error', $json->getErrorMessages()); } else { // Merge saved settings with custom settings $allSettings = $this->mergeSettings($allSettings, $customSettings->settings); } return $this->render('editSettings.html', $allSettings); }
php
{ "resource": "" }
q4960
ExternalDetector.lookForBrokenLinks
train
public function lookForBrokenLinks($postId = null, $url = null) { \BrokenLinkDetector\App::checkInstall(); $foundUrls = array(); if ($url) { $url = "REGEXP ('.*(href=\"{$url}\").*')"; } else { $url = "RLIKE ('href=*')"; } global $wpdb; $sql = " SELECT ID, post_content FROM $wpdb->posts WHERE post_content {$url} AND post_type NOT IN ('attachment', 'revision', 'acf', 'acf-field', 'acf-field-group') AND post_status IN ('publish', 'private', 'password') "; if (is_numeric($postId)) { $sql .= " AND ID = $postId"; } $posts = $wpdb->get_results($sql); if(is_array($posts) && !empty($posts)) { foreach ($posts as $post) { preg_match_all('/<a[^>]+href=([\'"])(http|https)(.+?)\1[^>]*>/i', $post->post_content, $m); if (!isset($m[3]) || count($m[3]) > 0) { foreach ($m[3] as $key => $url) { $url = $m[2][$key] . $url; // Replace whitespaces in url if (preg_match('/\s/', $url)) { $newUrl = preg_replace('/ /', '%20', $url); $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_content = REPLACE(post_content, %s, %s) WHERE post_content LIKE %s AND ID = %d", $url, $newUrl, '%' . $wpdb->esc_like($url) . '%', $post->ID ) ); $url = $newUrl; } if ($postId !== 'internal' && !$this->isBroken($url)) { continue; } $foundUrls[] = array( 'post_id' => $post->ID, 'url' => $url ); } } } } $this->saveBrokenLinks($foundUrls, $postId); }
php
{ "resource": "" }
q4961
ExternalDetector.isBroken
train
public function isBroken($url) { if (!$domain = parse_url($url, PHP_URL_HOST)) { return true; } if(in_array($domain, (array) apply_filters('brokenLinks/External/ExceptedDomains', array()))) { return false; } // Convert domain name to IDNA ASCII form if(count(explode('.', $domain)) == count(array_filter(explode('.', $domain), function($var) { if(strlen($var) < 1) { return false; } return true; }))) { try { $punycode = new Punycode(); $domainAscii = $punycode->encode($domain); $url = str_ireplace($domain, $domainAscii, $url); } catch (Exception $e) { return false; } } // Test if URL is internal and page exist if ($this->isInternal($url)) { return false; } // Validate domain name if (!$this->isValidDomainName(isset($domainAscii) ? $domainAscii : $domain)) { return true; } // Test if domain is available return !$this->isDomainAvailable($url); }
php
{ "resource": "" }
q4962
ExternalDetector.isDomainAvailable
train
public function isDomainAvailable($url, $timeOut = 7) { // Init curl $ch = curl_init($url); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeOut); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_HTTPGET, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_MAXREDIRS, 5); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // Get the response $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); $curlErrorNo = curl_errno($ch); curl_close($ch); //Curl response error if($curlErrorNo) { if(in_array($curlErrorNo, array(CURLE_TOO_MANY_REDIRECTS))) { if(defined("BROKEN_LINKS_LOG") && BROKEN_LINKS_LOG) { error_log("Broken links: Could not probe url " . $url . " due to a malfunction of curl [" . $curlErrorNo. " - " . $curlError . "]"); } return true; //Do not log } else { if(defined("BROKEN_LINKS_LOG") && BROKEN_LINKS_LOG) { error_log("Broken links: Could not probe url " . $url . ", link is considerd broken [" . $curlErrorNo. " - " . $curlError . "]"); } return false; // Do log } } if(defined("BROKEN_LINKS_LOG") && BROKEN_LINKS_LOG) { error_log("Broken links: Probe data " . $url . " [Curl error no: " . $curlErrorNo. "] [Curl error message:" . $curlError . "] [Http code: ".$httpCode."]"); } //Validate if($response) { //Genereic codes if($httpCode >= 200 && $httpCode < 400) { return true; } //Specific out of scope codes //401: Unathorized //406: Not acceptable //413: Payload to large //418: I'm a teapot if(in_array($httpCode, array(401, 406, 413))) { return true; } } return false; }
php
{ "resource": "" }
q4963
ExternalDetector.isInternal
train
public function isInternal($url) { // Check if post exist by url (only works with 'public' posts) $postId = url_to_postid($url); if ($postId > 0) { return true; } // Check if the URL is internal or external $siteUrlComponents = parse_url(get_site_url()); $urlComponents = parse_url($url); if (!empty($siteUrlComponents['host']) && !empty($urlComponents['host']) && strcasecmp($urlComponents['host'], $siteUrlComponents['host']) === 0) { // Test with get_page_by_path() to get other post statuses $postTypes = get_post_types(array('public' => true)); if (!empty($urlComponents['path']) && !empty(get_page_by_path(basename(untrailingslashit($urlComponents['path'])), ARRAY_A, $postTypes))) { return true; } } return false; }
php
{ "resource": "" }
q4964
ViewHelper.call
train
public function call($presenter, array $data = []) { $response = $this->builder ->getView() ->start($this->request, $this->response) ->call($presenter, $data); return $this->returnResponseBody($response); }
php
{ "resource": "" }
q4965
ViewHelper.render
train
public function render($viewFile, $data = []) { return $this->builder ->getView() ->start($this->request, $this->response) ->renderContents($viewFile, $data); }
php
{ "resource": "" }
q4966
EmailQueueItem.setIdent
train
public function setIdent($ident) { if ($ident === null) { $this->ident = null; return $this; } if (!is_string($ident)) { throw new InvalidArgumentException( 'Ident needs to be a string' ); } $this->ident = $ident; return $this; }
php
{ "resource": "" }
q4967
EmailQueueItem.process
train
public function process( callable $callback = null, callable $successCallback = null, callable $failureCallback = null ) { if ($this->processed() === true) { // Do not process twice, ever. return null; } $email = $this->emailFactory()->create('email'); $email->setData($this->data()); try { $res = $email->send(); if ($res === true) { $this->setProcessed(true); $this->setProcessedDate('now'); $this->update(['processed', 'processed_date']); if ($successCallback !== null) { $successCallback($this); } } else { if ($failureCallback !== null) { $failureCallback($this); } } if ($callback !== null) { $callback($this); } return $res; } catch (Exception $e) { // Todo log error if ($failureCallback !== null) { $failureCallback($this); } return false; } }
php
{ "resource": "" }
q4968
AdminController.home
train
public function home() { $json = $this->container->json; // Get Piton Engine version from composer.lock if (null === $definition = $json->getJson(ROOT_DIR . '/composer.lock')) { $this->setAlert('danger', 'Error Reading composer.lock', $json->getErrorMessages()); } $engineKey = array_search('pitoncms/engine', array_column($definition->packages, 'name')); $engineVersion = $definition->packages[$engineKey]->version; return $this->render('home.html', ['pitonEngineVersion' => $engineVersion]); }
php
{ "resource": "" }
q4969
AdminController.release
train
public function release($args) { $json = $this->container->json; $markdown = $this->container->markdownParser; $responseBody = ''; // If curl is not installed display alert if (!function_exists('curl_init')) { $this->setAlert('warning', 'Required PHP cURL not installed'); } else { // https://developer.github.com/v3/repos/releases $githubApi = 'https://api.github.com/repos/PitonCMS/Engine/releases'; $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_URL => $githubApi, CURLOPT_USERAGENT => $this->request->getHeaderLine('HTTP_USER_AGENT') ]); $responseBody = curl_exec($curl); $responseStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); // Verify that we have a response if ($responseStatus == '200') { $releases = json_decode($responseBody); $releases = array_slice($releases, 0, 5, true); // Format Markdown foreach ($releases as $key => $release) { $releases[$key]->body = $markdown->text($release->body); } // Check if there is a more current release if (array_search($args['release'], array_column($releases, 'tag_name')) > 0) { $message = "The current version is {$releases[0]->tag_name}, you have version {$args['release']}."; $message .= "\nTo upgrade, from your project root run <code>composer update pitoncms/engine</code>"; $this->setAlert('info', 'There is a newer version of the PitonCMS Engine', $message); } } else { $releases = []; $this->setAlert('warning', "$responseStatus Response From GitHub", $responseBody); } } return $this->render('releaseNotes.html', ['releases' => $releases]); }
php
{ "resource": "" }
q4970
Module.onBootstrap
train
public function onBootstrap(MvcEvent $e) { // we attach with wildcard events name $events = $e->getApplication()->getEventManager(); $events->attach( MvcEvent::EVENT_RENDER, new InjectSubNavigationListener(), 10 ); }
php
{ "resource": "" }
q4971
Discoverer.getEndpointForUrl
train
public function getEndpointForUrl($url) { if (!isset($this->cachedEndpoints[$url])) { $this->cachedEndpoints[$url] = $this->fetchEndpointForUrl($url); } return $this->cachedEndpoints[$url]; }
php
{ "resource": "" }
q4972
Discoverer.fetchEndpointForUrl
train
protected function fetchEndpointForUrl($url) { $client = new Client($url); $body = $client->send(); $regexp = str_replace( '@formats@', implode('|', $this->supportedFormats), self::LINK_REGEXP ); if (!preg_match_all($regexp, $body, $matches, PREG_SET_ORDER)) { throw new \InvalidArgumentException('No valid oEmbed links found on page.'); } foreach ($matches as $match) { if ($match['Format'] === $this->preferredFormat) { return $this->extractEndpointFromAttributes($match['Attributes']); } } return $this->extractEndpointFromAttributes($match['Attributes']); }
php
{ "resource": "" }
q4973
DateTimeComparator.lowest
train
public static function lowest(... $datetimes) { $lowest = null; foreach ($datetimes as $datetime) { if (!$datetime instanceof \DateTimeInterface) { continue; } if ($datetime < $lowest || null === $lowest) { $lowest = $datetime; } } return $lowest; }
php
{ "resource": "" }
q4974
DOIServiceProvider.authenticate
train
public function authenticate( $appID, $sharedSecret = null, $ipAddress = null, $manual = false ) { // set app_id before trying to authenticate for logging and report purpose $this->setResponse('app_id', $appID); // attempt authentication $client = $this->clientRepo->authenticate($appID, $sharedSecret, $ipAddress, $manual); // client is authenticated if ($client) { $this->setAuthenticatedClient($client); return true; } // client is not authenticated $this->setResponse('responsecode', 'MT009'); $this->setResponse('verbosemessage', $this->clientRepo->getMessage()); $this->clientRepo->setMessage(null); return false; }
php
{ "resource": "" }
q4975
DOIServiceProvider.isDoiAuthenticatedClients
train
public function isDoiAuthenticatedClients($doiValue, $client_id = null) { if ($client_id === null) { return false; } $client = $this->getAuthenticatedClient(); if ($client->client_id != $client_id) { return false; } // everyone has access to test prefix if (strpos($doiValue, DOIServiceProvider::$globalTestPrefix) === 0) { return true; } // check if the client owns the prefix foreach ($client->prefixes as $clientPrefix) { if (strpos($doiValue, $clientPrefix->prefix->prefix_value) === 0) { return true; } } return false; }
php
{ "resource": "" }
q4976
DOIServiceProvider.mint
train
public function mint($url, $xml, $manual = false) { // @todo event handler, message if (!$this->isClientAuthenticated()) { $this->setResponse("responsecode", "MT009"); return false; } // Validate URL and URL Domain $this->setResponse('url', $url); $validDomain = URLValidator::validDomains( $url, $this->getAuthenticatedClient()->domains ); if (!$validDomain) { $this->setResponse("responsecode", "MT014"); return false; } // construct DOI
 if($manual===true){ $doiValue = XMLValidator::getDOIValue($xml); }else{ $doiValue = $this->getNewDOI(); // replaced doiValue $xml = XMLValidator::replaceDOIValue($doiValue, $xml); } $this->setResponse('doi', $doiValue); // validation on the DOIValue // Validate xml if($this->validateXML($xml) === false){ $this->setResponse('responsecode', 'MT006'); return false; } //update the database DOIRepository $doi = $this->insertNewDOI($doiValue,$xml,$url); // mint using dataciteClient $result = $this->dataciteClient->mint($doiValue, $url, $xml); if ($result === true) { $this->setResponse('responsecode', 'MT001'); $this->doiRepo->doiUpdate($doi, array('status'=>'ACTIVE')); } else { $this->setResponse('responsecode', 'MT005'); $this->setResponse('verbosemessage', array_first($this->dataciteClient->getErrors())); } return $result; }
php
{ "resource": "" }
q4977
DOIServiceProvider.validateXML
train
public function validateXML($xml) { $xmlValidator = new XMLValidator(); $result = $xmlValidator->validateSchemaVersion($xml); if ($result === false) { $this->setResponse("verbosemessage", $xmlValidator->getValidationMessage()); return false; } return true; }
php
{ "resource": "" }
q4978
DOIServiceProvider.getNewDOI
train
public function getNewDOI() { // get the first active prefix for this authenticated client $prefix = ""; $testStr = ""; $client = $this->getAuthenticatedClient(); //if this client is not in test mode grab their production prefix if(sizeof($client->prefixes) > 0 && $client->mode !== 'test'){ foreach ($client->prefixes as $clientPrefix) { if($clientPrefix->active && $clientPrefix->is_test == 0) { $prefix = $clientPrefix->prefix->prefix_value; break; } } } if(sizeof($client->prefixes) > 0 && $client->mode == 'test'){ foreach ($client->prefixes as $clientPrefix) { if($clientPrefix->active && $clientPrefix->is_test == 1) { $prefix = $clientPrefix->prefix->prefix_value; $testStr = "TEST_DOI_"; break; } } } $prefix = ends_with($prefix, '/') ? $prefix : $prefix .'/'; $doiValue = uniqid(); return $prefix . $testStr . $doiValue; }
php
{ "resource": "" }
q4979
DOIServiceProvider.update
train
public function update($doiValue, $url=NULL, $xml=NULL) { if (!$this->isClientAuthenticated()) { $this->setResponse("responsecode", "MT009"); return false; } $doi = $this->doiRepo->getByID($doiValue); $this->setResponse('doi', $doiValue); if ($doi === null) { $this->setResponse('responsecode', 'MT011'); return true; } // check if this client owns this doi if (!$this->isDoiAuthenticatedClients($doiValue, $doi->client_id)) { $this->setResponse('responsecode', 'MT008'); $this->setResponse('verbosemessage',$doiValue." is not owned by ".$this->getAuthenticatedClient()->client_name); return false; } // Validate URL and URL Domain if (isset($url) && $url!="") { $this->setResponse('url', $url); $validDomain = URLValidator::validDomains( $url, $this->getAuthenticatedClient()->domains ); if (!$validDomain) { $this->setResponse("responsecode", "MT014"); return false; } } if(isset($xml) && $xml!="") { // need to check that doi provided in xml matches doi $xml = XMLValidator::replaceDOIValue($doiValue, $xml); // Validate xml if ($this->validateXML($xml) === false) { $this->setResponse('responsecode', 'MT007'); return false; } } if (isset($url) && $url!="") { $result = $this->dataciteClient->updateURL($doiValue, $url); if ($result === true) { $this->setResponse('responsecode', 'MT002'); //update the database DOIRepository $this->doiRepo->doiUpdate($doi, array('url'=>$url)); } else { $this->setResponse('responsecode', 'MT010'); $this->setResponse('verbosemessage', array_first($this->dataciteClient->getErrors())); return false; } } if(isset($xml) && $xml!="") { $result = $this->dataciteClient->update($xml); if ($result === true) { $this->setResponse('responsecode', 'MT002'); //update the database DOIRepository $this->doiRepo->doiUpdate($doi, array('datacite_xml'=>$xml,'status'=>'ACTIVE')); } else { $this->setResponse('responsecode', 'MT010'); $this->setResponse('verbosemessage', array_first($this->dataciteClient->getErrors())); return false; } } return true; }
php
{ "resource": "" }
q4980
DOIServiceProvider.activate
train
public function activate($doiValue) { // validate client if (!$this->isClientAuthenticated()) { $this->setResponse('responsecode', 'MT009'); return false; } //get the doi info $doi = $this->doiRepo->getByID($doiValue); $this->setResponse('doi', $doiValue); if ($doi === null) { $this->setResponse('responsecode', 'MT011'); return true; } // check if this client owns this doi if (!$this->isDoiAuthenticatedClients($doiValue, $doi->client_id)) { $this->setResponse('responsecode', 'MT008'); $this->setResponse('verbosemessage',$doiValue." is not owned by ".$this->getAuthenticatedClient()->client_name); return false; } $doi_xml = $doi->datacite_xml; //check if the doi is inactive if ($doi->status != 'INACTIVE') { $this->setResponse('responsecode', 'MT010'); $this->setResponse('verbosemessage', 'DOI ' . $doiValue . " not set to INACTIVE so cannot activate it"); return false; } // activate using dataciteClient update method; $result = $this->dataciteClient->update($doi_xml); if ($result === true) { $this->setResponse('responsecode', 'MT004'); //update the database DOIRepository $this->doiRepo->doiUpdate($doi, array('status'=>'ACTIVE')); } else { $this->setResponse('responsecode', 'MT010'); } return $result; }
php
{ "resource": "" }
q4981
DOIServiceProvider.getStatus
train
public function getStatus($doiValue) { // validate client if (!$this->isClientAuthenticated()) { $this->setResponse('responsecode', 'MT009'); return false; } //get the doi info $doi = $this->doiRepo->getByID($doiValue); $this->setResponse('doi', $doiValue); if ($doi === null) { $this->setResponse('responsecode', 'MT011'); return true; } // check if this client owns this doi if (!$this->isDoiAuthenticatedClients($doiValue, $doi->client_id)) { $this->setResponse('responsecode', 'MT008'); $this->setResponse('verbosemessage', $doiValue . " is not owned by " . $this->getAuthenticatedClient()->client_name); return false; } $this->setResponse('responsecode', 'MT019'); $this->setResponse('verbosemessage', $doi->status); return true; }
php
{ "resource": "" }
q4982
DOIServiceProvider.deactivate
train
public function deactivate($doiValue) { // validate client if (!$this->isClientAuthenticated()) { $this->setResponse('responsecode', 'MT009'); return false; } //get the doi info $doi = $this->doiRepo->getByID($doiValue); $this->setResponse('doi', $doiValue); if ($doi === null) { $this->setResponse('responsecode', 'MT011'); return true; } // check if this client owns this doi if (!$this->isDoiAuthenticatedClients($doiValue, $doi->client_id)) { $this->setResponse('responsecode', 'MT008'); $this->setResponse('verbosemessage',$doiValue." is not owned by ".$this->getAuthenticatedClient()->client_name); return false; } //check if the doi is inactive if ($doi->status != 'ACTIVE') { $this->setResponse('responsecode', 'MT010'); $this->setResponse('verbosemessage', 'DOI ' . $doiValue . " not set to ACTIVE so cannot deactivate it"); return false; } $result = $this->dataciteClient->deActivate($doiValue); if ($result === true) { $this->setResponse('responsecode', 'MT003'); //update the database DOIRepository $this->doiRepo->doiUpdate($doi, array('status'=>'INACTIVE')); } else { $this->setResponse('responsecode', 'MT010'); } return $result; }
php
{ "resource": "" }
q4983
Level.guardLevelBoundaries
train
private function guardLevelBoundaries($levelValue) { if ($levelValue < static::MIN_LEVEL) { throw new Exceptions\MinLevelUnderflow( 'Level has to be at least ' . self::MIN_LEVEL . ', got ' . $levelValue ); } if ($levelValue > static::MAX_LEVEL) { throw new Exceptions\MaxLevelOverflow( 'Level can not be greater than ' . self::MAX_LEVEL . ', got ' . $levelValue ); } }
php
{ "resource": "" }
q4984
PhpException.toJson
train
public static function toJson($e, bool $getTrace = true, string $catcher = null): string { if (!$getTrace) { return \json_encode(['msg' => "Error: {$e->getMessage()}"]); } $map = [ 'code' => $e->getCode() ?: 500, 'msg' => sprintf( '%s(%d): %s, File: %s(Line %d)', \get_class($e), $e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine() ), 'data' => $e->getTrace() ]; if ($catcher) { $map['catcher'] = $catcher; } if ($getTrace) { $map['trace'] = $e->getTrace(); } return \json_encode($map); }
php
{ "resource": "" }
q4985
Files.normalizeFilesArray
train
public static function normalizeFilesArray(array $files): array { $return = []; foreach ($files as $i => $file) { foreach ($file as $key => $value) { $return[$key][$i] = $value; } } return $return; }
php
{ "resource": "" }
q4986
PostsTagsController.index
train
public function index() { $page = $this->request->getQuery('page', 1); $this->paginate['order'] = ['tag' => 'ASC']; //Limit X4 $this->paginate['limit'] = $this->paginate['maxLimit'] = $this->paginate['limit'] * 4; //Sets the cache name $cache = sprintf('tags_limit_%s_page_%s', $this->paginate['limit'], $page); //Tries to get data from the cache list($tags, $paging) = array_values(Cache::readMany( [$cache, sprintf('%s_paging', $cache)], $this->PostsTags->getCacheName() )); //If the data are not available from the cache if (empty($tags) || empty($paging)) { $query = $this->PostsTags->Tags->find('active'); $tags = $this->paginate($query); //Writes on cache Cache::writeMany([ $cache => $tags, sprintf('%s_paging', $cache) => $this->request->getParam('paging'), ], $this->PostsTags->getCacheName()); //Else, sets the paging parameter } else { $this->request = $this->request->withParam('paging', $paging); } $this->set(compact('tags')); }
php
{ "resource": "" }
q4987
PostsTagsController.view
train
public function view($slug = null) { //Data can be passed as query string, from a widget if ($this->request->getQuery('q')) { return $this->redirect([$this->request->getQuery('q')]); } $slug = Text::slug($slug, ['replacement' => ' ']); $tag = $this->PostsTags->Tags->findActiveByTag($slug) ->cache((sprintf('tag_%s', md5($slug))), $this->PostsTags->getCacheName()) ->firstOrFail(); $page = $this->request->getQuery('page', 1); //Sets the cache name $cache = sprintf('tag_%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->PostsTags->getCacheName() )); //If the data are not available from the cache if (empty($posts) || empty($paging)) { $query = $this->PostsTags->Posts->find('active') ->find('forIndex') ->matching($this->PostsTags->Tags->getAlias(), function (Query $q) use ($slug) { return $q->where(['tag' => $slug]); }); $posts = $this->paginate($query); //Writes on cache Cache::writeMany([ $cache => $posts, sprintf('%s_paging', $cache) => $this->request->getParam('paging'), ], $this->PostsTags->getCacheName()); //Else, sets the paging parameter } else { $this->request = $this->request->withParam('paging', $paging); } $this->set(compact('posts', 'tag')); }
php
{ "resource": "" }
q4988
CreateGroupsCommand.execute
train
public function execute(Arguments $args, ConsoleIo $io) { $this->loadModel('MeCms.UsersGroups'); if (!$this->UsersGroups->find()->isEmpty()) { $io->error(__d('me_cms', 'Some user groups already exist')); return null; } //Truncates the table (this resets IDs), then saves groups ConnectionManager::get('default')->execute(sprintf('TRUNCATE TABLE `%s`', $this->UsersGroups->getTable())); $this->UsersGroups->saveMany($this->UsersGroups->newEntities([ ['id' => 1, 'name' => 'admin', 'label' => 'Admin'], ['id' => 2, 'name' => 'manager', 'label' => 'Manager'], ['id' => 3, 'name' => 'user', 'label' => 'User'], ])); $io->verbose(__d('me_cms', 'The user groups have been created')); return null; }
php
{ "resource": "" }
q4989
Glared.getCurrentMalus
train
public function getCurrentMalus(): int { if ($this->getGettingUsedToForRounds() === 0) { return $this->malus; } if ($this->isShined()) { // each rounds of getting used to lowers malus by one point return $this->malus + $this->getGettingUsedToForRounds(); } // ten rounds of getting used to are needed to lower glare malus by a single point return $this->malus + SumAndRound::floor($this->getGettingUsedToForRounds() / 10); }
php
{ "resource": "" }
q4990
Glared.setGettingUsedToForTime
train
public function setGettingUsedToForTime(Time $gettingUsedToFor) { $inRounds = $gettingUsedToFor->findRounds(); if ($inRounds === null) { // it can not be expressed by rounds, so definitely get used to it - malus zeroed if ($this->isShined()) { $this->gettingUsedToForRounds = -$this->malus; } else { // if blinded than needs ten more time to get used to it $this->gettingUsedToForRounds = -$this->malus * 10; } return; } if ($this->isShined()) { if ($this->malus + $inRounds->getValue() > 0) { // more time than needed, malus is gone $this->gettingUsedToForRounds = -$this->malus; // zeroed malus in fact } else { $this->gettingUsedToForRounds = $inRounds->getValue(); // not enough to remove whole glare and malus } } else { // if blinded than needs ten more time to get used to it if ($this->malus + $inRounds->getValue() / 10 > 0) { // more time than needed, malus is gone $this->gettingUsedToForRounds = -$this->malus * 10; // zeroed malus in fact } else { $this->gettingUsedToForRounds = $inRounds->getValue(); // not enough to remove whole glare and malus } } }
php
{ "resource": "" }
q4991
BaseMfa.loginUser
train
protected function loginUser() { // Set login data for this user $oUserModel = Factory::model('User', 'nails/module-auth'); $oUserModel->setLoginData($this->mfaUser->id); // If we're remembering this user set a cookie if ($this->remember) { $oUserModel->setRememberCookie( $this->mfaUser->id, $this->mfaUser->password, $this->mfaUser->email ); } // Update their last login and increment their login count $oUserModel->updateLastLogin($this->mfaUser->id); // -------------------------------------------------------------------------- // Generate an event for this log in create_event('did_log_in', ['method' => $this->loginMethod], $this->mfaUser->id); // -------------------------------------------------------------------------- // Say hello if ($this->mfaUser->last_login) { $oConfig = Factory::service('Config'); if ($oConfig->item('authShowNicetimeOnLogin')) { $sLastLogin = niceTime(strtotime($this->mfaUser->last_login)); } else { $sLastLogin = toUserDatetime($this->mfaUser->last_login); } if ($oConfig->item('authShowLastIpOnLogin')) { $sStatus = 'positive'; $sMessage = lang( 'auth_login_ok_welcome_with_ip', [ $this->mfaUser->first_name, $sLastLogin, $this->mfaUser->last_ip, ] ); } else { $sStatus = 'positive'; $sMessage = lang( 'auth_login_ok_welcome', [ $this->mfaUser->first_name, $sLastLogin, ] ); } } else { $sStatus = 'positive'; $sMessage = lang( 'auth_login_ok_welcome_notime', [ $this->mfaUser->first_name, ] ); } $oSession = Factory::service('Session', 'nails/module-auth'); $oSession->setFlashData($sStatus, $sMessage); // -------------------------------------------------------------------------- // Delete the token we generated, it's no needed, eh! $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oAuthModel->mfaTokenDelete($this->data['token']['id']); // -------------------------------------------------------------------------- $sRedirectUrl = $this->returnTo != site_url() ? $this->returnTo : $this->mfaUser->group_homepage; redirect($sRedirectUrl); }
php
{ "resource": "" }
q4992
LoadSiteSettings.loadSettings
train
public function loadSettings() { $SettingMapper = ($this->dataMapper)('SettingMapper'); $siteSettings = $SettingMapper->find(); // Create new multi-dimensional array keyed by the setting category and key $this->settings = array_column($siteSettings, 'setting_value', 'setting_key'); // Load some config file settings into new settings $this->settings['production'] = $this->appSettings['site']['production']; $this->settings['pitonDev'] = isset($this->appSettings['site']['pitonDev']) ? $this->appSettings['site']['pitonDev'] : false; }
php
{ "resource": "" }
q4993
LoadSiteSettings.loadPages
train
public function loadPages($request) { $pageMapper = ($this->dataMapper)('pageMapper'); // Fetch all published pages $this->pages = $pageMapper->findPages(); // Set flag on page for current request $url = $request->getUri()->getPath(); // Check if home page '/' to match slug name $url = ($url === '/') ? 'home' : ltrim($url, '/'); $key = array_search($url, array_column($this->pages, 'slug')); if (is_numeric($key)) { $this->pages[$key]->currentPage = true; } return; }
php
{ "resource": "" }
q4994
Literal.getValue
train
public function getValue(Db $db, ...$args) { $driver = $this->driverKey($db); if (isset($this->driverValues[$driver])) { return sprintf($this->driverValues[$driver], ...$args); } elseif (isset($this->driverValues['default'])) { return sprintf($this->driverValues['default'], ...$args); } else { throw new \InvalidArgumentException("No literal for driver '$driver'.", 500); } }
php
{ "resource": "" }
q4995
Literal.setValue
train
public function setValue($value, $driver = 'default') { $driver = $this->driverKey($driver); $this->driverValues[$driver] = $value; return $this; }
php
{ "resource": "" }
q4996
Literal.driverKey
train
protected function driverKey($key) { if (is_object($key)) { $key = get_class($key); } $key = strtolower(basename($key)); if (preg_match('`([az]+)(Db)?$`', $key, $m)) { $key = $m; } return $key; }
php
{ "resource": "" }
q4997
Helper.getOptions
train
public static function getOptions($userSpecified, $defaults) { $options = static::getAnyOptions($userSpecified, $defaults); foreach ($options as $key => $null) { if (array_key_exists($key, $defaults)) { continue; } throw new \InvalidArgumentException("Unknown parameter (" . $key . ")"); } return $options; }
php
{ "resource": "" }
q4998
Helper.toString
train
public static function toString($data) { if (is_array($data)) { $newData = []; foreach ($data as $key => $val) { $key = (string)$key; $newData[$key] = static::toString($val); } } else { $newData = (string)$data; } return $newData; }
php
{ "resource": "" }
q4999
Helper.toArray
train
public static function toArray($value) { # If it's already an array then just pass it back if (is_array($value)) { return $value; } if ($value instanceof SerialObject) { return $value->asArray(); } if ($value instanceof \ArrayObject) { return $value->getArrayCopy(); } # If it's not an array then create a new array to be returned $array = []; # If a value was passed as a string/int then include it in the new array if ($value) { $array[] = $value; } return $array; }
php
{ "resource": "" }