_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q4400
User.updateAddress
train
public function updateAddress(array $data, $user) { $this->getEventManager()->trigger('updateInfo.pre', $this, array('user' => $user, 'data' => $data)); $form = $this->getServiceManager()->get('playgrounduser_address_form'); $form->bind($user); $form->setData($data); $filter = $user->getInputFilter(); $filter->remove('password'); $filter->remove('passwordVerify'); $filter->remove('dob'); $form->setInputFilter($filter); if ($form->isValid()) { $user = $this->getUserMapper()->update($user); $this->getEventManager()->trigger('updateInfo.post', $this, array('user' => $user, 'data' => $data)); if ($user) { return $user; } } return false; }
php
{ "resource": "" }
q4401
User.getCSV
train
public function getCSV($array) { ob_start(); // buffer the output ... $out = fopen('php://output', 'w'); fputcsv($out, array_keys($array[0]), ";"); array_shift($array); foreach ($array as $line) { fputcsv($out, $line, ";"); } fclose($out); return ob_get_clean(); // ... then return it as a string! }
php
{ "resource": "" }
q4402
User.getProviderService
train
public function getProviderService() { if ($this->providerService == null) { $this->setProviderService($this->getServiceManager()->get('playgrounduser_provider_service')); } return $this->providerService; }
php
{ "resource": "" }
q4403
VersionUpdatesCommand.addEnableCommentsField
train
public function addEnableCommentsField() { Cache::clear(false, '_cake_model_'); foreach (['Pages', 'Posts'] as $table) { $Table = $this->loadModel('MeCms.' . $table); if (!$Table->getSchema()->hasColumn('enable_comments')) { $Table->getConnection()->execute(sprintf('ALTER TABLE `%s` ADD `enable_comments` BOOLEAN NOT NULL DEFAULT TRUE AFTER `preview`', $Table->getTable())); } } }
php
{ "resource": "" }
q4404
VersionUpdatesCommand.alterTagColumnSize
train
public function alterTagColumnSize() { $Tags = $this->loadModel('MeCms.Tags'); if ($Tags->getSchema()->getColumn('tag')['length'] < 255) { $Tags->getConnection()->execute('ALTER TABLE tags MODIFY tag varchar(255) NOT NULL'); } }
php
{ "resource": "" }
q4405
VersionUpdatesCommand.execute
train
public function execute(Arguments $args, ConsoleIo $io) { $this->addEnableCommentsField(); $this->alterTagColumnSize(); $this->deleteOldDirectories(); return null; }
php
{ "resource": "" }
q4406
XMLValidator.getSchemaVersion
train
public static function getSchemaVersion($xml) { $doiXML = new \DOMDocument(); $doiXML->loadXML($xml); $resources = $doiXML->getElementsByTagName('resource'); $theSchema = 'unknown'; if ($resources->length > 0) { if (isset($resources->item(0)->attributes->item(0)->name)) { $theSchema = substr($resources->item(0)->attributes->item(0)->nodeValue, strpos($resources->item(0)->attributes->item(0)->nodeValue, "/meta/kernel") + 5); } } return $theSchema; }
php
{ "resource": "" }
q4407
XMLValidator.replaceDOIValue
train
public static function replaceDOIValue($doiValue, $xml) { $doiXML = new \DOMDocument(); $doiXML->loadXML($xml); // remove the current identifier $currentIdentifier = $doiXML->getElementsByTagName('identifier'); for ($i = 0; $i < $currentIdentifier->length; $i++) { $doiXML ->getElementsByTagName('resource') ->item(0) ->removeChild($currentIdentifier->item($i)); } // add new identifier to the DOM $newIdentifier = $doiXML->createElement('identifier', $doiValue); $newIdentifier->setAttribute('identifierType', "DOI"); $doiXML ->getElementsByTagName('resource') ->item(0) ->insertBefore( $newIdentifier, $doiXML->getElementsByTagName('resource')->item(0)->firstChild ); return $doiXML->saveXML(); }
php
{ "resource": "" }
q4408
XMLValidator.getDOIValue
train
public static function getDOIValue($xml) { $doiXML = new \DOMDocument(); $doiXML->loadXML($xml); // get the current identifier $currentIdentifier = $doiXML->getElementsByTagName('identifier'); return $currentIdentifier->item(0)->nodeValue; }
php
{ "resource": "" }
q4409
AdminUserController.showUsers
train
public function showUsers() { // Get dependencies $userMapper = ($this->container->dataMapper)('UserMapper'); // Fetch users $users = $userMapper->find(); return $this->render('users.html', $users); }
php
{ "resource": "" }
q4410
Plugin.versions
train
public function versions() { $Plugin = new BasePlugin; $plugins['me_cms'] = trim(file_get_contents($Plugin->path('MeCms', 'version'))); foreach ($Plugin->all(['exclude' => 'MeCms']) as $plugin) { $file = $Plugin->path($plugin, 'version', true); $plugins['others'][$plugin] = __d('me_cms', 'n.a.'); if ($file) { $plugins['others'][$plugin] = trim(file_get_contents($file)); } } return $plugins; }
php
{ "resource": "" }
q4411
AbstractCheckup._isWriteable
train
protected function _isWriteable($paths) { foreach ((array)$paths as $path) { $result[$path] = is_writable_resursive($path); } return $result; }
php
{ "resource": "" }
q4412
DisableElementsCapableFormSettings.setForm
train
public function setForm($formOrContainer) { if (!$formOrContainer instanceof FormInterface && !$formOrContainer instanceof Container ) { throw new \InvalidArgumentException('Parameter must be either of type "\Zend\Form\FormInterface" or "\Core\Form\Container"'); } $this->form = $formOrContainer; $this->generateCheckboxes(); return $this; }
php
{ "resource": "" }
q4413
DisableElementsCapableFormSettings.prepareCheckboxes
train
protected function prepareCheckboxes(array $boxes, $prefix) { foreach ($boxes as $box) { if (is_array($box)) { $this->prepareCheckboxes($box, $prefix); } else { /* @var $box Checkbox */ $box->setName($prefix . $box->getName()); } } }
php
{ "resource": "" }
q4414
DisableElementsCapableFormSettings.createCheckbox
train
protected function createCheckbox($name, $options) { $box = new Checkbox($name, $options); $box->setAttribute('checked', true) ->setAttribute( 'id', preg_replace( array('~\[~', '~\]~', '~--+~', '~-$~'), array('-', '', '-', ''), $name ) ); return $box; }
php
{ "resource": "" }
q4415
MenuBuilderHelper.buildLinks
train
protected function buildLinks($links, array $linksOptions = []) { return array_map(function ($link) use ($linksOptions) { return $this->Html->link($link[0], $link[1], $linksOptions); }, $links); }
php
{ "resource": "" }
q4416
MenuBuilderHelper.getMenuMethods
train
protected function getMenuMethods($plugin) { //Gets all methods from `$PLUGIN\View\Helper\MenuHelper` $methods = get_child_methods(sprintf('\%s\View\Helper\MenuHelper', $plugin)); //Filters invalid name methods and returns return $methods ? array_values(preg_grep('/^(?!_).+$/', $methods)) : []; }
php
{ "resource": "" }
q4417
MenuBuilderHelper.generate
train
public function generate($plugin) { //Gets all menu name methods $methods = $this->getMenuMethods($plugin); if (empty($methods)) { return []; } $className = sprintf('%s.Menu', $plugin); //Loads the helper $helper = $this->_View->loadHelper($className, compact('className')); $menus = []; //Calls dynamically each method foreach ($methods as $method) { list($links, $title, $titleOptions) = call_user_func([$helper, $method]); if (empty($links) || empty($title)) { continue; } $menus[sprintf('%s.%s', $plugin, $method)] = compact('links', 'title', 'titleOptions'); } return $menus; }
php
{ "resource": "" }
q4418
MenuBuilderHelper.renderAsCollapse
train
public function renderAsCollapse($plugin) { return implode(PHP_EOL, array_map(function ($menu) { //Sets the collapse name $collapseName = 'collapse-' . strtolower(Text::slug($menu['title'])); $titleOptions = optionsParser($menu['titleOptions'], [ 'aria-controls' => $collapseName, 'aria-expanded' => 'false', 'class' => 'collapsed', 'data-toggle' => 'collapse', ]); $mainLink = $this->Html->link($menu['title'], '#' . $collapseName, $titleOptions->toArray()); $links = $this->Html->div('collapse', $this->buildLinks($menu['links']), ['id' => $collapseName]); return $this->Html->div('card', $mainLink . PHP_EOL . $links); }, $this->generate($plugin))); }
php
{ "resource": "" }
q4419
MenuBuilderHelper.renderAsDropdown
train
public function renderAsDropdown($plugin, array $titleOptions = []) { return array_map(function ($menu) use ($titleOptions) { $titleOptions = optionsParser($menu['titleOptions'], $titleOptions); $links = $this->buildLinks($menu['links'], ['class' => 'dropdown-item']); return $this->Dropdown->menu($menu['title'], $links, $titleOptions->toArray()); }, $this->generate($plugin)); }
php
{ "resource": "" }
q4420
FrontBaseController.buildElementsByBlock
train
protected function buildElementsByBlock($elements) { if (empty($elements)) { return $elements; } $output = []; foreach ($elements as $element) { $output[$element->block_key][] = $element; } return $output; }
php
{ "resource": "" }
q4421
FrontBaseController.buildPageSettings
train
protected function buildPageSettings($settings) { if (empty($settings)) { return $settings; } $output = []; foreach ($settings as $setting) { $output[$setting->setting_key] = $setting->setting_value; } return $output; }
php
{ "resource": "" }
q4422
Email.setFrom
train
public function setFrom($address, $name = null) : EmailInterface { // When using mail/sendmail, we need to set the PHPMailer "auto" flag to false // https://github.com/PHPMailer/PHPMailer/issues/1634 $this->mailer->setFrom($address, $name, false); return $this; }
php
{ "resource": "" }
q4423
Email.setTo
train
public function setTo($address, $name = null) : EmailInterface { $this->mailer->addAddress($address, $name); return $this; }
php
{ "resource": "" }
q4424
AdminBaseController.mergeSettings
train
public function mergeSettings(array $savedSettings, array $definedSettings) { // Test if the saved settings are for site or page. Only site settings have the category key $pageSetting = isset($savedSettings[0]->category) ? false : true; // Make index of saved setting keys to setting array for easy lookup $settingIndex = array_combine(array_column($savedSettings, 'setting_key'), array_keys($savedSettings)); // Loop through defined settings and update with saved values and meta info foreach ($definedSettings as $defKey => $setting) { if (isset($settingIndex[$setting->key])) { $definedSettings[$defKey]->id = $savedSettings[$settingIndex[$setting->key]]->id; $definedSettings[$defKey]->setting_value = $savedSettings[$settingIndex[$setting->key]]->setting_value; $definedSettings[$defKey]->created_by = $savedSettings[$settingIndex[$setting->key]]->created_by; $definedSettings[$defKey]->created_date = $savedSettings[$settingIndex[$setting->key]]->created_date; $definedSettings[$defKey]->updated_by = $savedSettings[$settingIndex[$setting->key]]->updated_by; $definedSettings[$defKey]->updated_date = $savedSettings[$settingIndex[$setting->key]]->updated_date; // Remove saved setting from array parameter now that we have updated the setting definition unset($savedSettings[$settingIndex[$setting->key]]); } else { // If a matching saved setting was NOT found, then set default value $definedSettings[$defKey]->setting_value = $definedSettings[$defKey]->value; } // Amend setting keys to what is expected in template $definedSettings[$defKey]->setting_key = $setting->key; $definedSettings[$defKey]->input_type = $definedSettings[$defKey]->inputType; // Include select options array if ($definedSettings[$defKey]->inputType === 'select') { $definedSettings[$defKey]->options = array_column($definedSettings[$defKey]->options, 'name', 'value'); } // Add setting catagory. Not needed for page settings, but not in the way either $definedSettings[$defKey]->category = 'custom'; // Remove JSON keys to avoid confusion in template unset($definedSettings[$defKey]->key); unset($definedSettings[$defKey]->value); unset($definedSettings[$defKey]->inputType); } // Check remaining saved settings for orphaned settings. array_walk($savedSettings, function(&$row) use ($pageSetting) { if ($pageSetting || (isset($row->category) && $row->category === 'custom')) { $row->orphaned = true; } }); // Append defined settings to end of saved settings array and return return array_merge($savedSettings, $definedSettings); }
php
{ "resource": "" }
q4425
AdminBaseController.getPageTemplates
train
public function getPageTemplates(string $templateType = null) { $toolbox = $this->container->toolbox; $json = $this->container->json; // Validate inputs if ($templateType !== null && !in_array($templateType, ['page','collection'])) { throw new Exception("PitonCMS Unexpected $templateType paramter. Expecting 'page' or 'collection'"); } $jsonPath = ROOT_DIR . "structure/definitions/pages/"; $templates = []; foreach ($toolbox->getDirectoryFiles($jsonPath) as $row) { // Get definition files if (null === $definition = $json->getJson($jsonPath . $row['filename'], 'page')) { $this->setAlert('danger', 'Page JSON Definition Error', $json->getErrorMessages()); break; } if ($templateType !== null && $definition->templateType !== $templateType) { continue; } $templates[] = [ 'filename' => $row['filename'], 'name' => $definition->templateName, 'description' => $definition->templateDescription ]; } return $templates; }
php
{ "resource": "" }
q4426
Admin.getThemes
train
public function getThemes() { $json = $this->container->json; if (null === $definition = $json->getJson(ROOT_DIR . 'structure/definitions/themes.json', 'themes')) { throw new Exception('PitonCMS: Get themes exception: ' . implode($json->getErrorMessages(), ',')); } return array_column($definition->themes, 'name', 'value'); }
php
{ "resource": "" }
q4427
Admin.getAlert
train
public function getAlert($context, $key = null) { $session = $this->container->sessionHandler; // Get alert notices from page context, or failing that then session flash data $alert = (isset($context['alert'])) ? $context['alert'] : $session->getFlashData('alert'); if ($key === null) { return $alert; } if (isset($alert[$key])) { if ($key === 'message' ) { return '<ul><li>' . implode('</li><li>', $alert['message']) . '</ul>'; } return $alert[$key]; } return null; }
php
{ "resource": "" }
q4428
Admin.getCollections
train
public function getCollections() { if ($this->collections) { return $this->collections; } $collectionMapper = ($this->container->dataMapper)('CollectionMapper'); return $this->collections = $collectionMapper->find(); }
php
{ "resource": "" }
q4429
Admin.getGalleries
train
public function getGalleries() { if ($this->galleries) { return $this->galleries; } $mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper'); return $this->galleries = $mediaCategoryMapper->findCategories(); }
php
{ "resource": "" }
q4430
Admin.getUnreadMessageCount
train
public function getUnreadMessageCount() { $messageMapper = ($this->container->dataMapper)('MessageMapper'); $count = $messageMapper->findUnreadCount(); return ($count === 0) ? null : $count; }
php
{ "resource": "" }
q4431
IntegrationCache.loadOverrides
train
protected function loadOverrides() { if ($this->overrides === null) { $this->overrides = []; if ($this->overrideFile !== null) { $this->overrides = Craft::$app->getConfig()->getConfigFromFile($this->overrideFile); } } }
php
{ "resource": "" }
q4432
ContactUsMailer.contactUsMail
train
public function contactUsMail($data) { //Checks that all required data is present key_exists_or_fail(['email', 'first_name', 'last_name', 'message'], $data); $this->viewBuilder()->setTemplate('MeCms.Systems/contact_us'); $this->setSender($data['email'], sprintf('%s %s', $data['first_name'], $data['last_name'])) ->setReplyTo($data['email'], sprintf('%s %s', $data['first_name'], $data['last_name'])) ->setTo(getConfigOrFail('email.webmaster')) ->setSubject(__d('me_cms', 'Email from {0}', getConfigOrFail('main.title'))) ->setViewVars([ 'email' => $data['email'], 'firstName' => $data['first_name'], 'lastName' => $data['last_name'], 'message' => $data['message'], ]); }
php
{ "resource": "" }
q4433
AdminCollectionController.showCollections
train
public function showCollections() { // Get dependencies $collectionMapper = ($this->container->dataMapper)('CollectionMapper'); $pageMapper = ($this->container->dataMapper)('PageMapper'); // Fetch collection pages, and chuck pages into sub-array by collection ID with meta info $collectionPages = $pageMapper->findCollectionPages(); foreach ($collectionPages as $col) { if (!isset($data['collectionPages'][$col->collection_id])) { $data['collectionPages'][$col->collection_id]['collection_id'] = $col->collection_id; $data['collectionPages'][$col->collection_id]['collection_title'] = $col->collection_title; $data['collectionPages'][$col->collection_id]['collection_slug'] = $col->collection_slug; } $data['collectionPages'][$col->collection_id]['pages'][] = $col; } // Get available templates and collection groups $data['templates'] = $this->getPageTemplates('collection'); $data['collections'] = $collectionMapper->find(); // Enrich collections array with matching description from templates array $templateArray = array_column($data['templates'], 'filename'); array_walk($data['collections'], function (&$collect) use ($data, $templateArray) { // Find matching collection template key for reference in $templateArray $key = array_search($collect->definition, $templateArray); $collect->templateName = $data['templates'][$key]['name']; $collect->templateDescription = $data['templates'][$key]['description']; }); return $this->render('collections.html', $data); }
php
{ "resource": "" }
q4434
AdminCollectionController.editCollection
train
public function editCollection($args) { // Get dependencies $collectionMapper = ($this->container->dataMapper)('CollectionMapper'); $json = $this->container->json; $toolbox = $this->container->toolbox; // Fetch collection group, or create new collection group if (isset($args['id']) && is_numeric($args['id'])) { $collection = $collectionMapper->findById($args['id']); } else { $definionParam = $this->request->getQueryParam('definition'); // Validate that we have a proper definition file name if (null === $definionParam || 1 !== preg_match('/^[a-zA-Z0-9]+\.json$/', $definionParam)) { throw new Exception("PitonCMS: Invalid query parameter for 'definition': $definionParam"); } // Create new collection and set template JSON file $collection = $collectionMapper->make(); $collection->definition = $definionParam; } return $this->render('editCollection.html', $collection); }
php
{ "resource": "" }
q4435
AdminCollectionController.confirmDeleteCollection
train
public function confirmDeleteCollection($args) { // Get dependencies $collectionMapper = ($this->container->dataMapper)('CollectionMapper'); $pageMapper = ($this->container->dataMapper)('PageMapper'); $data = $collectionMapper->findById($args['id']); $data->pages = $pageMapper->findCollectionPagesById($args['id'], false); return $this->render('confirmDeleteCollection.html', $data); }
php
{ "resource": "" }
q4436
CallsServices.call
train
public function call(string $service, ...$params) { return Container::getInstance()->make(ServiceCaller::class)->call($service, ...$params); }
php
{ "resource": "" }
q4437
AbstractPass.beforeRun
train
protected function beforeRun(array $strings) { $this->isOptional = (isset($strings[0]) && $strings[0] === []); if ($this->isOptional) { array_shift($strings); } return $strings; }
php
{ "resource": "" }
q4438
AbstractPass.isSingleCharStringList
train
protected function isSingleCharStringList(array $strings) { foreach ($strings as $string) { if (!$this->isSingleCharString($string)) { return false; } } return true; }
php
{ "resource": "" }
q4439
Cookie.logout
train
public function logout() { $authService = $this->getServiceManager()->get('zfcuser_auth_service'); $user = $authService->getIdentity(); $cookie = explode("\n", $this->getRememberMeService()->getCookie()); if ($cookie[0] !== '' && $user !== null) { $this->getRememberMeService()->removeSerie($user->getId(), $cookie[1]); $this->getRememberMeService()->removeCookie(); } }
php
{ "resource": "" }
q4440
Plugin.middleware
train
public function middleware($middleware) { $key = Configure::read('Security.cookieKey', md5(Configure::read('Security.salt'))); return $middleware->add(new EncryptedCookieMiddleware(['login'], $key)); }
php
{ "resource": "" }
q4441
Plugin.setVendorLinks
train
protected function setVendorLinks() { $links = array_unique(array_merge(Configure::read('VENDOR_LINKS', []), [ 'npm-asset' . DS . 'js-cookie' . DS . 'src' => 'js-cookie', 'sunhater' . DS . 'kcfinder' => 'kcfinder', 'enyo' . DS . 'dropzone' . DS . 'dist' => 'dropzone', ])); return Configure::write('VENDOR_LINKS', $links) ? $links : false; }
php
{ "resource": "" }
q4442
Plugin.setWritableDirs
train
protected function setWritableDirs() { $dirs = array_unique(array_filter(array_merge(Configure::read('WRITABLE_DIRS', []), [ getConfig('Assets.target'), getConfigOrFail('DatabaseBackup.target'), getConfigOrFail('Thumber.target'), BANNERS, LOGIN_RECORDS, PHOTOS, USER_PICTURES, ]))); return Configure::write('WRITABLE_DIRS', $dirs) ? $dirs : false; }
php
{ "resource": "" }
q4443
UsersController.changePassword
train
public function changePassword() { $user = $this->Users->get($this->Auth->user('id')); if ($this->request->is(['patch', 'post', 'put'])) { $user = $this->Users->patchEntity($user, $this->request->getData()); if ($this->Users->save($user)) { //Sends email $this->getMailer('MeCms.User')->send('changePassword', [$user]); $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['_name' => 'dashboard']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('user')); }
php
{ "resource": "" }
q4444
UsersController.changePicture
train
public function changePicture() { $id = $this->Auth->user('id'); if ($this->request->getData('file')) { //Deletes any picture that already exists foreach (((new Folder(USER_PICTURES))->find($id . '\..+')) as $filename) { @unlink(USER_PICTURES . $filename); } $filename = sprintf('%s.%s', $id, pathinfo($this->request->getData('file')['tmp_name'], PATHINFO_EXTENSION)); $uploaded = $this->Uploader->set($this->request->getData('file')) ->mimetype('image') ->save(USER_PICTURES, $filename); if (!$uploaded) { return $this->setUploadError($this->Uploader->getError()); } //Updates the authentication data and clears similar thumbnails $this->Auth->setUser(array_merge($this->Auth->user(), ['picture' => $uploaded])); (new ThumbManager)->clear($uploaded); } }
php
{ "resource": "" }
q4445
UsersController.lastLogin
train
public function lastLogin() { //Checks if login logs are enabled if (!getConfig('users.login_log')) { $this->Flash->error(I18N_DISABLED); return $this->redirect(['_name' => 'dashboard']); } $this->set('loginLog', $this->LoginRecorder->setConfig('user', $this->Auth->user('id'))->read()); }
php
{ "resource": "" }
q4446
Base.setStyles
train
public function setStyles(OutputInterface $oOutput): void { $oWarningStyle = new OutputFormatterStyle('white', 'yellow'); $oOutput->getFormatter()->setStyle('warning', $oWarningStyle); }
php
{ "resource": "" }
q4447
Base.confirm
train
protected function confirm($sQuestion, $bDefault) { $sQuestion = is_array($sQuestion) ? implode("\n", $sQuestion) : $sQuestion; $oHelper = $this->getHelper('question'); $sDefault = (bool) $bDefault ? 'Y' : 'N'; $oQuestion = new ConfirmationQuestion($sQuestion . ' [' . $sDefault . ']: ', $bDefault); return $oHelper->ask($this->oInput, $this->oOutput, $oQuestion); }
php
{ "resource": "" }
q4448
Base.ask
train
protected function ask($mQuestion, $sDefault) { $mQuestion = is_array($mQuestion) ? implode("\n", $mQuestion) : $mQuestion; $oHelper = $this->getHelper('question'); $oQuestion = new Question($mQuestion . ' [' . $sDefault . ']: ', $sDefault); return $oHelper->ask($this->oInput, $this->oOutput, $oQuestion); }
php
{ "resource": "" }
q4449
Base.outputBlock
train
protected function outputBlock(array $aLines, string $sType): void { $aLengths = array_map('strlen', $aLines); $iMaxLength = max($aLengths); $this->oOutput->writeln('<' . $sType . '> ' . str_pad('', $iMaxLength, ' ') . ' </' . $sType . '>'); foreach ($aLines as $sLine) { $this->oOutput->writeln('<' . $sType . '> ' . str_pad($sLine, $iMaxLength, ' ') . ' </' . $sType . '>'); } $this->oOutput->writeln('<' . $sType . '> ' . str_pad('', $iMaxLength, ' ') . ' </' . $sType . '>'); }
php
{ "resource": "" }
q4450
Base.callCommand
train
protected function callCommand($sCommand, array $aArguments = [], $bInteractive = true, $bSilent = false) { $oCmd = $this->getApplication()->find($sCommand); $aArguments = array_merge(['command' => $sCommand], $aArguments); $oCmdInput = new ArrayInput($aArguments); $oCmdInput->setInteractive($bInteractive); if ($bSilent) { $oCmdOutput = new NullOutput(); } else { $oCmdOutput = $this->oOutput; } return $oCmd->run($oCmdInput, $oCmdOutput); }
php
{ "resource": "" }
q4451
SocialSignOn.getProviders
train
public function getProviders($status = null) { if ($status == 'ENABLED') { return $this->aProviders['enabled']; } elseif ($status == 'DISABLED') { return $this->aProviders['disabled']; } else { return $this->aProviders['all']; } }
php
{ "resource": "" }
q4452
SocialSignOn.getProvider
train
public function getProvider($provider) { if (isset($this->aProviders['all'][strtolower($provider)])) { return $this->aProviders['all'][strtolower($provider)]; } else { return false; } }
php
{ "resource": "" }
q4453
SocialSignOn.getProviderClass
train
protected function getProviderClass($sProvider) { $aProviders = $this->getProviders(); return isset($aProviders[strtolower($sProvider)]['class']) ? $aProviders[strtolower($sProvider)]['class'] : null; }
php
{ "resource": "" }
q4454
SocialSignOn.authenticate
train
public function authenticate($sProvider, $mParams = null) { try { $sProvider = $this->getProviderClass($sProvider); return $this->oHybridAuth->authenticate($sProvider, $mParams); } catch (\Exception $e) { $this->setError('Provider Error: ' . $e->getMessage()); return false; } }
php
{ "resource": "" }
q4455
SocialSignOn.getUserProfile
train
public function getUserProfile($provider) { $oAdapter = $this->authenticate($provider); try { return $oAdapter->getUserProfile(); } catch (\Exception $e) { $this->setError('Provider Error: ' . $e->getMessage()); return false; } }
php
{ "resource": "" }
q4456
SocialSignOn.getUserByProviderId
train
public function getUserByProviderId($provider, $identifier) { $this->oDb->select('user_id'); $this->oDb->where('provider', $provider); $this->oDb->where('identifier', $identifier); $oUser = $this->oDb->get(NAILS_DB_PREFIX . 'user_social')->row(); if (empty($oUser)) { return false; } return $this->oUserModel->getById($oUser->user_id); }
php
{ "resource": "" }
q4457
SocialSignOn.restoreSession
train
public function restoreSession($user_id = null) { if (empty($user_id)) { $user_id = activeUser('id'); } if (empty($user_id)) { $this->setError('Must specify which user ID\'s session to restore.'); return false; } $oUser = $this->oUserModel->getById($user_id); if (!$oUser) { $this->setError('Invalid User ID'); return false; } // -------------------------------------------------------------------------- // Clean slate $this->oHybridAuth->logoutAllProviders(); // -------------------------------------------------------------------------- $this->oDb->where('user_id', $oUser->id); $aSessions = $this->oDb->get(NAILS_DB_PREFIX . 'user_social')->result(); $aRestore = []; foreach ($aSessions as $oSession) { $oSession->session_data = unserialize($oSession->session_data); $aRestore = array_merge($aRestore, $oSession->session_data); } return $this->oHybridAuth->restoreSessionData(serialize($aRestore)); }
php
{ "resource": "" }
q4458
SocialSignOn.api
train
public function api($sProvider, $call = '') { if (!$this->isConnectedWith($sProvider)) { $this->setError('Not connected with provider "' . $sProvider . '"'); return false; } try { $sProvider = $this->getProviderClass($sProvider); $oProvider = $this->oHybridAuth->getAdapter($sProvider); return $oProvider->api()->api($call); } catch (\Exception $e) { $this->setError('Provider Error: ' . $e->getMessage()); return false; } }
php
{ "resource": "" }
q4459
ModuleHandle.cacheModuleConfig
train
public function cacheModuleConfig($return=false) { $modules = $this->getModulesFromDb(); $arrayModule = array(); foreach($modules as $module) { if(!in_array($module->folder, $arrayModule)) $arrayModule[] = $module->folder; } if($return == false) { $filePath = Yii::getPathOfAlias('application.config'); $fileHandle = fopen($filePath.'/cache_module.php', 'w'); fwrite($fileHandle, implode("\n", $arrayModule)); fclose($fileHandle); } else return $arrayModule; }
php
{ "resource": "" }
q4460
ModuleHandle.getModuleConfig
train
public function getModuleConfig($module) { Yii::import('mustangostang.spyc.Spyc'); define('DS', DIRECTORY_SEPARATOR); $configPath = Yii::getPathOfAlias('application.vendor.ommu.'.$module).DS.$module.'.yaml'; if(file_exists($configPath)) return Spyc::YAMLLoad($configPath); else return null; }
php
{ "resource": "" }
q4461
ModuleHandle.deleteModuleDatabase
train
public function deleteModuleDatabase($module) { $config = $this->getModuleConfig($module); $tableName = $config['db_table_name']; if($config && $tableName) { foreach($tableName as $val){ Yii::app()->db->createCommand("DROP TABLE {$val}")->execute(); } } else return false; }
php
{ "resource": "" }
q4462
ModuleHandle.deleteModuleDb
train
public function deleteModuleDb($module) { if($module != null) { $model = OmmuPlugins::model()->findByAttributes(array('folder'=>$module)); if($model != null) $model->delete(); else return true; } else return true; }
php
{ "resource": "" }
q4463
ModuleHandle.setModules
train
public function setModules() { $moduleVendorPath = Yii::getPathOfAlias('application.vendor.ommu'); $installedModule = $this->getModulesFromDir(); $cacheModule = file(Yii::getPathOfAlias('application.config').'/cache_module.php'); $toBeInstalled = array(); $caches = array(); foreach($cacheModule as $val) { $caches[] = trim($val); } if(!$installedModule) $installedModule = array(); foreach($caches as $cache) { if(!in_array($cache, array_map("trim", $installedModule))) $this->deleteModuleDb($cache); } $moduleDb = $this->cacheModuleConfig(true); foreach($installedModule as $module) { $module = trim($module); if(!in_array($module, array_map("trim", $moduleDb))) { $config = $this->getModuleConfig($module); $moduleFile = join('/', array($moduleVendorPath, $module, ucfirst($module).'Module.php')); if($config && file_exists($moduleFile) && $module == $config['folder_name']) { $model=new OmmuPlugins; $model->folder = $module; $model->name = $config['name']; $model->desc = $config['description']; if($config['model']) $model->model = $config['model']; $model->save(); } } } $this->generateModules(); }
php
{ "resource": "" }
q4464
Formatter.fill
train
public function fill($payload) { $payload = $this->determineTypeAndMessage($payload); $payload = $this->fillBlanks($payload); return $payload; }
php
{ "resource": "" }
q4465
Formatter.fillBlanks
train
public function fillBlanks($payload) { $fields = ['doi', 'url', 'message', 'verbosemessage', 'responsecode', 'app_id']; foreach ($fields as $field) { if (!array_key_exists($field, $payload)) { $payload[$field] = ""; } } return $payload; }
php
{ "resource": "" }
q4466
AttachmentsConfig.setData
train
public function setData(array $data) { if (isset($data['attachables'])) { $this->setAttachables($data['attachables']); } if (isset($data['groups'])) { $this->setGroups($data['groups']); } if (isset($data['widgets'])) { $this->setWidgets($data['widgets']); } unset($data['attachables'], $data['groups'], $data['widgets']); return parent::setData($data); }
php
{ "resource": "" }
q4467
AttachmentsConfig.setAttachables
train
public function setAttachables(array $attachables) { foreach ($attachables as $attType => $attStruct) { if (!is_array($attStruct)) { throw new InvalidArgumentException(sprintf( 'The attachment structure for "%s" must be an array', $attType )); } if (isset($attStruct['attachment_type'])) { $attType = $attStruct['attachment_type']; } else { $attStruct['attachment_type'] = $attType; } if (!is_string($attType)) { throw new InvalidArgumentException( 'The attachment type must be a string' ); } $this->attachables[$attType] = $attStruct; } return $this; }
php
{ "resource": "" }
q4468
AttachmentsConfig.setGroups
train
public function setGroups(array $groups) { foreach ($groups as $groupIdent => $groupStruct) { if (!is_array($groupStruct)) { throw new InvalidArgumentException(sprintf( 'The attachment group "%s" must be an array of attachable objects', $groupIdent )); } if (isset($groupStruct['ident'])) { $groupIdent = $groupStruct['ident']; unset($groupStruct['ident']); } if (!is_string($groupIdent)) { throw new InvalidArgumentException( 'The attachment group identifier must be a string' ); } if (isset($groupStruct['attachable_objects'])) { $groupStruct = $groupStruct['attachable_objects']; } elseif (isset($groupStruct['attachables'])) { $groupStruct = $groupStruct['attachables']; } $this->groups[$groupIdent] = $groupStruct; } return $this; }
php
{ "resource": "" }
q4469
AttachmentsConfig.setWidgets
train
public function setWidgets(array $widgets) { foreach ($widgets as $widgetIdent => $widgetStruct) { if (!is_array($widgetStruct)) { throw new InvalidArgumentException(sprintf( 'The attachment widget "%s" must be an array of widget settings', $widgetIdent )); } if (isset($widgetStruct['ident'])) { $widgetIdent = $widgetStruct['ident']; unset($widgetStruct['ident']); } if (!is_string($widgetIdent)) { throw new InvalidArgumentException( 'The attachment widget identifier must be a string' ); } $this->widgets[$widgetIdent] = $widgetStruct; } return $this; }
php
{ "resource": "" }
q4470
MergePrefix.getPrefixLength
train
protected function getPrefixLength(array $strings) { $len = 1; $cnt = count($strings[0]); while ($len < $cnt && $this->stringsMatch($strings, $len)) { ++$len; } return $len; }
php
{ "resource": "" }
q4471
MergePrefix.getStringsByPrefix
train
protected function getStringsByPrefix(array $strings) { $byPrefix = []; foreach ($strings as $string) { $byPrefix[$string[0]][] = $string; } return $byPrefix; }
php
{ "resource": "" }
q4472
MergePrefix.mergeStrings
train
protected function mergeStrings(array $strings) { $len = $this->getPrefixLength($strings); $newString = array_slice($strings[0], 0, $len); foreach ($strings as $string) { $newString[$len][] = array_slice($string, $len); } return $newString; }
php
{ "resource": "" }
q4473
MergePrefix.stringsMatch
train
protected function stringsMatch(array $strings, $pos) { $value = $strings[0][$pos]; foreach ($strings as $string) { if (!isset($string[$pos]) || $string[$pos] !== $value) { return false; } } return true; }
php
{ "resource": "" }
q4474
PostsAndPagesTables.find
train
public function find($type = 'all', $options = []) { //Gets from cache the timestamp of the next record to be published $next = $this->getNextToBePublished(); //If the cache is invalid, it clears the cache and sets the next record // to be published if ($next && time() >= $next) { Cache::clear(false, $this->getCacheName()); //Sets the next record to be published $this->setNextToBePublished(); } return parent::find($type, $options); }
php
{ "resource": "" }
q4475
NextToBePublishedTrait.setNextToBePublished
train
public function setNextToBePublished() { $next = $this->find() ->where([ sprintf('%s.active', $this->getAlias()) => true, sprintf('%s.created >', $this->getAlias()) => new Time, ]) ->order([sprintf('%s.created', $this->getAlias()) => 'ASC']) ->extract('created') ->first(); $next = empty($next) ? false : $next->toUnixString(); Cache::write('next_to_be_published', $next, $this->getCacheName()); return $next; }
php
{ "resource": "" }
q4476
Types.ensureTypes
train
protected static function ensureTypes() { if (self::$doneScanning && count(self::$types) > 0) { return; } foreach (self::types() as $t) { } }
php
{ "resource": "" }
q4477
UsersGroupsController.add
train
public function add() { $group = $this->UsersGroups->newEntity(); if ($this->request->is('post')) { $group = $this->UsersGroups->patchEntity($group, $this->request->getData()); if ($this->UsersGroups->save($group)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('group')); }
php
{ "resource": "" }
q4478
UsersGroupsController.edit
train
public function edit($id = null) { $group = $this->UsersGroups->get($id); if ($this->request->is(['patch', 'post', 'put'])) { $group = $this->UsersGroups->patchEntity($group, $this->request->getData()); if ($this->UsersGroups->save($group)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('group')); }
php
{ "resource": "" }
q4479
UsersGroupsController.delete
train
public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $group = $this->UsersGroups->get($id); //Before deleting, checks if the group is a necessary group or if the group has some users if ($id > 3 && !$group->user_count) { $this->UsersGroups->deleteOrFail($group); $this->Flash->success(I18N_OPERATION_OK); } else { $this->Flash->alert($id <= 3 ? __d('me_cms', 'You cannot delete this users group') : I18N_BEFORE_DELETE); } return $this->redirect(['action' => 'index']); }
php
{ "resource": "" }
q4480
TicketSettings.getFormData
train
public function getFormData() { $data = Client::perform('get-class-values', ['class' => 'client,ticket_settings']); $this->ticket_emails = $data['ticket_emails']; $this->send_message_text = $data['send_message_text']; $this->new_messages_first = $data['new_messages_first']; }
php
{ "resource": "" }
q4481
OmmuPages.getPages
train
public static function getPages($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->page_id] = $val->name; } return $items; } else return false; } else return $model; }
php
{ "resource": "" }
q4482
OmmuMenus.getParentMenu
train
public static function getParentMenu($publish=null, $parent=null, $type=null) { $criteria=new CDbCriteria; if($publish != null) $criteria->compare('t.publish',$publish); if($parent != null) $criteria->compare('t.parent_id',$parent); $model = self::model()->findAll($criteria); if($type == null) { $items = array(); if($model != null) { foreach($model as $key => $val) { $items[$val->id] = $val->title->message; } return $items; } else { return false; } } else return $model; }
php
{ "resource": "" }
q4483
Io.getResponse
train
public function getResponse($question, $params = array()) { $params = $this->cleanParamsAndPrintPrompt($question, $params); $response = str_replace(array("\n", "\r"), array("", ""), $this->input()); return $this->validateResponse($response, $question, $params); }
php
{ "resource": "" }
q4484
Io.resetOutputLevel
train
public function resetOutputLevel() { if (count($this->outputLevelStack) > 0) { $this->setOutputLevel(reset($this->outputLevelStack)); $this->outputLevelStack = array(); } }
php
{ "resource": "" }
q4485
Io.getStream
train
private function getStream($type) { if (!isset($this->streams[$type])) { $this->streams[$type] = fopen($this->streamUrls[$type], $type == 'input' ? 'r' : 'w'); } return $this->streams[$type]; }
php
{ "resource": "" }
q4486
UserController.ajaxauthenticateAction
train
public function ajaxauthenticateAction() { // $this->getServiceLocator()->get('Zend\Log')->info('ajaxloginAction - // AUTHENT : '); if ($this->zfcUserAuthentication() ->getAuthService() ->hasIdentity()) { return true; } $adapter = $this->zfcUserAuthentication()->getAuthAdapter(); $adapter->prepareForAuthentication($this->getRequest()); $auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter); if (! $auth->isValid()) { $adapter->resetAdapters(); return false; } $user = $this->zfcUserAuthentication()->getIdentity(); if ($user->getState() && $user->getState() === 2) { $this->getUserService()->getUserMapper()->activate($user); } $this->getEventManager()->trigger('login.post', $this, array('user' => $user)); return true; }
php
{ "resource": "" }
q4487
UserController.emailExistsAction
train
public function emailExistsAction() { $email = $this->getEvent()->getRouteMatch()->getParam('email'); $request = $this->getRequest(); $response = $this->getResponse(); $user = $this->getUserService()->getUserMapper()->findByEmail($email); if (empty($user)) { $result = ['result' => false]; } else { $result = ['result' => true]; } $response->setContent(\Zend\Json\Json::encode($result)); return $response; }
php
{ "resource": "" }
q4488
UserController.autoCompleteUserAction
train
public function autoCompleteUserAction() { $field = $this->getEvent()->getRouteMatch()->getParam('field'); $value = $this->getEvent()->getRouteMatch()->getParam('value'); $request = $this->getRequest(); $response = $this->getResponse(); $result = $this->getUserService()->autoCompleteUser($field, $value); $response->setContent(\Zend\Json\Json::encode($result)); return $response; }
php
{ "resource": "" }
q4489
UserController.getPrizeCategoryForm
train
public function getPrizeCategoryForm() { if (! $this->prizeCategoryForm) { $this->setPrizeCategoryForm( $this->getServiceLocator()->get('playgroundgame_prizecategoryuser_form') ); } return $this->prizeCategoryForm; }
php
{ "resource": "" }
q4490
UserController.getBlockAccountForm
train
public function getBlockAccountForm() { if (! $this->blockAccountForm) { $this->setBlockAccountForm( $this->getServiceLocator()->get('playgrounduser_blockaccount_form') ); } return $this->blockAccountForm; }
php
{ "resource": "" }
q4491
UserController.getNewsletterForm
train
public function getNewsletterForm() { if (! $this->newsletterForm) { $this->setNewsletterForm( $this->getServiceLocator()->get('playgrounduser_newsletter_form') ); } return $this->newsletterForm; }
php
{ "resource": "" }
q4492
UserController.getAddressForm
train
public function getAddressForm() { if (! $this->addressForm) { $this->setAddressForm( $this->getServiceLocator()->get('playgrounduser_address_form') ); } return $this->addressForm; }
php
{ "resource": "" }
q4493
UserController.getProviderService
train
public function getProviderService() { if ($this->providerService == null) { $this->setProviderService($this->getServiceLocator()->get('playgrounduser_provider_service')); } return $this->providerService; }
php
{ "resource": "" }
q4494
UserController.getHybridAuth
train
public function getHybridAuth() { if (!$this->hybridAuth) { $this->hybridAuth = $this->getServiceLocator()->get('HybridAuth'); } return $this->hybridAuth; }
php
{ "resource": "" }
q4495
Ommu.getDefaultTheme
train
public function getDefaultTheme($type='public') { $theme = OmmuThemes::model()->find(array( 'select' => 'folder', 'condition' => 'group_page = :group AND default_theme = :default', 'params' => array( ':group' => $type, ':default' => '1', ), )); if($theme !== null) return $theme->folder; else return null; }
php
{ "resource": "" }
q4496
Ommu.getRulePos
train
public static function getRulePos($rules) { $result = 1; $before = array(); $after = array(); foreach($rules as $key => $val) { if($key == '<module:\w+>/<controller:\w+>/<action:\w+>') break; $result++; } $i = 1; foreach($rules as $key => $val) { if($i < $result) $before[$key] = $val; elseif($i >= $pos) $after[$key] = $val; $i++; } return array('after' => $after, 'before' => $before); }
php
{ "resource": "" }
q4497
Serializer.serializeStrings
train
public function serializeStrings(array $strings) { $info = $this->analyzeStrings($strings); $alternations = array_map([$this, 'serializeString'], $info['strings']); if (!empty($info['chars'])) { // Prepend the character class to the list of alternations array_unshift($alternations, $this->serializeCharacterClass($info['chars'])); } $expr = implode('|', $alternations); if ($this->needsParentheses($info)) { $expr = '(?:' . $expr . ')'; } return $expr . $info['quantifier']; }
php
{ "resource": "" }
q4498
Serializer.analyzeStrings
train
protected function analyzeStrings(array $strings) { $info = ['alternationsCount' => 0, 'quantifier' => '']; if ($strings[0] === []) { $info['quantifier'] = '?'; unset($strings[0]); } $chars = $this->getChars($strings); if (count($chars) > 1) { ++$info['alternationsCount']; $info['chars'] = array_values($chars); $strings = array_diff_key($strings, $chars); } $info['strings'] = array_values($strings); $info['alternationsCount'] += count($strings); return $info; }
php
{ "resource": "" }
q4499
Serializer.getChars
train
protected function getChars(array $strings) { $chars = []; foreach ($strings as $k => $string) { if ($this->isChar($string)) { $chars[$k] = $string[0]; } } return $chars; }
php
{ "resource": "" }