Exemplo n.º 1
0
 /**
  * Return all projects that this user is part of
  *
  * @access public
  * @param User $user
  * @param 
  * @return array
  */
 function getProjectsByUser(User $user, $additional_conditions = null, $additional_sort = null)
 {
     trace(__FILE__, "getProjectsByUser(user, {$additional_conditions}, {$additional_sort})");
     $projects_table = Projects::instance()->getTableName(true);
     trace(__FILE__, "getProjectsByUser():1");
     $project_users_table = ProjectUsers::instance()->getTableName(true);
     trace(__FILE__, "getProjectsByUser():2");
     $project_milestones_table = ProjectMilestones::instance()->getTableName(true);
     trace(__FILE__, "getProjectsByUser():3");
     $empty_datetime = DB::escape(EMPTY_DATETIME);
     $projects = array();
     if (trim($additional_sort) == 'milestone') {
         $sql = "SELECT distinct {$projects_table}.* FROM {$projects_table}";
         $sql .= " left outer join {$project_milestones_table} on {$project_milestones_table}.`project_id` = {$projects_table}.`id`";
         $sql .= " inner join {$project_users_table} on {$projects_table}.`id` = {$project_users_table}.`project_id`";
         $sql .= " where {$project_users_table}.`user_id` = " . DB::escape($user->getId()) . " and ({$project_milestones_table}.`completed_on` = {$empty_datetime} or isnull({$project_milestones_table}.`completed_on`))";
     } else {
         $sql = "SELECT {$projects_table}.* FROM {$projects_table}, {$project_users_table} WHERE ({$projects_table}.`id` = {$project_users_table}.`project_id` AND {$project_users_table}.`user_id` = " . DB::escape($user->getId()) . ')';
     }
     if (trim($additional_conditions) != '') {
         $sql .= " AND ({$additional_conditions})";
     }
     // if
     if (trim($additional_sort) == 'priority') {
         $sql .= " ORDER BY isnull({$projects_table}.`priority`), {$projects_table}.`priority`, {$projects_table}.`name`";
     } elseif (trim($additional_sort) == 'milestone') {
         $sql .= " ORDER BY isnull({$project_milestones_table}.`due_date`), {$project_milestones_table}.`due_date`, {$projects_table}.`name` ";
     } else {
         $sql .= " ORDER BY {$projects_table}.`name`";
     }
     trace(__FILE__, "getProjectsByUser(): sql={$sql}");
     $rows = DB::executeAll($sql);
     trace(__FILE__, "getProjectsByUser(): sql={$sql} ok");
     if (is_array($rows)) {
         foreach ($rows as $row) {
             $projects[] = Projects::instance()->loadFromRow($row);
         }
         // foreach
     }
     // if
     return count($projects) ? $projects : null;
 }
Exemplo n.º 2
0
 /**
  * Return all projects that this user is part of
  *
  * @access public
  * @param User $user
  * @param 
  * @return array
  */
 function getProjectsByUser(User $user, $additional_conditions = null)
 {
     $projects_table = Projects::instance()->getTableName(true);
     $project_users_table = ProjectUsers::instance()->getTableName(true);
     $projects = array();
     $sql = "SELECT {$projects_table}.* FROM {$projects_table}, {$project_users_table} WHERE ({$projects_table}.`id` = {$project_users_table}.`project_id` AND {$project_users_table}.`user_id` = " . DB::escape($user->getId()) . ')';
     if (trim($additional_conditions) != '') {
         $sql .= " AND ({$additional_conditions})";
     }
     // if
     $sql .= " ORDER BY {$projects_table}.`name`";
     $rows = DB::executeAll($sql);
     if (is_array($rows)) {
         foreach ($rows as $row) {
             $projects[] = Projects::instance()->loadFromRow($row);
         }
         // foreach
     }
     // if
     return count($projects) ? $projects : null;
 }
 function list_files()
 {
     ajx_current("empty");
     /* get query parameters */
     $start = (int) array_var($_GET, 'start');
     $limit = (int) array_var($_GET, 'limit');
     if (!$start) {
         $start = 0;
     }
     if (!$limit) {
         $limit = config_option('files_per_page');
     }
     $order = array_var($_GET, 'sort');
     $orderdir = array_var($_GET, 'dir');
     $page = (int) ($start / $limit) + 1;
     $hide_private = !logged_user()->isMemberOfOwnerCompany();
     $tag = array_var($_GET, 'tag');
     $type = array_var($_GET, 'type');
     $user = array_var($_GET, 'user');
     /* if there's an action to execute, do so */
     if (array_var($_GET, 'action') == 'delete') {
         $ids = explode(',', array_var($_GET, 'objects'));
         $succ = 0;
         $err = 0;
         foreach ($ids as $id) {
             $file = ProjectFiles::findById($id);
             if (isset($file) && $file->canDelete(logged_user())) {
                 try {
                     DB::beginWork();
                     $file->trash();
                     ApplicationLogs::createLog($file, $file->getWorkspaces(), ApplicationLogs::ACTION_TRASH);
                     DB::commit();
                     $succ++;
                 } catch (Exception $e) {
                     DB::rollback();
                     $err++;
                 }
             } else {
                 $err++;
             }
         }
         if ($succ > 0) {
             flash_success(lang("success delete files", $succ));
         } else {
             flash_error(lang("error delete files", $err));
         }
     } else {
         if (array_var($_GET, 'action') == 'tag') {
             $ids = explode(',', array_var($_GET, 'objects'));
             $tagTag = array_var($_GET, 'tagTag');
             $tagged = 0;
             $not_tagged = 0;
             foreach ($ids as $id) {
                 $file = ProjectFiles::findById($id);
                 if (isset($file) && $file->canEdit(logged_user())) {
                     $arr_tags = $file->getTags();
                     if (!array_search($tagTag, $arr_tags)) {
                         $arr_tags[] = $tagTag;
                         $file->setTagsFromCSV(implode(',', $arr_tags));
                         $tagged++;
                     }
                 } else {
                     $not_tagged++;
                 }
             }
             if ($tagged > 0) {
                 flash_success(lang("success tag objects", $tagged));
             } else {
                 flash_error(lang("error tag objects", $not_tagged));
             }
         } else {
             if (array_var($_GET, 'action') == 'untag') {
                 $ids = explode(',', array_var($_GET, 'objects'));
                 $tagTag = array_var($_GET, 'tagTag');
                 $untagged = 0;
                 $not_untagged = 0;
                 foreach ($ids as $id) {
                     $file = ProjectFiles::findById($id);
                     if (isset($file) && $file->canEdit(logged_user())) {
                         if ($tagTag != '') {
                             $file->deleteTag($tagTag);
                         } else {
                             $file->clearTags();
                         }
                         $untagged++;
                     } else {
                         flash_error(lang('no access permissions'));
                         $not_untagged++;
                     }
                 }
                 if ($untagged > 0) {
                     flash_success(lang("success untag objects", $untagged));
                 } else {
                     flash_error(lang("error untag objects", $not_untagged));
                 }
             } else {
                 if (array_var($_GET, 'action') == 'markasread') {
                     $ids = explode(',', array_var($_GET, 'objects'));
                     $succ = 0;
                     $err = 0;
                     foreach ($ids as $id) {
                         $file = ProjectFiles::findById($id);
                         try {
                             $file->setIsRead(logged_user()->getId(), true);
                             $succ++;
                         } catch (Exception $e) {
                             $err++;
                         }
                         // try
                     }
                     //for
                     if ($succ <= 0) {
                         flash_error(lang("error markasread files", $err));
                     }
                 } else {
                     if (array_var($_GET, 'action') == 'markasunread') {
                         $ids = explode(',', array_var($_GET, 'objects'));
                         $succ = 0;
                         $err = 0;
                         foreach ($ids as $id) {
                             $file = ProjectFiles::findById($id);
                             try {
                                 $file->setIsRead(logged_user()->getId(), false);
                                 $succ++;
                             } catch (Exception $e) {
                                 $err++;
                             }
                             // try
                         }
                         //for
                         if ($succ <= 0) {
                             flash_error(lang("error markasunread files", $err));
                         }
                     } else {
                         if (array_var($_GET, 'action') == 'zip_add') {
                             $this->zip_add();
                         } else {
                             if (array_var($_GET, 'action') == 'move') {
                                 $wsid = array_var($_GET, "moveTo");
                                 $destination = Projects::findById($wsid);
                                 if (!$destination instanceof Project) {
                                     $resultMessage = lang('project dnx');
                                     $resultCode = 1;
                                 } else {
                                     if (!can_add(logged_user(), $destination, 'ProjectFiles')) {
                                         $resultMessage = lang('no access permissions');
                                         $resultCode = 1;
                                     } else {
                                         $count = 0;
                                         $ids = explode(',', array_var($_GET, 'ids', ''));
                                         for ($i = 0; $i < count($ids); $i++) {
                                             $id = $ids[$i];
                                             $file = ProjectFiles::findById($id);
                                             if ($file instanceof ProjectFile && $file->canEdit(logged_user())) {
                                                 if (!array_var($_GET, "mantainWs")) {
                                                     $removed = "";
                                                     $ws = $file->getWorkspaces(null);
                                                     foreach ($ws as $w) {
                                                         if (can_add(logged_user(), $w, 'ProjectFiles')) {
                                                             $file->removeFromWorkspace($w);
                                                             $removed .= $w->getId() . ",";
                                                         }
                                                     }
                                                     $removed = substr($removed, 0, -1);
                                                     $log_action = ApplicationLogs::ACTION_MOVE;
                                                     $log_data = ($removed == "" ? "" : "from:{$removed};") . "to:{$wsid}";
                                                 } else {
                                                     $log_action = ApplicationLogs::ACTION_COPY;
                                                     $log_data = "to:{$wsid}";
                                                 }
                                                 $file->addToWorkspace($destination);
                                                 ApplicationLogs::createLog($file, $file->getWorkspaces(), $log_action, false, null, true, $log_data);
                                                 $count++;
                                             }
                                         }
                                         // for
                                         $resultMessage = lang("success move objects", $count);
                                         $resultCode = 0;
                                     }
                                 }
                             } else {
                                 if (array_var($_GET, 'action') == 'archive') {
                                     $ids = explode(',', array_var($_GET, 'ids'));
                                     $succ = 0;
                                     $err = 0;
                                     foreach ($ids as $id) {
                                         $file = ProjectFiles::findById($id);
                                         if (isset($file) && $file->canEdit(logged_user())) {
                                             try {
                                                 DB::beginWork();
                                                 $file->archive();
                                                 ApplicationLogs::createLog($file, $file->getWorkspaces(), ApplicationLogs::ACTION_ARCHIVE);
                                                 DB::commit();
                                                 $succ++;
                                             } catch (Exception $e) {
                                                 DB::rollback();
                                                 //Logger::log($e->getMessage());
                                                 $err++;
                                             }
                                         } else {
                                             $err++;
                                         }
                                     }
                                     if ($succ > 0) {
                                         flash_success(lang("success archive objects", $succ));
                                     } else {
                                         flash_error(lang("error archive objects", $err));
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     Hook::fire('classify_action', null, $ret);
     $project = active_project();
     /* perform query */
     $result = ProjectFiles::getProjectFiles($project, null, $hide_private, $order, $orderdir, $page, $limit, false, $tag, $type, $user);
     ProjectFiles::populateData($result[0]);
     $objects = null;
     $pagination = null;
     if (is_array($result)) {
         list($objects, $pagination) = $result;
         if ($pagination->getTotalItems() < ($page - 1) * $limit) {
             // if we are past the last page show the first page
             $start = 0;
             $page = 1;
             $result = ProjectFiles::getProjectFiles($project, null, $hide_private, $order, $orderdir, $page, $limit, false, $tag, $type, $user);
             if (is_array($result)) {
                 list($objects, $pagination) = $result;
             }
         }
     }
     /* prepare response object */
     $listing = array("totalCount" => $pagination ? $pagination->getTotalItems() : 0, "start" => $start, "files" => array());
     if ($objects) {
         $index = 0;
         foreach ($objects as $o) {
             $coName = "";
             $coId = $o->getCheckedOutById();
             if ($coId != 0) {
                 if ($coId == logged_user()->getId()) {
                     $coName = "self";
                 } else {
                     $coUser = Users::findById($coId);
                     if ($coUser instanceof User) {
                         $coName = $coUser->getUsername();
                     } else {
                         $coName = "";
                     }
                 }
             }
             if ($o->isMP3()) {
                 $songname = $o->getProperty("songname");
                 $artist = $o->getProperty("songartist");
                 $album = $o->getProperty("songalbum");
                 $track = $o->getProperty("songtrack");
                 $year = $o->getProperty("songyear");
                 $duration = $o->getProperty("songduration");
                 $songInfo = json_encode(array($songname, $artist, $album, $track, $year, $duration, $o->getDownloadUrl(), $o->getFilename(), $o->getId()));
             } else {
                 $songInfo = array();
             }
             $values = array("id" => $o->getId(), "ix" => $index++, "object_id" => $o->getId(), "name" => $o->getFilename(), "type" => $o->getTypeString(), "mimeType" => $o->getTypeString(), "tags" => project_object_tags($o), "createdBy" => $o->getCreatedByDisplayName(), "createdById" => $o->getCreatedById(), "dateCreated" => $o->getCreatedOn() instanceof DateTimeValue ? $o->getCreatedOn()->isToday() ? format_time($o->getCreatedOn()) : format_datetime($o->getCreatedOn()) : '', "dateCreated_today" => $o->getCreatedOn() instanceof DateTimeValue ? $o->getCreatedOn()->isToday() : 0, "updatedBy" => $o->getUpdatedByDisplayName(), "updatedById" => $o->getUpdatedById(), "dateUpdated" => $o->getUpdatedOn() instanceof DateTimeValue ? $o->getUpdatedOn()->isToday() ? format_time($o->getUpdatedOn()) : format_datetime($o->getUpdatedOn()) : '', "dateUpdated_today" => $o->getUpdatedOn() instanceof DateTimeValue ? $o->getUpdatedOn()->isToday() : 0, "icon" => $o->getTypeIconUrl(), "size" => $o->getFileSize(), "wsIds" => $o->getUserWorkspacesIdsCSV(logged_user(), ProjectUsers::instance()->getTableName(true) . ".`can_read_files` = 1"), "url" => $o->getOpenUrl(), "manager" => get_class($o->manager()), "checkedOutByName" => $coName, "checkedOutById" => $coId, "isModifiable" => $o->isModifiable() && $o->canEdit(logged_user()), "modifyUrl" => $o->getModifyUrl(), "songInfo" => $songInfo, "ftype" => $o->getType(), "url" => $o->getUrl(), "isRead" => $o->getIsRead(logged_user()->getId()));
             if ($o->isMP3()) {
                 $values['isMP3'] = true;
             }
             Hook::fire('add_classification_value', $o, $values);
             $listing["files"][] = $values;
         }
     }
     ajx_extra_data($listing);
     tpl_assign("listing", $listing);
 }
 /**
  * Return manager instance
  *
  * @access protected
  * @param void
  * @return ProjectUsers 
  */
 function manager()
 {
     if (!$this->manager instanceof ProjectUsers) {
         $this->manager = ProjectUsers::instance();
     }
     return $this->manager;
 }
Exemplo n.º 5
0
/**
 * Enter description here...
 * assumes manager has one field as PK
 *
 * @param DataManager $manager
 * @param $access_level ACCESS_LEVEL_XX objects that defines which permission is being checked
 * @param string $project_id string that will be compared to the project id while searching project_user table
 * @param int $user_id user whose permissions are being checked
 * @return unknown
 */
function permissions_sql_for_listings(DataManager $manager, $access_level, User $user, $project_id = '`project_id`', $table_alias = null)
{
    if (!$manager instanceof DataManager) {
        throw new Exception("Invalid manager '{$manager}' in permissions helper", -1);
        return '';
    }
    $user_id = $user->getId();
    $oup_tablename = ObjectUserPermissions::instance()->getTableName(true);
    $wo_tablename = WorkspaceObjects::instance()->getTableName(true);
    $users_table_name = Users::instance()->getTableName(true);
    $pu_table_name = ProjectUsers::instance()->getTableName(true);
    if ($user->isGuest() && $access_level == ACCESS_LEVEL_WRITE) {
        return 'false';
    }
    if (isset($table_alias) && $table_alias && $table_alias != '') {
        $object_table_name = $table_alias;
    } else {
        $object_table_name = $manager->getTableName();
    }
    if (!is_numeric($project_id)) {
        $project_id = "{$object_table_name}.{$project_id}";
    }
    $object_id_field = $manager->getPkColumns();
    $object_id = $object_table_name . '.' . $object_id_field;
    $object_manager = get_class($manager);
    $access_level_text = access_level_field_name($access_level);
    $item_class = $manager->getItemClass();
    $is_project_data_object = new $item_class() instanceof ProjectDataObject;
    // permissions for contacts
    if ($manager instanceof Contacts && can_manage_contacts($user)) {
        return 'true';
    }
    if ($manager instanceof Companies && can_manage_contacts($user)) {
        return 'true';
    }
    // permissions for file revisions
    if ($manager instanceof ProjectFileRevisions) {
        $pfTableName = "`" . TABLE_PREFIX . "project_files`";
        return "{$object_table_name}.`file_id` IN (SELECT `id` FROM {$pfTableName} WHERE " . permissions_sql_for_listings(ProjectFiles::instance(), $access_level, $user) . ")";
    }
    // permissions for projects
    if ($manager instanceof Projects) {
        $pcTableName = "`" . TABLE_PREFIX . 'project_users`';
        return "{$object_table_name}.`id` IN (SELECT `project_id` FROM {$pcTableName} `pc` WHERE `user_id` = {$user_id})";
    }
    // permissions for users
    if ($manager instanceof Users) {
        if (logged_user()->isMemberOfOwnerCompany()) {
            return "true";
        } else {
            return "{$object_table_name}.`company_id` = " . owner_company()->getId() . " OR {$object_table_name}.`company_id` = " . logged_user()->getCompanyId();
        }
    }
    $can_manage_object = manager_class_field_name($object_manager, $access_level);
    // user is creator
    $str = " ( `created_by_id` = {$user_id}) ";
    // element belongs to personal project
    /*if($is_project_data_object) // TODO: type of element belongs to a project
    			if (!in_array('project_id', $manager->getColumns())) {
    				$str .= "\n OR ( EXISTS(SELECT * FROM $users_table_name `xx_u`, $wo_tablename `xx_wo`
    				WHERE `xx_u`.`id` = $user_id
    					AND `xx_u`.`personal_project_id` = `xx_wo`.`workspace_id`
    					AND `xx_wo`.`object_id` = $object_id 
    					AND `xx_wo`.`object_manager` = '$object_manager' )) ";
    			} else {
    				$str .= "\n OR ( $project_id = (SELECT `personal_project_id` FROM $users_table_name `xx_u` WHERE `xx_u`.`id` = $user_id)) ";
    			}
    		*/
    // user or group has specific permissions over object
    $group_ids = $user->getGroupsCSV();
    $all_ids = '(' . $user_id . ($group_ids != '' ? ',' . $group_ids : '') . ')';
    $str .= "\n OR ( EXISTS ( SELECT * FROM {$oup_tablename} `xx_oup` \n\t\t\t\tWHERE `xx_oup`.`rel_object_id` = {$object_id} \n\t\t\t\t\tAND `xx_oup`.`rel_object_manager` = '{$object_manager}' \n\t\t\t\t\tAND `xx_oup`.`user_id` IN {$all_ids} \n\t\t\t\t\tAND `xx_oup`.{$access_level_text} = true) )";
    if ($is_project_data_object) {
        // TODO: type of element belongs to a project
        if (!in_array('project_id', $manager->getColumns())) {
            $str .= "\n OR ( EXISTS ( SELECT * FROM {$pu_table_name} `xx_pu`, {$wo_tablename} `xx_wo` \n\t\t\t\tWHERE `xx_pu`.`user_id` IN {$all_ids} \n\t\t\t\t\tAND `xx_pu`.`project_id` = `xx_wo`.`workspace_id`\n\t\t\t\t\tAND `xx_wo`.`object_id` = {$object_id} \n\t\t\t\t\tAND `xx_wo`.`object_manager` = '{$object_manager}'\n\t\t\t\t\tAND `xx_pu`.{$can_manage_object} = true ) ) ";
        } else {
            $str .= "\n OR ( EXISTS ( SELECT * FROM {$pu_table_name} `xx_pu` \n\t\t\t\tWHERE `xx_pu`.`user_id` IN {$all_ids} \n\t\t\t\t\tAND `xx_pu`.`project_id` = {$project_id} \n\t\t\t\t\tAND `xx_pu`.{$can_manage_object} = true ) ) ";
        }
    }
    // check account permissions in case of emails
    if ($manager instanceof MailContents) {
        $maccTableName = MailAccountUsers::instance()->getTableName(true);
        $str .= "\n OR EXISTS(SELECT `id` FROM {$maccTableName} WHERE `account_id` = {$object_table_name}.`account_id` AND `user_id` = {$user_id})";
        if (user_config_option('view deleted accounts emails', null, $user_id)) {
            $str .= "\n OR ((SELECT count(*) FROM `" . TABLE_PREFIX . "mail_accounts` WHERE `id` = {$object_table_name}.`account_id`) = 0) AND `created_by_id` = {$user_id}";
        }
    }
    $hookargs = array('manager' => $manager, 'access_level' => $access_level, 'user' => $user, 'project_id' => $project_id, 'table_alias' => $table_alias);
    Hook::fire('permissions_sql', $hookargs, $str);
    return ' (' . $str . ') ';
}
Exemplo n.º 6
0
 function getProjectIdsByUser(User $user, $additional_conditions = null, $order_by = null)
 {
     $projects_table = Projects::instance()->getTableName(true);
     $project_users_table = ProjectUsers::instance()->getTableName(true);
     $group_users_table = GroupUsers::instance()->getTableName(true);
     $projects = array();
     $usercond = "({$project_users_table}.`user_id` = " . DB::escape($user->getId()) . ")";
     $groupcond = "({$project_users_table}.`user_id` IN (SELECT `group_id` FROM {$group_users_table} WHERE {$group_users_table}.`user_id` = " . DB::escape($user->getId()) . "))";
     $commoncond = "{$projects_table}.`id` = {$project_users_table}.`project_id`";
     $sql = "SELECT {$projects_table}.`id` as `id` FROM {$projects_table}, {$project_users_table} WHERE {$commoncond} AND ({$usercond} OR {$groupcond}) ";
     if (trim($additional_conditions) != '') {
         $sql .= " AND ({$additional_conditions})";
     }
     // if
     if ($order_by) {
         $sql .= " ORDER BY '" . $order_by;
     } else {
         $sql .= " ORDER BY {$projects_table}.`name`";
     }
     $rows = DB::executeAll($sql);
     $ids = array();
     foreach ($rows as $row) {
         $ids[] = $row['id'];
     }
     return $ids;
 }
Exemplo n.º 7
0
 function getAllSubWorkspacesQuery($active = true, $user = null, $additional_conditions = null)
 {
     $addcond = $additional_conditions == null ? "" : "AND " . $additional_conditions;
     $id = $this->getId();
     $table = $this->getTableName(true);
     $condition = "(`p1` = {$id} OR `p2` = {$id} OR `p3` = {$id} OR `p4` = {$id} OR `p5` = {$id} OR `p6` = {$id} OR `p7` = {$id} OR `p8` = {$id} OR `p9` = {$id} OR `p10` = {$id})";
     if ($user instanceof User) {
         $pu_tbl = ProjectUsers::instance()->getTableName(true);
         $uquery = $user->getWorkspacesQuery();
         $condition .= " AND `id` IN ({$uquery}) {$addcond}";
     }
     if ($active !== null) {
         if ($active) {
             $condition .= " AND `completed_on` = " . DB::escape(EMPTY_DATETIME);
         } else {
             $condition .= " AND `completed_on` <> " . DB::escape(EMPTY_DATETIME);
         }
     }
     $query = "SELECT `id` FROM {$table} WHERE {$condition}";
     return $query;
 }
Exemplo n.º 8
0
 /**
  * This function will return paginated result. Result is an array where first element is 
  * array of returned object and second populated pagination object that can be used for 
  * obtaining and rendering pagination data using various helpers.
  * 
  * Items and pagination array vars are indexed with 0 for items and 1 for pagination
  * because you can't use associative indexing with list() construct
  *
  * @access public
  * @param array $arguments Query argumens (@see find()) Limit and offset are ignored!
  * @param integer $items_per_page Number of items per page
  * @param integer $current_page Current page number
  * @return array
  */
 function paginate($arguments = null, $items_per_page = 10, $current_page = 1)
 {
     if (isset($this) && instance_of($this, 'ProjectUsers')) {
         return parent::paginate($arguments, $items_per_page, $current_page);
     } else {
         return ProjectUsers::instance()->paginate($arguments, $items_per_page, $current_page);
         //$instance =& ProjectUsers::instance();
         //return $instance->paginate($arguments, $items_per_page, $current_page);
     }
     // if
 }
 function generate_ical_export_url()
 {
     $ws = active_project();
     if ($ws == null) {
         $cal_name = logged_user()->getDisplayName();
         $ws_ids = 0;
     } else {
         $cal_name = Projects::findById($ws->getId())->getName();
         if (isset($_GET['inc_subws']) && $_GET['inc_subws'] == 'true') {
             $ws_ids = $ws->getAllSubWorkspacesQuery(true, logged_user(), ProjectUsers::instance()->getTableName(true) . ".`can_read_events` = 1");
         } else {
             $ws_ids = $ws->getId();
         }
     }
     $token = logged_user()->getToken();
     $url = ROOT_URL . "/" . PUBLIC_FOLDER . "/tools/ical_export.php?cal={$ws_ids}&n={$cal_name}&t={$token}";
     $obj = array("url" => $url);
     ajx_extra_data($obj);
     ajx_current("empty");
 }
Exemplo n.º 10
0
 /**
  * Return users grouped by company, from the project IDs
  *
  * @param void
  * @return array
  */
 static function getGroupedByCompanyFromProjectIds($project_ids)
 {
     // Get user ids for project and subprojects
     $project_users_table = ProjectUsers::instance()->getTableName(true);
     $sql = "SELECT DISTINCT user_id FROM {$project_users_table} WHERE (`project_id` in ( {$project_ids} ) ) ";
     $rows = DB::executeAll($sql);
     $user_csvs = '';
     if (is_array($rows)) {
         foreach ($rows as $row) {
             $user_csvs .= ',' . $row['user_id'];
         }
         // foreach
     } else {
         return null;
     }
     if ($user_csvs) {
         //remove first comma
         $user_csvs = substr($user_csvs, 1);
     }
     $users = Users::findAll(array('conditions' => array('`id` in (' . $user_csvs . ')'), 'order' => 'display_name'));
     // findAll
     $result = array();
     if ($users) {
         foreach ($users as $user) {
             $comp_id = $user->getCompanyId();
             if (array_var($result, $comp_id, null)) {
                 $result[$comp_id][] = $user;
             } else {
                 // the first one
                 $result[$comp_id] = array($user);
             }
         }
         // foreach
     }
     return count($result) ? $result : null;
 }
Exemplo n.º 11
0
 /**
  * Return the user's workspaces query that returns user's workspaces ids.
  * @param bool $active If null, all projects; if true, only active, if false, only archived
  * @return string
  */
 function getWorkspacesQuery($active = null, $additional_conditions = null)
 {
     //return $this->getActiveProjectIdsCSV();
     $project_users_table = ProjectUsers::instance()->getTableName(true);
     $group_users_table = GroupUsers::instance()->getTableName(true);
     $usercond = "({$project_users_table}.`user_id` = " . DB::escape($this->getId()) . ")";
     $groupcond = "({$project_users_table}.`user_id` IN (SELECT `group_id` FROM {$group_users_table} WHERE {$group_users_table}.`user_id` = " . DB::escape($this->getId()) . "))";
     $addcond = $additional_conditions == null ? "" : "AND " . $additional_conditions;
     if ($active === null) {
         return "SELECT {$project_users_table}.`project_id` FROM {$project_users_table} WHERE ({$usercond} OR {$groupcond}) {$addcond}";
     } else {
         $projects_table = Projects::instance()->getTableName(true);
         $empty_date = DB::escape(EMPTY_DATETIME);
         $active_cond = $active ? "{$projects_table}.`completed_on` = {$empty_date}" : "{$projects_table}.`completed_on` <> {$empty_date}";
         $projectcond = "({$project_users_table}.`project_id` = {$projects_table}.`id` AND  {$active_cond})";
         return "SELECT {$project_users_table}.`project_id` FROM {$project_users_table}, {$projects_table} WHERE ({$usercond} OR {$groupcond}) AND {$projectcond} {$addcond}";
     }
 }
 function getUserWorkspaceColorsCSV($user)
 {
     $project_users_table = ProjectUsers::instance()->getTableName(true);
     $pids = $user->getWorkspacesQuery();
     return $this->getWorkspaceColorsCSV($pids);
 }
Exemplo n.º 13
0
 /**
  * Copy project
  *
  * @param void
  * @return null
  */
 function copy()
 {
     trace(__FILE__, "copy():begin");
     if (!Project::canAdd(logged_user())) {
         flash_error(lang('no access permissions'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     $this->setTemplate('copy_project');
     $this->setLayout('administration');
     $project_data = array_var($_POST, 'project');
     tpl_assign('project_data', $project_data);
     // Submitted...
     if (is_array($project_data)) {
         $source = Projects::findById($project_data['source']);
         if (!$source instanceof Project) {
             flash_error(lang('project dnx'));
             $this->redirectTo('administration', 'projects');
         }
         // if
         try {
             $shift_dates = isset($project_data['shift_dates']) ? $project_data['shift_dates'] == 'checked' : false;
             $copy_details = isset($project_data['copy_details']) ? $project_data['copy_details'] == 'checked' : false;
             $copy_tasks = isset($project_data['copy_tasks']) ? $project_data['copy_tasks'] == 'checked' : false;
             $copy_milestones = isset($project_data['copy_milestones']) ? $project_data['copy_milestones'] == 'checked' : false;
             $copy_messages = isset($project_data['copy_messages']) ? $project_data['copy_messages'] == 'checked' : false;
             $copy_links = isset($project_data['copy_links']) ? $project_data['copy_links'] == 'checked' : false;
             $copy_files = isset($project_data['copy_files']) ? $project_data['copy_files'] == 'checked' : false;
             $copy_users = isset($project_data['copy_users']) ? $project_data['copy_users'] == 'checked' : false;
             $copy_pages = isset($project_data['copy_pages']) ? $project_data['copy_pages'] == 'checked' : false;
             DB::beginWork();
             $project = new Project();
             $new_name = lang('projects copy new name', $source->getName());
             $new_name .= date(' z H:i:s');
             $project->setName($new_name);
             if ($copy_details) {
                 $project->setDescription($source->getDescription());
                 $project->setPriority($source->getPriority());
                 $project->setShowDescriptionInOverview($source->getShowDescriptionInOverview());
             }
             $project->save();
             $project_id = $project->getId();
             $add_seconds = 0;
             if (isset($project_data['add_days'])) {
                 $add_days = 0 + trim($project_data['add_days']);
                 $add_seconds = $add_days * 24 * 60 * 60;
             }
             $source_created_on = $source->getCreatedOn();
             //var_dump($source_created_on);
             $milestone_map = array(0 => 0);
             // project milestones
             if ($copy_milestones) {
                 $source_milestones = $source->getAllMilestones();
                 if (is_array($source_milestones)) {
                     foreach ($source_milestones as $source_milestone) {
                         $milestone = new ProjectMilestone();
                         //$milestone->copy($source_milestone);
                         $milestone->setName($source_milestone->getName());
                         $milestone->setDescription($source_milestone->getDescription());
                         if ($shift_dates) {
                             trace(__FILE__, "copy():shift dates");
                             $milestone->setDueDate(DateTimeValueLib::now());
                             $seconds = $source_milestone->getDueDate()->difference($source_created_on);
                             $milestone->getDueDate()->advance($seconds);
                         } else {
                             $milestone->setDueDate($source_milestone->getDueDate());
                         }
                         $milestone->getDueDate()->advance($add_seconds);
                         $milestone->setIsPrivate($source_milestone->getIsPrivate());
                         $milestone->setAssignedToUserId($source_milestone->getAssignedToUserId());
                         $milestone->setAssignedToCompanyId($source_milestone->getAssignedToCompanyId());
                         $milestone->setProjectId($project_id);
                         $milestone->save();
                         $milestone_map[$source_milestone->getId()] = $milestone->getId();
                     }
                     // foreach
                 }
                 // if
             }
             // if
             // project tasks
             if ($copy_tasks) {
                 $source_task_lists = $source->getAllTaskLists();
                 if (is_array($source_task_lists)) {
                     foreach ($source_task_lists as $source_task_list) {
                         $task_list = new ProjectTaskList();
                         //$task_list->copy($source_milestone);
                         $task_list->setName($source_task_list->getName());
                         $task_list->setPriority($source_task_list->getPriority());
                         $task_list->setDescription($source_task_list->getDescription());
                         if ($copy_milestones) {
                             $task_list->setMilestoneId($milestone_map[$source_task_list->getMilestoneId()]);
                         }
                         $task_list->setDueDate($source_task_list->getDueDate());
                         if ($task_list->getDueDate() instanceof DateTimeValue) {
                             if ($shift_dates) {
                                 trace(__FILE__, "copy():task list shift dates");
                                 $task_list->setDueDate(DateTimeValueLib::now());
                                 $seconds = $source_task_list->getDueDate()->difference($source_created_on);
                                 $task_list->getDueDate()->advance($seconds);
                             }
                             $task_list->getDueDate()->advance($add_seconds);
                         }
                         $task_list->setIsPrivate($source_task_list->getIsPrivate());
                         $task_list->setOrder($source_task_list->getOrder());
                         $task_list->setProjectId($project_id);
                         $task_list->save();
                         $source_tasks = $source_task_list->getTasks();
                         if (is_array($source_tasks)) {
                             foreach ($source_tasks as $source_task) {
                                 $task = new ProjectTask();
                                 $task->setOrder($source_task->getOrder());
                                 $task->setDueDate($source_task->getDueDate());
                                 if ($task->getDueDate() instanceof DateTimeValue) {
                                     if ($shift_dates) {
                                         trace(__FILE__, "copy():task shift dates");
                                         $task->setDueDate(DateTimeValueLib::now());
                                         $seconds = $source_task->getDueDate()->difference($source_created_on);
                                         $task->getDueDate()->advance($seconds);
                                     }
                                     $task->getDueDate()->advance($add_seconds);
                                 }
                                 $task->setText($source_task->getText());
                                 $task->getAssignedToUserId($source_task->getAssignedToUserId());
                                 $task->getAssignedToCompanyId($source_task->getAssignedToCompanyId());
                                 $task_list->attachTask($task);
                             }
                         }
                     }
                     // foreach
                 }
                 // if
             }
             // if
             // project messages
             if ($copy_messages) {
                 $source_messages = $source->getAllMessages();
                 if (is_array($source_messages)) {
                     foreach ($source_messages as $source_message) {
                         $message = new ProjectMessage();
                         //$message->copy($source_message);
                         $message->setTitle($source_message->getTitle());
                         $message->setText($source_message->getText());
                         $message->setAdditionalText($source_message->getAdditionalText());
                         if ($copy_milestones) {
                             $message->setMilestoneId($milestone_map[$source_message->getMilestoneId()]);
                         }
                         $message->setIsImportant($source_message->getIsImportant());
                         $message->setIsPrivate($source_message->getIsPrivate());
                         $message->setCommentsEnabled($source_message->getCommentsEnabled());
                         $message->setAnonymousCommentsEnabled($source_message->getAnonymousCommentsEnabled());
                         $message->setProjectId($project_id);
                         $message->save();
                     }
                     // foreach
                 }
                 // if
             }
             // if
             // project links
             if ($copy_links) {
                 $source_links = ProjectLinks::getAllProjectLinks($source);
                 if (is_array($source_links)) {
                     foreach ($source_links as $source_link) {
                         $link = new ProjectLink();
                         //$folder->copy($source_link);
                         $link->setTitle($source_link->getTitle());
                         $link->setUrl($source_link->getUrl());
                         $link->setProjectId($project_id);
                         $link->save();
                     }
                     // foreach
                 }
                 // if
             }
             // if
             // project folders & files
             if ($copy_files) {
                 $folder_map = array(0 => 0);
                 $source_folders = $source->getFolders();
                 if (is_array($source_folders)) {
                     foreach ($source_folders as $source_folder) {
                         $folder = new ProjectFolder();
                         //$folder->copy($source_folder);
                         $folder->setName($source_folder->getName());
                         $folder->setProjectId($project_id);
                         $folder->save();
                         $folder_map[$source_folder->getId()] = $folder->getId();
                     }
                     // foreach
                 }
                 // if
                 $source_files = ProjectFiles::getAllFilesByProject($source);
                 if (is_array($source_files)) {
                     foreach ($source_files as $source_file) {
                         $file = new ProjectFile();
                         $file->setProjectId($project_id);
                         $file->setFolderId($folder_map[$source_file->getFolderId()]);
                         $file->setFileName($source_file->getFileName());
                         $file->setDescription($source_file->getDescription());
                         $file->setIsPrivate($source_file->getIsPrivate());
                         $file->setIsImportant($source_file->getIsImportant());
                         $file->setIsLocked($source_file->getIsLocked());
                         $file->setIsVisible($source_file->getIsVisible());
                         $file->setExpirationTime($source_file->getExpirationTime());
                         $file->setCommentsEnabled($source_file->getCommentsEnabled());
                         $file->setAnonymousCommentsEnabled($source_file->getAnonymousCommentsEnabled());
                         $file->save();
                         $source_revision = $source_file->getLastRevision();
                         if ($source_revision instanceof ProjectFileRevision) {
                             $revision = new ProjectFileRevision();
                             $revision->setFileId($file->getId());
                             $revision->setRevisionNumber($source_revision->getRevisionNumber());
                             $revision->setRepositoryId($source_revision->getRepositoryId());
                             $revision->setFilesize($source_revision->getFilesize());
                             $revision->setFilename($source_revision->getFileName());
                             $revision->setTypeString($source_revision->getTypeString());
                             $revision->setThumbFilename($source_revision->getThumbFilename());
                             $revision->setFileTypeId($source_revision->getFileTypeId());
                             $revision->setComment($source_revision->getComment());
                             $revision->save();
                         }
                     }
                     // foreach
                 }
                 // if
             }
             // if
             if ($copy_pages) {
                 $source_pages = Wiki::getAllProjectPages($source);
                 if (is_array($source_pages)) {
                     foreach ($source_pages as $source_page) {
                         $page = new WikiPage();
                         $page->setProjectId($project_id);
                         $page->setProjectIndex($source_page->getProjectIndex());
                         $page->setProjectSidebar($source_page->getProjectSidebar());
                         if (plugin_active('tags')) {
                             //$page->setTags($source_page->getTagNames());
                         }
                         //Make a new revision of this page
                         $revision = $page->makeRevision();
                         $source_revision = $source_page->getLatestRevision();
                         //Set attributes
                         $revision->setName($source_revision->getName());
                         $revision->setContent($source_revision->getContent());
                         $revision->setLogMessage($source_revision->getLogMessage());
                         //Save the page
                         $page->save();
                     }
                     // foreach
                 }
                 // if
             }
             // if
             if ($copy_users) {
                 $source_companies = ProjectCompanies::instance()->getCompaniesByProject($source);
                 if (is_array($source_companies)) {
                     foreach ($source_companies as $source_company) {
                         $project_company = new ProjectCompany();
                         $project_company->setCompanyId($source_company->getId());
                         $project_company->setProjectId($project_id);
                         $project_company->save();
                     }
                     // foreach
                 }
                 $source_users = ProjectUsers::instance()->getUsersByProject($source);
                 if (is_array($source_users)) {
                     foreach ($source_users as $source_user) {
                         $project_user = new ProjectUser();
                         $project_user->setUserId($source_user->getId());
                         $project_user->setProjectId($project_id);
                         $project_user->save();
                     }
                     // foreach
                 }
             }
             /*
                       $permissions = array_keys(PermissionManager::getPermissionsText());
                       $auto_assign_users = owner_company()->getAutoAssignUsers();
                       
                       // We are getting the list of auto assign users. If current user is not in the list
                       // add it. He's creating the project after all...
                       if (is_array($auto_assign_users)) {
                         $auto_assign_logged_user = false;
                         foreach ($auto_assign_users as $user) {
                           if ($user->getId() == logged_user()->getId()) {
                             $auto_assign_logged_user = true;
                           }
                         } // if
                         if (!$auto_assign_logged_user) {
                           $auto_assign_users[] = logged_user();
                         }
                       } else {
                         $auto_assign_users[] = logged_user();
                       } // if
                       
                       foreach ($auto_assign_users as $user) {
                         $project_user = new ProjectUser();
                         $project_user->setProjectId($project->getId());
                         $project_user->setUserId($user->getId());
                         if (is_array($permissions)) {
                           foreach ($permissions as $permission) {
                             $user = Users::findById($project_user->getUserId());
                             $user->setProjectPermission($project,$permission,true);
                           }
                         } // if
                         $project_user->save();
                       } // foreach
             */
             ApplicationLogs::createLog($project, null, ApplicationLogs::ACTION_ADD, false, true);
             DB::commit();
             flash_success(lang('success copy project', $source->getName(), $project->getName()));
             $this->redirectToUrl($project->getPermissionsUrl());
         } catch (Exception $e) {
             echo $e->getMessage();
             tpl_assign('error', $e);
             DB::rollback();
         }
         // try
     }
     // if (submitted)
 }