_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
33
8k
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';
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())
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([
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
php
{ "resource": "" }
q4704
Front.getBlockElementsHtml
train
public function getBlockElementsHtml($block) { if (empty($block)) { return ''; }
php
{ "resource": "" }
q4705
Front.getElementHtml
train
public function getElementHtml($element) { // Ensure we have an element type if (!isset($element->template) && empty($element->template)) {
php
{ "resource": "" }
q4706
Front.getCollectionPages
train
public function getCollectionPages($collectionId) { $pageMapper = ($this->container->dataMapper)('PageMapper'); // Page Collection
php
{ "resource": "" }
q4707
Front.getGallery
train
public function getGallery(int $galleryId = null) { $mediaCategory = ($this->container->dataMapper)('MediaCategoryMapper');
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) {
php
{ "resource": "" }
q4709
AdminMessageController.showMessages
train
public function showMessages() { $messageMapper = ($this->container->dataMapper)('MessageMapper');
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
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
php
{ "resource": "" }
q4712
MediaCategoryMapper.deleteMediaCategoryAssignments
train
public function deleteMediaCategoryAssignments(int $mediaId) { $this->sql =
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,
php
{ "resource": "" }
q4714
HelpMessageGenerator.wrapHelp
train
private function wrapHelp($argumentPart, &$help, $minSize = 29) { if (strlen($argumentPart) <= $minSize) { 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(),
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] = '';
php
{ "resource": "" }
q4717
KcFinderComponent.uploadedDirIsWriteable
train
protected function uploadedDirIsWriteable() { $result = $this->Checkup->Webroot->isWriteable();
php
{ "resource": "" }
q4718
ServiceCaller.call
train
public function call($service, ...$params) { if (! $this->hasHandler($service)) { throw ServiceHandlerMethodException::notFound($service); }
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'
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.'
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) ) );
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) {
php
{ "resource": "" }
q4723
FetchModeTrait.setFetchMode
train
public function setFetchMode($mode, ...$args) { if (is_string($mode)) { array_unshift($args, PDO::$mode);
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'
php
{ "resource": "" }
q4725
Controller.onBeforeInit
train
function onBeforeInit() { foreach (Requirements::$disable_cache_busted_file_extensions_for as $class) {
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,
php
{ "resource": "" }
q4727
ConfigurationPool.saveAll
train
public function saveAll() { $this->init(); $parameters = []; foreach ($this->configurations as $configuration) {
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) {
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');
php
{ "resource": "" }
q4730
Session.setFlashData
train
public function setFlashData($mKey, $mValue = null) { $this->setup(true); if (empty($this->oSession)) {
php
{ "resource": "" }
q4731
Session.getFlashData
train
public function getFlashData($sKey = null) { $this->setup(); if (empty($this->oSession)) { return null;
php
{ "resource": "" }
q4732
Session.setUserData
train
public function setUserData($mKey, $mValue = null) { $this->setup(true); if (empty($this->oSession)) {
php
{ "resource": "" }
q4733
Session.getUserData
train
public function getUserData($sKey = null) { $this->setup(); if (empty($this->oSession)) { return null;
php
{ "resource": "" }
q4734
Session.unsetUserData
train
public function unsetUserData($mKey) { if (empty($this->oSession)) {
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();
php
{ "resource": "" }
q4736
Session.regenerate
train
public function regenerate($bDestroy = false) { if (empty($this->oSession)) {
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)
php
{ "resource": "" }
q4738
OFunction.validHostURL
train
public static function validHostURL($targetUrl) { $req = Yii::app()->request; $url = ($req->port == 80? 'http://': 'https://') . $req->serverName;
php
{ "resource": "" }
q4739
User.remove
train
public function remove($entity) { $entity->setState(0);
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]
php
{ "resource": "" }
q4741
TableDef.setColumn
train
public function setColumn($name, $type, $nullDefault = false) {
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.
php
{ "resource": "" }
q4743
TableDef.setPrimaryKey
train
public function setPrimaryKey($name, $type = 'int') { $column = $this->createColumnDef($type, false); $column['autoIncrement'] = true; $column['primary'] = true;
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
php
{ "resource": "" }
q4745
PromoteSingleStrings.promoteSingleStrings
train
protected function promoteSingleStrings(array $string) { $newString = []; foreach ($string as $element) { if (is_array($element) &&
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')
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',
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) {
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;
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
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');
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'], '')
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');
php
{ "resource": "" }
q4754
MetaCharacters.getExpression
train
public function getExpression($metaValue) { if (!isset($this->exprs[$metaValue])) { throw new InvalidArgumentException('Invalid
php
{ "resource": "" }
q4755
MetaCharacters.replaceMeta
train
public function replaceMeta(array $strings) { foreach ($strings as &$string) { foreach ($string as &$value) { if (isset($this->meta[$value])) {
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
php
{ "resource": "" }
q4757
MetaCharacters.exprIsQuantifiable
train
protected function exprIsQuantifiable($expr) { $regexps = [ // A dot or \R '(^(?:\\.|\\\\R)$)D', // A character class
php
{ "resource": "" }
q4758
MetaCharacters.matchesAny
train
protected function matchesAny($expr, array $regexps) { foreach ($regexps as $regexp) { if
php
{ "resource": "" }
q4759
Formula.getCurrentRealmsAffections
train
public function getCurrentRealmsAffections(): array { $realmsAffections = []; foreach ($this->getRealmsAffectionsSum() as $periodName => $periodSum) { $realmsAffections[$periodName]
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) {
php
{ "resource": "" }
q4761
Formula.getRadiusWithAddition
train
private function getRadiusWithAddition(): ?SpellRadius { $baseSpellRadius = $this->tables->getFormulasTable()->getSpellRadius($this->formulaCode); if ($baseSpellRadius === null) { return null; }
php
{ "resource": "" }
q4762
Formula.getCurrentSpellAttack
train
public function getCurrentSpellAttack(): ?SpellAttack { $spellAttackWithAddition = $this->getSpellAttackWithAddition(); if (!$spellAttackWithAddition) { return null; } return new SpellAttack( [
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 !=
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,
php
{ "resource": "" }
q4765
AuthHelper.user
train
public function user($key = null) { if (empty($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
php
{ "resource": "" }
q4767
AppController.setUploadError
train
protected function setUploadError($error) { $this->response = $this->response->withStatus(500);
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
php
{ "resource": "" }
q4769
AccessToken.revoke
train
public function revoke($iUserId, $mToken) { if (is_string($mToken)) { $oToken = $this->getByToken($mToken); } else { $oToken = $mToken; } if ($oToken) {
php
{ "resource": "" }
q4770
AccessToken.hasScope
train
public function hasScope($mToken, $sScope) { if (is_numeric($mToken)) { $oToken = $this->getById($mToken); } else { $oToken = $mToken; }
php
{ "resource": "" }
q4771
DBConnector.setDb
train
public static function setDb($db, $connection_name = self::DEFAULT_CONNECTION) {
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);
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
php
{ "resource": "" }
q4774
URLValidator.validDomains
train
public static function validDomains($url, $domains) { $theDomain = parse_url($url); foreach ($domains as $domain) {
php
{ "resource": "" }
q4775
Location.postalcodeToCoordinates
train
public function postalcodeToCoordinates(array $postalData, $shouldRunC2A = false) { $this->shouldRunC2A = ($this->shouldRunC2A) ? true : $shouldRunC2A; $this->returnLocationData =
php
{ "resource": "" }
q4776
Location.addressToCoordinates
train
public function addressToCoordinates(array $addressData = []) { $this->returnLocationData = array_merge($this->returnLocationData, array_only($addressData,
php
{ "resource": "" }
q4777
Location.coordinatesToAddress
train
public function coordinatesToAddress(array $coordinates = []) { $this->shouldRunC2A = true; $this->returnLocationData
php
{ "resource": "" }
q4778
Location.ipToCoordinates
train
public function ipToCoordinates($ip = null, $shouldRunC2A = false) { $this->shouldRunC2A = ($this->shouldRunC2A) ? true : $shouldRunC2A;
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);
php
{ "resource": "" }
q4780
Location.template
train
private function template($toObject) { if($toObject) { $response = new StdClass; foreach($this->returnLocationData as $key => $value) {
php
{ "resource": "" }
q4781
Location.p2c
train
private function p2c() { if($this->returnLocationData['postal_code'] && ! $this->returnLocationData['latitude']) { $this->method = 'GET';
php
{ "resource": "" }
q4782
Location.i2c
train
private function i2c() { if($this->ip && ! $this->returnLocationData['latitude']) { $this->method = 'POST';
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']) {
php
{ "resource": "" }
q4784
Location.buildUrl
train
private function buildUrl($urlVariables) { $url = ''; foreach($urlVariables as $variable => $value) { $url .= '&'.$variable.'='.($value);
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']);
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))
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
php
{ "resource": "" }
q4788
Location.reset
train
private function reset() { $this->returnLocationData = $this->locationDataTemplate; $this->locale
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.
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))
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) {
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]);
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,
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, [
php
{ "resource": "" }
q4795
CleanupScript.conclude
train
protected function conclude() { $cli = $this->climate(); if (count($this->messages)) { $cli->out(implode(' ', $this->messages));
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) )
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) {
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) {
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))); }
php
{ "resource": "" }