_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q4800
StaticPage.all
train
public static function all() { foreach (self::getAllPaths() as $path) { //Gets all files for each path $files = (new Folder($path))->findRecursive('^.+\.ctp$', true); foreach ($files as $file) { $pages[] = new Entity([ 'filename' => pathinfo($file, PATHINFO_FILENAME), 'path' => rtr($file), 'slug' => self::getSlug($file, $path), 'title' => self::title(pathinfo($file, PATHINFO_FILENAME)), 'modified' => new FrozenTime(filemtime($file)), ]); } } return $pages; }
php
{ "resource": "" }
q4801
StaticPage.get
train
public static function get($slug) { $locale = I18n::getLocale(); $slug = array_filter(explode('/', $slug)); $cache = sprintf('page_%s_locale_%s', md5(serialize($slug)), $locale); $page = Cache::read($cache, 'static_pages'); if (empty($page)) { //Sets the (partial) filename $filename = implode(DS, $slug); //Sets the filename patterns $patterns = [$filename . '-' . $locale]; if (preg_match('/^(\w+)_\w+$/', $locale, $matches)) { $patterns[] = $filename . '-' . $matches[1]; } $patterns[] = $filename; //Checks if the page exists in APP foreach ($patterns as $pattern) { $filename = self::getAppPath() . $pattern . '.ctp'; if (is_readable($filename)) { $page = DS . 'StaticPages' . DS . $pattern; break; } } //Checks if the page exists in each plugin foreach (Plugin::all() as $plugin) { foreach ($patterns as $pattern) { $filename = self::getPluginPath($plugin) . $pattern . '.ctp'; if (is_readable($filename)) { $page = $plugin . '.' . DS . 'StaticPages' . DS . $pattern; break; } } } Cache::write($cache, $page, 'static_pages'); } return $page; }
php
{ "resource": "" }
q4802
StaticPage.title
train
public static function title($slugOrPath) { //Gets only the filename (without extension) $slugOrPath = pathinfo($slugOrPath, PATHINFO_FILENAME); //Turns dashes into underscores (because `Inflector::humanize` will // remove only underscores) $slugOrPath = str_replace('-', '_', $slugOrPath); return Inflector::humanize($slugOrPath); }
php
{ "resource": "" }
q4803
Utility.applyCurrentTheme
train
public static function applyCurrentTheme($module = null) { $theme = Yii::app()->theme->name; Yii::app()->theme = $theme; if($module !== null) { $themePath = Yii::getPathOfAlias('webroot.themes.'.$theme.'.views.layouts'); $module->setLayoutPath($themePath); } }
php
{ "resource": "" }
q4804
Utility.getActiveDefaultColumns
train
public static function getActiveDefaultColumns($columns) { $column = array(); foreach($columns as $val) { $keyIndex = self::getKeyIndex($val); if($keyIndex) $column[] = $keyIndex; } return $column; }
php
{ "resource": "" }
q4805
Utility.getUrlTitle
train
public static function getUrlTitle($str, $separator = '-', $lowercase = true) { if($separator === 'dash') { $separator = '-'; } elseif($separator === 'underscore') { $separator = '_'; } $qSeparator = preg_quote($separator, '#'); $trans = array( '&.+?:;' => '', '[^a-z0-9 _-]' => '', '\s+' => $separator, '('.$qSeparator.')+' => $separator ); $str = strip_tags($str); foreach ($trans as $key => $val) { $str = preg_replace('#'.$key.'#i', $val, $str); } if ($lowercase === true) { $str = strtolower($str); } return trim(trim($str, $separator)); }
php
{ "resource": "" }
q4806
Utility.deleteFolder
train
public static function deleteFolder($path) { if(file_exists($path)) { $fh = dir($path); //print_r($fh); while (false !== ($files = $fh->read())) { /* echo $fh->path.'/'.$files."\n"; chmod($fh->path.'/'.$files, 0755); if(@unlink($fh->path.'/'.$files)) echo '1'."\n"; else echo '0'."\n"; */ @unlink($fh->path.'/'.$files); } $fh->close(); @rmdir($path); return true; } else return false; }
php
{ "resource": "" }
q4807
Utility.recursiveDelete
train
public static function recursiveDelete($path) { if(is_file($path)) { @unlink($path); } else { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($it as $file) { if (in_array($file->getBasename(), array('.', '..'))) { continue; }elseif ($file->isDir()) { rmdir($file->getPathname()); }elseif ($file->isFile() || $file->isLink()) { unlink($file->getPathname()); } } rmdir($path); } return false; }
php
{ "resource": "" }
q4808
Utility.getConnected
train
public static function getConnected($serverOptions) { if(Yii::app()->params['server_options']['default'] == true) $connectedUrl = Yii::app()->params['server_options']['default_host']; else { $connectedUrl = 'neither-connected'; foreach($serverOptions as $val) { if(self::isServerAvailible($val)) { $connectedUrl = $val; break; } } file_put_contents('assets/utility_server_actived.txt', $connectedUrl); } return $connectedUrl; }
php
{ "resource": "" }
q4809
Utility.isServerAvailible
train
public static function isServerAvailible($domain) { if(Yii::app()->params['server_options']['status'] == true) { //check, if a valid url is provided if (!filter_var($domain, FILTER_VALIDATE_URL)) return false; //initialize curl $curlInit = curl_init($domain); curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10); curl_setopt($curlInit,CURLOPT_HEADER,true); curl_setopt($curlInit,CURLOPT_NOBODY,true); curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true); //get answer $response = curl_exec($curlInit); curl_close($curlInit); if($response) return true; return false; } else return false; }
php
{ "resource": "" }
q4810
Utility.getLocalDayName
train
public static function getLocalDayName($date, $short=true) { $dayName = date('N', strtotime($date)); switch($dayName) { case 0: return ($short ? 'Min' : 'Minggu'); break; case 1: return ($short ? 'Sen' : 'Senin'); break; case 2: return ($short ? 'Sel' : 'Selasa'); break; case 3: return ($short ? 'Rab' : 'Rabu'); break; case 4: return ($short ? 'Kam' : 'Kamis'); break; case 5: return ($short ? 'Jum' : 'Jumat'); break; case 6: return ($short ? 'Sab' : 'Sabtu'); break; } }
php
{ "resource": "" }
q4811
Utility.hardDecode
train
public static function hardDecode($string) { $data = htmlspecialchars_decode($string); $data = html_entity_decode($data); $data = strip_tags($data); $data = chop(Utility::convert_smart_quotes($data)); $data = str_replace(array("\r", "\n", " "), "", $data); return ($data); }
php
{ "resource": "" }
q4812
Utility.cleanImageContent
train
public static function cleanImageContent($content) { $posImg = strpos($content, '<img'); $result = $content; if($posImg !== false) { $posClosedImg = strpos($content, '/>', $posImg) + 2; $img = substr($content, $posImg, ($posClosedImg-$posImg)); $result = str_replace($img, '', $content); } return $result; }
php
{ "resource": "" }
q4813
CachedService.resolveBaseService
train
private static function resolveBaseService() { $cachedServices = Config::get('service-classes.cached_services.classes', null); $baseService = $cachedServices[static::class] ?? static::translateBaseService(); return resolve($baseService); }
php
{ "resource": "" }
q4814
CachedService.translateBaseService
train
private static function translateBaseService() { $cachedServicePrefix = Config::get('service-classes.cached_services.prefix'); $cachedServiceNamespace = '\\'.Config::get('service-classes.cached_services.namespace'); return str_replace([$cachedServicePrefix, $cachedServiceNamespace], ['', ''], static::class); }
php
{ "resource": "" }
q4815
MetaEntity.getBundleName
train
public function getBundleName(): ?string { if ($this->getBundleNamespace() === static::NO_BUNDLE_NAMESPACE) { return null; } if (strpos('\\', $this->getBundleNamespace()) !== false) { $parts = explode('\\', $this->getBundleNamespace()); return array_pop($parts); } return $this->getBundleNamespace(); }
php
{ "resource": "" }
q4816
Provider.match
train
public function match($url) { if (!$this->schemes) { return true; } foreach ($this->schemes as $scheme) { if ($scheme->match($url)) { return true; } } return false; }
php
{ "resource": "" }
q4817
Object.factory
train
static public function factory($object) { if (!isset($object->type)) { throw new ObjectException('The object has no type.'); } $type = (string)$object->type; if (!isset(self::$types[$type])) { throw new NoSupportException(sprintf('The object type "%s" is unknown or invalid.', $type)); } $class = '\\Omlex\\Object\\'.self::$types[$type]; if (!class_exists($class)) { throw new ObjectException(sprintf('The object class "%s" is invalid or not found.', $class)); } $instance = new $class($object); return $instance; }
php
{ "resource": "" }
q4818
ConfigurableAttachmentsTrait.setConfig
train
public function setConfig($config) { if (is_array($config)) { $this->config = $this->createConfig($config); } elseif ($config instanceof ConfigInterface) { $this->config = $config; } else { throw new InvalidArgumentException( 'Configuration must be an array or a ConfigInterface object.' ); } return $this; }
php
{ "resource": "" }
q4819
ConfigurableAttachmentsTrait.config
train
public function config($key = null) { if ($this->config === null) { $this->config = $this->createConfig(); } if ($key !== null) { return $this->config->get($key); } else { return $this->config; } }
php
{ "resource": "" }
q4820
ConfigurableAttachmentsTrait.mergePresets
train
protected function mergePresets(array $data) { if (isset($data['attachable_objects'])) { $data['attachable_objects'] = $this->mergePresetAttachableObjects($data['attachable_objects']); } if (isset($data['default_attachable_objects'])) { $data['attachable_objects'] = $this->mergePresetAttachableObjects($data['default_attachable_objects']); } if (isset($data['preset'])) { $data = $this->mergePresetWidget($data); } return $data; }
php
{ "resource": "" }
q4821
ConfigurableAttachmentsTrait.mergePresetWidget
train
private function mergePresetWidget(array $data) { if (!isset($data['preset']) || !is_string($data['preset'])) { return $data; } $widgetIdent = $data['preset']; if ($this instanceof ObjectContainerInterface) { if ($this->hasObj()) { $widgetIdent = $this->obj()->render($widgetIdent); } } elseif ($this instanceof ModelInterface) { $widgetIdent = $this->render($widgetIdent); } $presetWidgets = $this->config('widgets'); if (!isset($presetWidgets[$widgetIdent])) { return $data; } $widgetData = $presetWidgets[$widgetIdent]; if (isset($widgetData['attachable_objects'])) { $widgetData['attachable_objects'] = $this->mergePresetAttachableObjects( $widgetData['attachable_objects'] ); } if (isset($widgetData['default_attachable_objects'])) { $widgetData['attachable_objects'] = $this->mergePresetAttachableObjects( $widgetData['default_attachable_objects'] ); } return array_replace_recursive($widgetData, $data); }
php
{ "resource": "" }
q4822
ConfigurableAttachmentsTrait.mergePresetAttachableObjects
train
private function mergePresetAttachableObjects($data) { if (is_string($data)) { $groupIdent = $data; if ($this instanceof ObjectContainerInterface) { if ($this->hasObj()) { $groupIdent = $this->obj()->render($groupIdent); } } elseif ($this instanceof ModelInterface) { $groupIdent = $this->render($groupIdent); } $presetGroups = $this->config('groups'); if (isset($presetGroups[$groupIdent])) { $data = $presetGroups[$groupIdent]; } } if (is_array($data)) { $presetTypes = $this->config('attachables'); $attachables = []; foreach ($data as $attType => $attStruct) { if (is_string($attStruct)) { $attType = $attStruct; $attStruct = []; } if (!is_string($attType)) { throw new InvalidArgumentException( 'The attachment type must be a string' ); } if (!is_array($attStruct)) { throw new InvalidArgumentException(sprintf( 'The attachment structure for "%s" must be an array', $attType )); } if (isset($presetTypes[$attType])) { $attStruct = array_replace_recursive( $presetTypes[$attType], $attStruct ); } $attachables[$attType] = $attStruct; } $data = $attachables; } return $data; }
php
{ "resource": "" }
q4823
View.call
train
public function call($presenter, array $data = []) { if ($presenter instanceof PresenterInterface) { return $this->callPresenter([$presenter, '__invoke'], $data); } if (is_callable($presenter)) { return $this->callPresenter($presenter, $data); } if ($resolver = $this->builder->getContainer()) { return $this->callPresenter($resolver->get($presenter), $data); } throw new \BadMethodCallException('cannot resolve a presenter.'); }
php
{ "resource": "" }
q4824
Method.isAjax
train
public function isAjax(): bool { if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) { return (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'); } if (isset($_SERVER['HTTP_X_AJAX'])) { return (strtolower($_SERVER['HTTP_X_AJAX']) == 'true' || $_SERVER['HTTP_X_AJAX'] == '1'); } return false; }
php
{ "resource": "" }
q4825
PhotosController.index
train
public function index() { //The "render" type can set by query or by cookies $render = $this->request->getQuery('render', $this->request->getCookie('render-photos')); $query = $this->Photos->find()->contain(['Albums' => ['fields' => ['id', 'slug', 'title']]]); $this->paginate['order'] = ['Photos.created' => 'DESC']; //Sets the paginate limit and the maximum paginate limit //See http://book.cakephp.org/3.0/en/controllers/components/pagination.html#limit-the-maximum-number-of-rows-that-can-be-fetched if ($render === 'grid') { $this->paginate['limit'] = $this->paginate['maxLimit'] = getConfigOrFail('admin.photos'); $this->viewBuilder()->setTemplate('index_as_grid'); } $this->set('photos', $this->paginate($this->Photos->queryFromFilter($query, $this->request->getQueryParams()))); if ($render) { $this->response = $this->response->withCookie((new Cookie('render-photos', $render))->withNeverExpire()); } }
php
{ "resource": "" }
q4826
AdminMediaController.showMedia
train
public function showMedia() { $mediaMapper = ($this->container->dataMapper)('MediaMapper'); $mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper'); $data['media'] = $mediaMapper->find(); $data['categories'] = $mediaCategoryMapper->findCategories(); $cats = $mediaCategoryMapper->findAllMediaCategoryAssignments(); // Assign any category ID's to each medium foreach ($data['media'] as $key => &$medium) { $medium->category = []; foreach ($cats as $cat) { if ($medium->id === $cat->media_id) { $medium->category[$cat->category_id] = 'on'; } } } return $this->render('media/media.html', $data); }
php
{ "resource": "" }
q4827
AdminMediaController.getMedia
train
public function getMedia() { $mediaMapper = ($this->container->dataMapper)('MediaMapper'); $data = $mediaMapper->find(); $template = <<<HTML {% import "@admin/media/_mediaCardMacro.html" as file %} <div class="card-wrapper"> {% for media in page.media %} {{ file.mediaCard(media) }} {% endfor %} </div> HTML; $mediaHtml = $this->container->view->fetchFromString($template, ['page' => ['media' => $data]]); $response = $this->response->withHeader('Content-Type', 'application/json'); return $response->write(json_encode(["html" => $mediaHtml])); }
php
{ "resource": "" }
q4828
AdminMediaController.editMediaCategories
train
public function editMediaCategories() { $mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper'); $data = $mediaCategoryMapper->find(); return $this->render('media/mediaCategories.html', ['categories' => $data]); }
php
{ "resource": "" }
q4829
AdminMediaController.saveMediaCategories
train
public function saveMediaCategories() { $mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper'); $categoriesPost = $this->request->getParsedBody(); foreach ($categoriesPost['category'] as $key => $cat) { // Skip if category name is empty if (empty($cat)) { continue; } // Make category object $category = $mediaCategoryMapper->make(); $category->id = $categoriesPost['id'][$key]; // Check if we need to delete a category, but only if this has been previously saved with an ID if (isset($categoriesPost['delete'][$key]) && !empty($categoriesPost['id'][$key])) { $mediaCategoryMapper->delete($category); } // Save $category->category = $cat; $mediaCategoryMapper->save($category); } // Return to showing categories return $this->redirect('adminEditMediaCategories'); }
php
{ "resource": "" }
q4830
View.getTitleForLayout
train
protected function getTitleForLayout() { if (!empty($this->titleForLayout)) { return $this->titleForLayout; } //Gets the main title setted by the configuration $title = getConfigOrFail('main.title'); //For homepage, it returns only the main title if ($this->request->isUrl(['_name' => 'homepage'])) { return $title; } //If exists, it adds the title setted by the controller, as if it has // been set via `$this->View->set()` if ($this->get('title')) { $title = sprintf('%s - %s', $this->get('title'), $title); //Else, if exists, it adds the title setted by the current view, as if // it has been set via `$this->View->Blocks->set()` } elseif ($this->fetch('title')) { $title = sprintf('%s - %s', $this->fetch('title'), $title); } return $this->titleForLayout = $title; }
php
{ "resource": "" }
q4831
AbstractActiveRecord.getSearchQueryResult
train
private function getSearchQueryResult(array $where = [], array $orderBy = [], $limit = -1, $offset = 0) { $query = (new Query($this->getPdo(), $this->getActiveRecordTable())) ->select(); $this->getSearchQueryWhere($query, $where); $this->getSearchQueryOrderBy($query, $orderBy); $this->getSearchQueryLimit($query, $limit, $offset); return $query->execute(); }
php
{ "resource": "" }
q4832
AbstractActiveRecord.getSearchQueryWhere
train
private function getSearchQueryWhere($query, $where) { foreach ($where as $key => $value) { $query->where($value[0], $value[1], $value[2]); } return $query; }
php
{ "resource": "" }
q4833
AbstractActiveRecord.getSearchQueryOrderBy
train
private function getSearchQueryOrderBy($query, $orderBy) { foreach ($orderBy as $key => $value) { $query->orderBy($key, $value); } return $query; }
php
{ "resource": "" }
q4834
AbstractActiveRecord.getSearchQueryLimit
train
private function getSearchQueryLimit($query, $limit, $offset) { if ($limit > -1) { $query->limit($limit); $query->offset($offset); } return $query; }
php
{ "resource": "" }
q4835
AttachmentContainerTrait.attachmentsMetadata
train
public function attachmentsMetadata() { if ($this->attachmentsMetadata === null) { $this->attachmentsMetadata = []; $metadata = $this->metadata(); if (isset($metadata['attachments'])) { $this->attachmentsMetadata = $this->mergePresets($metadata['attachments']); } } return $this->attachmentsMetadata; }
php
{ "resource": "" }
q4836
AttachmentContainerTrait.attachmentGroup
train
public function attachmentGroup() { if ($this->group === null) { $config = $this->attachmentsMetadata(); $group = AttachmentContainerInterface::DEFAULT_GROUPING; if (isset($config['group'])) { $group = $config['group']; // If the 'default_group' is not set, search for it. } elseif (isset($config['default_group'])) { $group = $config['default_group']; // If the 'default_group' is not set, search for it. } elseif (isset($config['default_widget'])) { $widget = $config['default_widget']; $metadata = $this->metadata(); $found = false; if (isset($metadata['admin']['form_groups'][$widget]['group'])) { $group = $metadata['admin']['form_groups'][$widget]['group']; $found = true; } if (!$found && isset($metadata['admin']['forms'])) { foreach ($metadata['admin']['forms'] as $form) { if (isset($form['groups'][$widget]['group'])) { $group = $form['groups'][$widget]['group']; $found = true; break; } } } if (!$found && isset($metadata['admin']['dashboards'])) { foreach ($metadata['admin']['dashboards'] as $dashboard) { if (isset($dashboard['widgets'][$widget]['group'])) { $group = $dashboard['widgets'][$widget]['group']; $found = true; break; } } } } if (!is_string($group)) { throw new UnexpectedValueException('The attachment grouping must be a string.'); } $this->group = $group; } return $this->group; }
php
{ "resource": "" }
q4837
AttachmentContainerTrait.attachableObjects
train
public function attachableObjects() { if ($this->attachableObjects === null) { $this->attachableObjects = []; $config = $this->attachmentsMetadata(); if (isset($config['attachable_objects'])) { foreach ($config['attachable_objects'] as $attType => $attMeta) { // Disable an attachable model if (isset($attMeta['active']) && !$attMeta['active']) { continue; } // Useful for replacing a pre-defined attachment type if (isset($attMeta['attachment_type'])) { $attType = $attMeta['attachment_type']; } else { $attMeta['attachment_type'] = $attType; } // Alias $attMeta['attachmentType'] = $attMeta['attachment_type']; if (isset($attMeta['label'])) { $attMeta['label'] = $this->translator()->translation($attMeta['label']); } else { $attMeta['label'] = ucfirst(basename($attType)); } $faIcon = ''; if (isset($attMeta['fa_icon']) && !empty($attMeta['fa_icon'])) { $faIcon = 'fa fa-'.$attMeta['fa_icon']; } elseif ($this->attachmentWidget()) { $attParts = explode('/', $attType); $defaultIcons = $this->attachmentWidget()->defaultIcons(); if (isset($defaultIcons[end($attParts)])) { $faIcon = 'fa fa-'.$defaultIcons[end($attParts)]; } } $attMeta['faIcon'] = $faIcon; $attMeta['hasFaIcon'] = !!$faIcon; // Custom forms if (isset($attMeta['form_ident'])) { $attMeta['formIdent'] = $attMeta['form_ident']; } else { $attMeta['formIdent'] = null; } if (isset($attMeta['quick_form_ident'])) { $attMeta['quickFormIdent'] = $attMeta['quick_form_ident']; } else { $attMeta['quickFormIdent'] = null; } $this->attachableObjects[$attType] = $attMeta; } } } return $this->attachableObjects; }
php
{ "resource": "" }
q4838
Sitemap.pages
train
public static function pages() { if (!getConfig('sitemap.pages')) { return []; } $table = TableRegistry::get('MeCms.PagesCategories'); $url = Cache::read('sitemap', $table->getCacheName()); if (!$url) { $alias = $table->Pages->getAlias(); $categories = $table->find('active') ->select(['id', 'lft', 'slug']) ->contain($alias, function (Query $q) use ($alias) { return $q->find('active') ->select(['category_id', 'slug', 'modified']) ->order([sprintf('%s.modified', $alias) => 'DESC']); }) ->order(['lft' => 'ASC']); if ($categories->isEmpty()) { return []; } //Adds categories index $url[] = self::parse(['_name' => 'pagesCategories']); foreach ($categories as $category) { //Adds the category $url[] = self::parse( ['_name' => 'pagesCategory', $category->slug], ['lastmod' => array_value_first($category->pages)->modified] ); //Adds each page foreach ($category->pages as $page) { $url[] = self::parse(['_name' => 'page', $page->slug], ['lastmod' => $page->modified]); } } Cache::write('sitemap', $url, $table->getCacheName()); } return $url; }
php
{ "resource": "" }
q4839
Sitemap.photos
train
public static function photos() { if (!getConfig('sitemap.photos')) { return []; } $table = TableRegistry::get('MeCms.PhotosAlbums'); $url = Cache::read('sitemap', $table->getCacheName()); if (!$url) { $alias = $table->Photos->getAlias(); $albums = $table->find('active') ->select(['id', 'slug']) ->contain($alias, function (Query $q) use ($alias) { return $q->find('active') ->select(['id', 'album_id', 'modified']) ->order([sprintf('%s.modified', $alias) => 'DESC']); }); if ($albums->isEmpty()) { return []; } $latest = $table->Photos->find('active') ->select(['modified']) ->order([sprintf('%s.modified', $alias) => 'DESC']) ->firstOrFail(); //Adds albums index $url[] = self::parse(['_name' => 'albums'], ['lastmod' => $latest->modified]); foreach ($albums as $album) { //Adds the album $url[] = self::parse(['_name' => 'album', $album->slug], ['lastmod' => array_value_first($album->photos)->modified]); //Adds each photo foreach ($album->photos as $photo) { $url[] = self::parse( ['_name' => 'photo', 'slug' => $album->slug, 'id' => $photo->id], ['lastmod' => $photo->modified] ); } } Cache::write('sitemap', $url, $table->getCacheName()); } return $url; }
php
{ "resource": "" }
q4840
Sitemap.posts
train
public static function posts() { if (!getConfig('sitemap.posts')) { return []; } $table = TableRegistry::get('MeCms.PostsCategories'); $url = Cache::read('sitemap', $table->getCacheName()); if (!$url) { $alias = $table->Posts->getAlias(); $categories = $table->find('active') ->select(['id', 'lft', 'slug']) ->contain($alias, function (Query $q) use ($alias) { return $q->find('active') ->select(['category_id', 'slug', 'modified']) ->order([sprintf('%s.modified', $alias) => 'DESC']); }) ->order(['lft' => 'ASC']); if ($categories->isEmpty()) { return []; } $latest = $table->Posts->find('active') ->select(['modified']) ->order([sprintf('%s.modified', $alias) => 'DESC']) ->firstOrFail(); //Adds posts index, categories index and posts search $url[] = self::parse(['_name' => 'posts'], ['lastmod' => $latest->modified]); $url[] = self::parse(['_name' => 'postsCategories']); $url[] = self::parse(['_name' => 'postsSearch'], ['priority' => '0.2']); foreach ($categories as $category) { //Adds the category $url[] = self::parse( ['_name' => 'postsCategory', $category->slug], ['lastmod' => array_value_first($category->posts)->modified] ); //Adds each post foreach ($category->posts as $post) { $url[] = self::parse(['_name' => 'post', $post->slug], ['lastmod' => $post->modified]); } } Cache::write('sitemap', $url, $table->getCacheName()); } return $url; }
php
{ "resource": "" }
q4841
Sitemap.postsTags
train
public static function postsTags() { if (!getConfig('sitemap.posts_tags')) { return []; } $table = TableRegistry::get('MeCms.Tags'); $url = Cache::read('sitemap', $table->getCacheName()); if (!$url) { $tags = $table->find('active') ->select(['tag', 'modified']) ->order(['tag' => 'ASC']); if ($tags->isEmpty()) { return []; } $latest = $table->find() ->select(['modified']) ->order(['modified' => 'DESC']) ->firstOrFail(); //Adds the tags index $url[] = self::parse(['_name' => 'postsTags'], ['lastmod' => $latest->modified]); //Adds each tag foreach ($tags as $tag) { $url[] = self::parse(['_name' => 'postsTag', $tag->slug], ['lastmod' => $tag->modified]); } Cache::write('sitemap', $url, $table->getCacheName()); } return $url; }
php
{ "resource": "" }
q4842
Sitemap.staticPages
train
public static function staticPages() { if (!getConfig('sitemap.static_pages')) { return []; } return array_map(function (Entity $page) { return self::parse(['_name' => 'page', $page->slug], ['lastmod' => $page->modified]); }, StaticPage::all()); }
php
{ "resource": "" }
q4843
Recurse.recurseString
train
protected function recurseString(array $string) { $isOptional = $this->isOptional; foreach ($string as $k => $element) { if (is_array($element)) { $string[$k] = $this->runner->run($element); } } $this->isOptional = $isOptional; return $string; }
php
{ "resource": "" }
q4844
ProcessQueueScript.run
train
public function run(RequestInterface $request, ResponseInterface $response) { // Unused parameter unset($request); // Lock script, to ensure it can not be run twice at the same time (before previous instance is done). $this->startLock(); $climate = $this->climate(); $processedCallback = function($success, $failures, $skipped) use ($climate) { if (!empty($success)) { $climate->green()->out(sprintf('%s emails were successfully sent.', count($success))); } if (!empty($failures)) { $climate->red()->out(sprintf('%s emails were not successfully sent', count($failures))); } if (!empty($skipped)) { $climate->dim()->out(sprintf('%s emails were skipped.', count($skipped))); } }; $queueManager = new EmailQueueManager([ 'logger' => $this->logger, 'queue_item_factory' => $this->queueItemFactory ]); $queueManager->setProcessedCallback($processedCallback); $queueManager->processQueue(); $this->stopLock(); return $response; }
php
{ "resource": "" }
q4845
Connector.ensureSslEndpoint
train
protected function ensureSslEndpoint($url) { // If the endpoint isn't on SSL if (substr($url, 0, 5) != 'https') { // Force an SSL endpoint $endpoint = parse_url($url); $url = 'https://' . $endpoint['host'] . $endpoint['path']; } // SSL already enabled return $url; }
php
{ "resource": "" }
q4846
Connector.Cache
train
protected function Cache($action, $filename, $data = '', $max_age = '') { if (!is_dir($this->cache_dir)) { return ''; } // Set the full path $cache_file = $this->cache_dir . $filename; $cache = ''; if ($action == 'get') { // Clear the file stats clearstatcache(); if (is_file($cache_file) && $max_age != '') { // Make sure $max_age is negitive if (is_string($max_age) && substr($max_age, 0, 1) != '-') { $max_age = '-' . $max_age; } // Make sure $max_age is an INT if (!is_int($max_age)) { $max_age = strtotime($max_age); } // Test to see if the file is still fresh enough if (filemtime($cache_file) >= date($max_age)) { $cache = file_get_contents($cache_file); } } } else { if (is_writable($this->cache_dir)) { // Serialize the Fields $store = serialize($data); //Open and Write the File $fp = fopen($cache_file, "w"); fwrite($fp, $store); fclose($fp); chmod($cache_file, 0770); $cache = strlen($store); } } return $cache; }
php
{ "resource": "" }
q4847
Connector.getEndpoint
train
protected function getEndpoint() { // If force production is in effect if ($this->force_production) { $this->force_production = false; return $this->endpoints['production']; } // Return the active endpoint return $this->endpoints[$this->active_endpoint]; }
php
{ "resource": "" }
q4848
Connector.addEndpoint
train
protected function addEndpoint($name, $url) { // Add or modify the endpoint URL $this->endpoints[$name] = $this->ensureSslEndpoint($url); $this->active_endpoint = $name; // Return boolean if endpoint has been added successfully return array_key_exists($name, $this->endpoints); }
php
{ "resource": "" }
q4849
Item.get_resource_url
train
public function get_resource_url() { $info = $this->data[$this->url]; if (!isset($info['http://purl.org/vocab/resourcelist/schema#resource'])) { return null; } return $info['http://purl.org/vocab/resourcelist/schema#resource'][0]['value']; }
php
{ "resource": "" }
q4850
Item.get_values
train
private function get_values($scheme) { $resourceurl = $this->get_resource_url(); if (!$resourceurl) { return array(); } $info = $this->data[$resourceurl]; if (!isset($info[$scheme])) { return array(); } $values = array(); foreach ($info[$scheme] as $k => $v) { $values[$k] = $v['value']; } return $values; }
php
{ "resource": "" }
q4851
Item.get_authors
train
public function get_authors() { $authors = array(); $url = $this->get_value('http://purl.org/ontology/bibo/authorList'); $info = $this->data[$url]; foreach ($info as $k => $v) { if (strpos($k, '#type') !== false) { continue; } $authors[] = $this->get_author($v[0]['value']); } return $authors; }
php
{ "resource": "" }
q4852
Item.get_publisher
train
public function get_publisher() { $url = $this->get_value('http://purl.org/dc/terms/publisher'); if (!$url) { return; } $info = $this->data[$url]; return $info['http://xmlns.com/foaf/0.1/name'][0]['value']; }
php
{ "resource": "" }
q4853
View.setFileHead
train
public function setFileHead(): void { // check local service file $this->fileHead = $this->prepareFilePath('head', false); if (!file_exists($this->fileHead)) { // look up for default file $this->fileHead = $this->prepareDefaultFilePath('head'); } }
php
{ "resource": "" }
q4854
View.setFileFoot
train
public function setFileFoot(): void { // check local service file $this->fileFoot = $this->prepareFilePath('foot', false); if (!file_exists($this->fileFoot)) { // look up for default file $this->fileFoot = $this->prepareDefaultFilePath('foot'); } }
php
{ "resource": "" }
q4855
View.prepareFilePath
train
private function prepareFilePath(string $file, bool $fileCheck = true): string { $file = str_replace(["\0", "\r", "\n"], '', trim($file)); if ($file == '') { throw new ViewException('No valid file given'); } // custom if ($file[0] == '.') { $fileCheck = false; if (!file_exists($file)) { throw new ViewException("Custom view file '{$file}' not found"); } } elseif ($file[0] == '@') { // custom in default view folder $file = sprintf('%s/app/service/_default/view/%s.php', APP_DIR, substr($file, 1)); $fileCheck = false; if (!file_exists($file)) { throw new ViewException("Default view file '{$file}' not found"); } } else { $file = sprintf('%s/app/service/%s/view/%s.php', APP_DIR, $this->service->getName(), $file); } if ($fileCheck && !file_exists($file)) { // look up default folder if ($this->service->isDefaultService()) { $file = sprintf('%s/app/service/_default/%s/view/%s', APP_DIR, $this->service->getName(), basename($file)); } if (!file_exists($file)) { throw new ViewException("View file '{$file}' not found"); } } return $file; }
php
{ "resource": "" }
q4856
View.prepareDefaultFilePath
train
private function prepareDefaultFilePath(string $file, bool $fileCheck = true): string { $file = sprintf('%s/app/service/_default/view/%s.php', APP_DIR, $file); if ($fileCheck && !file_exists($file)) { throw new ViewException("View file '{$file}' not found"); } return $file; }
php
{ "resource": "" }
q4857
DateTimeCalculator.clear
train
public function clear() { $this->date = $this->base->toInternalDateTime(); $this->calendar = $this->createCalendar($this->locale); if (null === $this->locale) { $this->calendar->setFirstDayOfWeek(\IntlCalendar::DOW_MONDAY); } }
php
{ "resource": "" }
q4858
BaseImplementation.validate
train
protected function validate($value) { if ($value < $this->minValue || $value > $this->maxValue) { throw new InvalidArgumentException('Value ' . $value . ' is out of bounds (' . $this->minValue . '..' . $this->maxValue . ')'); } }
php
{ "resource": "" }
q4859
AppView.setBlocks
train
protected function setBlocks() { //Sets the "theme color" (the toolbar color for some mobile browser) if (getConfig('default.toolbar_color')) { $this->Html->meta('theme-color', getConfig('default.toolbar_color')); } //Sets the meta tag for RSS posts if (getConfig('default.rss_meta')) { $this->Html->meta(__d('me_cms', 'Latest posts'), '/posts/rss', ['type' => 'rss']); } //Sets scripts for Google Analytics if (getConfig('default.analytics')) { echo $this->Library->analytics(getConfig('default.analytics')); } //Sets scripts for Shareaholic if (getConfig('shareaholic.site_id')) { echo $this->Library->shareaholic(getConfig('shareaholic.site_id')); } //Sets some Facebook's tags $this->Html->meta(['content' => $this->getTitleForLayout(), 'property' => 'og:title']); $this->Html->meta(['content' => Router::url(null, true), 'property' => 'og:url']); //Sets the app ID for Facebook if (getConfig('default.facebook_app_id')) { $this->Html->meta([ 'content' => getConfig('default.facebook_app_id'), 'property' => 'fb:app_id', ]); } }
php
{ "resource": "" }
q4860
AppView.userbar
train
public function userbar($content = null) { if (!$content) { return $this->userbar; } $this->userbar = array_merge($this->userbar, (array)$content); }
php
{ "resource": "" }
q4861
ModuleController.updateModule
train
public function updateModule() { $this->moduleHandle->cacheModuleConfig(); //oke $this->moduleHandle->setModules(); //oke $this->moduleHandle->updateModuleAddon(); }
php
{ "resource": "" }
q4862
PagesCategoriesController.add
train
public function add() { $category = $this->PagesCategories->newEntity(); if ($this->request->is('post')) { $category = $this->PagesCategories->patchEntity($category, $this->request->getData()); if ($this->PagesCategories->save($category)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('category')); }
php
{ "resource": "" }
q4863
PagesCategoriesController.edit
train
public function edit($id = null) { $category = $this->PagesCategories->get($id); if ($this->request->is(['patch', 'post', 'put'])) { $category = $this->PagesCategories->patchEntity($category, $this->request->getData()); if ($this->PagesCategories->save($category)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('category')); }
php
{ "resource": "" }
q4864
PagesCategoriesController.delete
train
public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $category = $this->PagesCategories->get($id); //Before deleting, it checks if the category has some pages if (!$category->page_count) { $this->PagesCategories->deleteOrFail($category); $this->Flash->success(I18N_OPERATION_OK); } else { $this->Flash->alert(I18N_BEFORE_DELETE); } return $this->redirect(['action' => 'index']); }
php
{ "resource": "" }
q4865
PostValidator.validTags
train
public function validTags($value) { $validator = new TagValidator; $messages = []; foreach ($value as $tag) { $errors = $validator->errors($tag); if (!empty($errors['tag'])) { foreach ($errors['tag'] as $error) { $messages[] = __d('me_cms', 'Tag "{0}": {1}', $tag['tag'], lcfirst($error)); } } } return empty($messages) ?: implode(PHP_EOL, $messages); }
php
{ "resource": "" }
q4866
Runner.run
train
public function run(array $strings) { foreach ($this->passes as $pass) { $strings = $pass->run($strings); } return $strings; }
php
{ "resource": "" }
q4867
PageElementMediaMapper.findElementsByPageId
train
public function findElementsByPageId($pageId) { $this->makeSelect(); $this->sql .= ' and page_element.page_id = ? order by block_key, element_sort'; $this->bindValues[] = $pageId; return $this->find(); }
php
{ "resource": "" }
q4868
Provider.getUserProviderMapper
train
public function getUserProviderMapper() { if ($this->userProviderMapper == null) { $this->userProviderMapper = $this->getServiceManager()->get('playgrounduser_userprovider_mapper'); } return $this->userProviderMapper; }
php
{ "resource": "" }
q4869
Provider.getHybridAuth
train
public function getHybridAuth() { if ($this->hybridAuth == null) { $this->hybridAuth = $this->getServiceManager()->get('HybridAuth'); } return $this->hybridAuth; }
php
{ "resource": "" }
q4870
Provider.getSocialConfig
train
public function getSocialConfig() { if ($this->SocialConfig == null) { $this->SocialConfig = $this->getServiceManager()->get('SocialConfig'); } return $this->SocialConfig; }
php
{ "resource": "" }
q4871
Provider.getInfoMe
train
public function getInfoMe($socialnetworktype, $options = array()) { $infoMe = null; $provider = ucfirst(strtolower($socialnetworktype)); if (is_string($socialnetworktype)) { try { $adapter = $this->getHybridAuth()->authenticate($provider); if ($adapter->isConnected()) { $infoMe = $adapter->getUserProfile(); } } catch (\Exception $ex) { // The following retry is efficient in case a user previously registered on his social account // with the app has unsubsribed from the app // cf http://hybridauth.sourceforge.net/userguide/HybridAuth_Sessions.html if (($ex->getCode() == 6) || ($ex->getCode() == 7)) { // Réinitialiser la session HybridAuth $this->getHybridAuth()->getAdapter($provider)->logout(); // Essayer de se connecter à nouveau $adapter = $this->getHybridAuth()->authenticate($provider); if ($adapter->isConnected()) { $infoMe = $adapter->getUserProfile(); } } else { // $authEvent->setCode(\Zend\Authentication\Result::FAILURE) // ->setMessages(array('Invalid provider')); // $this->setSatisfied(false); return null; } } } return $infoMe; }
php
{ "resource": "" }
q4872
Team.addUsers
train
public function addUsers(ArrayCollection $users) { foreach ($users as $user) { $user->addTeam($this); $this->users->add($user); } }
php
{ "resource": "" }
q4873
Team.removeUsers
train
public function removeUsers(ArrayCollection $users) { foreach ($users as $user) { $user->removeTeam($this); $this->users->removeElement($user); } }
php
{ "resource": "" }
q4874
MfaDevice.index
train
public function index() { // Validates the request token and generates a new one for the next request $this->validateToken(); // -------------------------------------------------------------------------- // Has this user already set up an MFA? $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oMfaDevice = $oAuthModel->mfaDeviceSecretGet($this->mfaUser->id); if ($oMfaDevice) { $this->requestCode(); } else { $this->setupDevice(); } }
php
{ "resource": "" }
q4875
MfaDevice.setupDevice
train
protected function setupDevice() { $oSession = Factory::service('Session', 'nails/module-auth'); $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oInput = Factory::service('Input'); if ($oInput->post()) { $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_rules('mfa_secret', '', 'required'); $oFormValidation->set_rules('mfa_code', '', 'required'); $oFormValidation->set_message('required', lang('fv_required')); if ($oFormValidation->run()) { $sSecret = $oInput->post('mfa_secret'); $sMfaCode = $oInput->post('mfa_code'); // Verify the inout if ($oAuthModel->mfaDeviceSecretValidate($this->mfaUser->id, $sSecret, $sMfaCode)) { // Codes have been validated and saved to the DB, sign the user in and move on $sStatus = 'success'; $sMessage = '<strong>Multi Factor Authentication Enabled!</strong><br />You successfully '; $sMessage .= 'associated an MFA device with your account. You will be required to use it '; $sMessage .= 'the next time you log in.'; $oSession->setFlashData($sStatus, $sMessage); $this->loginUser(); } else { $this->data['error'] = 'Sorry, that code failed to validate. Please try again.'; } } else { $this->data['error'] = lang('fv_there_were_errors'); } } // Generate the secret $this->data['secret'] = $oAuthModel->mfaDeviceSecretGenerate( $this->mfaUser->id, $oInput->post('mfa_secret', true) ); if (!$this->data['secret']) { $sStatus = 'error'; $sMessage = '<Strong>Sorry,</strong> it has not been possible to get an MFA device set up for this user. '; $sMessage .= $oAuthModel->lastError(); $oSession->setFlashData($sStatus, $sMessage); if ($this->returnTo) { redirect('auth/login?return_to=' . $this->returnTo); } else { redirect('auth/login'); } } // -------------------------------------------------------------------------- $this->data['page']->title = 'Set up a new MFA device'; $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/mfa/device/setup.php'); Factory::service('View') ->load([ 'structure/header/blank', 'auth/mfa/device/setup', 'structure/footer/blank', ]); }
php
{ "resource": "" }
q4876
MfaDevice.requestCode
train
protected function requestCode() { $oInput = Factory::service('Input'); if ($oInput->post()) { $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_rules('mfa_code', '', 'required'); $oFormValidation->set_message('required', lang('fv_required')); if ($oFormValidation->run()) { $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $sMfaCode = $oInput->post('mfa_code'); // Verify the inout if ($oAuthModel->mfaDeviceCodeValidate($this->mfaUser->id, $sMfaCode)) { $this->loginUser(); } else { $this->data['error'] = 'Sorry, that code failed to validate. Please try again. '; $this->data['error'] .= $oAuthModel->lastError(); } } else { $this->data['error'] = lang('fv_there_were_errors'); } } // -------------------------------------------------------------------------- $this->data['page']->title = 'Enter your Code'; $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/mfa/device/ask.php'); Factory::service('View') ->load([ 'structure/header/blank', 'auth/mfa/device/ask', 'structure/footer/blank', ]); }
php
{ "resource": "" }
q4877
ArgumentParser.addToOptionCache
train
private function addToOptionCache(string $identifier, $option) : void { if (!isset($option[$identifier])) { return; } $cacheKey = "${option['command']}${option[$identifier]}"; if (!isset($this->optionsCache[$cacheKey])) { $this->optionsCache[$cacheKey] = $option; } else { throw new OptionExistsException( "An argument option with $identifier {$option['command']} {$option[$identifier]} already exists." ); } }
php
{ "resource": "" }
q4878
ArgumentParser.addOption
train
public function addOption(array $option): void { $this->validator->validateOption($option, $this->commands); $option['command'] = $option['command'] ?? ''; $option['repeats'] = $option['repeats'] ?? false; $this->options[] = $option; $this->addToOptionCache('name', $option); $this->addToOptionCache('short_name', $option); }
php
{ "resource": "" }
q4879
ArgumentParser.parseShortArgument
train
private function parseShortArgument($command, $arguments, &$argPointer, &$output) { $argument = $arguments[$argPointer]; $option = $this->retrieveOptionFromCache($command, substr($argument, 1, 1)); $value = true; if (isset($option['type'])) { if (substr($argument, 2) != "") { $value = substr($argument, 2); } else { $value = $this->getNextValueOrFail($arguments, $argPointer, $option['name']); } } $this->assignValue($option, $output, $option['name'], $value); }
php
{ "resource": "" }
q4880
ArgumentParser.parse
train
public function parse($arguments = null) { try{ global $argv; $arguments = $arguments ?? $argv; $argPointer = 1; $parsed = []; $this->name = $this->name ?? $arguments[0]; $this->parseCommand($arguments, $argPointer, $parsed); $this->parseArgumentArray($arguments, $argPointer, $parsed); $this->maybeShowHelp($parsed); $this->validator->validateArguments($this->options, $parsed); $this->fillInDefaults($parsed); $parsed['__executed'] = $this->name; return $parsed; } catch (HelpMessageRequestedException $exception) { $this->programControl->quit(); } catch (InvalidArgumentException $exception) { print $exception->getMessage() . PHP_EOL; $this->programControl->quit(); } }
php
{ "resource": "" }
q4881
ArgumentParser.enableHelp
train
public function enableHelp(string $description = null, string $footer = null, string $name = null) : void { $this->name = $name; $this->description = $description; $this->footer = $footer; $this->helpEnabled = true; $this->addOption(['name' => 'help', 'short_name' => 'h', 'help' => "display this help message"]); foreach($this->commands as $command) { $this->addOption(['name' => 'help', 'help' => 'display this help message', 'command' => $command['name']]); } }
php
{ "resource": "" }
q4882
PagesController.view
train
public function view($slug = null) { //Checks if there exists a static page $static = StaticPage::get($slug); if ($static) { $page = new Entity(array_merge([ 'category' => new Entity(['slug' => null, 'title' => null]), 'title' => StaticPage::title($slug), 'subtitle' => null, ], compact('slug'))); $this->set(compact('page')); return $this->render($static); } $slug = rtrim($slug, '/'); $page = $this->Pages->findActiveBySlug($slug) ->contain([$this->Pages->Categories->getAlias() => ['fields' => ['title', 'slug']]]) ->cache(sprintf('view_%s', md5($slug)), $this->Pages->getCacheName()) ->firstOrFail(); $this->set(compact('page')); }
php
{ "resource": "" }
q4883
PagesController.preview
train
public function preview($slug = null) { $page = $this->Pages->findPendingBySlug($slug) ->contain([$this->Pages->Categories->getAlias() => ['fields' => ['title', 'slug']]]) ->firstOrFail(); $this->set(compact('page')); $this->render('view'); }
php
{ "resource": "" }
q4884
SitemapBuilder.getMethods
train
protected static function getMethods($plugin) { //Sets the class name $class = App::classname($plugin . '.Sitemap', 'Utility'); //Gets all methods from the `Sitemap` class of the plugin $methods = get_child_methods($class); if (empty($methods)) { return []; } return collection($methods)->map(function ($method) use ($class) { return array_merge(compact('class'), ['name' => $method]); })->toList(); }
php
{ "resource": "" }
q4885
Base.pathFor
train
public function pathFor($name, $data = [], $queryParams = []) { // The `pathfor('showPage', {'url': 'home'})` route should be an alias for `pathFor('home')` if ($name === 'showPage' && isset($data['url']) && $data['url'] === 'home') { $name = 'home'; unset($data['url']); } return $this->container->router->pathFor($name, $data, $queryParams); }
php
{ "resource": "" }
q4886
Base.getMediaPath
train
public function getMediaPath($fileName) { // If this is an external link to a media file, just return string if (stripos($fileName, 'http') === 0 || empty($fileName)) { return $fileName; } return ($this->container->filePath)($fileName) . $fileName; }
php
{ "resource": "" }
q4887
SystemsController.browser
train
public function browser() { //Gets the type from the query and the supported types from configuration $type = $this->request->getQuery('type'); $types = $this->KcFinder->getTypes(); //If there's only one type, it automatically sets the query value if (!$type && count($types) < 2) { $type = array_key_first($types); $this->request = $this->request->withQueryParams(compact('type')); } //Checks the type, then sets the KCFinder path if ($type && array_key_exists($type, $types)) { //Sets locale $locale = substr(I18n::getLocale(), 0, 2); $locale = empty($locale) ? 'en' : $locale; $this->set('kcfinder', sprintf('%s/kcfinder/browse.php?lang=%s&type=%s', Router::url('/vendor', true), $locale, $type)); } $this->set('types', array_combine(array_keys($types), array_keys($types))); }
php
{ "resource": "" }
q4888
Health.healFreshOrdinaryWounds
train
public function healFreshOrdinaryWounds(HealingPower $healingPower, WoundBoundary $woundBoundary): int { $this->checkIfNeedsToRollAgainstMalusFirst(); // can heal new and ordinary wounds only, up to limit by current treatment boundary $healedAmount = 0; $remainingHealUpToWounds = $healingPower->getHealUpToWounds(); foreach ($this->getUnhealedFreshOrdinaryWounds() as $newOrdinaryWound) { // wound is set as old internally, ALL OF THEM, even if no healing left $currentlyRegenerated = $newOrdinaryWound->heal($remainingHealUpToWounds); $remainingHealUpToWounds -= $currentlyRegenerated; $healedAmount += $currentlyRegenerated; } $this->treatmentBoundary = TreatmentBoundary::getIt($this->getUnhealedWoundsSum()); $this->resolveMalusAfterHeal($healedAmount, $woundBoundary); return $healedAmount; }
php
{ "resource": "" }
q4889
Health.regenerate
train
public function regenerate(HealingPower $healingPower, WoundBoundary $woundBoundary): int { $this->checkIfNeedsToRollAgainstMalusFirst(); // every wound becomes old after this $regeneratedAmount = 0; $remainingHealUpToWounds = $healingPower->getHealUpToWounds(); foreach ($this->getUnhealedWounds() as $unhealedWound) { // wound is set as old internally, ALL OF THEM, even if no healing left $currentlyRegenerated = $unhealedWound->heal($remainingHealUpToWounds); $remainingHealUpToWounds -= $currentlyRegenerated; $regeneratedAmount += $currentlyRegenerated; } $this->treatmentBoundary = TreatmentBoundary::getIt($this->getUnhealedWoundsSum()); $this->resolveMalusAfterHeal($regeneratedAmount, $woundBoundary); return $regeneratedAmount; }
php
{ "resource": "" }
q4890
Health.getUnhealedFreshOrdinaryWoundsSum
train
public function getUnhealedFreshOrdinaryWoundsSum(): int { return \array_sum( \array_map( function (OrdinaryWound $ordinaryWound) { return $ordinaryWound->getValue(); }, $this->getUnhealedFreshOrdinaryWounds() ) ); }
php
{ "resource": "" }
q4891
Health.getUnhealedFreshSeriousWoundsSum
train
public function getUnhealedFreshSeriousWoundsSum(): int { return \array_sum( \array_map( function (SeriousWound $seriousWound) { return $seriousWound->getValue(); }, $this->getUnhealedFreshSeriousWounds() ) ); }
php
{ "resource": "" }
q4892
Matcher.identifier
train
public static function identifier(array $match) { $name = $match[1]; // this should be the matched name. if($name === '*') { return '(?P<pathInfo>.*)'; } $type = '[-_0-9a-zA-Z]'; if (strpos($name, ':') !== false) { list($name, $type) = explode(':', $name, 2); if(isset(self::$types[$type])) { $type = self::$types[$type]; } } return "(?P<{$name}>{$type}+)"; }
php
{ "resource": "" }
q4893
TemporaryFile.remove
train
public function remove() { if ($this->removed) { return; } if (!\unlink($this->file)) { throw new RuntimeException(sprintf('Impossible to remove file "%s"', $this->file)); } $this->removed = true; }
php
{ "resource": "" }
q4894
Password.isCorrect
train
public function isCorrect($iUserId, $sPassword) { if (empty($iUserId) || empty($sPassword)) { return false; } // -------------------------------------------------------------------------- $oDb = Factory::service('Database'); $oDb->select('u.password, u.password_engine, u.salt'); $oDb->where('u.id', $iUserId); $oDb->limit(1); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user u'); // -------------------------------------------------------------------------- if ($oResult->num_rows() !== 1) { return false; } // -------------------------------------------------------------------------- /** * @todo: use the appropriate driver to determine password correctness, but * for now, do it the old way */ $sHash = sha1(sha1($sPassword) . $oResult->row()->salt); return $oResult->row()->password === $sHash; }
php
{ "resource": "" }
q4895
Password.isExpired
train
public function isExpired($iUserId) { if (empty($iUserId)) { return false; } $oDb = Factory::service('Database'); $oDb->select('u.password_changed,ug.password_rules'); $oDb->where('u.id', $iUserId); $oDb->join(NAILS_DB_PREFIX . 'user_group ug', 'ug.id = u.group_id'); $oDb->limit(1); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user u'); if ($oResult->num_rows() !== 1) { return false; } // Decode the password rules $oGroupPwRules = json_decode($oResult->row()->password_rules); if (empty($oGroupPwRules->expiresAfter)) { return false; } $sChanged = $oResult->row()->password_changed; if (is_null($sChanged)) { return true; } else { $oThen = new \DateTime($sChanged); $oNow = new \DateTime(); $oInterval = $oNow->diff($oThen); return $oInterval->days >= $oGroupPwRules->expiresAfter; } }
php
{ "resource": "" }
q4896
Password.expiresAfter
train
public function expiresAfter($iGroupId) { if (empty($iGroupId)) { return null; } $oDb = Factory::service('Database'); $oDb->select('password_rules'); $oDb->where('id', $iGroupId); $oDb->limit(1); $oResult = $oDb->get(NAILS_DB_PREFIX . 'user_group'); if ($oResult->num_rows() !== 1) { return null; } // Decode the password rules $oGroupPwRules = json_decode($oResult->row()->password_rules); return empty($oGroupPwRules->expiresAfter) ? null : $oGroupPwRules->expiresAfter; }
php
{ "resource": "" }
q4897
Password.generateHash
train
public function generateHash($iGroupId, $sPassword) { if (empty($sPassword)) { $this->setError('No password to hash'); return false; } // -------------------------------------------------------------------------- // Check password satisfies password rules $aPwRules = $this->getRules($iGroupId); // Long enough? if (!empty($aPwRules['min']) && strlen($sPassword) < $aPwRules['min']) { $this->setError('Password is too short.'); return false; } // Too long? if (!empty($aPwRules['max']) && strlen($sPassword) > $aPwRules['max']) { $this->setError('Password is too long.'); return false; } // Satisfies all the requirements $aFailedRequirements = []; if (!empty($aPwRules['requirements'])) { foreach ($aPwRules['requirements'] as $sRequirement => $bValue) { switch ($sRequirement) { case 'symbol': if (!$this->strContainsFromCharset($sPassword, 'symbol')) { $aFailedRequirements[] = 'a symbol'; } break; case 'number': if (!$this->strContainsFromCharset($sPassword, 'number')) { $aFailedRequirements[] = 'a number'; } break; case 'lower_alpha': if (!$this->strContainsFromCharset($sPassword, 'lower_alpha')) { $aFailedRequirements[] = 'a lowercase letter'; } break; case 'upper_alpha': if (!$this->strContainsFromCharset($sPassword, 'upper_alpha')) { $aFailedRequirements[] = 'an uppercase letter'; } break; } } } if (!empty($aFailedRequirements)) { $sError = 'Password must contain ' . implode(', ', $aFailedRequirements) . '.'; $sError = str_lreplace(', ', ' and ', $sError); $this->setError($sError); return false; } // Not be a banned password? if (!empty($aPwRules['banned'])) { foreach ($aPwRules['banned'] as $sStr) { if (trim(strtolower($sPassword)) == strtolower($sStr)) { $this->setError('Password cannot be "' . $sStr . '"'); return false; } } } // -------------------------------------------------------------------------- // Password is valid, generate hash object return $this->generateHashObject($sPassword); }
php
{ "resource": "" }
q4898
Password.strContainsFromCharset
train
private function strContainsFromCharset($sStr, $sCharset) { if (empty($this->aCharset[$sCharset])) { return true; } return preg_match('/[' . preg_quote($this->aCharset[$sCharset], '/') . ']/', $sStr); }
php
{ "resource": "" }
q4899
Password.generateHashObject
train
public function generateHashObject($sPassword) { $sSalt = $this->salt(); // -------------------------------------------------------------------------- $oOut = new \stdClass(); $oOut->password = sha1(sha1($sPassword) . $sSalt); $oOut->password_md5 = md5($oOut->password); $oOut->salt = $sSalt; $oOut->engine = 'NAILS_1'; return $oOut; }
php
{ "resource": "" }