_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q4700
Login.with_hashes
train
public function with_hashes() { $oUri = Factory::service('Uri'); $oConfig = Factory::service('Config'); if (!$oConfig->item('authEnableHashedLogin')) { show404(); } // -------------------------------------------------------------------------- $hash['id'] = $oUri->segment(4); $hash['pw'] = $oUri->segment(5); if (empty($hash['id']) || empty($hash['pw'])) { throw new NailsException(lang('auth_with_hashes_incomplete_creds'), 1); } // -------------------------------------------------------------------------- /** * If the user is already logged in we need to check to see if we check to see if they are * attempting to login as themselves, if so we redirect, otherwise we log them out and try * again using the hashes. */ if (isLoggedIn()) { if (md5(activeUser('id')) == $hash['id']) { // We are attempting to log in as who we're already logged in as, redirect normally if ($this->data['return_to']) { redirect($this->data['return_to']); } else { // Nowhere to go? Send them to their default homepage redirect(activeUser('group_homepage')); } } else { // We are logging in as someone else, log the current user out and try again $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oAuthModel->logout(); redirect(preg_replace('/^\//', '', $_SERVER['REQUEST_URI'])); } } // -------------------------------------------------------------------------- /** * The active user is a guest, we must look up the hashed user and log them in * if all is ok otherwise we report an error. */ $oSession = Factory::service('Session', 'nails/module-auth'); $oUserModel = Factory::model('User', 'nails/module-auth'); $oUser = $oUserModel->getByHashes($hash['id'], $hash['pw']); // -------------------------------------------------------------------------- if ($oUser) { // User was verified, log the user in $oUserModel->setLoginData($oUser->id); // -------------------------------------------------------------------------- // Say hello if ($oUser->last_login) { $lastLogin = $oConfig->item('authShowNicetimeOnLogin') ? niceTime(strtotime($oUser->last_login)) : toUserDatetime($oUser->last_login); if ($oConfig->item('authShowLastIpOnLogin')) { $sStatus = 'positive'; $sMessage = lang('auth_login_ok_welcome_with_ip', [ $oUser->first_name, $lastLogin, $oUser->last_ip, ]); } else { $sStatus = 'positive'; $sMessage = lang('auth_login_ok_welcome', [$oUser->first_name, $oUser->last_login]); } } else { $sStatus = 'positive'; $sMessage = lang('auth_login_ok_welcome_notime', [$oUser->first_name]); } $oSession->setFlashData($sStatus, $sMessage); // -------------------------------------------------------------------------- // Update their last login $oUserModel->updateLastLogin($oUser->id); // -------------------------------------------------------------------------- // Redirect user if ($this->data['return_to'] != site_url()) { // We have somewhere we want to go redirect($this->data['return_to']); } else { // Nowhere to go? Send them to their default homepage redirect($oUser->group_homepage); } } else { // Bad lookup, invalid hash. $oSession->setFlashData('error', lang('auth_with_hashes_autologin_fail')); redirect($this->data['return_to']); } }
php
{ "resource": "" }
q4701
Login.requestData
train
protected function requestData(&$aRequiredData, $provider) { $oInput = Factory::service('Input'); if ($oInput->post()) { $oFormValidation = Factory::service('FormValidation'); if (isset($aRequiredData['email'])) { $oFormValidation->set_rules('email', 'email', 'trim|required|valid_email|is_unique[' . NAILS_DB_PREFIX . 'user_email.email]'); } if (isset($aRequiredData['username'])) { $oFormValidation->set_rules('username', 'username', 'trim|required|is_unique[' . NAILS_DB_PREFIX . 'user.username]'); } if (empty($aRequiredData['first_name'])) { $oFormValidation->set_rules('first_name', '', 'trim|required'); } if (empty($aRequiredData['last_name'])) { $oFormValidation->set_rules('last_name', '', 'trim|required'); } $oFormValidation->set_message('required', lang('fv_required')); $oFormValidation->set_message('valid_email', lang('fv_valid_email')); if (APP_NATIVE_LOGIN_USING == 'EMAIL') { $oFormValidation->set_message( 'is_unique', lang('fv_email_already_registered', site_url('auth/password/forgotten')) ); } elseif (APP_NATIVE_LOGIN_USING == 'USERNAME') { $oFormValidation->set_message( 'is_unique', lang('fv_username_already_registered', site_url('auth/password/forgotten')) ); } else { $oFormValidation->set_message( 'is_unique', lang('fv_identity_already_registered', site_url('auth/password/forgotten')) ); } if ($oFormValidation->run()) { // Valid!Ensure required data is set correctly then allow system to move on. if (isset($aRequiredData['email'])) { $aRequiredData['email'] = $oInput->post('email'); } if (isset($aRequiredData['username'])) { $aRequiredData['username'] = $oInput->post('username'); } if (empty($aRequiredData['first_name'])) { $aRequiredData['first_name'] = $oInput->post('first_name'); } if (empty($aRequiredData['last_name'])) { $aRequiredData['last_name'] = $oInput->post('last_name'); } } else { $this->data['error'] = lang('fv_there_were_errors'); $this->requestDataForm($aRequiredData, $provider); } } else { $this->requestDataForm($aRequiredData, $provider); } }
php
{ "resource": "" }
q4702
Login.requestDataForm
train
protected function requestDataForm(&$aRequiredData, $provider) { $oUri = Factory::service('Uri'); $this->data['required_data'] = $aRequiredData; $this->data['form_url'] = 'auth/login/' . $provider; if ($oUri->segment(4) == 'register') { $this->data['form_url'] .= '/register'; } if ($this->data['return_to']) { $this->data['form_url'] .= '?return_to=' . urlencode($this->data['return_to']); } Factory::service('View') ->load([ 'structure/header/blank', 'auth/register/social_request_data', 'structure/footer/blank', ]); $oOutput = Factory::service('Output'); echo $oOutput->get_output(); exit(); }
php
{ "resource": "" }
q4703
Login._remap
train
public function _remap() { $oUri = Factory::service('Uri'); $method = $oUri->segment(3) ? $oUri->segment(3) : 'index'; if (method_exists($this, $method) && substr($method, 0, 1) != '_') { $this->{$method}(); } else { // Assume the 3rd segment is a login provider supported by Hybrid Auth $oSocial = Factory::service('SocialSignOn', 'nails/module-auth'); if ($oSocial->isValidProvider($method)) { $this->socialSignon($method); } else { show404(); } } }
php
{ "resource": "" }
q4704
Front.getBlockElementsHtml
train
public function getBlockElementsHtml($block) { if (empty($block)) { return ''; } $blockHtml = ''; foreach ($block as $element) { $blockHtml .= $this->getElementHtml($element) . PHP_EOL; } return $blockHtml; }
php
{ "resource": "" }
q4705
Front.getElementHtml
train
public function getElementHtml($element) { // Ensure we have an element type if (!isset($element->template) && empty($element->template)) { throw new Exception("Missing page element template"); } return $this->container->view->fetch("elements/{$element->template}", ['element' => $element]); }
php
{ "resource": "" }
q4706
Front.getCollectionPages
train
public function getCollectionPages($collectionId) { $pageMapper = ($this->container->dataMapper)('PageMapper'); // Page Collection $data = $pageMapper->findCollectionPagesById($collectionId); return $data; }
php
{ "resource": "" }
q4707
Front.getGallery
train
public function getGallery(int $galleryId = null) { $mediaCategory = ($this->container->dataMapper)('MediaCategoryMapper'); return $mediaCategory->findMediaByCategoryId($galleryId); }
php
{ "resource": "" }
q4708
Uri.generateSegments
train
public function generateSegments(string $root = null): void { $path = rawurldecode($this->sourceData['path'] ?? ''); if ($path && $path != '/') { // drop root if exists if ($root && $root != '/') { $root = '/'. trim($root, '/'). '/'; // prevent wrong generate action if (strpos($path, $root) === false) { throw new HttpException("Uri path '{$path}' has no root such '{$root}'"); } $path = substr($path, strlen($root)); // update segments root $this->segmentsRoot = $root; } $segments = array_map('trim', preg_split('~/+~', $path, -1, PREG_SPLIT_NO_EMPTY)); if ($segments != null) { // push index next foreach ($segments as $i => $segment) { $this->segments[$i + 1] = $segment; } } } }
php
{ "resource": "" }
q4709
AdminMessageController.showMessages
train
public function showMessages() { $messageMapper = ($this->container->dataMapper)('MessageMapper'); $messages = $messageMapper->findAllInDateOrder(); return $this->render('messages.html', ['messages' => $messages]); }
php
{ "resource": "" }
q4710
MediaCategoryMapper.findMediaByCategoryId
train
public function findMediaByCategoryId(int $catId = null) { if (null === $catId) { return; } $this->sql = <<<SQL select mc.category, m.id, m.file, m.caption from media_category mc join media_category_map mcp on mc.id = mcp.category_id join media m on mcp.media_id = m.id where mc.id = ? SQL; $this->bindValues[] = $catId; return $this->find(); }
php
{ "resource": "" }
q4711
MediaCategoryMapper.saveMediaCategoryAssignments
train
public function saveMediaCategoryAssignments(int $mediaId, array $categoryIds = null) { // Delete current category assignments for this media ID $this->deleteMediaCategoryAssignments($mediaId); // Insert all assignments, if the category ID's array is not empty if (null !== $categoryIds) { $this->sql = 'insert into media_category_map (media_id, category_id) values '; foreach ($categoryIds as $id) { $this->sql .= '(?, ?),'; $this->bindValues[] = $mediaId; $this->bindValues[] = $id; } $this->sql = rtrim($this->sql, ',') . ';'; $this->execute(); } }
php
{ "resource": "" }
q4712
MediaCategoryMapper.deleteMediaCategoryAssignments
train
public function deleteMediaCategoryAssignments(int $mediaId) { $this->sql = 'delete from media_category_map where media_id = ?'; $this->bindValues[] = $mediaId; $this->execute(); }
php
{ "resource": "" }
q4713
Me.anyIndex
train
public function anyIndex() { return Factory::factory('ApiResponse', 'nails/module-api') ->setData([ 'id' => (int) activeUser('id'), 'first_name' => activeUser('first_name') ?: null, 'last_name' => activeUser('last_name') ?: null, 'email' => activeUser('email') ?: null, 'username' => activeUser('username') ?: null, 'avatar' => cdnAvatar() ?: null, 'gender' => activeUser('gender') ?: null, ]); }
php
{ "resource": "" }
q4714
HelpMessageGenerator.wrapHelp
train
private function wrapHelp($argumentPart, &$help, $minSize = 29) { if (strlen($argumentPart) <= $minSize) { return $argumentPart . array_shift($help); } else { return $argumentPart; } }
php
{ "resource": "" }
q4715
KcFinderComponent.getDefaultConfig
train
protected function getDefaultConfig() { $defaultConfig = [ 'denyExtensionRename' => true, 'denyUpdateCheck' => true, 'dirnameChangeChars' => [' ' => '_', ':' => '_'], 'disabled' => false, 'filenameChangeChars' => [' ' => '_', ':' => '_'], 'jpegQuality' => 100, 'uploadDir' => UPLOADED, 'uploadURL' => Router::url('/files', true), 'types' => $this->getTypes(), ]; //If the user is not and admin if (!$this->Auth->isGroup(['admin'])) { //Only admins can delete or rename directories $defaultConfig['access']['dirs'] = [ 'create' => true, 'delete' => false, 'rename' => false, ]; //Only admins can delete, move or rename files $defaultConfig['access']['files'] = [ 'upload' => true, 'delete' => false, 'copy' => true, 'move' => false, 'rename' => false, ]; } return $defaultConfig; }
php
{ "resource": "" }
q4716
KcFinderComponent.getTypes
train
public function getTypes() { //Gets the folders list list($folders) = (new Folder(UPLOADED))->read(true, true); //Each folder is a file type supported by KCFinder foreach ($folders as $type) { $types[$type] = ''; } //Adds the "images" type by default $types['images'] = '*img'; return $types; }
php
{ "resource": "" }
q4717
KcFinderComponent.uploadedDirIsWriteable
train
protected function uploadedDirIsWriteable() { $result = $this->Checkup->Webroot->isWriteable(); return $result && array_key_exists(UPLOADED, $result) ? $result[UPLOADED] : false; }
php
{ "resource": "" }
q4718
ServiceCaller.call
train
public function call($service, ...$params) { if (! $this->hasHandler($service)) { throw ServiceHandlerMethodException::notFound($service); } return $this->container->make($service)->{$this::$handlerMethod}(...$params); }
php
{ "resource": "" }
q4719
Groups.getPostObject
train
protected function getPostObject(): array { $oInput = Factory::service('Input'); $oUserGroupModel = Factory::model('UserGroup', 'nails/module-auth'); $oUserPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); return [ 'slug' => $oInput->post('slug'), 'label' => $oInput->post('label'), 'description' => $oInput->post('description'), 'default_homepage' => $oInput->post('default_homepage'), 'registration_redirect' => $oInput->post('registration_redirect'), 'acl' => $oUserGroupModel->processPermissions($oInput->post('acl')), 'password_rules' => $oUserPasswordModel->processRules($oInput->post('pw')), ]; }
php
{ "resource": "" }
q4720
Groups.set_default
train
public function set_default(): void { if (!userHasPermission('admin:auth:groups:setDefault')) { show404(); } $oUri = Factory::service('Uri'); $oUserGroupModel = Factory::model('UserGroup', 'nails/module-auth'); $oSession = Factory::service('Session', 'nails/module-auth'); if ($oUserGroupModel->setAsDefault($oUri->segment(5))) { $oSession->setFlashData( 'success', 'Group set as default successfully.' ); } else { $oSession->setFlashData( 'error', 'Failed to set default user group. ' . $oUserGroupModel->lastError() ); } redirect('admin/auth/groups'); }
php
{ "resource": "" }
q4721
DisableElementsCapableFormSettingsFieldset.build
train
public function build() { if ($this->isBuild) { return; } $settings = $this->getObject(); $form = $this->formManager->get($settings->getForm()); $this->setLabel( $form->getOption('settings_label') ?: sprintf( /*@translate*/ 'Customize enabled elements for %s', get_class($form) ) ); $this->add( array( 'type' => 'Checkbox', 'name' => 'isActive', 'options' => array( 'label' => /*@translate*/ 'Activate', 'long_label' => /*@translate*/ 'Enables the form element customization.', ), 'attributes' => array( 'class' => 'decfs-active-toggle', ), ) ); $element = new DisableElementsCapableFormSettings('disableElements'); $element->setForm($form); $this->add($element); $this->isBuild = true; }
php
{ "resource": "" }
q4722
JsonEntityType.toPHP
train
public function toPHP($value, Driver $driver) { $value = parent::toPHP($value, $driver); return is_array($value) ? array_map(function ($value) { return is_array($value) ? new Entity($value) : $value; }, $value) : $value; }
php
{ "resource": "" }
q4723
FetchModeTrait.setFetchMode
train
public function setFetchMode($mode, ...$args) { if (is_string($mode)) { array_unshift($args, PDO::$mode); $mode = PDO::FETCH_CLASS; } $this->fetchArgs = array_merge([$mode], $args); return $this; }
php
{ "resource": "" }
q4724
QueueController.sendResponse
train
protected function sendResponse($output, $status = 200, $header = array(), $json = true) { $output = date('Y.m.d H:i:s') . " - $output"; $data = json_encode(['output' => $output]); return new JsonResponse($data, $status, $header, $json); }
php
{ "resource": "" }
q4725
Controller.onBeforeInit
train
function onBeforeInit() { foreach (Requirements::$disable_cache_busted_file_extensions_for as $class) { if (is_a($this->owner, $class)) { Requirements::$use_cache_busted_file_extensions = false; } } }
php
{ "resource": "" }
q4726
CopyConfigCommand.execute
train
public function execute(Arguments $args, ConsoleIo $io) { foreach ($this->config as $file) { list($plugin, $file) = pluginSplit($file); $this->copyFile( $io, Plugin::path($plugin, 'config' . DS . $file . '.php'), Folder::slashTerm(CONFIG) . $file . '.php' ); } return null; }
php
{ "resource": "" }
q4727
ConfigurationPool.saveAll
train
public function saveAll() { $this->init(); $parameters = []; foreach ($this->configurations as $configuration) { $parameters = array_merge($parameters, $this->getConfigurationParameters($configuration)); } $this->parameterRepository->save($parameters); }
php
{ "resource": "" }
q4728
ConfigurationPool.init
train
public function init() { if ($this->initialized) { return; } $parameters = []; foreach ($this->parameterRepository->getAllParameters() as $parameter) { $configurationName = $parameter->getConfigurationName(); if (!isset($parameters[$configurationName])) { $parameters[$configurationName] = []; } $parameters[$configurationName][$parameter->getName()] = $parameter; } $this->persistedParameters = $parameters; foreach ($this->configurations as $configuration) { $configurationName = $configuration->getName(); $this->initConfiguration( $configuration, isset($parameters[$configurationName]) ? $parameters[$configurationName] : [] ); } $this->initialized = true; }
php
{ "resource": "" }
q4729
Session.setup
train
protected function setup($bForceSetup = false) { if (!empty($this->oSession)) { return; } $oInput = Factory::service('Input'); // class_exists check in case the class is called before CI has finished instanciating if (!$oInput::isCli() && class_exists('CI_Controller')) { /** * Look for the session cookie, if it exists, then a session exists * and the whole service should be loaded up. */ $oConfig = Factory::service('Config'); $sCookieName = $oConfig->item('sess_cookie_name'); if ($bForceSetup || $oInput::cookie($sCookieName)) { // @todo (Pablo - 2018-03-19) - Remove dependency on CI Sessions $oCi = get_instance(); $oCi->load->library('session'); if (empty($oCi->session)) { throw new NailsException('Failed to load CodeIgniter session library.'); } $this->oSession = $oCi->session; } } }
php
{ "resource": "" }
q4730
Session.setFlashData
train
public function setFlashData($mKey, $mValue = null) { $this->setup(true); if (empty($this->oSession)) { return $this; } $this->oSession->set_flashdata($mKey, $mValue); return $this; }
php
{ "resource": "" }
q4731
Session.getFlashData
train
public function getFlashData($sKey = null) { $this->setup(); if (empty($this->oSession)) { return null; } return $this->oSession->flashdata($sKey); }
php
{ "resource": "" }
q4732
Session.setUserData
train
public function setUserData($mKey, $mValue = null) { $this->setup(true); if (empty($this->oSession)) { return $this; } $this->oSession->set_userdata($mKey, $mValue); return $this; }
php
{ "resource": "" }
q4733
Session.getUserData
train
public function getUserData($sKey = null) { $this->setup(); if (empty($this->oSession)) { return null; } return $this->oSession->userdata($sKey); }
php
{ "resource": "" }
q4734
Session.unsetUserData
train
public function unsetUserData($mKey) { if (empty($this->oSession)) { return $this; } $this->oSession->unset_userdata($mKey); return $this; }
php
{ "resource": "" }
q4735
Session.destroy
train
public function destroy() { if (empty($this->oSession)) { return $this; } $oConfig = Factory::service('Config'); $sCookieName = $oConfig->item('sess_cookie_name'); $this->oSession->sess_destroy(); if (isset($_COOKIE) && array_key_exists($sCookieName, $_COOKIE)) { delete_cookie($sCookieName); unset($_COOKIE[$sCookieName]); } return $this; }
php
{ "resource": "" }
q4736
Session.regenerate
train
public function regenerate($bDestroy = false) { if (empty($this->oSession)) { return $this; } $this->oSession->sess_regenerate($bDestroy); return $this; }
php
{ "resource": "" }
q4737
OFunction.getDataProviderPager
train
public static function getDataProviderPager($dataProvider, $attr=true) { if($attr == true) $data = $dataProvider->getPagination(); else $data = $dataProvider; $pageCount = $data->itemCount >= $data->pageSize ? ($data->itemCount % $data->pageSize === 0 ? (int)($data->itemCount/$data->pageSize) : (int)($data->itemCount/$data->pageSize)+1) : 1; $currentPage = $data->itemCount != 0 ? $data->currentPage+1 : 1; $nextPage = (($pageCount != $currentPage) && ($pageCount > $currentPage)) ? $currentPage+1 : 0; $return = array( 'pageVar'=>$data->pageVar, 'itemCount'=>$data->itemCount, 'pageSize'=>$data->pageSize, 'pageCount'=>$pageCount, 'currentPage'=>$currentPage, 'nextPage'=>$nextPage, ); return $return; }
php
{ "resource": "" }
q4738
OFunction.validHostURL
train
public static function validHostURL($targetUrl) { $req = Yii::app()->request; $url = ($req->port == 80? 'http://': 'https://') . $req->serverName; if(substr($targetUrl, 0, 1) != '/') $targetUrl = '/'.$targetUrl; return $url = $url.$targetUrl; }
php
{ "resource": "" }
q4739
User.remove
train
public function remove($entity) { $entity->setState(0); $this->em->persist($entity); $this->em->flush(); }
php
{ "resource": "" }
q4740
PhpDotEnv.settingEnv
train
private function settingEnv(array $data): void { $loadedVars = \array_flip(\explode(',', \getenv(self::FULL_KEY))); unset($loadedVars['']); foreach ($data as $name => $value) { if (\is_int($name) || !\is_string($value)) { continue; } $name = \strtoupper($name); $notHttpName = 0 !== \strpos($name, 'HTTP_'); // don't check existence with getenv() because of thread safety issues if ((isset($_ENV[$name]) || (isset($_SERVER[$name]) && $notHttpName)) && !isset($loadedVars[$name])) { continue; } // is a constant var if ($value && \defined($value)) { $value = \constant($value); } // eg: "FOO=BAR" \putenv("$name=$value"); $_ENV[$name] = $value; if ($notHttpName) { $_SERVER[$name] = $value; } $loadedVars[$name] = true; } if ($loadedVars) { $loadedVars = \implode(',', \array_keys($loadedVars)); \putenv(self::FULL_KEY . "=$loadedVars"); $_ENV[self::FULL_KEY] = $loadedVars; $_SERVER[self::FULL_KEY] = $loadedVars; } }
php
{ "resource": "" }
q4741
TableDef.setColumn
train
public function setColumn($name, $type, $nullDefault = false) { $this->columns[$name] = $this->createColumnDef($type, $nullDefault); return $this; }
php
{ "resource": "" }
q4742
TableDef.createColumnDef
train
private function createColumnDef($dbtype, $nullDefault = false) { $column = Db::typeDef($dbtype); if ($column === null) { throw new \InvalidArgumentException("Unknown type '$dbtype'.", 500); } if ($column['dbtype'] === 'bool' && in_array($nullDefault, [true, false], true)) { // Booleans have a special meaning. $column['allowNull'] = false; $column['default'] = $nullDefault; } elseif ($column['dbtype'] === 'timestamp' && empty($column['default'])) { $column['default'] = 'current_timestamp'; } elseif ($nullDefault === null || $nullDefault === true) { $column['allowNull'] = true; } elseif ($nullDefault === false) { $column['allowNull'] = false; } else { $column['allowNull'] = false; $column['default'] = $nullDefault; } return $column; }
php
{ "resource": "" }
q4743
TableDef.setPrimaryKey
train
public function setPrimaryKey($name, $type = 'int') { $column = $this->createColumnDef($type, false); $column['autoIncrement'] = true; $column['primary'] = true; $this->columns[$name] = $column; // Add the pk index. $this->addIndex(Db::INDEX_PK, $name); return $this; }
php
{ "resource": "" }
q4744
TableDef.addIndex
train
public function addIndex($type, ...$columns) { if (empty($columns)) { throw new \InvalidArgumentException("An index must contain at least one column.", 500); } $type = strtolower($type); // Look for a current index row. $currentIndex = null; foreach ($this->indexes as $i => $index) { if ($type !== $index['type']) { continue; } if ($type === Db::INDEX_PK || array_diff($index['columns'], $columns) == []) { $currentIndex =& $this->indexes[$i]; break; } } if ($currentIndex) { $currentIndex['columns'] = $columns; } else { $indexDef = [ 'type' => $type, 'columns' => $columns, ]; $this->indexes[] = $indexDef; } return $this; }
php
{ "resource": "" }
q4745
PromoteSingleStrings.promoteSingleStrings
train
protected function promoteSingleStrings(array $string) { $newString = []; foreach ($string as $element) { if (is_array($element) && count($element) === 1) { $newString = array_merge($newString, $element[0]); } else { $newString[] = $element; } } return $newString; }
php
{ "resource": "" }
q4746
Accounts.indexCheckboxFilters
train
protected function indexCheckboxFilters(): array { $oGroupModel = Factory::model('UserGroup', 'nails/module-auth'); $aGroups = $oGroupModel->getAll(); return array_merge( parent::indexCheckboxFilters(), [ Factory::factory('IndexFilter', 'nails/module-admin') ->setLabel('Group') ->setColumn('group_id') ->addOptions(array_map(function ($oGroup) { return Factory::factory('IndexFilterOption', 'nails/module-admin') ->setLabel($oGroup->label) ->setValue($oGroup->id) ->setIsSelected(true); }, $aGroups)), Factory::factory('IndexFilter', 'nails/module-admin') ->setLabel('Suspended') ->setColumn('is_suspended') ->addOptions([ Factory::factory('IndexFilterOption', 'nails/module-admin') ->setLabel('Yes') ->setValue(true), Factory::factory('IndexFilterOption', 'nails/module-admin') ->setLabel('No') ->setValue(false) ->setIsSelected(true), ]), ] ); }
php
{ "resource": "" }
q4747
Accounts.suspend
train
public function suspend(): void { if (!userHasPermission('admin:auth:accounts:suspend')) { unauthorised(); } // -------------------------------------------------------------------------- // Get the user's details $oUri = Factory::service('Uri'); $oInput = Factory::service('Input'); $oSession = Factory::service('Session', 'nails/module-auth'); $oUserModel = Factory::model('User', 'nails/module-auth'); $iUserId = $oUri->segment(5); $oUser = $oUserModel->getById($iUserId); $bOldValue = $oUser->is_suspended; // -------------------------------------------------------------------------- // Non-superusers editing superusers is not cool if (!isSuperuser() && userHasPermission('superuser', $oUser)) { $oSession->setFlashData('error', lang('accounts_edit_error_noteditable')); $this->returnToIndex(); } // -------------------------------------------------------------------------- // Suspend user $oUserModel->suspend($iUserId); // -------------------------------------------------------------------------- // Get the user's details, again $oUser = $oUserModel->getById($iUserId); $bNewValue = $oUser->is_suspended; // -------------------------------------------------------------------------- // Define messages if (!$oUser->is_suspended) { $oSession->setFlashData( 'error', lang('accounts_suspend_error', title_case($oUser->first_name . ' ' . $oUser->last_name)) ); } else { $oSession->setFlashData( 'success', lang('accounts_suspend_success', title_case($oUser->first_name . ' ' . $oUser->last_name)) ); } // -------------------------------------------------------------------------- // Update admin changelog $this->oChangeLogModel->add( 'suspended', 'a', 'user', $iUserId, '#' . number_format($iUserId) . ' ' . $oUser->first_name . ' ' . $oUser->last_name, 'admin/auth/accounts/edit/' . $iUserId, 'is_suspended', $bOldValue, $bNewValue, false ); // -------------------------------------------------------------------------- $this->returnToIndex(); }
php
{ "resource": "" }
q4748
Accounts.delete_profile_img
train
public function delete_profile_img(): void { $oUri = Factory::service('Uri'); if ($oUri->segment(5) != activeUser('id') && !userHasPermission('admin:auth:accounts:editOthers')) { unauthorised(); } // -------------------------------------------------------------------------- $oInput = Factory::service('Input'); $oSession = Factory::service('Session', 'nails/module-auth'); $oUserModel = Factory::model('User', 'nails/module-auth'); $iUserId = $oUri->segment(5); $oUser = $oUserModel->getById($iUserId); $sReturnTo = $oInput->get('return_to') ? $oInput->get('return_to') : 'admin/auth/accounts/edit/' . $iUserId; // -------------------------------------------------------------------------- if (!$oUser) { $oSession->setFlashData('error', lang('accounts_delete_img_error_noid')); redirect('admin/auth/accounts'); } else { // Non-superusers editing superusers is not cool if (!isSuperuser() && userHasPermission('superuser', $oUser)) { $oSession->setFlashData('error', lang('accounts_edit_error_noteditable')); redirect($sReturnTo); } // -------------------------------------------------------------------------- if ($oUser->profile_img) { $oCdn = Factory::service('Cdn', 'nails/module-cdn'); if ($oCdn->objectDelete($oUser->profile_img, 'profile-images')) { // Update the user $oUserModel->update($iUserId, ['profile_img' => null]); $sStatus = 'notice'; $sMessage = lang('accounts_delete_img_success'); } else { $sStatus = 'error'; $sMessage = lang('accounts_delete_img_error', implode('", "', $oCdn->getErrors())); } } else { $sStatus = 'notice'; $sMessage = lang('accounts_delete_img_error_noimg'); } $oSession->setFlashData($sStatus, $sMessage); // -------------------------------------------------------------------------- redirect($sReturnTo); } }
php
{ "resource": "" }
q4749
GroupsCommand.execute
train
public function execute(Arguments $args, ConsoleIo $io) { $this->loadModel('MeCms.UsersGroups'); $groups = $this->UsersGroups->find()->map(function (UsersGroup $group) { return $group->extract(['id', 'name', 'label', 'user_count']); }); //Checks for user groups if ($groups->isEmpty()) { $io->error(__d('me_cms', 'There are no user groups')); return null; } //Sets header and prints as table $header = [I18N_ID, I18N_NAME, I18N_LABEL, I18N_USERS]; $io->helper('table')->output(array_merge([$header], $groups->toList())); return null; }
php
{ "resource": "" }
q4750
CheckLastSearchTrait.checkLastSearch
train
protected function checkLastSearch($id = false) { $interval = getConfig('security.search_interval'); if (!$interval) { return true; } $id = $id ? md5($id) : false; $lastSearch = $this->request->getSession()->read('last_search'); if ($lastSearch) { //Checks if it's the same search if ($id && !empty($lastSearch['id']) && $id === $lastSearch['id']) { return true; //Checks if the interval has not yet expired } elseif (($lastSearch['time'] + $interval) > time()) { return false; } } $this->request->getSession()->write('last_search', compact('id') + ['time' => time()]); return true; }
php
{ "resource": "" }
q4751
LoadRoleData.load
train
public function load(ObjectManager $manager) { $userRole = new Role(); $userRole->setRoleId('user'); $manager->persist($userRole); $manager->flush(); $adminRole = new Role(); $adminRole->setRoleId('admin'); $adminRole->setParent($userRole); $manager->persist($adminRole); $manager->flush(); $supervisorRole = new Role(); $supervisorRole->setRoleId('supervisor'); $supervisorRole->setParent($userRole); $manager->persist($supervisorRole); $manager->flush(); $gameManagerRole = new Role(); $gameManagerRole->setRoleId('game-manager'); $gameManagerRole->setParent($supervisorRole); $manager->persist($gameManagerRole); $manager->flush(); // store reference to admin role for User relation to Role $this->addReference('admin-role', $adminRole); $this->addReference('supervisor-role', $supervisorRole); $this->addReference('game-role', $gameManagerRole); }
php
{ "resource": "" }
q4752
FrontController.submitMessage
train
public function submitMessage() { $messageMapper = ($this->container->dataMapper)('MessageMapper'); $email = $this->container->emailHandler; // Check honepot and if clean, then submit message if ('alt@example.com' === $this->request->getParsedBodyParam('alt-email')) { $message = $messageMapper->make(); $message->name = $this->request->getParsedBodyParam('name'); $message->email = $this->request->getParsedBodyParam('email'); $message->message = $this->request->getParsedBodyParam('message'); $messageMapper->save($message); // Send message to workflow email $siteName = empty($this->siteSettings['displayName']) ? 'PitonCMS' : $this->siteSettings['displayName']; $email->setTo($this->siteSettings['contactFormEmail'], '') ->setSubject("New Contact Message to $siteName") ->setMessage("From: {$message->email}\n\n{$message->message}") ->send(); } // Set the response type and return $r = $this->response->withHeader('Content-Type', 'application/json'); return $r->write(json_encode(["response" => $this->siteSettings['contactFormAcknowledgement']])); }
php
{ "resource": "" }
q4753
MetaCharacters.add
train
public function add($char, $expr) { $split = $this->input->split($char); if (count($split) !== 1) { throw new InvalidArgumentException('Meta-characters must be represented by exactly one character'); } if (@preg_match('(' . $expr . ')u', '') === false) { throw new InvalidArgumentException("Invalid expression '" . $expr . "'"); } $inputValue = $split[0]; $metaValue = $this->computeValue($expr); $this->exprs[$metaValue] = $expr; $this->meta[$inputValue] = $metaValue; }
php
{ "resource": "" }
q4754
MetaCharacters.getExpression
train
public function getExpression($metaValue) { if (!isset($this->exprs[$metaValue])) { throw new InvalidArgumentException('Invalid meta value ' . $metaValue); } return $this->exprs[$metaValue]; }
php
{ "resource": "" }
q4755
MetaCharacters.replaceMeta
train
public function replaceMeta(array $strings) { foreach ($strings as &$string) { foreach ($string as &$value) { if (isset($this->meta[$value])) { $value = $this->meta[$value]; } } } return $strings; }
php
{ "resource": "" }
q4756
MetaCharacters.computeValue
train
protected function computeValue($expr) { $properties = [ 'exprIsChar' => self::IS_CHAR, 'exprIsQuantifiable' => self::IS_QUANTIFIABLE ]; $value = (1 + count($this->meta)) * -pow(2, count($properties)); foreach ($properties as $methodName => $bitValue) { if ($this->$methodName($expr)) { $value |= $bitValue; } } return $value; }
php
{ "resource": "" }
q4757
MetaCharacters.exprIsQuantifiable
train
protected function exprIsQuantifiable($expr) { $regexps = [ // A dot or \R '(^(?:\\.|\\\\R)$)D', // A character class '(^\\[\\^?(?:([^\\\\\\]]|\\\\.)(?:-(?-1))?)++\\]$)D' ]; return $this->matchesAny($expr, $regexps) || $this->exprIsChar($expr); }
php
{ "resource": "" }
q4758
MetaCharacters.matchesAny
train
protected function matchesAny($expr, array $regexps) { foreach ($regexps as $regexp) { if (preg_match($regexp, $expr)) { return true; } } return false; }
php
{ "resource": "" }
q4759
Formula.getCurrentRealmsAffections
train
public function getCurrentRealmsAffections(): array { $realmsAffections = []; foreach ($this->getRealmsAffectionsSum() as $periodName => $periodSum) { $realmsAffections[$periodName] = new RealmsAffection([$periodSum, $periodName]); } return $realmsAffections; }
php
{ "resource": "" }
q4760
Formula.getCurrentSpellRadius
train
public function getCurrentSpellRadius(): ?SpellRadius { $radiusWithAddition = $this->getRadiusWithAddition(); if (!$radiusWithAddition) { return null; } $radiusModifiersChange = $this->getParameterBonusFromModifiers(ModifierMutableSpellParameterCode::SPELL_RADIUS); if (!$radiusModifiersChange) { return new SpellRadius([$radiusWithAddition->getValue(), 0], $this->tables); } return new SpellRadius([$radiusWithAddition->getValue() + $radiusModifiersChange, 0], $this->tables); }
php
{ "resource": "" }
q4761
Formula.getRadiusWithAddition
train
private function getRadiusWithAddition(): ?SpellRadius { $baseSpellRadius = $this->tables->getFormulasTable()->getSpellRadius($this->formulaCode); if ($baseSpellRadius === null) { return null; } return $baseSpellRadius->getWithAddition($this->formulaSpellParameterChanges[FormulaMutableSpellParameterCode::SPELL_RADIUS]); }
php
{ "resource": "" }
q4762
Formula.getCurrentSpellAttack
train
public function getCurrentSpellAttack(): ?SpellAttack { $spellAttackWithAddition = $this->getSpellAttackWithAddition(); if (!$spellAttackWithAddition) { return null; } return new SpellAttack( [ $spellAttackWithAddition->getValue() + (int)$this->getParameterBonusFromModifiers(ModifierMutableSpellParameterCode::SPELL_ATTACK), 0 // no addition ], Tables::getIt() ); }
php
{ "resource": "" }
q4763
OmmuMenuCategory.getCategory
train
public static function getCategory($publish=null, $array=true) { $criteria=new CDbCriteria; if($publish != null) $criteria->compare('t.publish', $publish); $model = self::model()->findAll($criteria); if($array == true) { $items = array(); if($model != null) { foreach($model as $key => $val) { $items[$val->cat_id] = $val->title->message; } return $items; } else return false; } else return $model; }
php
{ "resource": "" }
q4764
MetaEntityFactory.addMissingProperty
train
public function addMissingProperty(MetaEntityInterface $metaEntity, RelationMetaPropertyInterface $property) { $inversedBy = $property->getInversedBy(); $mappedBy = $property->getMappedBy(); if ($newPropertyName = $mappedBy ?: $inversedBy) { $inversedType = MetaPropertyFactory::getInversedType($property->getOrmType()); /** @var RelationMetaPropertyInterface $newProperty */ $newProperty = $this->metaPropertyFactory->createMetaProperty( $metaEntity, $inversedType, $newPropertyName ); $newProperty->setTargetEntity($property->getMetaEntity()); if ($inversedBy) { $newProperty->setMappedBy($property->getName()); } else { $newProperty->setInversedBy($property->getName()); } } }
php
{ "resource": "" }
q4765
AuthHelper.user
train
public function user($key = null) { if (empty($this->user)) { return null; } return $key ? Hash::get($this->user, $key) : $this->user; }
php
{ "resource": "" }
q4766
AppController.isAuthorized
train
public function isAuthorized($user = null) { //Any registered user can access public functions if (!$this->request->getParam('prefix')) { return true; } //Only admin and managers can access all admin actions if ($this->request->isAdmin()) { return $this->Auth->isGroup(['admin', 'manager']); } //Default deny return false; }
php
{ "resource": "" }
q4767
AppController.setUploadError
train
protected function setUploadError($error) { $this->response = $this->response->withStatus(500); $this->set(compact('error')); $this->set('_serialize', ['error']); }
php
{ "resource": "" }
q4768
AdminPageController.newElementForm
train
public function newElementForm() { $parsedBody = $this->request->getParsedBody(); $form['block_key'] = $parsedBody['blockKey']; $form['definition'] = $parsedBody['elementType']; $form['element_sort'] = 1; // Only include element type options if the string is not empty if (!empty($parsedBody['elementTypeOptions'])) { $form['elementTypeOptions'] = explode(',', $parsedBody['elementTypeOptions']); } $template = '{% import "@admin/editElementMacro.html" as form %}'; $template .= ' {{ form.elementForm(element, element.block_key, element.elementTypeOptions) }}'; $elementFormHtml = $this->container->view->fetchFromString($template, ['element' => $form]); // Set the response type $r = $this->response->withHeader('Content-Type', 'application/json'); return $r->write(json_encode(["html" => $elementFormHtml])); }
php
{ "resource": "" }
q4769
AccessToken.revoke
train
public function revoke($iUserId, $mToken) { if (is_string($mToken)) { $oToken = $this->getByToken($mToken); } else { $oToken = $mToken; } if ($oToken) { if ($oToken->user_id === $iUserId) { return $this->delete($oToken->id); } else { $this->setError('Not authorised to revoke that token.'); return false; } } else { return false; } }
php
{ "resource": "" }
q4770
AccessToken.hasScope
train
public function hasScope($mToken, $sScope) { if (is_numeric($mToken)) { $oToken = $this->getById($mToken); } else { $oToken = $mToken; } if ($oToken) { return in_array($sScope, $oToken->scope); } else { return false; } }
php
{ "resource": "" }
q4771
DBConnector.setDb
train
public static function setDb($db, $connection_name = self::DEFAULT_CONNECTION) { static::_initDbConfigWithDefaultVals($connection_name); static::$_db[$connection_name] = $db; }
php
{ "resource": "" }
q4772
DBConnector.dbFetchOne
train
public function dbFetchOne( $select_query, $parameters = array() ) { $bool_and_statement = static::_execute($select_query, $parameters, true, $this->_connection_name); $statement = array_pop($bool_and_statement); return $statement->fetch(\PDO::FETCH_ASSOC); }
php
{ "resource": "" }
q4773
EmailConfig.setSmtpSecurity
train
public function setSmtpSecurity($security) { $security = strtoupper($security); $validSecurity = [ '', 'TLS', 'SSL' ]; if (!in_array($security, $validSecurity)) { throw new InvalidArgumentException( 'SMTP Security is not valid. Must be "", "TLS" or "SSL".' ); } $this->smtpSecurity = $security; return $this; }
php
{ "resource": "" }
q4774
URLValidator.validDomains
train
public static function validDomains($url, $domains) { $theDomain = parse_url($url); foreach ($domains as $domain) { $check = strpos($theDomain['host'], $domain->client_domain); if ($check || $check === 0) { return true; } } return false; }
php
{ "resource": "" }
q4775
Location.postalcodeToCoordinates
train
public function postalcodeToCoordinates(array $postalData, $shouldRunC2A = false) { $this->shouldRunC2A = ($this->shouldRunC2A) ? true : $shouldRunC2A; $this->returnLocationData = array_merge($this->returnLocationData, array_only($postalData, ['street_number', 'postal_code'])); return $this; }
php
{ "resource": "" }
q4776
Location.addressToCoordinates
train
public function addressToCoordinates(array $addressData = []) { $this->returnLocationData = array_merge($this->returnLocationData, array_only($addressData, ['country', 'region', 'city', 'street', 'street_number'])); return $this; }
php
{ "resource": "" }
q4777
Location.coordinatesToAddress
train
public function coordinatesToAddress(array $coordinates = []) { $this->shouldRunC2A = true; $this->returnLocationData = array_merge($this->returnLocationData, array_only($coordinates, ['latitude', 'longitude'])); return $this; }
php
{ "resource": "" }
q4778
Location.ipToCoordinates
train
public function ipToCoordinates($ip = null, $shouldRunC2A = false) { $this->shouldRunC2A = ($this->shouldRunC2A) ? true : $shouldRunC2A; if(! $ip) { $ip = Request::ip(); } $this->ip = $ip; return $this; }
php
{ "resource": "" }
q4779
Location.get
train
public function get($toObject = false) { if(!env('GOOGLE_KEY')) { throw new Exception("Need an env key for geo request", 401); } $this->response = null; $this->error = null; if($this->c2a()) { $response = $this->template($toObject); } elseif($this->a2c()) { $response = $this->template($toObject); } elseif($this->i2c()) { $response = $this->template($toObject); } elseif($this->p2c()) { $response = $this->template($toObject); } if($response) { $this->reset(); return $response; } throw new Exception(trans('location::errors.not_enough_data')); }
php
{ "resource": "" }
q4780
Location.template
train
private function template($toObject) { if($toObject) { $response = new StdClass; foreach($this->returnLocationData as $key => $value) { $response->{$key} = $value; } return $response; } return $this->returnLocationData; }
php
{ "resource": "" }
q4781
Location.p2c
train
private function p2c() { if($this->returnLocationData['postal_code'] && ! $this->returnLocationData['latitude']) { $this->method = 'GET'; $this->updateResponseWithResults($this->gateway($this->createAddressUrl())); if($this->shouldRunC2A) { $this->c2a(); } return true; } }
php
{ "resource": "" }
q4782
Location.i2c
train
private function i2c() { if($this->ip && ! $this->returnLocationData['latitude']) { $this->method = 'POST'; $this->updateResponseWithResults($this->gateway($this->createGeoUrl())); if($this->shouldRunC2A) { $this->c2a(); } return true; } }
php
{ "resource": "" }
q4783
Location.createAddressUrl
train
private function createAddressUrl() { $urlVariables = [ 'language' => $this->locale, ]; if(count($this->isos)) { $urlVariables['components'] = 'country:'.implode(',', $this->isos); } // if true it will always be the final stage in getting the address if($this->returnLocationData['latitude'] && $this->returnLocationData['longitude']) { $urlVariables['latlng'] = $this->returnLocationData['latitude'].','.$this->returnLocationData['longitude']; return $this->buildUrl($urlVariables); } if($this->returnLocationData['city'] && $this->returnLocationData['country']) { $urlVariables['address'] = $this->returnLocationData['city'].', '.$this->returnLocationData['country']; return $this->buildUrl($urlVariables); } if($this->returnLocationData['postal_code']) { $urlVariables['address'] = $this->returnLocationData['postal_code'].(($this->returnLocationData['street_number']) ? ' '.$this->returnLocationData['street_number'] : ''); return $this->buildUrl($urlVariables); } }
php
{ "resource": "" }
q4784
Location.buildUrl
train
private function buildUrl($urlVariables) { $url = ''; foreach($urlVariables as $variable => $value) { $url .= '&'.$variable.'='.($value); } return config('location.google-maps-url').env('GOOGLE_KEY').$url; }
php
{ "resource": "" }
q4785
Location.updateResponseWithResults
train
private function updateResponseWithResults($json) { $response = $this->jsonToArray($json); if(isset($response['results'][0])) { $this->response = $response['results'][0]; if(@$response['results'][0]['partial_match'] && $this->excludePartials) { throw new Exception(trans('location::errors.no_results')); } if(! $this->returnLocationData['country']) { $this->returnLocationData['country'] = $this->findInGoogleSet($response, ['country']); $this->returnLocationData['iso'] = $this->findInGoogleSet($response, ['country'], 'short_name'); } if(! $this->returnLocationData['region']) { $this->returnLocationData['region'] = $this->findInGoogleSet($response, ['administrative_area_level_1']); } if(! $this->returnLocationData['city']) { $this->returnLocationData['city'] = $this->findInGoogleSet($response, ['administrative_area_level_2']); } if(! $this->returnLocationData['street']) { $this->returnLocationData['street'] = $this->findInGoogleSet($response, ['route']); } if(! $this->returnLocationData['street_number']) { $this->returnLocationData['street_number'] = $this->findInGoogleSet($response, ['street_number']); } if(! $this->returnLocationData['postal_code']) { $this->returnLocationData['postal_code'] = $this->findInGoogleSet($response, ['postal_code']); } if(! $this->returnLocationData['latitude']) { $this->returnLocationData['latitude'] = $response['results'][0]['geometry']['location']['lat']; } if(! $this->returnLocationData['longitude']) { $this->returnLocationData['longitude'] = $response['results'][0]['geometry']['location']['lng']; } } elseif(@$response['location']) { $this->returnLocationData['latitude'] = $response['location']['lat']; $this->returnLocationData['longitude'] = $response['location']['lng']; } else { throw new Exception(trans('location::errors.no_results')); } }
php
{ "resource": "" }
q4786
Location.findInGoogleSet
train
private function findInGoogleSet($response, array $find = [], $type = 'long_name') { try { foreach($response['results'][0]['address_components'] as $data) { foreach($data['types'] as $key) { if(in_array($key, $find)) { return $data[$type]; } } } return ''; } catch(Exception $e) { $this->error = $e; return ''; } }
php
{ "resource": "" }
q4787
Location.jsonToArray
train
private function jsonToArray($json) { try { $data = json_decode($json, true); if(is_array($data)) { return $data; } else { $this->error = 'The given data string was not json'; return []; } } catch(Exception $e) { $this->error = $e; } }
php
{ "resource": "" }
q4788
Location.reset
train
private function reset() { $this->returnLocationData = $this->locationDataTemplate; $this->locale = (config('location.language')) ? config('location.language') : App::getLocale(); $this->ip = null; $this->client = null; }
php
{ "resource": "" }
q4789
DisableElementsCapableFormSettings.convert
train
protected function convert(array $value) { $return = array(); foreach ($value as $name => $elements) { if (is_array($elements)) { // We have a checkbox hit for a subform/fieldset, if (isset($elements['__all__'])) { if ('0' == $elements['__all__']) { // The whole subform/fieldset shall be disabled, so add it and continue. $return[] = $name; continue; } else { // We do not need the toggle all checkbox value anymore. unset($elements['__all__']); } } // recurse with the subform/fieldset element toggle checkboxes. $result = $this->convert($elements); if (count($result)) { // Some elements on the subform shall be disabled, so add the result array. $return[$name] = $result; } continue; } if ('0' == $elements) { // We have a disabled element, add it to the array. $return[] = $name; } } return $return; }
php
{ "resource": "" }
q4790
PostsTable.buildRules
train
public function buildRules(RulesChecker $rules) { return $rules->add($rules->existsIn(['category_id'], 'Categories', I18N_SELECT_VALID_OPTION)) ->add($rules->existsIn(['user_id'], 'Users', I18N_SELECT_VALID_OPTION)) ->add($rules->isUnique(['slug'], I18N_VALUE_ALREADY_USED)) ->add($rules->isUnique(['title'], I18N_VALUE_ALREADY_USED)); }
php
{ "resource": "" }
q4791
PostsTable.getRelated
train
public function getRelated(Post $post, $limit = 5, $images = true) { key_exists_or_fail(['id', 'tags'], $post->toArray(), __d('me_cms', 'ID or tags of the post are missing')); $cache = sprintf('related_%s_posts_for_%s', $limit, $post->id); if ($images) { $cache .= '_with_images'; } return Cache::remember($cache, function () use ($images, $limit, $post) { $related = []; if ($post->has('tags')) { //Sorts and takes tags by `post_count` field $tags = collection($post->tags)->sortBy('post_count')->take($limit)->toList(); //This array will be contain the ID to be excluded $exclude[] = $post->id; //For each tag, gets a related post. //It reverses the tags order, because the tags less popular have // less chance to find a related post foreach (array_reverse($tags) as $tag) { $post = $this->queryForRelated($tag->id, $images) ->where([sprintf('%s.id NOT IN', $this->getAlias()) => $exclude]) ->first(); //Adds the current post to the related posts and its ID to the // IDs to be excluded for the next query if ($post) { $related[] = $post; $exclude[] = $post->id; } } } return $related; }, $this->getCacheName()); }
php
{ "resource": "" }
q4792
PostsTable.queryForRelated
train
public function queryForRelated($tagId, $images = true) { $query = $this->find('active') ->select(['id', 'title', 'preview', 'slug', 'text']) ->matching('Tags', function (Query $q) use ($tagId) { return $q->where([sprintf('%s.id', $this->Tags->getAlias()) => $tagId]); }); if ($images) { $query->where([sprintf('%s.preview NOT IN', $this->getAlias()) => [null, []]]); } return $query; }
php
{ "resource": "" }
q4793
OmmuSystemPhrase.getPublicPhrase
train
public static function getPublicPhrase($select=null) { $criteria=new CDbCriteria; $criteria->condition = 'phrase_id > :first AND phrase_id < :last'; $criteria->params = array( ':first'=>1000, ':last'=>1500, ); if($select != null) $criteria->select = $select; $model = self::model()->findAll($criteria); return $model; }
php
{ "resource": "" }
q4794
CleanupScript.pruneRelationships
train
protected function pruneRelationships() { $cli = $this->climate(); $ask = $this->interactive(); $dry = $this->dryRun(); $verb = $this->verbose(); $mucho = ($dry || $verb); $attach = $this->modelFactory()->get(Attachment::class); $pivot = $this->modelFactory()->get(Join::class); $source = $attach->source(); $db = $source->db(); $defaultBinds = [ '%pivotTable' => $pivot->source()->table(), '%sourceType' => 'object_type', '%sourceId' => 'object_id', ]; $sql = 'SELECT DISTINCT `%sourceType` FROM `%pivotTable`;'; $rows = $db->query(strtr($sql, $binds), PDO::FETCH_ASSOC); if ($rows->rowCount()) { error_log(get_called_class().'::'.__FUNCTION__); /** @todo Confirm each distinct source type */ foreach ($rows as $row) { try { $model = $this->modelFactory()->get($row['object_type']); } catch (Exception $e) { unset($e); $model = $row['object_type']; } if ($model instanceof ModelInterface) { $sql = 'SELECT p.* FROM `%pivotTable` AS p WHERE p.`%sourceType` = :objType AND p.`%sourceId` NOT IN ( SELECT o.`%objectKey` FROM `%objectTable` AS o );'; $binds = array_merge($defaultBinds, [ '%objectTable' => $model->source()->table(), '%objectKey' => $model->key(), ]); $rows = $source->dbQuery( strtr($sql, $binds), [ 'objType' => $row['object_type'] ] ); /** @todo Show found rows, confirm deletion of dead relationships */ /* $sql = 'DELETE FROM `%pivotTable` AS p WHERE p.`%sourceType` = :objType AND p.`%sourceId` NOT IN ( SELECT o.`%objectKey` FROM `%objectTable` AS o );'; error_log('-- Delete Dead Objects: '.var_export($sql, true)); $source->dbQuery( strtr($sql, $defaultBinds), [ 'objType' => $model ] ); */ } elseif (is_string($model)) { $sql = 'SELECT p.* FROM `%pivotTable` AS p WHERE p.`%sourceType` = :objType;'; $rows = $source->dbQuery( strtr($sql, $defaultBinds), [ 'objType' => $model ] ); /** @todo Explain missing model, confirm deletion of dead relationships */ /* $sql = 'DELETE FROM `%pivotTable` WHERE `%sourceType` = :objType;'; error_log('-- Delete Dead Model: '.var_export($sql, true)); $source->dbQuery( strtr($sql, $defaultBinds), [ 'objType' => $model ] ); */ } } /* if (!$this->describeCount( $this->total, '%d dead objects were found.', '%d dead object was found.', 'All objects are associated!' )) { return $this; } */ $this->conclude(); } return $this; }
php
{ "resource": "" }
q4795
CleanupScript.conclude
train
protected function conclude() { $cli = $this->climate(); if (count($this->messages)) { $cli->out(implode(' ', $this->messages)); $this->messages = []; } else { $cli->info('Done!'); } return $this; }
php
{ "resource": "" }
q4796
CleanupScript.describeCount
train
protected function describeCount($count, $plural, $singular, $zero) { if (!is_int($count)) { throw new InvalidArgumentException( sprintf( 'Must be an integer', is_object($count) ? get_class($count) : gettype($count) ) ); } $cli = $this->climate(); if ($count === 0) { $cli->info( sprintf($zero, $count) ); return false; } elseif ($count === 1) { $cli->comment( sprintf($singular, $count) ); } else { $cli->comment( sprintf($plural, $count) ); } $cli->br(); return true; }
php
{ "resource": "" }
q4797
Gallery.attachmentsAsRows
train
public function attachmentsAsRows() { $rows = []; if ($this->hasAttachments()) { $rows = array_chunk($this->attachments()->values(), $this->numColumns); /** Map row content with useful front-end properties. */ array_walk($rows, function(&$value, $key) { $value = [ 'columns' => $value, 'isFirst' => $key === 0 ]; }); } return $rows; }
php
{ "resource": "" }
q4798
StaticPage.getAllPaths
train
protected static function getAllPaths() { $paths = Cache::read('paths', 'static_pages'); if (empty($paths)) { //Adds all plugins to paths $paths = collection(Plugin::all()) ->map(function ($plugin) { return self::getPluginPath($plugin); }) ->filter(function ($path) { return file_exists($path); }) ->toList(); //Adds APP to paths array_unshift($paths, self::getAppPath()); Cache::write('paths', $paths, 'static_pages'); } return $paths; }
php
{ "resource": "" }
q4799
StaticPage.getSlug
train
protected static function getSlug($path, $relativePath) { if (string_starts_with($path, $relativePath)) { $path = substr($path, strlen(Folder::slashTerm($relativePath))); } $path = preg_replace(sprintf('/\.[^\.]+$/'), null, $path); return DS == '/' ? $path : str_replace(DS, '/', $path); }
php
{ "resource": "" }