/** * Returns all the modules and the access for one roleId. * * Returns a list of all the modules with: * <pre> * - id => id of the module. * - name => Name of the module. * - label => Display for the module. * - none => True or false for none access. * - read => True or false for read access. * - write => True or false for write access. * - access => True or false for access access. * - create => True or false for create access. * - copy => True or false for copy access. * - delete => True or false for delete access. * - download => True or false for download access. * - admin => True or false for admin access. * </pre> * * OPTIONAL request parameters: * <pre> * - integer <b>id</b> The role id for consult. * </pre> * * The return is in JSON format. * * @return void */ public function jsonGetModulesAccessAction() { $role = Phprojekt_Loader::getLibraryClass('Phprojekt_Role_RoleModulePermissions'); $roleId = (int) $this->getRequest()->getParam('id', null); $modules = $role->getRoleModulePermissionsById($roleId); Phprojekt_Converter_Json::echoConvert($modules); }
/** * Save the settings for the timecard * * @param array $params $_POST values * * @return void */ public function setSettings($params) { $namespace = new Zend_Session_Namespace(Phprojekt_Setting::IDENTIFIER . Phprojekt_Auth::getUserId()); $fields = $this->getFieldDefinition(Phprojekt_ModelInformation_Default::ORDERING_FORM); foreach ($fields as $data) { foreach ($params as $key => $value) { if ($key == $data['key']) { $setting = Phprojekt_Loader::getLibraryClass('Phprojekt_Setting'); $setting->setModule('Timecard'); if ($key == 'favorites') { $value = serialize($value); } $where = sprintf('user_id = %d AND key_value = %s AND module_id = %d', (int) Phprojekt_Auth::getUserId(), $setting->_db->quote($key), (int) Phprojekt_Module::getId('Timecard')); $record = $setting->fetchAll($where); if (isset($record[0])) { $record[0]->keyValue = $key; $record[0]->value = $value; $record[0]->save(); } else { $setting->userId = Phprojekt_Auth::getUserId(); $setting->moduleId = Phprojekt_Module::getId('Timecard'); $setting->keyValue = $key; $setting->value = $value; $setting->identifier = 'Timecard'; $setting->save(); } $namespace->{$key} = $value; break; } } } }
/** * Save the configurations into the table. * * @param array $params Array with values to save. * * @return void */ public function setConfigurations($params) { $fields = $this->getFieldDefinition(Phprojekt_ModelInformation_Default::ORDERING_FORM); $configuration = Phprojekt_Loader::getLibraryClass('Phprojekt_Configuration'); $configuration->setModule('General'); foreach ($fields as $data) { foreach ($params as $key => $value) { if ($key == $data['key']) { if ($key == 'companyName') { // Update Root node $project = Phprojekt_Loader::getModel('Project', 'Project'); $project->find(1); $project->title = $value; $project->parentSave(); } $where = sprintf('key_value = %s AND module_id = 0', $configuration->_db->quote($key)); $record = $configuration->fetchAll($where); if (isset($record[0])) { $record[0]->keyValue = $key; $record[0]->value = $value; $record[0]->save(); } else { $configuration->moduleId = 0; $configuration->keyValue = $key; $configuration->value = $value; $configuration->save(); } break; } } } }
/** * Returns the recipients for this Helpdesk item. * * @return array Array with user IDs. */ public function getTo() { $userId = Phprojekt_Auth::getUserId(); // Gets only the recipients with at least a 'read' right. $recipients = parent::getTo(); // Assigned user if (isset($this->_model->assigned) && $this->_model->assigned != $userId) { $recipients[] = $this->_model->assigned; } // Author user if (isset($this->_model->author) && $this->_model->author != $userId) { $recipients[] = $this->_model->author; } // Owner user if (isset($this->_model->ownerId) && $this->_model->ownerId != $userId) { $recipients[] = $this->_model->ownerId; } // If the item has been reassigned, add the previous assigned user to the recipients $history = Phprojekt_Loader::getLibraryClass('Phprojekt_History'); $olUser = $history->getLastAssignedUser($this->_model, 'assigned'); if ($olUser > 0) { $recipients[] = $olUser; } // Return without duplicates return array_unique($recipients); }
/** * Get all the values for the current project and sub-projects and return 3 array: * 1. With Projects names. * 2. With users names. * 3. Relations Projects-User-Bookings. * * @param string $startDate Start date for make the query. * @param string $endDate End date for make the query. * @param integer $projectId Current Project ID. * * @return array Array with 'users', 'projects' and 'rows'. */ public function getStatistics($startDate, $endDate, $projectId) { $data['data'] = array(); $data['data']['users'] = array(); $data['data']['projects'] = array(); $data['data']['rows'] = array(); // Get Sub-Projects $activeRecord = Phprojekt_Loader::getModel('Project', 'Project'); $tree = new Phprojekt_Tree_Node_Database($activeRecord, $projectId); $tree = $tree->setup(); $projectsId = array(0); foreach ($tree as $node) { if ($node->id) { $projectsId[] = (int) $node->id; $data['data']['projects'][$node->id] = $node->getDepthDisplay('title'); } } // Get Timecard $model = Phprojekt_Loader::getModel('Timecard', 'Timecard'); $where = sprintf('(DATE(start_datetime) >= %s AND DATE(start_datetime) <= %s AND project_id IN (%s))', $model->_db->quote($startDate), $model->_db->quote($endDate), implode(", ", $projectsId)); $records = $model->fetchAll($where); $users = Phprojekt_Loader::getLibraryClass('Phprojekt_User_User'); foreach ($records as $record) { if (!isset($data['data']['users'][$record->ownerId])) { $user = $users->findUserById($record->ownerId); $data['data']['users'][$record->ownerId] = $user->username; } if (!isset($data['data']['rows'][$record->projectId][$record->ownerId])) { $data['data']['rows'][$record->projectId][$record->ownerId] = 0; } $data['data']['rows'][$record->projectId][$record->ownerId] += $record->minutes; } return $data; }
/** * Search for words. * * Returns a list of items that have the word, sorted by module with: * <pre> * - id => id of the item found. * - moduleId => id of the module. * - moduleName => Name of the module. * - moduleLabel => Display for the module. * - firstDisplay => Firts display for the item (Ej. title). * - secondDisplay => Second display for the item (Ej. notes). * - projectId => Parent project id of the item. * </pre> * * REQUIRES request parameters: * <pre> * - string <b>words</b> An string of words (Will be separated by the spaces). * </pre> * * OPTIONAL request parameters: * <pre> * - integer <b>count</b> Number of results. * </pre> * * The return is in JSON format. * * @return void */ public function jsonSearchAction() { $words = (string) $this->getRequest()->getParam('words'); $count = (int) $this->getRequest()->getParam('count', null); $offset = (int) $this->getRequest()->getParam('start', null); $search = Phprojekt_Loader::getLibraryClass('Phprojekt_Search'); $results = $search->search($words, $count); Phprojekt_Converter_Json::echoConvert($results); }
/** * Return all the modules in an array and the access if exists. * * @param integer $roleId The role ID. * * @return array Array with 'id', 'name', 'label' and the access. */ public function getRoleModulePermissionsById($roleId) { $modules = array(); $model = Phprojekt_Loader::getLibraryClass('Phprojekt_Module_Module'); foreach ($model->fetchAll('(save_type = 0 OR save_type = 2)', 'name ASC') as $module) { $modules['data'][$module->id] = array(); $modules['data'][$module->id]['id'] = $module->id; $modules['data'][$module->id]['name'] = $module->name; $modules['data'][$module->id]['label'] = Phprojekt::getInstance()->translate($module->label, null, $module->name); $modules['data'][$module->id] = array_merge($modules['data'][$module->id], Phprojekt_Acl::convertBitmaskToArray(0)); } $where = 'role_module_permissions.role_id = ' . (int) $roleId; foreach ($this->fetchAll($where) as $right) { if (isset($modules['data'][$right->moduleId])) { $modules['data'][$right->moduleId] = array_merge($modules['data'][$right->moduleId], Phprojekt_Acl::convertBitmaskToArray($right->access)); } } return $modules; }
/** * Return all the modules in an array and the permission if exists. * * @param integer $projectId The Project ID. * * @return array Array with 'id', 'name', 'label' and 'inProject'. */ function getProjectModulePermissionsById($projectId) { $modules = array(); $model = Phprojekt_Loader::getLibraryClass('Phprojekt_Module_Module'); foreach ($model->fetchAll('active = 1 AND (save_type = 0 OR save_type = 2)', 'name ASC') as $module) { $modules['data'][$module->id] = array(); $modules['data'][$module->id]['id'] = (int) $module->id; $modules['data'][$module->id]['name'] = $module->name; $modules['data'][$module->id]['label'] = Phprojekt::getInstance()->translate($module->label, null, $module->name); $modules['data'][$module->id]['inProject'] = false; } $where = sprintf('project_module_permissions.project_id = %d AND module.active = 1', (int) $projectId); $select = ' module.id AS module_id '; $join = ' RIGHT JOIN module ON ( module.id = project_module_permissions.module_id '; $join .= ' AND (module.save_type = 0 OR module.save_type = 2) )'; foreach ($this->fetchAll($where, 'module.name ASC', null, null, $select, $join) as $right) { $modules['data'][$right->moduleId]['inProject'] = true; } return $modules; }
/** * Helper to create an array of users. * * @param string $idList Comma-separated list of user ids. * @param string $idListNN Optional additional lists of comma-separated user ids. * * @return array Array with 'id' and 'display' */ public static function expandIdList($idList = '') { if (1 < ($num = func_num_args())) { for ($i = 1; $i < $num; $i++) { $addList = (string) func_get_arg($i); if ("" != $addList) { $idList .= ',' . $addList; } } } $data = array(); if (!empty($idList)) { $user = Phprojekt_Loader::getLibraryClass('Phprojekt_User_User'); $display = $user->getDisplay(); $userList = $user->fetchAll(sprintf('id IN (%s)', $idList), $display); foreach ($userList as $record) { $data[] = array('id' => (int) $record->id, 'display' => $record->applyDisplay($display, $record)); } } return $data; }
/** * Returns the list of actions done in one item. * * REQUIRES request parameters: * <pre> * - integer <b>moduleId</b> id of the module (if moduleName is sent, this is not necessary). * - integer <b>itemId</b> id of the item. * </pre> * * OPTIONAL request parameters: * <pre> * - integer <b>userId</b> To filter by user id. * - string <b>moduleName</b> Name of the module (if moduleId is sent, this is not necessary). * - date <b>startDate</b> To filter by start date. * - date <b>endDate</b> To filter by end date. * </pre> * * The return is in JSON format. * * @throws Phprojekt_PublishedException On missing or wrong moduleId or itemId. * * @return void */ public function jsonListAction() { $moduleId = (int) $this->getRequest()->getParam('moduleId', null); $itemId = (int) $this->getRequest()->getParam('itemId', null); $userId = (int) $this->getRequest()->getParam('userId', null); $moduleName = Cleaner::sanitize('alnum', $this->getRequest()->getParam('moduleName', 'Default')); $startDate = Cleaner::sanitize('date', $this->getRequest()->getParam('startDate', null)); $endDate = Cleaner::sanitize('date', $this->getRequest()->getParam('endDate', null)); $this->setCurrentProjectId(); if (empty($moduleId)) { $moduleId = Phprojekt_Module::getId($moduleName); } if (empty($itemId) || empty($moduleId)) { throw new Phprojekt_PublishedException("Invalid module or item"); } else { $history = Phprojekt_Loader::getLibraryClass('Phprojekt_History'); $data = $history->getHistoryData(null, $itemId, $moduleId, $startDate, $endDate, $userId); $data = array('data' => $data); Phprojekt_Converter_Json::echoConvert($data); } }
/** * Save the roles-user relation for one projectId. * * @param array $roles Array with the roles ID. * @param array users Array with the users ID. * @param integer $projectId The project ID. * * @return void */ public function saveRelation($roles, $users, $projectId) { $where = sprintf('project_id = %d', (int) $projectId); foreach ($this->fetchAll($where) as $relation) { $relation->delete(); } // Save roles only for allowed users $activeRecord = Phprojekt_Loader::getLibraryClass('Phprojekt_User_User'); $result = $activeRecord->getAllowedUsers(); foreach ($result as $user) { $userId = $user['id']; if (in_array($userId, $users)) { $clone = clone $this; $clone->roleId = $roles[$userId]; $clone->userId = $userId; $clone->projectId = $projectId; $clone->save(); // Reset cache $sessionName = 'Project_Models_ProjectRoleUserPermissions-fetchUserRole-' . $projectId . '-' . $userId; $roleNamespace = new Zend_Session_Namespace($sessionName); $roleNamespace->unsetAll(); } } }
/** * Get all the modules-item with the wordId. * * @param array $words Array with words IDs. * @param string $operator Query operator. * @param integer $count Limit query. * * @return array Array of results. */ public function searchModuleByWordId($words, $operator = 'AND', $count = 0) { $ids = array(); $result = array(); $rights = Phprojekt_Loader::getLibraryClass('Phprojekt_Item_Rights'); $userId = Phprojekt_Auth::getUserId(); $db = Phprojekt::getInstance()->getDb(); foreach ($words as $content) { $ids[] = (int) $content['id']; } if (!empty($ids)) { // Search by AND if ($operator == 'AND') { $sqlString = ''; $selects = array(); $first = true; while (!empty($ids)) { $id = array_pop($ids); if ($first) { $first = false; if (!empty($ids)) { $selects[] = $db->select()->from('search_word_module', array('item_id'))->where('word_id = ' . (int) $id); } else { $selects[] = $db->select()->from('search_word_module')->where('word_id = ' . (int) $id); } } else { if (!empty($ids)) { $selects[] = $db->select()->from('search_word_module', array('item_id'))->where('word_id = ' . (int) $id . ' AND item_id IN (%s)'); } else { $selects[] = $db->select()->from('search_word_module')->where('word_id = ' . (int) $id . ' AND item_id IN (%s)'); } } } $first = true; while (!empty($selects)) { $select = array_shift($selects)->__toString(); if ($first) { $sqlString = $select; $first = false; } else { $sqlString = sprintf($select, $sqlString); } } $stmt = $db->query($sqlString); $tmpResult = $stmt->fetchAll(Zend_Db::FETCH_ASSOC); } else { // Search By OR $where = 'word_id IN (' . implode(', ', $ids) . ')'; $order = array('module_id ASC', 'item_id DESC'); $tmpResult = $this->fetchAll($where, $order)->toArray(); } foreach ($tmpResult as $data) { // Limit to $count results if ((int) $count > 0 && count($result) >= $count) { break; } // Only fetch records with read access if ($rights->getItemRight($data['module_id'], $data['item_id'], $userId) > 0) { $result[$data['module_id'] . '-' . $data['item_id']] = $data; } } } return $result; }
/** * Saves the new values of the projects dates. * * OPTIONAL request parameters: * <pre> * - array <b>projects</b> Array with projectId,startDate and endDate by comma separated * </pre> * * If there is an error, the save will return a Phprojekt_PublishedException, * if not, it returns a string in JSON format with: * <pre> * - type => 'success'. * - message => Success message. * - code => 0. * - id => 0. * </pre> * * @throws Phprojekt_PublishedException On error in the action save or wrong parameters. * * @return void */ public function jsonSaveAction() { $projects = (array) $this->getRequest()->getParam('projects', array()); $activeRecord = Phprojekt_Loader::getModel('Project', 'Project'); $rights = Phprojekt_Loader::getLibraryClass('Phprojekt_Item_Rights'); $userId = Phprojekt_Auth::getUserId(); $this->setCurrentProjectId(); // Error check: no project received if (empty($projects)) { $label = Phprojekt::getInstance()->translate('Projects'); $message = Phprojekt::getInstance()->translate('No project info was received'); throw new Phprojekt_PublishedException($label . ': ' . $message); } foreach ($projects as $project) { list($id, $startDate, $endDate) = explode(",", $project); // Check: are the three values available? if (empty($id) || empty($startDate) || empty($endDate)) { $label = Phprojekt::getInstance()->translate('Projects'); $message = Phprojekt::getInstance()->translate('Incomplete data received'); throw new Phprojekt_PublishedException($label . ': ' . $message); } $id = (int) $id; $activeRecord->find($id); // Check: project id exists? if (empty($activeRecord->id)) { $label = Phprojekt::getInstance()->translate('Project'); $message = Phprojekt::getInstance()->translate('Id not found #') . $id; throw new Phprojekt_PublishedException($label . ': ' . $message); } // Check: dates are valid? $validStart = Cleaner::validate('date', $startDate, false); $validEnd = Cleaner::validate('date', $endDate, false); if (!$validStart || !$validEnd) { $label = Phprojekt::getInstance()->translate('Project id #') . $id; if (!$validStart) { $message = Phprojekt::getInstance()->translate('Start date invalid'); } else { $message = Phprojekt::getInstance()->translate('End date invalid'); } throw new Phprojekt_PublishedException($label . ': ' . $message); } // Check: start date after end date? $startDateTemp = strtotime($startDate); $endDateTemp = strtotime($endDate); if ($startDateTemp > $endDateTemp) { $label = Phprojekt::getInstance()->translate('Project id #') . $id; $message = Phprojekt::getInstance()->translate('Start date can not be after End date'); throw new Phprojekt_PublishedException($label . ': ' . $message); } $activeRecord->startDate = $startDate; $activeRecord->endDate = $endDate; if ($rights->getItemRight(1, $id, $userId) >= Phprojekt_Acl::WRITE) { $activeRecord->parentSave(); } } $message = Phprojekt::getInstance()->translate(self::EDIT_MULTIPLE_TRUE_TEXT); $return = array('type' => 'success', 'message' => $message, 'code' => 0, 'id' => 0); Phprojekt_Converter_Json::echoConvert($return); }
/** * Returns the fields part of the Notification body using a custom criterion for the Calendar module. * * @param Zend_Locale $lang Locale for use in translations. * * @return array Array with 'label' and 'value'. */ public function getBodyFields($lang) { $bodyFields = array(); $bodyFields[] = array('label' => Phprojekt::getInstance()->translate('Title', $lang), 'value' => $this->_model->title); $bodyFields[] = array('label' => Phprojekt::getInstance()->translate('Place', $lang), 'value' => $this->_model->place); $bodyFields[] = array('label' => Phprojekt::getInstance()->translate('Notes', $lang), 'value' => $this->_model->notes); $bodyFields[] = array('label' => Phprojekt::getInstance()->translate('Start', $lang), 'value' => $this->translateDate($this->_model->startDateNotif, $lang) . ' ' . substr($this->_model->startDatetime, 11, 5)); $bodyFields[] = array('label' => Phprojekt::getInstance()->translate('End', $lang), 'value' => $this->translateDate($this->_model->endDateNotif, $lang) . ' ' . substr($this->_model->startDatetime, 11, 5)); $phpUser = Phprojekt_Loader::getLibraryClass('Phprojekt_User_User'); $participants = $this->_model->notifParticipants; $participantsValue = ""; $i = 0; $lastItem = count($participants); // Participants field foreach ($participants as $participant) { $i++; $phpUser->find((int) $participant); $fullname = trim($phpUser->firstname . ' ' . $phpUser->lastname); if (!empty($fullname)) { $participantsValue .= $fullname . ' (' . $phpUser->username . ')'; } else { $participantsValue .= $phpUser->username; } if ($i < $lastItem) { $participantsValue .= ", "; } } $bodyFields[] = array('label' => Phprojekt::getInstance()->translate('Participants', $lang), 'value' => $participantsValue); if ($this->_model->rrule !== null) { $bodyFields = array_merge($bodyFields, $this->getRruleDescriptive($this->_model->rrule, $lang)); } return $bodyFields; }
/** * Disables all frontend messages. * * @return void */ public function jsonDisableFrontendMessagesAction() { $notification = Phprojekt_Loader::getLibraryClass('Phprojekt_Notification'); try { $notification->disableFrontendMessages(); $message = Phprojekt::getInstance()->translate(self::DISABLE_FRONTEND_MESSAGES_TRUE_TEXT); $resultType = 'success'; } catch (Exception $error) { Phprojekt::getInstance()->getLog()->debug('Error: ' . $error->message); $message = Phprojekt::getInstance()->translate(self::DISABLE_FRONTEND_MESSAGES_FALSE_TEXT); $resultType = 'error'; } $return = array('type' => $resultType, 'message' => $message, 'code' => 0, 'id' => 0); Phprojekt_Converter_Json::echoConvert($return); }
/** * Collects all mail addresses from user ids. * * @param array $userIdList Array of user ids to be fetched. * @param Zend_Validate_Abstract $validator Validator to be used for the mail addresses. * * @return array Array of arrays with either 'mail'/'name' pairs or 'message'/'value' errors. */ private function _getMailFromUserIds($userIdList, Zend_Validate_Abstract $validator) { // Add regular recipients: $idList = array(); if (!empty($userIdList) && is_array($userIdList)) { foreach ($userIdList as $recipientId) { if (is_numeric($recipientId)) { $idList[] = (int) $recipientId; } } } $userMailList = array(); if (count($idList)) { /* @var $userModel Phprojekt_User_User */ $userModel = Phprojekt_Loader::getLibraryClass('Phprojekt_User_User'); $userList = $userModel->fetchAll(sprintf('id IN (%s)', implode(',', $idList))); $setting = Phprojekt_Loader::getLibraryClass('Phprojekt_Setting'); $display = $userModel->getDisplay(); /* @var $record Phprojekt_User_User */ foreach ($userList as $record) { $address = $setting->getSetting('email', (int) $record->id); if ($validator->isValid($address)) { $userMailList[] = array('mail' => $address, 'name' => $record->applyDisplay($display, $record)); } else { $userMailList[] = array('message' => 'Invalid email address detected:', 'value' => $address); } } } return $userMailList; }
/** * Saves the settings for one module. * * OPTIONAL request parameters: * <pre> * - string <b>moduleName</b> Name of the module. * - mixed <b>all other module fields</b> All the fields values to save. * </pre> * * The return is a string in JSON format with: * <pre> * - type => 'success' or 'error'. * - message => Success or error message. * - code => 0. * - id => 0. * </pre> * * @throws Phprojekt_PublishedException On error in the action save or wrong id. * * @return void */ public function jsonSaveAction() { $module = Cleaner::sanitize('alnum', $this->getRequest()->getParam('moduleName', null)); $this->setCurrentProjectId(); $setting = Phprojekt_Loader::getLibraryClass('Phprojekt_Setting'); $setting->setModule($module); $message = $setting->validateSettings($this->getRequest()->getParams()); if (!empty($message)) { $type = "error"; } else { $message = Phprojekt::getInstance()->translate(self::EDIT_TRUE_TEXT); $setting->setSettings($this->getRequest()->getParams()); $type = "success"; } $return = array('type' => $type, 'message' => $message, 'code' => 0, 'id' => 0); Phprojekt_Converter_Json::echoConvert($return); }
/** * Save the settings into the table. * * @param array $params $_POST fields. * @param integer $userId The user ID, if is not setted, the current user is used. * * @return void */ public function setSettings($params, $userId = 0) { if (!$userId) { $userId = Phprojekt_Auth::getUserId(); } $setting = Phprojekt_Loader::getLibraryClass('Phprojekt_Setting'); $setting->setModule('User'); if (empty($params['password'])) { $password = $setting->getSetting('password', $userId); } else { $password = Phprojekt_Auth::cryptString($params['password']); } $namespace = new Zend_Session_Namespace(Phprojekt_Setting::IDENTIFIER, $userId); $fields = $this->getFieldDefinition(Phprojekt_ModelInformation_Default::ORDERING_FORM); foreach ($fields as $data) { foreach ($params as $key => $value) { if ($key == $data['key'] && $key != 'oldValue' && $key != 'confirmValue') { $setting = Phprojekt_Loader::getLibraryClass('Phprojekt_Setting'); $setting->setModule('User'); if ($key == 'password') { $value = $password; } $where = sprintf('user_id = %d AND key_value = %s AND module_id = %d', (int) $userId, $setting->_db->quote($key), 0); $record = $setting->fetchAll($where); if (isset($record[0])) { $record[0]->keyValue = $key; $record[0]->value = $value; $record[0]->save(); } else { $setting->userId = $userId; $setting->moduleId = 0; $setting->keyValue = $key; $setting->value = $value; $setting->identifier = 'Core'; $setting->save(); } $namespace->{$key} = $value; break; } } } }
/** * Define the clone function for prevent the same point to same object. * * @return void */ public function __clone() { parent::__clone(); $this->_validate = Phprojekt_Loader::getLibraryClass('Phprojekt_Model_Validate'); $this->_informationManager = Phprojekt_Loader::getModel('Minutes_SubModules_MinutesItem', 'MinutesItemInformation'); }
/** * Save the login data into Settings and Cookies. * * @param integer $userId Current user ID. * * @return void */ private static function _saveLoginData($userId) { // The hash string is changed everytime it is used, and the expiration time updated. // DB Settings table: create new md5 hash and update expiration time for it // Set the settings pair to save $pair = array(self::LOGGED_TOKEN . '_hash' => md5(time() . mt_rand()), self::LOGGED_TOKEN . '_expires' => strtotime('+1 week')); // Store matching keepLogged data in DB and browser $user = Phprojekt_Loader::getLibraryClass('Phprojekt_User_User'); $user->find($userId); $settings = $user->settings->fetchAll(); foreach ($pair as $key => $value) { $found = false; foreach ($settings as $setting) { // Update if ($setting->keyValue == $key) { $setting->value = $value; $setting->save(); $found = true; break; } } if (!$found) { // Create $record = $user->settings->create(); $record->moduleId = 0; $record->keyValue = $key; $record->value = $value; $record->identifier = 'Login'; $record->save(); } } // Cookies: update md5 hash and expiration time // If we are under Unittest execution, don't work with cookies: if (!headers_sent()) { self::_setCookies($pair[self::LOGGED_TOKEN . '_hash'], $userId, $pair[self::LOGGED_TOKEN . '_expires']); } }
/** * Define the clone function for prevent the same point to same object. * * @return void */ public function __clone() { parent::__clone(); $this->_validate = Phprojekt_Loader::getLibraryClass('Phprojekt_Model_Validate'); $this->_informationManager = Phprojekt_Loader::getModel('Timecard', 'Information'); }
/** * Saves an user. * * If the request parameter "id" is null or 0, the function will add a new user, * if the "id" is an existing user, the function will update it. * * The save action will save some values into the setting table. * * OPTIONAL request parameters: * <pre> * - integer <b>id</b> id of the user to save. * - mixed <b>all other user fields</b> All the fields values to save. * </pre> * * If there is an error, the save will return a Phprojekt_PublishedException, * if not, it returns a string in JSON format with: * <pre> * - type => 'success'. * - message => Success message. * - code => 0. * - id => Id of the user. * </pre> * * @throws Phprojekt_PublishedException On error in the action save or wrong id. * * @return void */ public function jsonSaveAction() { $id = (int) $this->getRequest()->getParam('id'); $this->setCurrentProjectId(); // Settings $setting = Phprojekt_Loader::getLibraryClass('Phprojekt_Setting'); $setting->setModule('User'); $message = $setting->validateSettings($this->getRequest()->getParams()); if (!empty($message)) { $type = "error"; $id = 0; } else { if (empty($id)) { $model = $this->getModelObject(); $message = Phprojekt::getInstance()->translate(self::ADD_TRUE_TEXT); } else { $model = $this->getModelObject()->find($id); $message = Phprojekt::getInstance()->translate(self::EDIT_TRUE_TEXT); } $params = $this->setParams($this->getRequest()->getParams(), $model); Default_Helpers_Save::save($model, $params); if (empty($id)) { $id = $model->id; } $setting->setSettings($this->getRequest()->getParams(), $id); $type = "success"; } $return = array('type' => $type, 'message' => $message, 'code' => 0, 'id' => $id); Phprojekt_Converter_Json::echoConvert($return); }
/** * Returns all global modules. * * Returns a list of all the global modules with: * <pre> * - id => id of the module. * - name => Name of the module. * - label => Display for the module. * </pre> * Also return in the metadata, if the user is an admin or not. * * The return is in JSON format. * * @return array */ function jsonGetGlobalModulesAction() { $modules = array(); $model = Phprojekt_Loader::getLibraryClass('Phprojekt_Module_Module'); foreach ($model->fetchAll('active = 1 AND (save_type = 1 OR save_type = 2)', 'name ASC') as $module) { $modules['data'][$module->id] = array(); $modules['data'][$module->id]['id'] = $module->id; $modules['data'][$module->id]['name'] = $module->name; $modules['data'][$module->id]['label'] = Phprojekt::getInstance()->translate($module->label, null, $module->name); } $modules['metadata'] = Phprojekt_Auth::isAdminUser(); Phprojekt_Converter_Json::echoConvert($modules); }
/** * Help to save a model by setting the models properties. * Validation is based on the ModelInformation implementation. * * @param Phprojekt_Model_Interface $model The model * @param array $params The parameters used to feed the model. * * @throws Exception If validation of parameters fails. * * @return boolean True for a sucessful save. */ protected static function _saveModel(Phprojekt_Model_Interface $model, array $params) { foreach ($params as $k => $v) { if (isset($model->{$k})) { // Don't allow to set the id on save, since it is done by the ActiveRecord if (!in_array($k, array('id'))) { $model->{$k} = $v; } } } if (empty($model->id)) { $newItem = true; } else { $newItem = false; } // Set the owner if ($newItem && isset($model->ownerId)) { $model->ownerId = Phprojekt_Auth::getUserId(); } // Parent Project if (isset($model->projectId)) { $projectId = $model->projectId; } else { $projectId = 0; } // Checks $moduleName = Phprojekt_Loader::getModuleFromObject($model); $moduleId = Phprojekt_Module::getId($moduleName); if (!$model->recordValidate()) { $errors = $model->getError(); $error = array_pop($errors); throw new Phprojekt_PublishedException($error['label'] . ': ' . $error['message']); } else { if (!self::_checkModule($moduleId, $projectId)) { throw new Phprojekt_PublishedException('The parent project do not have enabled this module'); } else { if (!self::_checkItemRights($model, $moduleName)) { throw new Phprojekt_PublishedException('You do not have access to do this action'); } else { // Set the projectId to 1 for global modules if (isset($model->projectId) && Phprojekt_Module::saveTypeIsGlobal($moduleId)) { $model->projectId = 1; } $model->save(); // Save access only if the user have "admin" right $itemRights = Phprojekt_Loader::getLibraryClass('Phprojekt_Item_Rights'); $check = $itemRights->getRights($moduleId, $model->id); if ($check['currentUser']['admin']) { if ($moduleName == 'Core') { $rights = Default_Helpers_Right::getModuleRights($params); } else { $rights = Default_Helpers_Right::getItemRights($params, $moduleId, $newItem); } if (count($rights) > 0) { $model->saveRights($rights); } } return $model; } } } }
/** * Save the rights for the current item. * * The users are a POST array with user IDs. * * @param array $rights Array of user IDs with the bitmask access. * * @return void */ public function saveRights($rights) { // Do the default action parent::saveRights($rights); // Update access and delete the cache also for the children $itemRights = Phprojekt_Loader::getLibraryClass('Phprojekt_Item_Rights'); $activeRecord = Phprojekt_Loader::getModel('Project', 'Project'); $tree = new Phprojekt_Tree_Node_Database($activeRecord, $this->id); $tree = $tree->setup(); $users = array(); foreach ($rights as $userId => $access) { $users[] = (int) $userId; } // Just a check if (empty($users)) { $users[] = 1; } // Keep on the childen only the access for the allowed users in the parent foreach ($tree as $node) { $projectId = (int) $node->id; // Delete users that are not allowed in the parent $where = sprintf('module_id = 1 AND item_id = %d AND user_id NOT IN (%s)', $projectId, implode(",", $users)); $itemRights->delete($where); // Reset access by module-item-user foreach ($users as $userId) { // Reset cache $sessionName = 'Phprojekt_Item_Rights-getItemRight' . '-1-' . $projectId . '-' . $userId; $rightNamespace = new Zend_Session_Namespace($sessionName); $rightNamespace->unsetAll(); } // Reset access by module-item $sessionName = 'Phprojekt_Item_Rights-getUsersRights' . '-1-' . $projectId; $rightNamespace = new Zend_Session_Namespace($sessionName); $rightNamespace->unsetAll(); // Reset users by module-item $sessionName = 'Phprojekt_Item_Rights-getUsersWithRight' . '-1-' . $projectId; $rightNamespace = new Zend_Session_Namespace($sessionName); $rightNamespace->unsetAll(); // Reset users by project $sessionName = 'Phprojekt_User_User-getAllowedUsers' . '-' . $projectId; $rightNamespace = new Zend_Session_Namespace($sessionName); $rightNamespace->unsetAll(); } }
/** * Returns the statistics data. * * Also return the Total per rows. * * OPTIONAL request parameters: * <pre> * - date <b>startDate</b> ISO start date for filter. * - date <b>endDate</b> ISO end date for filter. * - integer <b>nodeId</b> List all the projects under nodeId. * </pre> * * The return is in CSV format. * * @return void */ public function csvListAction() { $startDate = Cleaner::sanitize('date', $this->getRequest()->getParam('startDate', date("Y-m-d"))); $endDate = Cleaner::sanitize('date', $this->getRequest()->getParam('endDate', date("Y-m-d"))); $projectId = (int) $this->getRequest()->getParam('nodeId', null); $this->setCurrentProjectId(); $data = $this->getModelObject()->getStatistics($startDate, $endDate, $projectId); $data = $data['data']; $rows = array(); $sumPerUser = array(); $index = 0; $rows[$index][] = 'Project'; foreach ($data['users'] as $name) { $rows[$index][] = $name; } $rows[$index][] = 'Total'; $index++; $converter = Phprojekt_Loader::getLibraryClass('Phprojekt_Converter_Time'); foreach ($data['projects'] as $projectId => $title) { $sumPerProject = 0; $rows[$index][] = $title; foreach (array_keys($data['users']) as $userId) { if (!isset($data['rows'][$projectId][$userId])) { $rows[$index][] = $converter->convertMinutesToHours(0); } else { $rows[$index][] = $converter->convertMinutesToHours($data['rows'][$projectId][$userId]); $sumPerProject = $sumPerProject + $data['rows'][$projectId][$userId]; if (!isset($sumPerUser[$userId])) { $sumPerUser[$userId] = 0; } $sumPerUser[$userId] = $sumPerUser[$userId] + $data['rows'][$projectId][$userId]; } } $rows[$index][] = $converter->convertMinutesToHours($sumPerProject); $index++; } $rows[$index][] = 'Total'; $total = 0; foreach (array_keys($data['users']) as $userId) { if (!isset($sumPerUser[$userId])) { $rows[$index][] = $converter->convertMinutesToHours(0); } else { $rows[$index][] = $converter->convertMinutesToHours($sumPerUser[$userId]); $total = $total + $sumPerUser[$userId]; } } $rows[$index][] = $converter->convertMinutesToHours($total); Phprojekt_Converter_Csv::echoConvert($rows); }
/** * Collect all the values of the settings and return it in one row. * * @param integer $moduleId The current moduleId. * @param array $metadata Array with all the fields. * @param integer $userId The user ID, if is not setted, the current user is used. * * @return array Array with all the settings and values. */ public function getList($moduleId, $metadata, $userId = null) { $setting = Phprojekt_Loader::getLibraryClass('Phprojekt_Setting'); $setting->setModule('Notification'); $settings = array(); if ($userId === null) { $userId = (int) Phprojekt_Auth::getUserId(); } $where = sprintf('module_id = %d AND user_id = %d', (int) $moduleId, (int) $userId); $record = $setting->fetchAll($where); $data = array(); $data['id'] = 0; foreach ($metadata as $meta) { $data[$meta['key']] = $meta['default']; // This is to use the default value defined in getFieldDefinition() foreach ($record as $oneSetting) { if ($oneSetting->keyValue == $meta['key']) { $getter = 'get' . ucfirst($oneSetting->keyValue); if (method_exists($this, $getter)) { $data[$meta['key']] = call_user_func(array($this, $getter), $oneSetting->value); } else { $data[$meta['key']] = $oneSetting->value; } break; } } } $settings[] = $data; return $settings; }
/** * Sets the recipients according to the received IDs. * * @param array $recipients Array with user IDs. * * @return void */ public function setTo($recipients) { $phpUser = Phprojekt_Loader::getLibraryClass('Phprojekt_User_User'); $setting = Phprojekt_Loader::getLibraryClass('Phprojekt_Setting'); foreach ($recipients as $recipient) { $email = $setting->getSetting('email', (int) $recipient); if ((int) $recipient) { $phpUser->find($recipient); } else { $phpUser->find(Phprojekt_Auth::getUserId()); } $name = trim($phpUser->firstname . ' ' . $phpUser->lastname); if (!empty($name)) { $name = $name . ' (' . $phpUser->username . ')'; } else { $name = $phpUser->username; } $this->addTo($email, $name); } }
/** * Return all the modules with the relation User-Tag. * * @param integer $tagUserId Relation User-Tag ID. * * @return array Array with 'itemId' and 'moduleId'. */ public function getModulesByRelationId($tagUserId) { $foundResults = array(); $rights = Phprojekt_Loader::getLibraryClass('Phprojekt_Item_Rights'); $userId = Phprojekt_Auth::getUserId(); $where = sprintf('tag_user_id = %d', (int) $tagUserId); $modules = $this->fetchAll($where, 'item_id DESC'); foreach ($modules as $moduleData) { if ($rights->getItemRight($moduleData->module_id, $moduleData->item_id, $userId) > 0) { $foundResults[] = array('itemId' => $moduleData->item_id, 'moduleId' => $moduleData->module_id); } } return $foundResults; }
/** * Disables all types of frontend messages. * * @return void */ public function disableFrontendMessages() { $defaultSettings = array(Core_Models_Notification_Setting::FIELD_LOGIN_LOGOUT => 0, Core_Models_Notification_Setting::FIELD_DATARECORDS => 0, Core_Models_Notification_Setting::FIELD_USERGENERATED => 0, Core_Models_Notification_Setting::FIELD_ALERTS => 0); $setting = Phprojekt_Loader::getLibraryClass('Phprojekt_Setting'); $setting->setModule('Notification'); $setting->setSettings($defaultSettings); }