_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 33 8k | 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), | 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;
| 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
| php | {
"resource": ""
} |
q4803 | Utility.applyCurrentTheme | train | public static function applyCurrentTheme($module = null)
{
$theme = Yii::app()->theme->name;
Yii::app()->theme = $theme;
if($module !== null) {
| php | {
"resource": ""
} |
q4804 | Utility.getActiveDefaultColumns | train | public static function getActiveDefaultColumns($columns)
{
$column = array();
foreach($columns as $val) {
$keyIndex = self::getKeyIndex($val);
| 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(
| 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";
| 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()) {
| 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) | 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);
| 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;
| 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 = | 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, | php | {
"resource": ""
} |
q4813 | CachedService.resolveBaseService | train | private static function resolveBaseService()
{
$cachedServices = Config::get('service-classes.cached_services.classes', null);
| php | {
"resource": ""
} |
q4814 | CachedService.translateBaseService | train | private static function translateBaseService()
{
$cachedServicePrefix = Config::get('service-classes.cached_services.prefix');
| php | {
"resource": ""
} |
q4815 | MetaEntity.getBundleName | train | public function getBundleName(): ?string
{
if ($this->getBundleNamespace() === static::NO_BUNDLE_NAMESPACE) {
return null;
}
if (strpos('\\', $this->getBundleNamespace()) !== false) {
| php | {
"resource": ""
} |
q4816 | Provider.match | train | public function match($url)
{
if (!$this->schemes) {
return true;
}
foreach ($this->schemes as $scheme) {
| 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];
| 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 {
| php | {
"resource": ""
} |
q4819 | ConfigurableAttachmentsTrait.config | train | public function config($key = null)
{
if ($this->config === null) {
$this->config = $this->createConfig();
}
if ($key !== null) {
return | 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'])) {
| 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];
| 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 = [];
| 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 = | 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 | 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'] | 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(); | 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;
| php | {
"resource": ""
} |
q4828 | AdminMediaController.editMediaCategories | train | public function editMediaCategories()
{
$mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper');
$data = $mediaCategoryMapper->find();
| 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
| 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 | 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); | php | {
"resource": ""
} |
q4832 | AbstractActiveRecord.getSearchQueryWhere | train | private function getSearchQueryWhere($query, $where)
{
foreach ($where | php | {
"resource": ""
} |
q4833 | AbstractActiveRecord.getSearchQueryOrderBy | train | private function getSearchQueryOrderBy($query, $orderBy)
{
foreach ($orderBy as $key => $value) {
| php | {
"resource": ""
} |
q4834 | AbstractActiveRecord.getSearchQueryLimit | train | private function getSearchQueryLimit($query, $limit, $offset)
{
if ($limit > -1) {
| php | {
"resource": ""
} |
q4835 | AttachmentContainerTrait.attachmentsMetadata | train | public function attachmentsMetadata()
{
if ($this->attachmentsMetadata === null) {
$this->attachmentsMetadata = [];
$metadata = $this->metadata(); | 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'])) { | 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)];
| 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) {
| 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]);
| 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]);
| 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()) {
| php | {
"resource": ""
} |
q4842 | Sitemap.staticPages | train | public static function staticPages()
{
if (!getConfig('sitemap.static_pages')) {
return [];
}
return array_map(function (Entity $page) {
| php | {
"resource": ""
} |
q4843 | Recurse.recurseString | train | protected function recurseString(array $string)
{
$isOptional = $this->isOptional;
foreach ($string as $k => $element)
{
if (is_array($element))
{
| 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)));
}
| 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);
| 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
| php | {
"resource": ""
} |
q4847 | Connector.getEndpoint | train | protected function getEndpoint()
{
// If force production is in effect
if ($this->force_production) {
| 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;
| 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;
} | 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();
}
| 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') !== | 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 | 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)) {
| 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)) {
| 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");
}
| 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)) {
| php | {
"resource": ""
} |
q4857 | DateTimeCalculator.clear | train | public function clear()
{
$this->date = $this->base->toInternalDateTime();
$this->calendar = $this->createCalendar($this->locale);
| php | {
"resource": ""
} |
q4858 | BaseImplementation.validate | train | protected function validate($value)
{
if ($value < $this->minValue || $value > $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'));
}
| php | {
"resource": ""
} |
q4860 | AppView.userbar | train | public function userbar($content = null)
{
if (!$content) {
return $this->userbar;
}
| php | {
"resource": ""
} |
q4861 | ModuleController.updateModule | train | public function updateModule()
{
$this->moduleHandle->cacheModuleConfig(); //oke
$this->moduleHandle->setModules(); | 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);
| 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);
| 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);
| 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) {
| php | {
"resource": ""
} |
q4866 | Runner.run | train | public function run(array $strings)
{
foreach ($this->passes as $pass)
{
$strings | php | {
"resource": ""
} |
q4867 | PageElementMediaMapper.findElementsByPageId | train | public function findElementsByPageId($pageId)
{
$this->makeSelect();
$this->sql .= ' and page_element.page_id = ? order by block_key, | php | {
"resource": ""
} |
q4868 | Provider.getUserProviderMapper | train | public function getUserProviderMapper()
{
if ($this->userProviderMapper == null) {
| php | {
"resource": ""
} |
q4869 | Provider.getHybridAuth | train | public function getHybridAuth()
{
if ($this->hybridAuth == null) {
$this->hybridAuth = | php | {
"resource": ""
} |
q4870 | Provider.getSocialConfig | train | public function getSocialConfig()
{
if ($this->SocialConfig == null) {
$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);
| php | {
"resource": ""
} |
q4872 | Team.addUsers | train | public function addUsers(ArrayCollection $users)
{
foreach ($users as | php | {
"resource": ""
} |
q4873 | Team.removeUsers | train | public function removeUsers(ArrayCollection $users)
{
foreach ($users as $user) {
$user->removeTeam($this);
| 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');
| 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 | 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 {
| 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 | 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;
| 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 {
| 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;
| 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"]);
| 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);
}
| php | {
"resource": ""
} |
q4883 | PagesController.preview | train | public function preview($slug = null)
{
$page = $this->Pages->findPendingBySlug($slug)
->contain([$this->Pages->Categories->getAlias() => | 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)) {
| 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';
| 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)) {
| 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
| 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
| 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) {
| php | {
"resource": ""
} |
q4890 | Health.getUnhealedFreshOrdinaryWoundsSum | train | public function getUnhealedFreshOrdinaryWoundsSum(): int
{
return \array_sum(
\array_map(
function (OrdinaryWound $ordinaryWound) | php | {
"resource": ""
} |
q4891 | Health.getUnhealedFreshSeriousWoundsSum | train | public function getUnhealedFreshSeriousWoundsSum(): int
{
return \array_sum(
\array_map(
function (SeriousWound $seriousWound) | 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) {
| php | {
"resource": ""
} |
q4893 | TemporaryFile.remove | train | public function remove()
{
if ($this->removed) {
return;
}
if (!\unlink($this->file)) { | 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);
| 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)) {
| 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);
| 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';
| php | {
"resource": ""
} |
q4898 | Password.strContainsFromCharset | train | private function strContainsFromCharset($sStr, $sCharset)
{
if (empty($this->aCharset[$sCharset])) {
| php | {
"resource": ""
} |
q4899 | Password.generateHashObject | train | public function generateHashObject($sPassword)
{
$sSalt = $this->salt();
// --------------------------------------------------------------------------
$oOut = new \stdClass();
$oOut->password = | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.