/** * Clusterize Transactions * * @param array $transactions array((int)ID => array((int|string)attr1, attr2, ...), ...) * @param array $params array('repulsion' => (float)$number) * * @return array */ public function clusterize($transactions, $params) { $this->ClopeTransaction->createSchema(); $this->ClopeCluster->createSchema(); $this->ClopeAttribute->createSchema(); $this->repulsion = $params['repulsion']; // Add transactions foreach ($transactions as $id => $transaction) { $data = array('ClopeTransaction' => array('custom_id' => $id), 'ClopeAttribute' => Hash::map($transaction, '{n}', function ($attr) { return array('attribute' => $attr); })); $this->ClopeTransaction->saveAssociated($data, array('deep' => true)); } unset($transaction); // Clustering $this->_clusterize(); // Result $groupedByCluster = array(); foreach ($transactions as $id => &$transaction) { $groupedByCluster[$this->ClopeTransaction->clusterID($id)][$id] = $transaction; unset($transactions[$id]); } $this->ClopeTransaction->dropSchema(); $this->ClopeCluster->dropSchema(); $this->ClopeAttribute->dropSchema(); return $groupedByCluster; }
/** * Adds any new plugins on WordPress.org, and queues them up for updates. * * @return int Shell return code. */ function main() { $this->out(__('Fetching list of plugins from SVN repository...')); $repo_url = Configure::read('App.svn_url'); $command = "svn list {$repo_url} | sed 's/\\/\$//'"; $results = shell_exec($command); if (is_null($results)) { $this->_unlock(); $this->error(__('Error'), __('Failed to fetch list of plugins using SVN.')); return 1; } $plugins = explode("\n", $results); $this->out(__('Looking for new plugins that have not been added yet...')); $plugins = array_filter($plugins, function ($value) { return preg_match('/^[-0-9a-z_]+$/i', $value); }); $plugins = array_diff($plugins, $this->Plugin->find('list', array('fields' => array('slug')))); if (empty($plugins)) { $this->out(__('<info>No new plugins to add.</info>')); $this->_unlock(); return 0; } // TODO: Remove once live, or testing repo is in place. $plugins = array_slice($plugins, 0, 1000); $this->out(__('Saving %d new plugins...', count($plugins))); $plugins = Hash::map($plugins, '{n}', array($this, '_newPluginMap')); if ($this->Plugin->saveAll($plugins, array('deep' => true))) { $this->out(__('<info>All new plugins added successfully.</info>')); $this->_unlock(); return 0; } $this->_unlock(); $this->error(__('Database Error'), __('Failed adding %d new plugins to the database.', count($plugins))); return 1; }
/** * список групп, для просмотра в профиле пользователя * * * @param int $userId * @return array */ public function getUserGroupsList($userId) { $data = $this->getUserGroups($userId, -1, 0); $groupIds = Hash::extract($data, '{n}.Group.id'); $this->membersCount = $this->groupMembersCount($groupIds); $this->loadModel('GroupCategory'); $fields = array('GroupCategory.id', 'GroupCategory.name'); $this->groupCategories = $this->GroupCategory->find('list', compact('fields')); $data = Hash::map($data, '{n}', array($this, 'userGroupsCallback')); $results = Hash::extract($data, '{n}.Group'); return $results; }
/** * Test map() * * @return void */ public function testMap() { $data = static::articleData(); $result = Hash::map($data, '{n}.Article.id', array($this, 'mapCallback')); $expected = array(2, 4, 6, 8, 10); $this->assertEquals($expected, $result); }
/** * Save circular notice content * * @param array $data input data * @return bool * @throws InternalErrorException */ public function saveCircularNoticeContent($data) { // 必要なモデル読み込み $this->loadModels(['CircularNoticeContent' => 'CircularNotices.CircularNoticeContent', 'CircularNoticeChoice' => 'CircularNotices.CircularNoticeChoice', 'CircularNoticeTargetUser' => 'CircularNotices.CircularNoticeTargetUser']); $this->begin(); try { $users = array(); if (isset($data['CircularNoticeTargetUser'])) { $users = $data['CircularNoticeTargetUser']; } // ルームに所属する全ユーザが対象の場合、ルームの参加者を取得 if ($data['CircularNoticeContent']['is_room_target']) { $this->loadModels(['RolesRoomsUser' => 'Rooms.RolesRoomsUser']); $rolesRoomsUsers = $this->RolesRoomsUser->getRolesRoomsUsers(array('Room.id' => Current::read('Room.id'))); $targetUsers = Hash::extract($rolesRoomsUsers, '{n}.RolesRoomsUser.user_id'); $users = $targetUsers; // 取得したUserでデータを差し替え $targetUsers = array(); foreach ($users as $userId) { $targetUsers[] = array('CircularNoticeTargetUser' => array('id' => null, 'user_id' => $userId)); } } else { //新着データのユーザIDセット $this->setTopicUsers(Hash::extract($users, '{n}.user_id')); $targetUsers = Hash::map($users, '{n}.user_id', function ($value) { return array('CircularNoticeTargetUser' => array('id' => null, 'user_id' => $value)); }); } $data['CircularNoticeTargetUsers'] = $targetUsers; // データセット+検証 $this->validateCircularNoticeContent($data); if (!$this->CircularNoticeChoice->validateCircularChoices($data)) { $this->validationErrors = Hash::merge($this->validationErrors, $this->CircularNoticeChoice->validationErrors); } if ($this->validationErrors) { return false; } // メール処理 $sendTimes = array($data['CircularNoticeContent']['publish_start']); $this->setSendTimeReminder($sendTimes); $mailSendUserIdArr = Hash::extract($data, 'CircularNoticeTargetUsers.{n}.CircularNoticeTargetUser.user_id'); $this->setSetting(MailQueueBehavior::MAIL_QUEUE_SETTING_USER_IDS, $mailSendUserIdArr); // CircularNoticeContentを保存 if (!($content = $this->save(null, false))) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } // 保存されたCircularNoticeContentでデータを差し替え $data['CircularNoticeContent'] = $content['CircularNoticeContent']; // CircularNoticeChoices・CircularNoticeTargetUsersを保存 if (!$this->__saveChoiceAndTargetUsers($data)) { return false; } $this->commit(); } catch (Exception $ex) { $this->rollback(); CakeLog::error($ex); throw $ex; } return $data; }
/** * Выдает список статей по категории * * @param int $userId * @param int $categoryId * @return array */ public function categoryArticles($userId, $categoryId) { $this->loadModel('Api.ApiArticleEvent'); $fields = array('Article.id', 'Article.title', 'Article.owner_id', 'Article.group_id', 'Article.published', 'Article.created', 'ArticleMedia.*', 'Group.owner_id'); $conditions = array('Article.cat_id' => $categoryId, 'OR' => array(array('Article.published' => 1), array('Article.owner_id' => $userId, 'published' => 0))); $order = array('Article.created DESC'); $limit = 25; //администраторы группы $joins = array(array('table' => 'groups', 'alias' => 'Group', 'type' => 'LEFT', 'conditions' => array('`Group`.id = `Article`.group_id AND `Article`.group_id IS NOT NULL'))); $articles = $this->Article->find('all', compact('conditions', 'fields', 'joins', 'order', 'limit')); $articleIds = Hash::extract($articles, '{n}.Article.id'); $this->commentsCount = $this->ApiArticleEvent->getCommentsCount($articleIds); $result['Articles'] = Hash::map($articles, '{n}', array($this, 'articlesListCallback')); return $result; }
/** * Convert array using given paths into chart array format * * Chart short names: * - c means cell * - v means value * - f means formatted value * * @param array $data * @param array $paths * @return array */ public function dataFromArray(array $data, array $paths) { if (count($paths) === 0 || count($data) === 0) { return array(); } $resultData = array('cols' => array(), 'rows' => array()); $paths2 = array(); foreach ($paths as $pathName => $path) { if (is_numeric($pathName) && !empty($path['names'])) { $names = Hash::extract($data, $path['names']); foreach ($names as $name) { $callback = function ($element) use($name) { return sprintf($element, $name); }; $paths2[$name] = Hash::map($path['values'], '', $callback); } unset($paths[$pathName]); } } $paths += $paths2; $dataRaw = array_combine(array_keys($paths), array_fill(0, count($paths), array())); foreach ($dataRaw as $type => &$one) { if (is_array($paths[$type])) { foreach ($paths[$type] as $variable => $path) { $part = Hash::extract($data, $path); $partCount = count($part); for ($i = 0; $i < $partCount; $i++) { if (!isset($one[$i])) { $one[$i] = array(); } $one[$i][$variable] = $part[$i]; } } } else { $one = Hash::extract($data, $paths[$type]); foreach ($one as &$value) { $value = array('v' => $value, 'f' => (string) $value); } unset($value); } } $headers = array_keys($dataRaw); foreach ($headers as $header) { $value = isset($dataRaw[$header][0]['v']) ? $dataRaw[$header][0]['v'] : (isset($dataRaw[$header][0]) ? $dataRaw[$header][0] : ''); $decodedHeader = json_decode($header, true); if ($decodedHeader) { $col = array('p' => $decodedHeader); } else { $col = array('id' => $header, 'label' => $header); } $resultData['cols'][] = $col + array('type' => gettype($value) !== 'string' ? strlen((string) $value) === 10 ? 'datetime' : 'number' : 'string'); } $dataRawCount = count($dataRaw[$headers[0]]); for ($i = 0; $i < $dataRawCount; $i++) { $resultDataPart = array(); foreach ($headers as $header) { $resultDataPart[] = isset($dataRaw[$header][$i]) ? $dataRaw[$header][$i] : null; } $resultData['rows'][] = array('c' => $resultDataPart); } return $resultData; }
private function updateUserRanking($mw, $tasks) { if (!$this->User) { $this->loadModel('User'); } $valid = $this->Evaluation->EvaluationResult->isValidRating($tasks); // extract a list of all ratings $ratings = Hash::map($tasks, '{n}.answer.0.rating', function ($rating) { // remove description text from rating if (strpos($rating, ' ') !== FALSE) { $rating = substr($rating, 0, strpos($rating, ' ')); } return (int) $rating; }); foreach ($tasks as $i => $task) { $this->User->readFromTaskId($mw, $task['taskid']); // evaluate the current effect on the rating if ($valid) { $current_rating = 1; // user did a good job } else { // check is at least half of the ratings are near this particial one $current = $this->Evaluation->EvaluationResult->getRatingValue($task['rating']); $matching = 0; foreach ($ratings as $rating) { if (abs($rating - $current) <= 1) { $matching++; } } if ($matching < count($rating) / 2) { // this one is a bad one $current_rating = -1; } } // update the evaluations and rating $rating = $this->User->data['User']['rating'] + $current_rating; // after the first saveField data gets reset $this->User->saveField('evaluations', $this->User->data['User']['evaluations'] + 1); $this->User->saveField('rating', $rating); if ($this->User->data['User']['rating'] + $current_rating <= 0) { // bann the user from the system $this->User->saveField('banned', 1); } } }