예제 #1
0
 /**
  * List all broker
  *
  * @return void
  * @author Chaiwut <*****@*****.**>
  * @since 16 July 2015
  */
 public function index()
 {
     //Set default for parmas
     if (!isset($this->params->query['name'])) {
         $this->params->query['name'] = '';
     }
     if (!isset($this->params->query['sort'])) {
         $this->params->query['sort'] = 3;
     }
     //set condition for text filter
     $conditions = array('Broker.name LIKE' => '%' . $this->params->query['name'] . '%');
     $this->Paginator->settings = array('conditions' => $conditions, 'limit' => 20, 'order' => array('Broker.created' => 'DESC'));
     $brokers = $this->Paginate('Broker');
     //Count and keep it in the same array
     foreach ($brokers as $key => $value) {
         $brokers[$key]['Broker']['point_sum'] = count($value['Point']);
         $brokers[$key]['Broker']['comment_sum'] = count($value['Comment']);
     }
     //Sorting array
     //Please see : http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::sort
     if ($this->params->query['sort'] == 1) {
         $brokers = Hash::sort($brokers, '{n}.Broker.point_sum', 'desc');
     } else {
         if ($this->params->query['sort'] == 2) {
             $brokers = Hash::sort($brokers, '{n}.Broker.comment_sum', 'desc');
         }
     }
     $this->set('brokers', $brokers);
     $this->set('title_for_layout', __('โบรกเกอร์ทั้งหมด'));
 }
예제 #2
0
 /**
  * Find all comments related to a specific content
  * @param string $ref Model linked with comments
  * @param int $ref_id ID of the content linked with the comments
  * @todo  Supprimer les commentaires inline : si le code est suffisamment clair cela se lit tout seul, sinon séparer en sous méthodes protected
  **/
 public function findRelated($ref, $ref_id, $options = array())
 {
     // We had the conditions to find linked comments only
     $options['conditions']['ref'] = $ref;
     $options['conditions']['ref_id'] = $ref_id;
     // We need to retrieve User informations
     if (!isset($options['contain']['User'])) {
         $fields = Configure::read('Plugin.Comment.user');
         unset($fields['model']);
         $fields[] = 'id';
         $fields = array_values($fields);
         $options['contain']['User'] = $fields;
     }
     $comments = $this->find('all', $options);
     if (Configure::read('Plugin.Comment.subcomments')) {
         $comments = Hash::combine($comments, '{n}.Comment.id', '{n}', '{n}.Comment.parent_id');
         if (!isset($comments[0])) {
             return array();
         }
         foreach ($comments[0] as $k => $coms) {
             $comments[0][$k]['Answer'] = array();
         }
         foreach ($comments as $parent_id => $coms) {
             if ($parent_id != 0) {
                 $comments[0][$parent_id]['Answer'] = Hash::sort($coms, '{n}.Comment.id', 'ASC');
             }
         }
         return $comments[0];
     } else {
         return $comments;
     }
 }
예제 #3
0
 /** Generate Admin menus added by CroogoNav::add()
  *
  * @param array $menus
  * @param array $options
  * @return string menu html tags
  */
 public function adminMenus($menus, $options = array(), $depth = 0)
 {
     $options = Hash::merge(array('children' => true, 'htmlAttributes' => array('class' => 'nav nav-stacked')), $options);
     $aclPlugin = Configure::read('Site.acl_plugin');
     $userId = AuthComponent::user('id');
     if (empty($userId)) {
         return '';
     }
     $out = null;
     $sorted = Hash::sort($menus, '{s}.weight', 'ASC');
     if (empty($this->Role)) {
         $this->Role = ClassRegistry::init('Users.Role');
         $this->Role->Behaviors->attach('Croogo.Aliasable');
     }
     $currentRole = $this->Role->byId($this->Layout->getRoleId());
     foreach ($sorted as $menu) {
         $htmlAttributes = $options['htmlAttributes'];
         if ($currentRole != 'admin' && !$this->{$aclPlugin}->linkIsAllowedByUserId($userId, $menu['url'])) {
             continue;
         }
         if (empty($menu['htmlAttributes']['class'])) {
             $menuClass = Inflector::slug(strtolower('menu-' . $menu['title']), '-');
             $menu['htmlAttributes'] = Hash::merge(array('class' => $menuClass), $menu['htmlAttributes']);
         }
         $title = '';
         if (empty($menu['icon'])) {
             $menu['htmlAttributes'] += array('icon' => 'white');
         } else {
             $menu['htmlAttributes'] += array('icon' => $menu['icon']);
         }
         $title .= '<span>' . $menu['title'] . '</span>';
         $children = '';
         if (!empty($menu['children'])) {
             $childClass = 'nav nav-stacked sub-nav ';
             $childClass .= ' submenu-' . Inflector::slug(strtolower($menu['title']), '-');
             if ($depth > 0) {
                 $childClass .= ' dropdown-menu';
             }
             $children = $this->adminMenus($menu['children'], array('children' => true, 'htmlAttributes' => array('class' => $childClass)), $depth + 1);
             $menu['htmlAttributes']['class'] .= ' hasChild dropdown-close';
         }
         $menu['htmlAttributes']['class'] .= ' sidebar-item';
         $menuUrl = $this->url($menu['url']);
         if ($menuUrl == env('REQUEST_URI')) {
             if (isset($menu['htmlAttributes']['class'])) {
                 $menu['htmlAttributes']['class'] .= ' current';
             } else {
                 $menu['htmlAttributes']['class'] = 'current';
             }
         }
         $link = $this->Html->link($title, $menu['url'], $menu['htmlAttributes']);
         $liOptions = array();
         if (!empty($children) && $depth > 0) {
             $liOptions['class'] = ' dropdown-submenu';
         }
         $out .= $this->Html->tag('li', $link . $children, $liOptions);
     }
     return $this->Html->tag('ul', $out, $htmlAttributes);
 }
 public function getPrototypes()
 {
     $searchdirs['App'] = APP . 'View';
     $searchdirs['Basic'] = CakePlugin::path('Muffin');
     foreach (CakePlugin::loaded() as $plugin) {
         if ($plugin != 'Muffin') {
             $searchdirs[$plugin] = CakePlugin::path($plugin) . 'View';
         }
     }
     $configs = array();
     foreach ($searchdirs as $plugin => $searchdir) {
         $dir = new Folder($searchdir, false);
         if ($files = $dir->findRecursive('config.xml')) {
             $configs = Hash::merge($configs, array($plugin => $files));
         }
     }
     $prototypes = array();
     foreach ($configs as $plugin => $configFiles) {
         $i = 0;
         foreach ($configFiles as $configFile) {
             $xml = Xml::build($configFile);
             $items = $xml->xpath('menu/item');
             if (!is_array($items) || empty($items)) {
                 continue;
             }
             foreach ($items as $item) {
                 $item = Xml::toArray($item);
                 if (empty($item['item']['@label'])) {
                     continue;
                 }
                 if (!isset($item['item']['@id']) || empty($item['item']['@id'])) {
                     $id = ucfirst(Inflector::variable($item['item']['@label']));
                 } else {
                     $id = $item['item']['@id'];
                 }
                 $fields = array();
                 foreach ($item['item']['field'] as $key => $field) {
                     foreach ($field as $name => $value) {
                         $name = str_replace('@', '', $name);
                         $fields[$key][$name] = $value;
                     }
                 }
                 $prototypes[$plugin][$i]['Link']['id'] = $id;
                 $prototypes[$plugin][$i]['Link']['priority'] = !empty($item['item']['@priority']) ? $item['item']['@priority'] : '10';
                 $prototypes[$plugin][$i]['Link']['model'] = !empty($item['item']['@model']) ? $item['item']['@model'] : '';
                 $prototypes[$plugin][$i]['Link']['label'] = $item['item']['@label'];
                 $prototypes[$plugin][$i]['Field'] = $fields;
                 $i++;
             }
         }
     }
     foreach ($prototypes as $plugin => $section) {
         $prototypes[$plugin] = Hash::sort($section, '{n}.Link.priority', 'asc');
     }
     return $prototypes;
 }
예제 #5
0
 public function get_for_parent($parent, $page)
 {
     $options = array('conditions' => array('Comment.object_id' => $parent), 'limit' => 5, 'page' => $page, 'order' => 'Comment.created DESC', 'contain' => array('Author' => array('fields' => array('id', 'first_name', 'last_name', 'avatar'))));
     $comments = $this->Comment->find('all', $options);
     $comments = Hash::sort($comments, '{n}.Comment.created', 'asc');
     $view = new View($this, false);
     $view->layout = false;
     $view->set('comments', $comments);
     $response['html'] = $view->render('get_for_parent');
     $view = new View($this->controller, false);
     $view->layout = 'ajax';
     $view->set('data', $response);
     $html = $view->render('/Shared/json/data');
     echo $html;
     die;
 }
예제 #6
0
 /**
  * Gets the dashboard markup
  *
  * @return string
  */
 public function dashboards()
 {
     $registered = Configure::read('Dashboards');
     $userId = AuthComponent::user('id');
     if (empty($userId)) {
         return '';
     }
     $columns = array(CroogoDashboard::LEFT => array(), CroogoDashboard::RIGHT => array(), CroogoDashboard::FULL => array());
     if (empty($this->Role)) {
         $this->Role = ClassRegistry::init('Users.Role');
         $this->Role->Behaviors->attach('Croogo.Aliasable');
     }
     $currentRole = $this->Role->byId($this->Layout->getRoleId());
     $cssSetting = $this->Layout->themeSetting('css');
     if (!empty($this->_View->viewVars['boxes_for_dashboard'])) {
         $boxesForLayout = Hash::combine($this->_View->viewVars['boxes_for_dashboard'], '{n}.DashboardsDashboard.alias', '{n}.DashboardsDashboard');
         $dashboards = array();
         $registeredUnsaved = array_diff_key($registered, $boxesForLayout);
         foreach ($boxesForLayout as $alias => $userBox) {
             if (isset($registered[$alias]) && $userBox['status']) {
                 $dashboards[$alias] = array_merge($registered[$alias], $userBox);
             }
         }
         $dashboards = Hash::merge($dashboards, $registeredUnsaved);
         $dashboards = Hash::sort($dashboards, '{s}.weight', 'ASC');
     } else {
         $dashboards = Hash::sort($registered, '{s}.weight', 'ASC');
     }
     foreach ($dashboards as $alias => $dashboard) {
         if ($currentRole != 'admin' && !in_array($currentRole, $dashboard['access'])) {
             continue;
         }
         $opt = array('alias' => $alias, 'dashboard' => $dashboard);
         Croogo::dispatchEvent('Croogo.beforeRenderDashboard', $this->_View, compact('alias', 'dashboard'));
         $dashboardBox = $this->_View->element('Extensions.admin/dashboard', $opt);
         Croogo::dispatchEvent('Croogo.afterRenderDashboard', $this->_View, compact('alias', 'dashboard', 'dashboardBox'));
         if ($dashboard['column'] === false) {
             $dashboard['column'] = count($columns[0]) <= count($columns[1]) ? CroogoDashboard::LEFT : CroogoDashboard::RIGHT;
         }
         $columns[$dashboard['column']][] = $dashboardBox;
     }
     $dashboardTag = $this->settings['dashboardTag'];
     $columnDivs = array(0 => $this->Html->tag($dashboardTag, implode('', $columns[CroogoDashboard::LEFT]), array('class' => $cssSetting['dashboardLeft'] . ' ' . $cssSetting['dashboardClass'], 'id' => 'column-0')), 1 => $this->Html->tag($dashboardTag, implode('', $columns[CroogoDashboard::RIGHT]), array('class' => $cssSetting['dashboardRight'] . ' ' . $cssSetting['dashboardClass'], 'id' => 'column-1')));
     $fullDiv = $this->Html->tag($dashboardTag, implode('', $columns[CroogoDashboard::FULL]), array('class' => $cssSetting['dashboardFull'] . ' ' . $cssSetting['dashboardClass'], 'id' => 'column-2'));
     return $this->Html->tag('div', $fullDiv, array('class' => $cssSetting['row'])) . $this->Html->tag('div', implode('', $columnDivs), array('class' => $cssSetting['row']));
 }
예제 #7
0
 public function subscriptions()
 {
     /*
     //test for members operate after subscription change
     $this->BillingSubscription->Behaviors->load('Billing.Limitable', array(
     	'remoteModel' => 'GroupLimit',
     	'remoteField' => 'members_limit',
     	'scope' => 'owner_id',
     ));
     $this->BillingSubscription->membersOperate(71);
     exit();
     */
     $this->layout = 'profile_new';
     $this->BillingSubscription->recursive = -1;
     $subscriptions = $this->BillingSubscription->find('all', array('conditions' => array('BillingSubscription.user_id' => $this->currUser['User']['id'], 'BillingSubscription.active' => true)));
     //maybe buggy
     foreach ($subscriptions as $key => $subscription) {
         if (isset($subscription['BraintreeSubscription']->status) && $subscription['BraintreeSubscription']->status == 'Canceled') {
             unset($subscriptions[$key]);
             $sameGroupCount = Hash::extract($subscriptions, "{n}.BillingSubscription[group_id=" . $subscription['BillingSubscription']['group_id'] . "]");
             if (count($sameGroupCount) > 0) {
                 $this->BillingSubscription->cancel($subscription['BillingSubscription']['id']);
             }
         } else {
             $this->BillingGroup->recursive = -1;
             $this->BillingGroup->unbindTranslations();
             $subscriptions[$key] = Hash::merge($subscriptions[$key], $this->BillingGroup->find('first', array('conditions' => array('BillingGroup.id' => $subscription['BillingSubscription']['group_id']), 'callbacks' => false)));
             $this->BillingPlan->recursive = -1;
             $this->BillingPlan->unbindTranslations();
             $billingPlans = $this->BillingPlan->find('first', array('conditions' => array('BillingPlan.id' => $subscription['BillingSubscription']['plan_id'])));
             unset($billingPlans['BraintreePlan']);
             $subscriptions[$key] = Hash::merge($subscriptions[$key], $billingPlans);
         }
     }
     $this->BillingPlan->recursive = 0;
     $plans = $this->BillingPlan->find('all');
     foreach ($plans as $plan) {
         $subscribedInGroup = Hash::extract($subscriptions, "{n}.BillingSubscription[group_id=" . $plan['BillingPlan']['group_id'] . "]");
         if ($plan['BillingPlan']['free'] == true && empty($subscribedInGroup)) {
             $subscriptions[] = Hash::merge(array('BillingSubscription' => array('group_id' => $plan['BillingPlan']['group_id'], 'plan_id' => $plan['BillingPlan']['id'], 'user_id' => $this->currUser['User']['id'], 'remote_subscription_id' => null, 'remote_plan_id' => null, 'limit_value' => $plan['BillingPlan']['limit_value'], 'active' => true, 'status' => 'Active', 'expires' => null, 'created' => $this->currUser['User']['created'], 'modified' => $this->currUser['User']['modified'])), $plan);
         }
     }
     $subscriptions = Hash::sort($subscriptions, '{n}.BillingSubscription.group_id', 'asc');
     $transactions = Braintree_Transaction::search([Braintree_TransactionSearch::customerId()->is('konstruktor-' . $this->currUser['User']['id'])]);
     $this->set(compact('subscriptions', 'transactions', 'plans'));
 }
 /**
  * _sorted method
  * to sort a given array by key
  *
  * @param array $obj data array
  * @return array ソート後配列
  */
 protected function _sorted($obj)
 {
     // シーケンス順に並び替え、かつ、インデックス値は0オリジン連番に変更
     // ページ配列もないのでそのまま戻す
     if (!Hash::check($obj, 'RegistrationPage.{n}')) {
         return $obj;
     }
     $obj['RegistrationPage'] = Hash::sort($obj['RegistrationPage'], '{n}.page_sequence', 'asc', 'numeric');
     foreach ($obj['RegistrationPage'] as &$page) {
         if (Hash::check($page, 'RegistrationQuestion.{n}')) {
             $page['RegistrationQuestion'] = Hash::sort($page['RegistrationQuestion'], '{n}.question_sequence', 'asc', 'numeric');
             foreach ($page['RegistrationQuestion'] as &$question) {
                 if (Hash::check($question, 'RegistrationChoice.{n}')) {
                     $question['RegistrationChoice'] = Hash::sort($question['RegistrationChoice'], '{n}.choice_sequence', 'asc', 'numeric');
                 }
             }
         }
     }
     return $obj;
 }
예제 #9
0
 public function afterFind(Model $Model, $results, $primary = false)
 {
     if (!$primary) {
         return parent::afterFind($results, $primary);
     }
     foreach ($results as $key => $val) {
         if ($primary && array_key_exists($Model->alias, $val) && array_key_exists('id', $val[$Model->alias])) {
             $Comment = ClassRegistry::init('Social.Comment');
             // Getting total Comments
             $totalComments = $Comment->find('count', array('conditions' => array('Comment.object_id' => $val[$Model->alias]['id'], 'Comment.object' => $Model->alias)));
             $results[$key]['Commented']['total'] = $totalComments;
         }
         // Reorder the Comments by creation order
         // (even though we got them by descending order)
         if (array_key_exists('Comment', $val) && count($val['Comment'])) {
             $results[$key]['Comment'] = Hash::sort($val['Comment'], '{n}.created', 'asc');
         }
     }
     return $results;
 }
예제 #10
0
 /**
  * タイムゾーンの取得
  *
  * @param Model $model Model ビヘイビア呼び出し元モデル
  * @param string $what タイムゾーン(地域)
  * @param string $country 2文字のISO3166-1互換の国コード
  * @return array タイムゾーン配列
  */
 public function getTimezone(Model $model, $what = null, $country = null)
 {
     $results = array();
     if (isset($country)) {
         $what = DateTimeZone::PER_COUNTRY;
     }
     if (!isset($what)) {
         $what = DateTimeZone::ALL;
     }
     $timezoneIdentifiers = DateTimeZone::listIdentifiers($what, $country);
     foreach ($timezoneIdentifiers as $timezone) {
         $date = new DateTime('now', new DateTimeZone($timezone));
         if ($timezone === 'UTC') {
             $timezoneValue = __d('data_types', '(UTC%s)', '') . ' ';
         } else {
             $timezoneValue = __d('data_types', '(UTC%s)', $date->format('P')) . ' ';
         }
         $results[] = array('key' => $timezone, 'name' => $timezoneValue . __d('data_types', $timezone), 'code' => $timezone, 'language_id' => Current::read('Language.id'), 'sort' => $date->format('Z'));
     }
     $results = Hash::sort($results, '{n}.sort', 'asc');
     return $results;
 }
예제 #11
0
 /**
  * view method
  *
  * @throws NotFoundException
  * @param string $id
  * @return void
  */
 public function view($id = null)
 {
     if (!$this->Question->exists($id)) {
         throw new NotFoundException(__('Invalid question'));
     }
     $options1 = array('conditions' => array('Question.' . $this->Question->primaryKey => $id), 'recursive' => 0);
     $value = $this->Question->find('first', $options1);
     $value['Question']['numVotos'] = $this->Question->VoteQuestion->getVotes($value['Question']['id']);
     if (AuthComponent::user()) {
         $user = $this->Auth->User('id');
         $votoQ = $this->Question->VoteQuestion->find('first', array('conditions' => array('question_id' => $value['Question']['id'], 'user_id' => $user), 'recursive' => -1, 'fields' => array('VoteQuestion.value')));
         if ($votoQ != null) {
             $value['Question']['voted'] = $votoQ['VoteQuestion']['value'];
         }
         $answers = $this->Question->Answer->getAnswersloged($value['Question']['id'], $user);
     } else {
         $answers = $this->Question->Answer->getAnswers($value['Question']['id']);
     }
     $this->set('question', $value);
     $this->set('answersV', Hash::sort($answers, '{n}.Answer.numVotos', 'desc'));
     $this->set('answersR', Hash::sort($answers, '{n}.Answer.date', 'desc'));
 }
예제 #12
0
 protected function formatResponse($response)
 {
     $service_code = array('01' => 'UPS Next Day Air', '02' => 'UPS 2nd Day Air', '03' => 'UPS Ground', '07' => 'UPS Worldwide Express', '08' => 'UPS Worldwide Expedited', '11' => 'UPS Standard', '12' => 'UPS 3 Day Select', '13' => 'UPS Next Day Air Saver', '14' => 'UPS Next Day Air Early A.M.', '54' => 'UPS Worldwide Express Plus', '59' => 'UPS 2nd Day Air A.M.');
     $service_enabled = array('01', '02', '12', '03');
     $results = array();
     $i = 0;
     foreach ($response['RatingServiceSelectionResponse']['RatedShipment'] as $result) {
         $code = $result['Service']['Code'];
         if (in_array($code, $service_enabled)) {
             $results[$i]['ServiceCode'] = $code;
             $results[$i]['ServiceName'] = $service_code[$code];
             $results[$i]['TotalCharges'] = $result['TotalCharges']['MonetaryValue'];
             $i++;
         }
     }
     $results = Hash::sort($results, '{n}.TotalCharges', 'ASC');
     return $results;
 }
예제 #13
0
 /**
  * Used to read records from the Datasource. The "R" in CRUD
  *
  * @param Model $model The model being read.
  * @param array $queryData An array of query data used to find the data you want
  * @return mixed
  */
 public function read(Model $model, $queryData = array(), $recursive = null)
 {
     if (!isset($model->records) || !is_array($model->records) || empty($model->records)) {
         $this->_requestsLog[] = array('query' => 'Model ' . $model->alias, 'error' => __('No records found in model.'), 'affected' => 0, 'numRows' => 0, 'took' => 0);
         return array($model->alias => array());
     }
     $startTime = microtime(true);
     $data = array();
     $i = 0;
     $limit = false;
     if ($recursive === null && isset($queryData['recursive'])) {
         $recursive = $queryData['recursive'];
     }
     if (!is_null($recursive)) {
         $_recursive = $model->recursive;
         $model->recursive = $recursive;
     }
     if (is_integer($queryData['limit']) && $queryData['limit'] > 0) {
         $limit = $queryData['page'] * $queryData['limit'];
     }
     foreach ($model->records as $pos => $record) {
         // Tests whether the record will be chosen
         if (!empty($queryData['conditions'])) {
             $queryData['conditions'] = (array) $queryData['conditions'];
             if (!$this->conditionsFilter($model, $record, $queryData['conditions'])) {
                 continue;
             }
         }
         $data[$i][$model->alias] = $record;
         $i++;
         // Test limit
         if ($limit !== false && $i == $limit && empty($queryData['order'])) {
             break;
         }
     }
     if ($queryData['fields'] === 'COUNT') {
         $this->_registerLog($model, $queryData, microtime(true) - $startTime, 1);
         if ($limit !== false) {
             $data = array_slice($data, ($queryData['page'] - 1) * $queryData['limit'], $queryData['limit'], false);
         }
         return array(array(array('count' => count($data))));
     }
     // Order
     if (!empty($queryData['order'])) {
         if (is_string($queryData['order'][0])) {
             $field = $queryData['order'][0];
             $alias = $model->alias;
             if (strpos($field, '.') !== false) {
                 list($alias, $field) = explode('.', $field, 2);
             }
             if ($alias === $model->alias) {
                 $sort = 'ASC';
                 if (strpos($field, ' ') !== false) {
                     list($field, $sort) = explode(' ', $field, 2);
                 }
                 if ($data) {
                     $data = Hash::sort($data, '{n}.' . $model->alias . '.' . $field, $sort);
                 }
             }
         }
     }
     // Limit
     if ($limit !== false) {
         $data = array_slice($data, ($queryData['page'] - 1) * $queryData['limit'], $queryData['limit'], false);
     }
     // Filter fields
     if (!empty($queryData['fields'])) {
         $listOfFields = array();
         foreach ((array) $queryData['fields'] as $field) {
             if (strpos($field, '.') !== false) {
                 list($alias, $field) = explode('.', $field, 2);
                 if ($alias !== $model->alias) {
                     continue;
                 }
             }
             $listOfFields[] = $field;
         }
         foreach ($data as $id => $record) {
             foreach ($record[$model->alias] as $field => $value) {
                 if (!in_array($field, $listOfFields)) {
                     unset($data[$id][$model->alias][$field]);
                 }
             }
         }
     }
     $this->_registerLog($model, $queryData, microtime(true) - $startTime, count($data));
     $_associations = $model->_associations;
     if ($model->recursive > -1) {
         foreach ($_associations as $type) {
             foreach ($model->{$type} as $assoc => $assocData) {
                 $linkModel = $model->{$assoc};
                 if ($model->useDbConfig == $linkModel->useDbConfig) {
                     $db = $this;
                 } else {
                     $db = ConnectionManager::getDataSource($linkModel->useDbConfig);
                 }
                 if (isset($db)) {
                     if (method_exists($db, 'queryAssociation')) {
                         $stack = array($assoc);
                         $db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $queryData, true, $data, $model->recursive - 1, $stack);
                     }
                     unset($db);
                 }
             }
         }
     }
     if ($model->findQueryType === 'first') {
         if (!isset($data[0])) {
             $data = array();
         } else {
             $data = array($data[0]);
         }
     }
     if (!is_null($recursive)) {
         $model->recursive = $_recursive;
     }
     return $data;
 }
예제 #14
0
 /**
  * testSyncWithSessionData
  *
  * @return void
  */
 public function testMergeItems()
 {
     $itemsBefore = $this->Cart->CartsItem->find('all', array('contain' => array(), 'conditions' => array('cart_id' => 'cart-1')));
     $itemCount = count($itemsBefore);
     $sessionData = array('Cart' => array(), 'CartsItem' => array(array('name' => 'CakePHP', 'model' => 'Item', 'foreign_key' => 'item-2', 'quantity' => 1, 'price' => 999.1), array('model' => 'Item', 'foreign_key' => 'item-1', 'quantity' => 2, 'price' => 12)));
     $result = $this->Cart->mergeItems('cart-1', $sessionData['CartsItem']);
     $this->assertEquals($result, 1);
     $itemsAfter = $this->Cart->CartsItem->find('all', array('contain' => array(), 'conditions' => array('cart_id' => 'cart-1')));
     // Sort the items by name so that we can be sure an item is at a certain index in the array
     $itemsAfter = Hash::sort($itemsAfter, '{n}.CartsItem.name', 'desc');
     $this->assertEquals(count($itemsAfter), $itemCount + 1);
     $this->assertEquals($itemsAfter[0]['CartsItem']['name'], 'Eizo Flexscan S2431W');
     $this->assertEquals($itemsAfter[0]['CartsItem']['quantity'], 2);
 }
예제 #15
0
 /**
  * プラグインの一覧を表示する
  *
  * @return void
  * @access public
  */
 public function admin_index()
 {
     $this->Plugin->cacheQueries = false;
     $datas = $this->Plugin->find('all', array('order' => 'Plugin.priority'));
     if (!$datas) {
         $datas = array();
     }
     // プラグインフォルダーのチェックを行う。
     $pluginInfos = array();
     $paths = App::path('Plugin');
     foreach ($paths as $path) {
         $Folder = new Folder($path);
         $files = $Folder->read(true, true, true);
         foreach ($files[0] as $file) {
             $pluginInfos[basename($file)] = $this->_getPluginInfo($datas, $file);
         }
     }
     $pluginInfos = array_values($pluginInfos);
     // Hash::sortの為、一旦キーを初期化
     $pluginInfos = array_reverse($pluginInfos);
     // Hash::sortの為、逆順に変更
     $availables = $unavailables = array();
     foreach ($pluginInfos as $pluginInfo) {
         if (isset($pluginInfo['Plugin']['priority'])) {
             $availables[] = $pluginInfo;
         } else {
             $unavailables[] = $pluginInfo;
         }
     }
     //並び替えモードの場合はDBにデータが登録されていないプラグインを表示しない
     if (!empty($this->passedArgs['sortmode'])) {
         $sortmode = true;
         $pluginInfos = Hash::sort($availables, '{n}.Plugin.priority', 'asc', 'numeric');
     } else {
         $sortmode = false;
         $pluginInfos = array_merge(Hash::sort($availables, '{n}.Plugin.priority', 'asc', 'numeric'), $unavailables);
     }
     // 表示設定
     $this->set('datas', $pluginInfos);
     $this->set('corePlugins', Configure::read('BcApp.corePlugins'));
     $this->set('sortmode', $sortmode);
     if ($this->request->is('ajax')) {
         $this->render('ajax_index');
     }
     $this->subMenuElements = array('plugins');
     $this->pageTitle = 'プラグイン一覧';
     $this->help = 'plugins_index';
 }
 protected function _sortItems(&$model, $items, $order)
 {
     if (empty($order) || empty($order[0])) {
         return $items;
     }
     foreach ($order as $orderItem) {
         if (is_string($orderItem)) {
             $orderItem = array($orderItem => 'asc');
         }
         foreach ($orderItem as $field => $direction) {
             $items = Hash::sort($items, '{n}.' . $field, $direction, $type = 'natural');
         }
     }
     return $items;
 }
예제 #17
0
파일: Question.php 프로젝트: hectorn/Soru
 /**
  * Metodo que devolve as 10 preguntas mais votadas
  */
 public function featured()
 {
     $data = $this->find('all', array('recursive' => 0, 'fields' => array('Question.title', 'Question.id')));
     $i = array();
     foreach ($data as $aux) {
         $aux['Question']['numVotos'] = $this->VoteQuestion->getVotes($aux['Question']['id']);
         array_push($i, $aux);
     }
     unset($aux);
     $data = Hash::sort($i, '{n}.Question.numVotos', 'desc');
     array_slice($data, 0, 10);
     return $data;
 }
예제 #18
0
 /**
  * view method
  *
  * @throws NotFoundException
  * @param string $id
  * @return void
  */
 public function view($id = null)
 {
     if (!$this->Artist->exists($id)) {
         throw new NotFoundException(__('Invalid artist'));
     }
     $options = array('conditions' => array('Artist.' . $this->Artist->primaryKey => $id), 'contain' => array('Tag', 'Link' => array('LinkType')));
     $artist = $this->Artist->find('first', $options);
     // Clean up the links : reordering them by Link Type Title
     $artist['Link'] = Hash::sort($artist['Link'], '{n}.LinkType.title', 'asc');
     $this->set('artist', $artist);
     //$events = $this->Artist->Event->find('list');
     $this->set('page_title', __('Artistes'));
     $this->set('can_edit_artist', $this->actionIsAllowedForLoggedInUser('can_edit_artist'));
     $this->set('artistHasContactInformation', $this->Artist->hasContactInformation($id));
     // Handling the breadcrumb
     $this->breadcrumb[__('Artistes')] = Router::url('/') . 'artists';
     $this->breadcrumb[$artist['Artist']['title']] = '#';
 }
예제 #19
0
파일: GpzApi.php 프로젝트: Mirocow/gpz
 private function processPrices($table, $sort, $order, $lFullInfo)
 {
     $table = Hash::sort($table, '{n}.' . $sort, $order);
     if ($sort == 'price2') {
         return $table;
     }
     // вторичная сортировка - по цене
     $_table = array();
     foreach ($table as $row) {
         $_table[$row[$sort]][] = $row;
     }
     foreach ($_table as $k => $rows) {
         $_table[$k] = Hash::sort($rows, '{n}.price2', 'asc');
     }
     $table = array();
     foreach ($_table as $rows) {
         foreach ($rows as $row) {
             $table[] = $row;
         }
     }
     return $table;
 }
 /**
  * 複数選択登録作成
  *
  * @param string $index 登録データのPOST用dataのインデックス値
  * @param string $fieldName フィールド名
  * @param array $question 項目データ
  * @param bool $readonly 読み取り専用
  * @return string 複数選択肢登録のHTML
  */
 public function multipleChoice($index, $fieldName, $question, $readonly)
 {
     $ret = '';
     $otherAnswerFieldName = 'RegistrationAnswer.' . $index . '.0.other_answer_value';
     if (isset($question['RegistrationChoice'])) {
         $afterLabel = '';
         $choices = Hash::sort($question['RegistrationChoice'], '{n}.other_choice_type', 'asc');
         $options = $this->_getChoiceOptionElement($choices);
         $otherChoice = Hash::extract($question['RegistrationChoice'], '{n}[other_choice_type!=' . RegistrationsComponent::OTHER_CHOICE_TYPE_NO_OTHER_FILED . ']');
         if ($otherChoice) {
             $otherInput = $this->NetCommonsForm->input($otherAnswerFieldName, array('type' => 'text', 'label' => false, 'div' => false, 'disabled' => $readonly, 'error' => false));
             $afterLabel = '<div class="checkbox-inline">' . $otherInput . '</div>';
         }
         $checkboxClass = 'checkbox';
         if ($question['is_choice_horizon'] == RegistrationsComponent::USES_USE) {
             $checkboxClass = 'checkbox-inline';
         }
         $ret .= $this->NetCommonsForm->input($fieldName, array('type' => 'select', 'multiple' => 'checkbox', 'options' => $options, 'label' => false, 'div' => false, 'class' => $checkboxClass . ' nc-checkbox', 'disabled' => $readonly, 'hiddenField' => !$readonly, 'error' => false));
         $ret .= $afterLabel;
     }
     return $ret;
 }
예제 #21
0
 public function getPrivileges($netId, $type = null, $writeOnly = false)
 {
     if (empty($type) || !in_array($type, $this->hierarchy)) {
         return array();
     }
     $personId = $this->Person->getPersonIdByNetId($netId);
     if (empty($personId)) {
         return array();
     }
     //regardless of $type, we need the highest-level permissions to calculate inherited permissions
     $conditions = array('DeptPriv.person_id' => $personId);
     if ($writeOnly) {
         $conditions['DeptPriv.priv_level LIKE'] = '%W%';
     }
     $explicitDepts = $this->DeptPriv->find('all', array('fields' => array('DeptPriv.priv_level', 'Department.id', 'Department.dept_name AS name', 'Department.dept_type'), 'conditions' => $conditions));
     $depts = array();
     foreach ($explicitDepts as $dept) {
         $depts = $this->_addDeptPriv($depts, $dept, $dept['DeptPriv']['priv_level']);
         $inheritedDepts = $this->DeptPriv->query("SELECT Department.id, Department.dept_name AS name, Department.dept_type\n\t\t\t\tFROM {$this->DeptPriv->Department->schemaName}.{$this->DeptPriv->Department->table} Department\n\t\t\t\tSTART WITH id = {$dept['Department']['id']}\n\t\t\t\tCONNECT BY PRIOR id = parent_department");
         foreach ($inheritedDepts as $subDept) {
             $depts = $this->_addDeptPriv($depts, $subDept, $dept['DeptPriv']['priv_level']);
         }
     }
     if (!empty($type) && in_array($type, array_slice($this->hierarchy, 0, 3))) {
         $results = empty($depts[$type]) ? array() : $this->_addDeptPeople($depts, $type);
         return Hash::sort($results, "{n}.name", 'asc');
     }
     //---- If we get this far, then we also need Teaching Areas
     $teachingAreas = array();
     $conditions = array('TeachingAreaPriv.person_id' => $personId);
     if ($writeOnly) {
         $conditions['TeachingAreaPriv.priv_level LIKE'] = '%W%';
     }
     $explicitAreas = $this->TeachingAreaPriv->find('all', array('fields' => array('TeachingAreaPriv.teaching_area', 'TeachingAreaPriv.priv_level'), 'conditions' => $conditions));
     foreach ($explicitAreas as $area) {
         $teachingAreas = $this->_addTeachingAreaPriv($teachingAreas, $area['TeachingAreaPriv']['teaching_area'], $area['TeachingAreaPriv']['priv_level']);
     }
     if (!empty($depts)) {
         $rawDepts = Hash::combine($depts, '{s}.{n}.id', '{s}.{n}');
         $inheritedAreas = $this->DeptTeachArea->find('all', array('recursive' => -1, 'conditions' => array('DeptTeachArea.department_id' => array_keys($rawDepts))));
         foreach ($inheritedAreas as $area) {
             $teachingAreas = $this->_addTeachingAreaPriv($teachingAreas, $area['DeptTeachArea']['teaching_area'], $rawDepts[$area['DeptTeachArea']['department_id']]);
         }
     }
     if ($type == 'Teaching Area') {
         $teachingAreas = $this->_addTeachingAreaPeople($teachingAreas);
         return array_values(Hash::sort($teachingAreas, '{s}.name', 'asc'));
     }
     //----- If we get this far, then we also need Courses
     $conditions = array('CoursePriv.person_id' => $personId);
     if ($writeOnly) {
         $conditions['CoursePriv.priv_level LIKE'] = '%W%';
     }
     $explicitCourses = $this->CoursePriv->find('all', array('fields' => array('CoursePriv.teaching_area', 'CoursePriv.catalog_number', 'CoursePriv.priv_level'), 'conditions' => $conditions));
     $courses = array();
     foreach ($explicitCourses as $course) {
         $courses = $this->_addCoursePriv($courses, $course['CoursePriv'], $course['CoursePriv']['priv_level']);
     }
     if (!empty($teachingAreas)) {
         $inheritedCourses = $this->CourseSectionOracle->find('all', array('fields' => array('DISTINCT CourseSection.teaching_area', 'CourseSection.catalog_number'), 'conditions' => array('CourseSection.teaching_area' => array_keys($teachingAreas))));
         foreach ($inheritedCourses as $course) {
             $courses = $this->_addCoursePriv($courses, $course['CourseSection'], $teachingAreas[$course['CourseSection']['teaching_area']]);
         }
     }
     if ($type == 'Course') {
         $courses = $this->_addCoursePeople($courses);
         return array_values(Hash::sort($courses, '{s}.name', 'asc'));
     }
     $depts['Teaching Area'] = array_values(Hash::sort($teachingAreas, '{s}.name', 'asc'));
     $depts['Courses'] = array_values(Hash::sort($courses, '{s}.name', 'asc'));
     return $depts;
 }
 /**
  * カレントフォルダのファイル・フォルダリストを返す
  *
  * @param int $currentTreeId 現在のCabinetFileTree.id
  * @return array CabinetFileの一覧
  */
 protected function _getCurrentFolderFiles($currentTreeId)
 {
     // カレントフォルダのファイル・フォルダリストを得る。
     $conditions = ['parent_id' => $currentTreeId, 'cabinet_id' => $this->viewVars['cabinet']['Cabinet']['id']];
     //  workflowコンディションを混ぜ込む
     $conditions = $this->CabinetFile->getWorkflowConditions($conditions);
     // ソート順変更
     list($sort, $direction) = $this->_getSortParams();
     // ソート順変更リンクをPaginatorHelperで出力するときに必要な値をセットしておく。
     $this->request->params['paging'] = ['CabinetFile' => ['options' => ['sort' => $sort, 'direction' => $direction], 'paramType' => 'named']];
     // 昇順のときフォルダが先、降順の時フォルダが後
     $folderDirection = $direction === 'asc' ? 'desc' : 'asc';
     $order = ['is_folder' => $folderDirection];
     if ($sort != 'size') {
         $order['CabinetFile.' . $sort] = $direction;
     }
     $results = $this->CabinetFile->find('all', ['conditions' => $conditions, 'order' => $order]);
     $folders = array();
     $files = array();
     foreach ($results as &$file) {
         if ($file['CabinetFile']['is_folder']) {
             $file['CabinetFile']['size'] = $this->CabinetFile->getTotalSizeByFolder($file);
             $file['CabinetFile']['has_children'] = $this->CabinetFile->hasChildren($file);
             $folders[] = $file;
         } else {
             $file['CabinetFile']['size'] = $file['UploadFile']['file']['size'];
             $files[] = $file;
         }
     }
     if ($sort == 'size') {
         // sizeでのソートは自前でおこなう@
         $files = Hash::sort($files, '{n}.CabinetFile.size', $direction, 'numeric');
         // フォルダ・ファイルは別れるようにする。
         $folders = Hash::sort($folders, '{n}.CabinetFile.size', $direction, 'numeric');
     }
     if ($direction == 'asc') {
         // ascならフォルダ先 Hash::mergeだと上書きされてしまうのであえてarray_merge使用
         $files = array_merge($folders, $files);
     } else {
         $files = array_merge($files, $folders);
     }
     return $files;
 }
예제 #23
0
 /**
  * Constructor. Binds the model's database table to the object.
  *
  * @param bool|int|string|array $id Set this ID for this model on startup,
  * can also be an array of options, see above.
  * @param string $table Name of database table to use.
  * @param string $ds DataSource connection name.
  * @see Model::__construct()
  * @SuppressWarnings(PHPMD.BooleanArgumentFlag)
  */
 public function __construct($id = false, $table = null, $ds = null)
 {
     parent::__construct($id, $table, $ds);
     $pluginDir = APP . 'Plugin' . DS . $this->plugin . DS . WEBROOT_DIR . DS . 'img' . DS;
     //カテゴリ間の区切り線
     $dir = new Folder($pluginDir . 'line');
     $files = $dir->find('.*\\..*');
     $files = Hash::sort($files, '{n}', 'asc');
     self::$categorySeparators = array(array('key' => null, 'name' => __d('links', '(no line)'), 'style' => null), array('key' => self::CATEGORY_SEPARATOR_DEFAULT, 'name' => '', 'style' => ''));
     foreach ($files as $file) {
         $info = getimagesize($dir->pwd() . DS . $file);
         $img = '/' . Inflector::underscore($this->plugin) . DS . 'img' . DS . 'line' . DS . $file;
         self::$categorySeparators[] = array('key' => $file, 'name' => '', 'style' => 'background-image: url(' . $img . '); ' . 'border-image: url(' . $img . '); ' . 'height: ' . $info[1] . 'px;');
     }
     unset($dir);
     //線スタイル
     $dir = new Folder($pluginDir . 'mark');
     $files = $dir->find('.*\\..*');
     $files = Hash::sort($files, '{n}', 'asc');
     self::$listStyles = array(array('key' => null, 'name' => '', 'style' => 'list-style-type: ' . self::LINE_STYLE_NONE . ';'), array('key' => self::LINE_STYLE_DISC, 'name' => '', 'style' => 'list-style-type: ' . self::LINE_STYLE_DISC . ';'), array('key' => self::LINE_STYLE_CIRCLE, 'name' => '', 'style' => 'list-style-type: ' . self::LINE_STYLE_CIRCLE . ';'), array('key' => self::LINE_STYLE_LOWER_ALPHA, 'name' => '', 'style' => 'list-style-type: ' . self::LINE_STYLE_LOWER_ALPHA . ';'), array('key' => self::LINE_STYLE_UPPER_ALPHA, 'name' => '', 'style' => 'list-style-type: ' . self::LINE_STYLE_UPPER_ALPHA . ';'));
     foreach ($files as $file) {
         $info = getimagesize($dir->pwd() . DS . $file);
         $img = '/' . Inflector::underscore($this->plugin) . DS . 'img' . DS . 'mark' . DS . $file;
         self::$listStyles[] = array('key' => $file, 'name' => '', 'style' => 'list-style-type: none; ' . 'list-style-image: url(' . $img . '); ');
     }
     unset($dir);
 }
예제 #24
0
 /**
  * test regular sorting ignoring case.
  *
  * @return void
  */
 public function testSortRegularIgnoreCase()
 {
     $toSort = array(array('Item' => array('name' => 'bar')), array('Item' => array('name' => 'Baby')), array('Item' => array('name' => 'Baz')), array('Item' => array('name' => 'bat')));
     $sorted = Hash::sort($toSort, '{n}.Item.name', 'asc', array('type' => 'regular', 'ignoreCase' => true));
     $expected = array(array('Item' => array('name' => 'Baby')), array('Item' => array('name' => 'bar')), array('Item' => array('name' => 'bat')), array('Item' => array('name' => 'Baz')));
     $this->assertEquals($expected, $sorted);
 }
예제 #25
0
 /**
  * test sorting with string keys.
  *
  * @return void
  */
 public function testSortString()
 {
     $toSort = array('four' => array('number' => 4, 'some' => 'foursome'), 'six' => array('number' => 6, 'some' => 'sixsome'), 'five' => array('number' => 5, 'some' => 'fivesome'), 'two' => array('number' => 2, 'some' => 'twosome'), 'three' => array('number' => 3, 'some' => 'threesome'));
     $sorted = Hash::sort($toSort, '{s}.number', 'asc');
     $expected = array('two' => array('number' => 2, 'some' => 'twosome'), 'three' => array('number' => 3, 'some' => 'threesome'), 'four' => array('number' => 4, 'some' => 'foursome'), 'five' => array('number' => 5, 'some' => 'fivesome'), 'six' => array('number' => 6, 'some' => 'sixsome'));
     $this->assertEquals($expected, $sorted);
     $menus = array('blogs' => array('title' => 'Blogs', 'weight' => 3), 'comments' => array('title' => 'Comments', 'weight' => 2), 'users' => array('title' => 'Users', 'weight' => 1));
     $expected = array('users' => array('title' => 'Users', 'weight' => 1), 'comments' => array('title' => 'Comments', 'weight' => 2), 'blogs' => array('title' => 'Blogs', 'weight' => 3));
     $result = Hash::sort($menus, '{s}.weight', 'ASC');
     $this->assertEquals($expected, $result);
 }
예제 #26
0
파일: AutoxpApi.php 프로젝트: Mirocow/gpz
 private function _getModelsInfo($html)
 {
     $response = array();
     if ($table = $html->find('table', 3)) {
         foreach ($table->find('tr') as $i => $tr) {
             if (!($i % 2)) {
                 continue;
             }
             $motor = explode('/', trim($tr->find('td', 1)->plaintext));
             $aYear = array();
             $j = 3;
             while ($td = $tr->find('td', $j)) {
                 if (($year = trim($td->plaintext)) && $year != '&nbsp') {
                     $aYear[] = $year;
                 }
                 $j++;
             }
             $date_from = '';
             $date_to = '';
             if ($aYear) {
                 $date_from = $aYear[0];
                 $date_to = array_pop($aYear);
             }
             $a = $tr->find('td', 0)->find('a', 0);
             list($spam, $hash) = explode("','", $a);
             $response[] = array('hash' => $hash, 'model' => $a->plaintext, 'volume' => trim($motor[0]), 'kw' => trim($motor[1]), 'hp' => trim($motor[2]), 'date_issue' => $date_from . ' - ' . $date_to, 'kpp' => trim($tr->find('td', 2)->plaintext));
         }
     }
     if ($response) {
         $response = Hash::sort($response, '{n}.model', 'asc');
     }
     return $response;
 }
 /**
  * testMixedCreateUpdateWithArrayLocale method
  *
  * @return void
  */
 public function testMixedCreateUpdateWithArrayLocale()
 {
     $this->loadFixtures('Translate', 'TranslatedItem');
     $TestModel = new TranslatedItem();
     $TestModel->locale = array('cze', 'deu');
     $data = array('TranslatedItem' => array('id' => 1, 'title' => array('eng' => 'Updated Title #1', 'spa' => 'Nuevo leyenda #1'), 'content' => 'Upraveny obsah #1'));
     $TestModel->create();
     $TestModel->save($data);
     $TestModel->unbindTranslation();
     $translations = array('title' => 'Title', 'content' => 'Content');
     $TestModel->bindTranslation($translations, false);
     $result = $TestModel->read(null, 1);
     $result['Title'] = Hash::sort($result['Title'], '{n}.id', 'asc');
     $result['Content'] = Hash::sort($result['Content'], '{n}.id', 'asc');
     $expected = array('TranslatedItem' => array('id' => 1, 'slug' => 'first_translated', 'locale' => 'cze', 'title' => 'Titulek #1', 'content' => 'Upraveny obsah #1', 'translated_article_id' => 1), 'Title' => array(array('id' => 1, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Updated Title #1'), array('id' => 3, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titel #1'), array('id' => 5, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titulek #1'), array('id' => 19, 'locale' => 'spa', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Nuevo leyenda #1')), 'Content' => array(array('id' => 2, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Content #1'), array('id' => 4, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Inhalt #1'), array('id' => 6, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Upraveny obsah #1')));
     $this->assertEquals($expected, $result);
 }
예제 #28
0
파일: Member.php 프로젝트: JodiWarren/hms
 /**
  * Get a list of account and member details that is suitable for populating a drop-down box
  * 
  * @return null List of values on success, null on failure.
  */
 public function getReadableAccountList()
 {
     $memberList = $this->find('all', array('fields' => array('Member.member_id', 'Member.firstname', 'Member.surname', 'Member.account_id'), 'order' => array('Member.account_id ASC'), 'conditions' => array('Member.account_id !=' => null)));
     // Group the member list by the account id
     $groupedMemberList = Hash::combine($memberList, '{n}.Member.member_id', '{n}.Member', '{n}.Member.account_id');
     $accountList = array();
     foreach ($groupedMemberList as $accountId => $members) {
         $memberNames = array();
         foreach (Hash::sort($members, '{n}.surname', 'asc') as $id => $data) {
             $fullName = sprintf('%s %s', $data['firstname'], $data['surname']);
             array_push($memberNames, $fullName);
         }
         $accountList[$accountId] = String::toList($memberNames);
     }
     $accountList['-1'] = 'Create new';
     ksort($accountList);
     return $accountList;
 }
 /**
  * testSaveAllHasMany method
  *
  * @return void
  */
 public function testSaveAllHasMany()
 {
     $this->loadFixtures('Article', 'Comment');
     $TestModel = new Article();
     $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC');
     $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array();
     $result = $TestModel->saveAll(array('Article' => array('id' => 2), 'Comment' => array(array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1), array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2))));
     $this->assertFalse(empty($result));
     $result = $TestModel->findById(2);
     $expected = array('First Comment for Second Article', 'Second Comment for Second Article', 'First new comment', 'Second new comment');
     $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment');
     $this->assertEquals($expected, $result);
     $result = $TestModel->saveAll(array('Article' => array('id' => 2), 'Comment' => array(array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 1))), array('atomic' => false));
     $this->assertFalse(empty($result));
     $result = $TestModel->findById(2);
     $expected = array('First Comment for Second Article', 'Second Comment for Second Article', 'First new comment', 'Second new comment', 'Third new comment');
     $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment');
     $this->assertEquals($expected, $result);
     $TestModel->beforeSaveReturn = false;
     $result = $TestModel->saveAll(array('Article' => array('id' => 2), 'Comment' => array(array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 1))), array('atomic' => false));
     $this->assertEquals(array('Article' => false), $result);
     $result = $TestModel->findById(2);
     $expected = array('First Comment for Second Article', 'Second Comment for Second Article', 'First new comment', 'Second new comment', 'Third new comment');
     $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment');
     $this->assertEquals($expected, $result);
 }
예제 #30
0
 /**
  * For admin use only
  * Get all controllers and generates menu
  *
  * @return array
  */
 private function getAdminMenu($role)
 {
     $controllers = $this->getControllersByRole($role);
     // Exclude following controllers
     $exclude = array('App', 'Home', 'Services');
     $menu_defaults = array('active' => false, 'items' => array());
     $menu = array(__d('admin', 'Dashboard') => $menu_defaults, __d('admin', 'Paintings') => $menu_defaults, __d('admin', 'Pages') => $menu_defaults, __d('admin', 'Administrative') => $menu_defaults, __d('admin', 'Other') => $menu_defaults);
     foreach ($controllers as $controller) {
         $controller = preg_replace('/controller/i', '', $controller);
         // Skip if controller is excluded
         if (in_array($controller, $exclude)) {
             continue;
         }
         $active = $this->name == $controller ? true : false;
         $menu_item = array('name' => preg_replace('/([a-z])([A-Z])/', '$1 $2', $controller), 'icon' => '', 'url' => Inflector::underscore($controller), 'active' => $active, 'priority' => 0);
         // Place items in right menu
         switch (true) {
             case preg_match('/admin/i', $controller):
                 $category = __d('admin', 'Dashboard');
                 break;
             case preg_match('/page/i', $controller):
                 $category = __d('admin', 'Pages');
                 break;
             case preg_match('/project|collection/i', $controller):
                 $category = __d('admin', 'Paintings');
                 break;
             case preg_match('/user|group/i', $controller):
                 $category = __d('admin', 'Administrative');
                 break;
             default:
                 $category = __d('admin', 'Other');
         }
         // Order menu items
         switch (true) {
             case preg_match('/^(Collections)$/', $controller):
                 $menu_item['priority'] = 9;
                 break;
             case preg_match('/^(Projects)$/', $controller):
                 $menu_item['priority'] = 11;
                 break;
             case preg_match('/^(Pages)$/', $controller):
                 $menu_item['priority'] = 6;
                 break;
             case preg_match('/^(Users)$/', $controller):
                 $menu_item['priority'] = 3;
                 break;
             case preg_match('/^(Groups)$/', $controller):
                 $menu_item['priority'] = 2;
                 break;
         }
         $menu[$category]['items'][] = $menu_item;
         if ($active && !$menu[$category]['active']) {
             $menu[$category]['active'] = true;
         }
     }
     // Remove unused menu tabs
     foreach ($menu as $k => $tab) {
         if (empty($tab['items'])) {
             unset($menu[$k]);
         } else {
             $menu[$k]['items'] = Hash::sort($menu[$k]['items'], '{n}.priority', 'desc');
             $menu[$k]['items'] = Hash::sort($menu[$k]['items'], '{n}.priority', 'desc');
         }
     }
     return $menu;
 }