_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
33
8k
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; }
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 = [];
php
{ "resource": "" }
q4902
Password.getRulesAsString
train
public function getRulesAsString($iGroupId) { $aRules = $this->getRulesAsArray($iGroupId); if (empty($aRules)) { return ''; } $sStr = 'Passwords
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':
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
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,
php
{ "resource": "" }
q4906
PageSettingMapper.findPageSettings
train
public function findPageSettings($pageId) { $this->makeSelect(); $this->sql .= ' and page_id = ?';
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
php
{ "resource": "" }
q4908
WidgetHelper.all
train
public function all() { foreach ($this->getAll() as $widget) { foreach ($widget as $name => $args) { $widgets[] = $this->widget($name, $args); }
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]) ?
php
{ "resource": "" }
q4910
BackupsController.index
train
public function index() { $backups = collection($this->BackupManager->index()) ->map(function (Entity $backup) {
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
php
{ "resource": "" }
q4912
BackupsController.delete
train
public function delete($filename) { $this->request->allowMethod(['post', 'delete']); $this->BackupManager->delete($this->getFilename($filename));
php
{ "resource": "" }
q4913
BackupsController.deleteAll
train
public function deleteAll() { $this->request->allowMethod(['post', 'delete']); $this->BackupManager->deleteAll();
php
{ "resource": "" }
q4914
BackupsController.restore
train
public function restore($filename) { //Imports and clears the cache (new BackupImport)->filename($this->getFilename($filename))->import(); Cache::clearAll();
php
{ "resource": "" }
q4915
BackupsController.send
train
public function send($filename) { $this->BackupManager->send($this->getFilename($filename), getConfigOrFail('email.webmaster'));
php
{ "resource": "" }
q4916
OEmbed.setURL
train
public function setURL($url) { if (!$this->validateURL($url)) { throw new \InvalidArgumentException(sprintf('The URL "%s" is invalid.', $url));
php
{ "resource": "" }
q4917
OEmbed.removeProvider
train
public function removeProvider(Provider $provider) { $index = array_search($provider, $this->providers); if ($index !== false) {
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.'); }
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);
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
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,
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'))
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
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;
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,
php
{ "resource": "" }
q4926
Connection.get
train
public function get($resource, $body = null, $params = []) {
php
{ "resource": "" }
q4927
Connection.post
train
public function post($resource, $body = null, $params = []) {
php
{ "resource": "" }
q4928
Connection.send
train
protected function send(Request $request) { try { $response = $this->client->send($request); } catch (ClientException $e) { $response = $e->getResponse();
php
{ "resource": "" }
q4929
Connection.prepare
train
protected function prepare($method, $resource, $body, $params) { // Append the username parameter to the end of every resource URI.
php
{ "resource": "" }
q4930
PrintableAscii.escapeControlCode
train
protected function escapeControlCode($cp) { $table = [9 => '\\t', 10 => '\\n', 13 => '\\r'];
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());
php
{ "resource": "" }
q4932
ClientRepository.create
train
public function create($params) { $client = new Client; $client->fill($params); $client->save();
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";
php
{ "resource": "" }
q4934
Request.postParam
train
public function postParam(string $name, $valueDefault =
php
{ "resource": "" }
q4935
Request.cookieParam
train
public function cookieParam(string $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'];
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
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
php
{ "resource": "" }
q4939
WeightTable.getMalusFromLoad
train
public function getMalusFromLoad(Strength $strength, Weight $cargoWeight): int { $requiredStrength = $cargoWeight->getBonus()->getValue(); $missingStrength
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) {
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. */
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
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 =
php
{ "resource": "" }
q4944
DateTime.withDateAtStartOfYear
train
public function withDateAtStartOfYear() : self { $instance = $this->withTimeAtMidnight();
php
{ "resource": "" }
q4945
DateTime.withDateAtEndOfMonth
train
public function withDateAtEndOfMonth() : self { $instance = $this->withDateAtStartOfMonth(); $instance->date->modify('+1
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)
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);
php
{ "resource": "" }
q4948
DateTime.withTimeZone
train
public function withTimeZone(\DateTimeZone $timezone) : self { if ($this->timezone()->getName() === $timezone->getName()) { return $this; } $instance = clone
php
{ "resource": "" }
q4949
DateTime.subtract
train
public function subtract($interval) : self { $instance = clone $this;
php
{ "resource": "" }
q4950
DateTime.add
train
public function add($interval) : self { $instance = clone $this;
php
{ "resource": "" }
q4951
DateTime.modify
train
public function modify(string $specification) : self { $instance = clone $this;
php
{ "resource": "" }
q4952
DateRange.contains
train
public function contains(DateTime $dateTime) : bool { return
php
{ "resource": "" }
q4953
DateRange.equals
train
public function equals(self $other) : bool { if ($other === $this) {
php
{ "resource": "" }
q4954
DateRange.dateDiff
train
private function dateDiff() : DateInterval { if (null === $this->dateDiff) { $this->dateDiff =
php
{ "resource": "" }
q4955
DateRange.fullDiff
train
private function fullDiff() : DateInterval { if (null === $this->fullDiff) {
php
{ "resource": "" }
q4956
ObjectAttributeTrait.applyObjectConditions
train
protected function applyObjectConditions() { if ($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,
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);
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',
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
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);
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))) {
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
php
{ "resource": "" }
q4964
ViewHelper.call
train
public function call($presenter, array $data = []) { $response = $this->builder ->getView() ->start($this->request, $this->response)
php
{ "resource": "" }
q4965
ViewHelper.render
train
public function render($viewFile, $data = []) { return $this->builder ->getView()
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(
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) {
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()); }
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) {
php
{ "resource": "" }
q4970
Module.onBootstrap
train
public function onBootstrap(MvcEvent $e) { // we attach with wildcard events name $events = $e->getApplication()->getEventManager(); $events->attach(
php
{ "resource": "" }
q4971
Discoverer.getEndpointForUrl
train
public function getEndpointForUrl($url) { if (!isset($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.'); }
php
{ "resource": "" }
q4973
DateTimeComparator.lowest
train
public static function lowest(... $datetimes) { $lowest = null; foreach ($datetimes as $datetime) { if (!$datetime instanceof \DateTimeInterface) { continue; }
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;
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
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;
php
{ "resource": "" }
q4977
DOIServiceProvider.validateXML
train
public function validateXML($xml) { $xmlValidator = new XMLValidator(); $result = $xmlValidator->validateSchemaVersion($xml); if ($result === false) {
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) {
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));
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');
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');
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') {
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 ); }
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(),
php
{ "resource": "" }
q4985
Files.normalizeFilesArray
train
public static function normalizeFilesArray(array $files): array { $return = []; foreach ($files as $i => $file) { foreach ($file as $key => $value) {
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');
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) {
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,
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(); }
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; }
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
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 =
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
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'])) {
php
{ "resource": "" }
q4995
Literal.setValue
train
public function setValue($value, $driver = 'default') { $driver = $this->driverKey($driver);
php
{ "resource": "" }
q4996
Literal.driverKey
train
protected function driverKey($key) { if (is_object($key)) { $key = get_class($key); } $key = strtolower(basename($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)) {
php
{ "resource": "" }
q4998
Helper.toString
train
public static function toString($data) { if (is_array($data)) { $newData = []; foreach ($data as $key => $val) { $key = (string)$key;
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
php
{ "resource": "" }