/**
  * Returns not the IDs of the item, module, user, etc. but real values.
  *
  * @param integer $userId The ID of the user who calls this method.
  *
  * @return array Array with 'user', 'module', 'process', 'description', 'itemId',
  *                          'item', 'projectId', 'details', 'time' and 'project'.
  */
 public function getMessage($userId)
 {
     $messageData = $this->getMessageData($userId);
     $data = array();
     $this->_deleteOutdatedMessages();
     if (true === empty($messageData)) {
         return false;
     }
     $userObject = new Phprojekt_User_User();
     $user = $userObject->find($messageData[0]->actorId);
     $data['user'] = $userObject->displayName;
     $data['module'] = ucfirst(Phprojekt_Module::getModuleName($messageData[0]->moduleId));
     $data['process'] = $messageData[0]->process;
     $data['description'] = Phprojekt::getInstance()->translate($messageData[0]->description);
     $data['itemId'] = $messageData[0]->itemId;
     $data['item'] = $messageData[0]->itemName;
     $data['projectId'] = $messageData[0]->projectId;
     $data['details'] = $messageData[0]->details;
     // Convert time to user timezone
     if ($messageData[0]->process == Phprojekt_Notification::LAST_ACTION_REMIND) {
         $addTime = Phprojekt::getInstance()->getConfig()->remindBefore * 60;
     } else {
         $addTime = 0;
     }
     $data['time'] = date("H:i", Phprojekt_Converter_Time::utcToUser($messageData[0]->validFrom) + $addTime);
     // Convert project name
     $project = new Project_Models_Project();
     $data['project'] = $project->find($data['projectId'])->title;
     return $data;
 }
Example #2
0
 /**
  * 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 = new Project_Models_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 = new Timecard_Models_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 = new 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;
 }
 /**
  * Test saveToBackingStore function
  */
 public function testSaveToFilter()
 {
     $user = new Phprojekt_User_User(array('db' => $this->sharedFixture));
     $user->find(1);
     $record = new Phprojekt_Project(array('db' => $this->sharedFixture));
     $filter = new Phprojekt_Filter_UserFilter($record, 'title', 'PHProjekt');
     $tree = new Phprojekt_Tree_Node_Database($record, 1);
     $tree = $tree->setup($filter);
     $filter->saveToBackingStore($user);
 }
 /**
  * Lazy load the userId list.
  *
  * @return array $_userIdList
  */
 protected function _getUserIdList()
 {
     if (empty(self::$_userIdList)) {
         /* @var $user Phprojekt_User_User */
         $user = new Phprojekt_User_User();
         $users = $user->getAllowedUsers();
         foreach ($users as $node) {
             self::$_userIdList[$node['id']] = $this->getRangeValues($node['id'], $node['name']);
         }
     }
     return self::$_userIdList;
 }
Example #5
0
 /**
  * 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()
 {
     $addArray = array();
     $num = func_num_args();
     for ($i = 0; $i < $num; $i++) {
         $addList = (string) func_get_arg($i);
         if ("" != $addList) {
             $addArray[] = $addList;
         }
     }
     $idList = implode(",", $addArray);
     $data = array();
     if (!empty($idList)) {
         $user = new Phprojekt_User_User();
         $userList = $user->fetchAll(sprintf('id IN (%s)', $idList));
         foreach ($userList as $record) {
             $data[] = array('id' => (int) $record->id, 'display' => $record->displayName);
         }
     }
     return $data;
 }
Example #6
0
 /**
  * Sets the recipients according to the received IDs.
  *
  * @param array $recipients Array with user IDs.
  *
  * @return void
  */
 public function setTo($recipients)
 {
     $phpUser = new Phprojekt_User_User();
     $setting = new Phprojekt_Setting();
     foreach ($recipients as $recipient) {
         $email = $setting->getSetting('email', (int) $recipient);
         if (!empty($email)) {
             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);
         }
     }
 }
 /**
  * Returns the detail (fields and data) of one user.
  *
  * The return have:
  *  - The metadata of each field.
  *  - The data of the user.
  *  - The number of rows.
  *
  * If the request parameter "id" is null or 0, the data will be all values of a "new user",
  * if the "id" is an existing user, the data will be all the values of the user.
  *
  * OPTIONAL request parameters:
  * <pre>
  *  - integer <b>id</b> id of the user to consult.
  * </pre>
  *
  * The return is in JSON format.
  *
  * @return void
  */
 public function jsonDetailAction()
 {
     $user = new Phprojekt_User_User();
     $id = (int) $this->getRequest()->getParam("id");
     $user->find($id);
     $data = array();
     $data['id'] = $user->id;
     $data['username'] = empty($user->username) ? "" : $user->username;
     $data['firstname'] = empty($user->firstname) ? "" : $user->firstname;
     $data['lastname'] = empty($user->lastname) ? "" : $user->lastname;
     $data['status'] = empty($user->status) ? "" : $user->status;
     $data['admin'] = empty($user->admin) ? "" : $user->admin;
     $setting = new Phprojekt_Setting();
     $setting->setModule('User');
     $fields = $setting->getModel()->getFieldDefinition(Phprojekt_ModelInformation_Default::ORDERING_FORM);
     $values = $setting->getList(0, $fields, $user->id);
     $values = $values[0];
     unset($values['id']);
     if (!empty($data['id'])) {
         $data = array_merge($data, $values);
     } else {
         foreach ($fields as $field) {
             if (!array_key_exists($field['key'], $values)) {
                 continue;
             }
             if (!is_null($field['default'])) {
                 $data[$field['key']] = $field['default'];
             } else {
                 $data[$field['key']] = "";
             }
         }
     }
     $records = array($data);
     $metadata = $user->getInformation(Phprojekt_ModelInformation_Default::ORDERING_FORM);
     $metadata = $metadata->getFieldDefinition(Phprojekt_ModelInformation_Default::ORDERING_FORM);
     $data = array("metadata" => $metadata, "data" => $records, "numRows" => count($records));
     Phprojekt_Converter_Json::echoConvert($data);
 }
Example #8
0
 /**
  * Convert a UTC time to user or user to UTC and return the timestamp.
  *
  * @param string  $value Date value to convert.
  * @param integer $side  1 for utc to user, -1 for user to utc.
  *
  * @return integer Unix timestamp value.
  */
 public static function convert($value, $side)
 {
     $timeZone = Phprojekt_User_User::getSetting("timeZone", 'UTC');
     if (strstr($timeZone, "_")) {
         list($hours, $minutes) = explode("_", $timeZone);
     } else {
         $hours = (int) $timeZone;
         $minutes = 0;
     }
     $hoursComplement = $hours * $side;
     $minutesComplement = $minutes * $side;
     $u = strtotime($value);
     return mktime(date("H", $u) + $hoursComplement, date("i", $u) + $minutesComplement, date("s", $u), date("m", $u), date("d", $u), date("Y", $u));
 }
Example #9
0
 /**
  * Sets a fields definitions for each field.
  *
  * @return void
  */
 public function setFields()
 {
     // password
     $this->fillField('password', 'Password', 'password', 0, 1, array('length' => 50));
     // confirmValue
     $this->fillField('confirmValue', 'Confirm Password', 'password', 0, 2, array('length' => 50));
     // oldValue
     $this->fillField('oldValue', 'Old Password', 'password', 0, 3, array('length' => 50));
     // email
     $this->fillField('email', 'Email', 'text', 0, 4, array('length' => 255));
     // language
     $range = array();
     foreach ($this->_languageRange as $key => $value) {
         $range[] = $this->getRangeValues($key, $value);
     }
     $this->fillField('language', 'Language', 'selectbox', 0, 5, array('range' => $range, 'required' => true, 'default' => 'en'));
     // timeZone
     $range = array();
     foreach ($this->_timeZoneRange as $key => $value) {
         $range[] = $this->getRangeValues($key, $value);
     }
     $this->fillField('timeZone', 'Time zone', 'selectbox', 0, 6, array('range' => $range, 'required' => true, 'default' => '000'));
     // Proxies
     Phprojekt::setCurrentProjectId(IndexController::INVISIBLE_ROOT);
     $user = new Phprojekt_User_User();
     $range = $user->getAllowedUsers();
     // remove ourselves from the proxy list
     $i = 0;
     foreach ($range as $entry) {
         if ((int) $entry['id'] == Phprojekt_Auth::getUserId()) {
             array_splice($range, $i, 1);
             break;
         }
         $i++;
     }
     $this->fillField('proxies', 'Proxies', 'multiplefilteringselectbox', 0, 7, array('range' => $range, 'required' => true));
 }
 /**
  * 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 = new 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();
         }
     }
 }
 /**
  * Return all the roles in an array and their relations if exists.
  *
  * @param integer $projectId The Project ID.
  *
  * @return array Array with 'id', 'name' and 'users'.
  */
 function getProjectRoleUserPermissions($projectId)
 {
     $roles = array();
     $model = Phprojekt_Loader::getLibraryClass('Phprojekt_Role_Role');
     foreach ($model->fetchAll(null, 'name ASC') as $role) {
         $roles['data'][$role->id] = array();
         $roles['data'][$role->id]['id'] = (int) $role->id;
         $roles['data'][$role->id]['name'] = $role->name;
         $roles['data'][$role->id]['users'] = array();
     }
     $where = sprintf('project_role_user_permissions.project_id = %d', (int) $projectId);
     $order = 'project_role_user_permissions.user_id ASC';
     $select = ' user.username, user.firstname, user.lastname ';
     $join = ' LEFT JOIN user ON user.id = project_role_user_permissions.user_id ';
     $display = Phprojekt_User_User::getDisplay();
     foreach ($this->fetchAll($where, $order, null, null, $select, $join) as $right) {
         $userDisplay = Phprojekt_User_User::applyDisplay($display, $right);
         $roles['data'][$right->roleId]['users'][] = array('id' => (int) $right->userId, 'display' => $userDisplay);
     }
     return $roles;
 }
Example #12
0
 private function applyICalendarTimes($start, $end, $timezoneID = null)
 {
     $utc = new DateTimezone('UTC');
     $timezone = null;
     $userTimeZone = Phprojekt_User_User::getUserDateTimeZone();
     if ('Z' === substr($start, -1)) {
         $timezone = $utc;
     } else {
         if (!is_null($timezoneID)) {
             $timezone = new DateTimeZone($timezoneID);
         } else {
             $timezone = $userTimeZone;
         }
     }
     // We can't use ->setTimezone with the timezones returned by getUserDateTimeZone, as these are non-standard
     // timezones. Unless we start storing correct timezones, we can't directly set the user timezone, so we go to
     // UTC and convert to usertime from there. Because utcToUser returns a unix timestamp, but ActiveRecords expects
     // a "Y-m-d H:i:s" timestamp, we have to go through Datetime again.
     $start = new Datetime($start, $timezone);
     $start->setTimezone($utc);
     $startTs = Phprojekt_Converter_Time::utcToUser($start->format('Y-m-d H:i:s'));
     $start = new Datetime('@' . $startTs);
     $end = new Datetime($end, $timezone);
     $end->setTimezone($utc);
     $endTs = Phprojekt_Converter_Time::utcToUser($end->format('Y-m-d H:i:s'));
     $end = new Datetime('@' . $endTs);
     if ($start->diff($end)->invert) {
         throw new Sabre_DAV_Exception_BadRequest('Start must be before End');
     }
     $this->_timecard->startDatetime = $start->format('Y-m-d H:i:s');
     if ($start->format('z') == $end->format('z')) {
         // Same day
         $this->_timecard->endTime = $end->format('H:i:s');
     } else {
         $this->_timecard->endTime = '23:59:00';
     }
 }
Example #13
0
 protected static function _setEffectiveUserById($userId)
 {
     $user = new Phprojekt_User_User();
     self::$_effectiveUser = $user->findUserById($userId);
 }
Example #14
0
 /**
  * Standard action.
  *
  * The function sets up the template index.phtml and renders it.
  *
  * @return void
  */
 public function indexAction()
 {
     $language = Phprojekt_User_User::getSetting("language", Phprojekt::getInstance()->getConfig()->language);
     $this->view->webpath = Phprojekt::getInstance()->getConfig()->webpath;
     $this->view->language = $language;
     $this->view->compressedDojo = (bool) Phprojekt::getInstance()->getConfig()->compressedDojo;
     $this->view->frontendMsg = (bool) Phprojekt::getInstance()->getConfig()->frontendMessages;
     // Since the time for re-starting a poll to the server is in milliseconds, a multiple of 1000 is needed here.
     $this->view->pollingLoop = Phprojekt::getInstance()->getConfig()->pollingLoop * 1000;
     $this->render('index');
 }
Example #15
0
 /**
  * Updates this Calendar2 object with data from the given VEVENT
  *
  * The returned object must be save()d before it is persistent.
  * This also means that additional changes can be made before any database calls are made.
  *
  * @param Sabre_VObject_Component $vevent The vevent component
  *
  * @throws Exception If the provided component is not a vevent
  *
  * @return void
  */
 public function fromVObject(Sabre_VObject_Component $vevent)
 {
     if (strtolower($vevent->name) !== 'vevent') {
         throw new Exception("Invalid type of vobject_component passed to Calendar2_Models_Calendar2::fromVobject ({$vevent->name})");
     }
     // Workarounds for missing features. We currently don't support locale-time (we just assume it's the user's
     // usual timzeone) or date values without time (we just assume 0800 - 2000 there).
     if (!is_null($vevent->dtstart['VALUE']) && $vevent->dtstart['VALUE']->value === 'DATE') {
         // No T means it's only a date. iCalendar dicates that dtend must be a date, too.
         $vevent->dtstart->value .= 'T080000';
         unset($vevent->dtstart['VALUE']);
         // Caldav end dates are not inclusive
         $end = new Datetime($vevent->dtend->value);
         $end->sub(new DateInterval('P1D'));
         $vevent->dtend->value = $end->format('Ymd') . 'T200000';
         unset($vevent->dtend['VALUE']);
     }
     $utc = new DateTimezone('UTC');
     $timezone = null;
     if ('Z' === substr($vevent->dtstart->value, -1)) {
         $timezone = $utc;
     } else {
         if (!is_null($vevent->dtstart['tzid'])) {
             $timezone = new DateTimeZone($vevent->dtstart['tzid']->value);
         } else {
             $timezone = Phprojekt_User_User::getUserDateTimeZone();
         }
     }
     // 0-1
     // handled:
     //  last-mod, description, dtstart, location, summary, uid
     // not handled
     //  class, created, geo, organizer, priority, dtstamp, seq, status, transp, url, recurid
     //
     // none or one of these two
     //  dtend, duration (only assumes dtend case for now)
     //
     // 0 - n
     // TODO: Check how we can handle these. Maybe just concat them?
     // handling: (only one is handled atm, though)
     //  comment, rrule
     // not handling:
     //  attach, attendee, categories, contact, exdate, exrule, rstatus, related, resources, rdate, x-prop
     $mappable = array(array('veventkey' => 'SUMMARY', 'ourkey' => 'summary', 'default' => '_'), array('veventkey' => 'LOCATION', 'ourkey' => 'location', 'default' => ''), array('veventkey' => 'DESCRIPTION', 'ourkey' => 'description', 'default' => ''), array('veventkey' => 'COMMENT', 'ourkey' => 'comments'), array('veventkey' => 'UID', 'ourkey' => 'uid'), array('veventkey' => 'LAST-MODIFIED', 'ourkey' => 'lastModified'), array('veventkey' => 'RRULE', 'ourkey' => 'rrule', 'default' => ''));
     foreach ($mappable as $m) {
         if (isset($vevent->{$m}['veventkey'])) {
             $this->{$m}['ourkey'] = $vevent->{$m}['veventkey'];
         } else {
             if (array_key_exists('default', $m)) {
                 $this->{$m}['ourkey'] = $m['default'];
             }
         }
     }
     $start = new Datetime($vevent->dtstart->value, $timezone);
     $start->setTimezone($utc);
     $this->start = Phprojekt_Converter_Time::utcToUser($start->format('Y-m-d H:i:s'));
     if ($vevent->dtend) {
         $end = new Datetime($vevent->dtend->value, $timezone);
     } else {
         if ($vevent->duration) {
             $duration = new DateInterval($vevent->duration->value);
             $end = clone $start;
             $end->add($duration);
         }
     }
     $end->setTimezone($utc);
     $this->end = Phprojekt_Converter_Time::utcToUser($end->format('Y-m-d H:i:s'));
 }
Example #16
0
 protected function _isValidUserId($userId)
 {
     if (!is_numeric($userId) || $userId < 1) {
         return false;
     }
     $validUser = false;
     $user = new Phprojekt_User_User();
     if ($user->find((int) $userId)) {
         $validUser = true;
     }
     return $validUser;
 }
Example #17
0
 /**
  * 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 = new 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']);
     }
 }
Example #18
0
 /**
  * Returns all users that have a given right (or any right if none is given) on an item.
  *
  * @param string  $moduleId The module ID.
  * @param integer $itemId   The item ID.
  * @param int     $rights   A bitmask of rights (Constants in Phprojekt_Acl). All users with any rights will be
  *                              returned if null or omitted.
  * @param bool    $exact    Only get users with exact $rights instead of all users that have at least $rights.
  *                              Default is false.
  *
  * @return array Array of user IDs.
  */
 public function getUsersWithRight($moduleId, $itemId, $rights = null, $exact = false)
 {
     $db = Phprojekt::getInstance()->getDb();
     $where = $db->quoteInto('module_id = ? AND ', (int) $moduleId);
     $where .= $db->quoteInto('item_id = ?', (int) $itemId);
     if (is_null($rights)) {
         $where .= ' AND access > 0';
     } else {
         if ($exact) {
             $where .= $db->quoteInto(' AND access = ?', (int) $rights);
         } else {
             $where .= $db->quoteInto(' AND (access & ?) = ?', (int) $rights, (int) $rights);
         }
     }
     $user = new Phprojekt_User_User();
     $users = $user->fetchAll($where, null, null, null, null, "JOIN item_rights ON item_rights.user_id = user.id");
     return $users;
 }
 /**
  * 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 = new Phprojekt_User_User();
         $userList = $userModel->fetchAll(sprintf('id IN (%s)', implode(',', $idList)));
         /* @var $record Phprojekt_User_User */
         foreach ($userList as $record) {
             $address = $record->getSetting('email');
             if ($validator->isValid($address)) {
                 $userMailList[] = array('mail' => $address, 'name' => $record->displayName);
             } else {
                 $userMailList[] = array('message' => 'Invalid email address detected:', 'value' => $address);
             }
         }
     }
     return $userMailList;
 }
Example #20
0
 /**
  * Test create an user
  */
 public function testCreateUser()
 {
     try {
         $user = new Phprojekt_User_User(array('db' => $this->sharedFixture));
         $user->username = '******';
         $user->firstname = 'Gustavo';
         $user->lastname = 'Solt';
         $this->assertTrue($user->save());
         $gustavo = new Phprojekt_User_User(array('db' => $this->sharedFixture));
         $gustavo->find($user->id);
         $this->assertEquals('gustavo', $gustavo->username);
     } catch (Exception $e) {
         $this->fail($e->getMessage());
     }
 }
 /**
  * Return ical busy times for the given time period and user. If no
  * user is given, default to the currently logged in user.
  *
  * Request parameters:
  *  int         user    => The id of the user. May be null.
  *  datetime    start   => The start of the period to check.
  *  datetime    end     => The end of the period to check.
  *
  * Response
  *  Array of {
  *      datetime start => The start of the busy period.
  *      datetime end   => The end of the busy period.
  *  }
  */
 public function jsonBusyTimesAction()
 {
     $user = $this->getRequest()->getParam('user', Phprojekt_Auth_Proxy::getEffectiveUserId());
     $start = $this->getRequest()->getParam('start');
     $end = $this->getRequest()->getParam('end');
     if (!Cleaner::validate('int', $user)) {
         throw new Zend_Controller_Action_Exception("Invalid id '{$id}'", 400);
     }
     $user = (int) $user;
     if (!self::_validateTimestamp($start)) {
         throw new Zend_Controller_Action_Exception("Invalid start timestamp '{$start}'", 400);
     }
     if (!self::_validateTimestamp($end)) {
         throw new Zend_Controller_Action_Exception("Invalid end timestamp '{$start}'", 400);
     }
     $start = new Datetime($start, Phprojekt_User_User::getUserDateTimeZone());
     $end = new Datetime($end, Phprojekt_User_User::getUserDateTimeZone());
     $model = new Calendar2_Models_Calendar2();
     $events = $model->fetchAllForPeriod($start, $end);
     $busyPeriods = array();
     foreach ($events as $event) {
         $busyPeriods[] = array('start' => new Datetime($event->start, new DateTimeZone('UTC')), 'end' => new Datetime($event->end, new DateTimeZone('UTC')));
     }
     Phprojekt_Converter_Json::echoConvert(Calendar2_Helper_Time::compactPeriods($busyPeriods));
 }
Example #22
0
 /**
  * Translate a string using the current module.
  *
  * @param string             $message    Message to translate.
  * @param string|Zend_Locale $locale     Locale/Language to set.
  * @param string             $moduleName Module where search the string.
  *
  * @return string Translated string.
  */
 public function translate($message, $locale = null, $moduleName = null)
 {
     $translate = Phprojekt::getInstance()->getTranslate($locale);
     if (null === $moduleName) {
         $moduleName = Zend_Controller_Front::getInstance()->getRequest()->getModuleName();
     }
     // Fix for request to the core
     if ($moduleName == 'Core') {
         $paramModule = Zend_Controller_Front::getInstance()->getRequest()->getParam('moduleName', null);
         // Use a $moduleName param if is not a system Setting or Configuration
         if (null !== $paramModule && !in_array($paramModule, array('General', 'User', 'Notification'))) {
             $moduleName = $paramModule;
         }
     }
     if (null === $locale) {
         $locale = Phprojekt_User_User::getSetting("language", $this->_config->language);
     }
     return $translate->translate($message, $moduleName, $locale);
 }
Example #23
0
 /**
  * Test the display
  */
 public function testdisplay()
 {
     $user = new Phprojekt_User_User();
     $this->assertEquals(array('lastname', 'firstname'), $user->getDisplay());
     $user->find(2);
     $this->assertEquals('Solt, Gustavo', $user->applyDisplay(array('lastname', 'firstname'), $user));
     $this->assertEquals('gus, Solt, Gustavo', $user->applyDisplay(array('username', 'lastname', 'firstname'), $user));
     $this->assertEquals('gus', $user->applyDisplay(array('username'), $user));
 }
 /**
  * Gets the data range for a select using a model.
  *
  * @param Phprojekt_ModelInformation_Interface $field Class with data of the field.
  *
  * @return array Array with 'id' and 'name'.
  */
 public function getRangeFromModel(Phprojekt_ModelInformation_Interface $field)
 {
     $options = array();
     list($module, $key, $value) = explode('#', $field->formRange);
     $module = trim($module);
     $key = trim($key);
     $value = trim($value);
     switch ($module) {
         case 'Project':
             $activeRecord = new Project_Models_Project();
             $tree = new Phprojekt_Tree_Node_Database($activeRecord, 1);
             $tree = $tree->setup();
             foreach ($tree as $node) {
                 $options[] = array('id' => (int) $node->{$key}, 'name' => $node->getDepthDisplay($value));
             }
             break;
         case 'User':
             $activeRecord = new Phprojekt_User_User();
             $result = $activeRecord->getAllowedUsers();
             if (!$field->isRequired && $field->formType == 'selectValues') {
                 $options[] = array('id' => 0, 'name' => '');
             }
             $options = array_merge($options, $result);
             break;
         default:
             $activeRecord = Phprojekt_Loader::getModel($module, $module);
             if (method_exists($activeRecord, 'getRangeFromModel')) {
                 $options = call_user_func(array($activeRecord, 'getRangeFromModel'), $field);
             } else {
                 $result = $activeRecord->fetchAll();
                 $options = $this->_setRangeValues($field, $result, $key, $value);
             }
             break;
     }
     return $options;
 }
Example #25
0
 /**
  * Test the display
  */
 public function testdisplay()
 {
     $user = new Phprojekt_User_User();
     $this->assertEquals(array('lastname', 'firstname'), $user->getDisplay());
     $user->find(1);
     $this->assertEquals('Mustermann, Max', $user->applyDisplay(array('lastname', 'firstname'), $user));
     $this->assertEquals('Test, Mustermann, Max', $user->applyDisplay(array('username', 'lastname', 'firstname'), $user));
     $this->assertEquals('Test', $user->applyDisplay(array('username'), $user));
 }
Example #26
0
 /**
  * Has Many and belongs to many test
  *
  * @return void
  */
 public function testHasManyAndBelongsToMany()
 {
     $user = new Phprojekt_User_User(array('db' => $this->sharedFixture));
     $user->find(1);
     $group = $user->groups->fetchAll();
     $this->assertEquals('default', $user->groups->find(1)->name);
     $this->assertEquals('ninasgruppe', $group[1]->name);
     $this->assertEquals('TEST GROUP', $group[2]->name);
     $this->assertEquals(5, $user->groups->count());
     $group = new Phprojekt_Groups_Groups(array('db' => $this->sharedFixture));
     $group->find(1);
     $users = $group->users->fetchAll();
     $this->assertEquals('david', $users[0]->username);
     $this->assertEquals(5, $group->users->count());
 }
Example #27
0
 /**
  * Test found user by id
  */
 public function testUserId()
 {
     $user = new Phprojekt_User_User(array('db' => $this->sharedFixture));
     $clone = $user->findUserById(1);
     $this->assertEquals('Test', $clone->username);
     $clone = $user->findUserById(0);
     $this->assertEquals('', $clone->username);
 }
Example #28
0
 /**
  * Gets only the recipients with at least a 'read' right
  * and checks if the user has disabled/enabled the settings for saving the messages.
  *
  * If no recipient is given, returns an empty array.
  *
  * @return array Array with user IDs.
  */
 public function getRecipients()
 {
     if (false === empty($this->_recipients)) {
         return $this->_recipients;
     }
     $recipients = array();
     if ($this->_model instanceof Phprojekt_Tree_Node_Database || $this->_model instanceof Phprojekt_Model_Interface) {
         $userIds = $this->_model->getUsersRights();
         if (is_array($userIds) && !empty($userIds)) {
             foreach ($userIds as $userId => $right) {
                 if ($userId == Phprojekt_Auth::getUserId() || true === $right['none']) {
                     continue;
                 }
                 $recipients[] = $userId;
             }
         }
     } else {
         $user = new Phprojekt_User_User();
         $userIds = $user->fetchAll();
         foreach ($userIds as $user) {
             if ($user->id == Phprojekt_Auth::getUserId()) {
                 continue;
             }
             $recipients[] = $user->id;
         }
     }
     return $this->filterRecipientsToSettings($recipients);
 }