/** * Index method * * @return \Cake\Network\Response|null */ public function index() { // Get all tag IDs associated with members $tags = $this->Tags->find('all')->find('forMembers')->select(['id', 'parent_id'])->toArray(); $memberTagIds = Hash::extract($tags, '{n}.id'); // Get all of those tags' parent IDs $tagParentIds = Hash::extract($tags, '{n}.parent_id'); // Collect all parent tags that lead from member tags to the tag tree root $tagIds = $memberTagIds; while (!empty($tagParentIds)) { // Search for unrecognized parents $parentsToFind = []; foreach ($tagParentIds as $tagId) { if (!in_array($tagId, $tagIds)) { $parentsToFind[] = $tagId; } } if (empty($parentsToFind)) { break; } // Add these parent tag IDs to the full list $additionalTags = $this->Tags->find('all')->where([function ($exp, $q) use($parentsToFind) { return $exp->in('id', $parentsToFind); }])->select(['id', 'parent_id'])->order(['Tags.name' => 'ASC'])->toArray(); $tagIds = array_merge(Hash::extract($additionalTags, '{n}.id'), $tagIds); // Set up next round of searching for parents $tagParentIds = Hash::extract($additionalTags, '{n}.parent_id'); } $tags = $this->Tags->find('all')->find('threaded')->where([function ($exp, $q) use($tagIds) { return $exp->in('id', $tagIds); }])->select(['id', 'name', 'slug', 'parent_id'])->order(['Tags.name' => 'ASC'])->all(); $this->set(['pageTitle' => 'Art Tags', 'tags' => $tags, 'memberTagIds' => $memberTagIds]); }
/** * Check if current user has allow given acoName or not * @param $acoName * @return bool */ public function hasAllow($acoName) { if ($this->user('id')) { $userAllowed = $this->Acl->checkUserAllow($this->user('id'), $acoName); return !is_null($userAllowed) ? $userAllowed : $this->Acl->checkRoleAllow(Hash::extract($this->user('roles'), '{n}.id'), $acoName); } return false; }
public function getErrorMessages() { if (!$this->hasErrors()) { return false; } $messages = Hash::extract($this->errors(), '{s}.{s}'); return $messages; }
/** * Normalizes roles. * * It will return the single role for single role setup, and a flat * list of roles for multi role setup. * * @param string|array Roles as simple or complex (Role.id) array. * @return array Roles */ public static function roles($roles) { if (!is_array($roles)) { return (array) $roles; } if (isset($roles[0]['id'])) { $roles = Hash::extract($roles, '{n}.id'); } return $roles; }
/** * Retrieve the installed version of a Composer package by parsing composer.lock. * * @param string $path Full path to the directory holding the composer.lock file. * @param string $package Name of the package to get the version for. * @return mixed String containing value or false when key lookup fails */ public static function getComposerLockVersion($path, $package) { if (!file_exists("{$path}/composer.lock")) { return false; } // escape / in package name to not break Xpath query $package = str_replace('/', '\\/', $package); $json = json_decode(file_get_contents("{$path}/composer.lock"), true); return implode(Hash::extract($json, "packages.{n}[name=/{$package}/].version")); }
public function onUserLoginSuccessfully(Event $event) { $user =& $event->data['user']; $user['roles'] = []; $UsersRoles = TableRegistry::get('AclManager.UsersRoles'); $roles = $UsersRoles->find()->where(['user_id' => $user['id']])->contain(['Roles'])->toArray(); if (!empty($roles)) { $user['roles'] = Hash::extract($roles, '{n}.role'); } }
public function getThumbnail($url, $config = []) { if (empty($this->_getUrlInfo())) { $this->fetchUrlInfo($url, $config); } $thumbnail = Hash::extract($this->_getUrlInfo(), '{s}.thumbnail_url'); if (empty($thumbnail)) { return false; } return $thumbnail[0]; }
/** * @param $query * @return array */ private function getConditions($query) { $result = []; if (!empty($query['spec'])) { $uIDtmp = $this->UsersSpecializations->find('all', ['fields' => ['user_id'], 'conditions' => ['specialization_id' => $this->request->query['spec']]])->toArray(); if (!empty($uIDtmp)) { $result['Users.id IN'] = Hash::extract($uIDtmp, '{n}.user_id'); } } return $result; }
protected function getSettingPrototype($path, $plugin = null) { $defaults = ['title' => null, 'description' => null, 'cell' => null, 'default' => null, 'options' => null, 'hidden' => false]; //TODO: maybe implement cache for reader results or remember results in table class in future $settingsReader = new PhpConfig(); $input = 'settings'; if (!empty($plugin)) { $input = $plugin . '.settings'; } $settingPrototypes = $settingsReader->read($input); if ($setting = Hash::extract($settingPrototypes, '{n}[path=' . $path . ']')[0]) { return array_merge($defaults, $setting); } return []; }
public function unsentRiskEmails($eventId) { //Make sure event exists, and grab existing Requests at the same time $event = $this->Events->get($eventId, ['contain' => ['EventApprovalRequests']]); $riskManagers = TableRegistry::get('Users')->roleEmails('risk'); $previouslySentEmails = Hash::extract($event->event_approval_requests, '{n}.email'); $toSend = []; foreach ($riskManagers as $email => $name) { if (is_numeric($email)) { $email = $name; } if (in_array($email, $previouslySentEmails)) { continue; } $toSend[] = $email; } return $toSend; }
public function index() { $articlesRes = $this->Articles->find('all')->where(['Articles.article_status_id' => ARTICLE_STATUS_ACTIVE, 'Articles.article_type_id !=' => ARTICLE_TYPE_SYSTEM])->toArray(); $articles = array(); foreach ($articlesRes as $key => $article) { if (is_object($article)) { $articlesRes[$key] = $article->toArray(); } $articles[$articlesRes[$key]['id']] = $articlesRes[$key]; } $intro = $this->Articles->find('all', ['fields' => ['body'], 'conditions' => ['SystemPages.article_id = Articles.id', 'SystemPages.name' => 'intro'], 'contain' => ['SystemPages']])->first(); $featured = Hash::extract($articles, '{n}[article_type_id=2]'); array_splice($featured, 3); $this->loadComponent('Util'); $articles = $this->Util->arrayDiff($articles, $featured); $belowFooter = 'googlemap'; //TODO: make this into a more global and elegant construct $this->set(compact('articles', 'featured', 'intro', 'belowFooter')); }
/** * Loads the featured image (if any) * * @return void */ public function getFeaturedImage(Event $event, Entity $entity) { $featuredImage = Hash::extract($entity->meta, '{n}[key=featured_image]'); if (empty($featuredImage)) { return; } $featuredImage = end($featuredImage); $entity->featured_image_meta_id = $featuredImage->id; $entity->featured_image_id = $featuredImage->value; try { $entity->featured_image = TableRegistry::get('Croogo/FileManager.Attachments')->get($entity->featured_image_id); } catch (RecordNotFoundException $e) { //Image does not exist unset($entity->featured_image_id); } $entity->meta = collection($entity->meta)->reject(function ($item) { return $item->key === 'featured_image'; })->toList(); }
/** * @param $options (match_fields, paginate) * @return \Cake\ORM\Query|bool */ public function search(array $options) { $index = isset($options['index']) ? $options['index'] : $this->config('defaultIndex'); $sphinx = SphinxQL::create($this->conn)->select('id')->from($index)->match(empty($options['match_fields']) ? "*" : $options['match_fields'], $options['term'])->limit(empty($options['limit']) ? 1000 : $options['limit']); $result = $sphinx->execute()->fetchAllAssoc(); if (!empty($result)) { $ids = Hash::extract($result, '{n}.id'); $query = $this->_table->find(); if (!empty($options['paginate']['fields'])) { $query->select($options['paginate']['fields']); } if (!empty($options['paginate']['contain'])) { $query->contain($options['paginate']['contain']); } $query->where([$this->_table->alias() . '.' . $this->_table->primaryKey() . ' IN' => $ids]); return $query; } return false; }
/** * Index page. * * @return void */ public function home() { $this->loadModel('Users'); $this->loadModel('PremiumTransactions'); $usersCount = Number::format($this->Users->find()->where(['end_subscription >' => new Time()])->count()); $premiumTransactions = $this->PremiumTransactions->find()->select(['price'])->hydrate(false)->toArray(); $amountTotal = array_sum(Hash::extract($premiumTransactions, '{n}.price')); $registeredDiscounts = $this->PremiumTransactions->find()->where(function ($exp) { return $exp->isNotNull('premium_discount_id'); })->count(); $discounts = $this->PremiumTransactions->find()->contain(['PremiumDiscounts', 'PremiumOffers'])->where(function ($exp) { return $exp->isNotNull('premium_discount_id'); })->toArray(); $discountAmountTotal = []; foreach ($discounts as $discount) { array_push($discountAmountTotal, $discount->discount); } $discountAmountTotal = array_sum($discountAmountTotal); $this->set(compact('usersCount', 'amountTotal', 'registeredDiscounts', 'discountAmountTotal')); }
/** * View method * * @param string|null $id Gpio id. * @return void * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function view($id = 1) { $gpio = $this->Gpios->newEntity(); $pins = $gpio->readall(); if ($this->request->is('post')) { $data = $this->request->data; //debug($data); if (!isset($data['v'])) { $data['v'] = $pins[$data['physical']]['v']; } if ($data['mode'] === '0') { $data['mode'] = GPIO_MODE_IN; } //debug($data); exit; if ($data['mode'] != $pins[$data['physical']]['mode']) { $result = $gpio->setMode($data['wpi'], $data['mode']); if ($result['RC'] == 0) { $this->Flash->success(__('Pin mode was changed.')); } else { $this->Flash->error(__('Pin mode could not be changed.')); } } else { if ($data['v'] != $pins[$data['physical']]['v']) { $result = $gpio->setValue($data['wpi'], $data['v']); if ($result['RC'] == 0) { $this->Flash->success(__('Pin was changed.')); } else { $this->Flash->error(__('Pin could not be changed.')); } } else { $this->Flash->set(__('No change was made.')); } } return $this->redirect(['action' => 'view', $data['physical']]); } $rowTop = Hash::extract($pins, '{n}[row=1]'); $rowBottom = Hash::extract($pins, '{n}[row=0]'); $this->set('pins', $pins); $this->set('rows', [$rowTop, $rowBottom]); $this->set('activePin', $id); }
/** * Sends reminder emails to users who have already been invited nad have not yet responded * * @param int $surveyId Survey ID * @param array $sender User who is sending the email * @return bool */ public function sendReminders($surveyId, $sender) { $surveysTable = TableRegistry::get('Surveys'); $survey = $surveysTable->get($surveyId); $communitiesTable = TableRegistry::get('Communities'); $clients = $communitiesTable->getClients($survey->community_id); $email = new Email('survey_invitation'); $email->to(Configure::read('noreply_email')); if ($sender['email']) { $email->replyTo($sender['email'], $sender['name']); } $respondentsTable = TableRegistry::get('Respondents'); $recipients = $respondentsTable->getUnresponsive($surveyId); $recipients = Hash::extract($recipients, '{n}.email'); foreach ($recipients as $recipient) { $email->addBcc($recipient); } $email->viewVars(['clients' => $clients, 'criUrl' => Router::url('/', true), 'surveyType' => $survey->type, 'surveyUrl' => $survey->sm_url]); if ($email->send()) { $survey->reminder_sent = date('Y-m-d H:i:s'); return $surveysTable->save($survey); } return false; }
/** * Get a list of relevant models to contain using Containable * * If the user haven't configured any relations for an action * we assume all relations will be used. * * The user can chose to suppress specific relations using the blacklist * functionality. * * @param array $relations List of relations. * @return array */ protected function _getRelatedModels($relations = []) { $models = $this->_action()->config('scaffold.relations'); if (empty($models)) { $associations = $this->_associations(); if (empty($relations)) { $relations = array_keys($associations); } $models = []; foreach ($relations as $relation) { $models = Hash::merge($models, (array) Hash::extract($associations, "{$relation}.{s}.model")); } } $models = Hash::normalize($models); $blacklist = $this->_action()->config('scaffold.relations_blacklist'); if (!empty($blacklist)) { $blacklist = Hash::normalize($blacklist); $models = array_diff_key($models, $blacklist); } foreach ($models as $key => $value) { if (!is_array($value)) { $models[$key] = []; } } return $models; }
/** * Get all available values for this enum. * * @return array */ public static function getValues() { return Hash::extract(self::getConstants(), '{s}.value'); }
/** * Returns the primary key columns name for a given table * * @param string $table Name of the table ot retrieve primary key for * @return array */ public function primaryKeysColumnsList($table) { $primaryKeys = $this->primaryKeys($table); $primaryKeysColumns = Hash::extract($primaryKeys, '{n}.name'); sort($primaryKeysColumns); return $primaryKeysColumns; }
/** * Get all permissions paths (Plugin.Controller.action) for a specific $groupId. * * @param string $groupId The group id. * @return array of permission paths */ public function getAllPermissionPathsForGroup($groupId) { $groupPermissions = $this->find('all')->select('path')->where(['group_id' => $groupId])->hydrate(false)->toArray(); return Hash::extract($groupPermissions, '{n}.path'); }
/** * Render the body of the email. * * @param array $content Content to render * @return array Email body ready to be sent */ protected function _render($content) { $this->_textMessage = $this->_htmlMessage = ''; $content = implode("\n", $content); $rendered = $this->_renderTemplates($content); $this->_createBoundary(); $msg = array(); $contentIds = array_filter((array) Hash::extract($this->_attachments, '{s}.contentId')); $hasInlineAttachments = count($contentIds) > 0; $hasAttachments = !empty($this->_attachments); $hasMultipleTypes = count($rendered) > 1; $multiPart = $hasAttachments || $hasMultipleTypes; $boundary = $relBoundary = $textBoundary = $this->_boundary; if ($hasInlineAttachments) { $msg[] = '--' . $boundary; $msg[] = 'Content-Type: multipart/related; boundary="rel-' . $boundary . '"'; $msg[] = ''; $relBoundary = $textBoundary = 'rel-' . $boundary; } if ($hasMultipleTypes && $hasAttachments) { $msg[] = '--' . $relBoundary; $msg[] = 'Content-Type: multipart/alternative; boundary="alt-' . $boundary . '"'; $msg[] = ''; $textBoundary = 'alt-' . $boundary; } if (isset($rendered['text'])) { if ($multiPart) { $msg[] = '--' . $textBoundary; $msg[] = 'Content-Type: text/plain; charset=' . $this->_getContentTypeCharset(); $msg[] = 'Content-Transfer-Encoding: ' . $this->_getContentTransferEncoding(); $msg[] = ''; } $this->_textMessage = $rendered['text']; $content = explode("\n", $this->_textMessage); $msg = array_merge($msg, $content); $msg[] = ''; } if (isset($rendered['html'])) { if ($multiPart) { $msg[] = '--' . $textBoundary; $msg[] = 'Content-Type: text/html; charset=' . $this->_getContentTypeCharset(); $msg[] = 'Content-Transfer-Encoding: ' . $this->_getContentTransferEncoding(); $msg[] = ''; } $this->_htmlMessage = $rendered['html']; $content = explode("\n", $this->_htmlMessage); $msg = array_merge($msg, $content); $msg[] = ''; } if ($textBoundary !== $relBoundary) { $msg[] = '--' . $textBoundary . '--'; $msg[] = ''; } if ($hasInlineAttachments) { $attachments = $this->_attachInlineFiles($relBoundary); $msg = array_merge($msg, $attachments); $msg[] = ''; $msg[] = '--' . $relBoundary . '--'; $msg[] = ''; } if ($hasAttachments) { $attachments = $this->_attachFiles($boundary); $msg = array_merge($msg, $attachments); } if ($hasAttachments || $hasMultipleTypes) { $msg[] = ''; $msg[] = '--' . $boundary . '--'; $msg[] = ''; } return $msg; }
/** * Unselects the rows that exceed the limit * * @param int $count The number of currently selected elements * @param array $conditions ORM conditions to be used * @param string $field name of the field to be configured * @param array $config config array for the specified field * @return void */ public function unselect($count, $conditions, $field, $config) { $trimmedRows = $this->_table->find()->select([$this->_table->primaryKey()])->where($conditions)->order($config['order'])->limit($count - $config['limit'] + 1)->hydrate(false); $ids = Hash::extract($trimmedRows->toArray(), '{n}.' . $this->_table->primaryKey()); $this->_table->query()->update()->set([$field => !$config['state']])->where([$this->_table->primaryKey() . ' IN' => $ids])->execute(); }
/** * Get the role(s) of the current session. * * It will return the single role for single role setup, and a flat * list of roles for multi role setup. * * @return mixed String or array of roles or null if inexistent. */ public function roles() { $roles = $this->user(USER_ROLE_KEY); if (!is_array($roles)) { return $roles; } if (isset($roles[0]['id'])) { $roles = Hash::extract($roles, '{n}.id'); } return $roles; }
/** * Read check constraints starting with "cakephp_validate_" for the current * table. * * @return array */ protected function constraints() { $schema = Hash::get($this->_table->connection()->config(), 'schema') ?: 'public'; $conditions = ["pg_namespace.nspname = '{$schema}'", "pg_class.relname = '{$this->_table->table()}'", "pg_constraint.consrc ~ '^cakephp_validate_'"]; return Hash::extract($this->_table->connection()->driver()->constraints($conditions), '{n}.source'); }
/** * Get admin stats * * @return array */ public function stats() { $keys = []; $keys['unused_valid'] = $this->find('count', ['conditions' => [$this->alias() . '.used' => 0, $this->alias() . '.created >=' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]); $keys['used_valid'] = $this->find('count', ['conditions' => [$this->alias() . '.used' => 1, $this->alias() . '.created >=' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]); $keys['unused_invalid'] = $this->find('count', ['conditions' => [$this->alias() . '.used' => 0, $this->alias() . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]); $keys['used_invalid'] = $this->find('count', ['conditions' => [$this->alias() . '.used' => 1, $this->alias() . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]); $types = $this->find('all', ['conditions' => [], 'fields' => ['DISTINCT type']]); $keys['types'] = !empty($types) ? Hash::extract('{n}.type', $types) : []; return $keys; }
/** * Returns all current (not overridden by more recent) * approved responses for the selected survey. * * @param int $surveyId Survey ID * @return \Cake\ORM\Query */ public function getCurrent($surveyId) { $surveysTable = TableRegistry::get('Surveys'); $sectorFields = $surveysTable->getSectorFieldNames(); $respondentsTable = TableRegistry::get('Respondents'); $respondents = $respondentsTable->find('all')->select(['id'])->where(['survey_id' => $surveyId, 'approved' => 1])->toArray(); $respondentIds = Hash::extract($respondents, '{n}.id'); if (empty($respondentIds)) { return []; } $responses = $this->find('all')->where(['survey_id' => $surveyId, function ($exp, $q) use($respondentIds) { return $exp->in('respondent_id', $respondentIds); }])->order(['response_date' => 'DESC']); $retval = []; foreach ($responses as $response) { $rId = $response->respondent_id; if (isset($retval[$rId])) { if ($retval[$rId]['response_date'] < $response->response_date) { $retval[$rId] = $response; } } else { $retval[$rId] = $response; } } return $retval; }
/** * Return all the unique types * * @return array Types */ public function getTypes() { $types = $this->find()->select(['type'])->distinct('type')->order('type ASC')->toArray(); return Hash::extract($types, '{n}.type'); }
{ public function up() { <?php foreach ($tables as $table) { $foreignKeys = []; $primaryKeysColumns = $this->Migration->primaryKeysColumnsList($table); $primaryKeys = $this->Migration->primaryKeys($table); $specialPk = count($primaryKeys) > 1 || $primaryKeys[0]['name'] !== 'id' || $primaryKeys[0]['info']['columnType'] !== 'integer'; if ($specialPk) { ?> $table = $this->table('<?php echo $table; ?> ', ['id' => false, 'primary_key' => ['<?php echo implode("', '", \Cake\Utility\Hash::extract($primaryKeys, '{n}.name')); ?> ']]); <?php } else { ?> $table = $this->table('<?php echo $table; ?> '); <?php } ?> $table <?php if ($specialPk) {
/** * Test that uneven keys are handled correctly. * * @return void */ public function testExtractUnevenKeys() { $data = ['Level1' => ['Level2' => ['test1', 'test2'], 'Level2bis' => ['test3', 'test4']]]; $this->assertEquals(['test1', 'test2'], Hash::extract($data, 'Level1.Level2')); $this->assertEquals(['test3', 'test4'], Hash::extract($data, 'Level1.Level2bis')); $data = new ArrayObject(['Level1' => new ArrayObject(['Level2' => ['test1', 'test2'], 'Level2bis' => ['test3', 'test4']])]); $this->assertEquals(['test1', 'test2'], Hash::extract($data, 'Level1.Level2')); $this->assertEquals(['test3', 'test4'], Hash::extract($data, 'Level1.Level2bis')); $data = ['Level1' => ['Level2bis' => [['test3', 'test4'], ['test5', 'test6']]]]; $expected = [['test3', 'test4'], ['test5', 'test6']]; $this->assertEquals($expected, Hash::extract($data, 'Level1.Level2bis')); $data['Level1']['Level2'] = ['test1', 'test2']; $this->assertEquals($expected, Hash::extract($data, 'Level1.Level2bis')); $data = new ArrayObject(['Level1' => new ArrayObject(['Level2bis' => [['test3', 'test4'], ['test5', 'test6']]])]); $this->assertEquals($expected, Hash::extract($data, 'Level1.Level2bis')); $data['Level1']['Level2'] = ['test1', 'test2']; $this->assertEquals($expected, Hash::extract($data, 'Level1.Level2bis')); }
use Spider\Lib\Spider; use Cake\Core\Plugin; //(new EventManager())->dispatch('Spider.bootstrap.start'); // //if (!Configure::check('Spider.installed')) { // return Plugin::load('Install', ['bootstrap' => true, 'routes' => true, 'autoload' => true]); //} /** * List of core plugins */ $corePlugins = ['Spider/Settings', 'Spider/AclManager', 'Spider/PluginManager', 'Spider/Users', 'Spider/Search']; Configure::write('Core.corePlugins', $corePlugins); if (!Configure::check('Hook.plugins')) { Configure::write('Hook.plugins', Configure::read('Core.corePlugins')); } $plugins = Spider::mergeConfig('Hook.plugins', \Cake\Utility\Hash::extract(SpiderPlugin::getPlugins(), '{n}.name')); //Configure::read('App.paths.plugins'); foreach ($plugins as $plugin) { $pluginName = Inflector::camelize($plugin); $pluginPath = APP . 'plugins' . DS . $pluginName; if (!file_exists($pluginPath) && strpos($pluginName, 'Spider/') === false) { $pluginFound = false; foreach (App::path('Plugin') as $path) { if (is_dir($path . $pluginName)) { $pluginFound = true; break; } } if (!$pluginFound) { Log::error('Plugin not found during bootstrap: ' . $pluginName); continue;