Beispiel #1
0
 public function save()
 {
     // Get all inputs
     $input = Input::all();
     // Retrive the project details
     $project = Project::find($input['project_id']);
     // Assign values
     $project->name = $input['name'];
     $project->project_type = $input['project_type'];
     $project->description = $input['description'];
     $project->client_name = $input['client_name'];
     $project->start_at = $input['start_at'];
     $project->complete_at = $input['complete_at'];
     // Identify if this project is on hold or not
     if (isset($input['status'])) {
         $project->status = 2;
     } else {
         $project->status = 1;
     }
     // Update the project details
     $project->save();
     // Assign each user in a project
     foreach (array_merge($input['developers'], $input['qc']) as $key => $value) {
         $user = ProjectUsers::firstOrCreate(array('project_id' => $input['project_id'], 'user_id' => $value));
         $user->key = Crypt::encrypt(time());
         $user->save();
     }
     // Redirect to project page with message
     return Redirect::to('/project/' . $project->slug)->with('flash_msg', 'This project was successfully updated!');
 }
 /**
  * Return activities of all active projects by user
  *
  * @param User $user
  * @param integer $count
  * @return array
  */
 function findActiveProjectsActivitiesByUser($user, $count = 30)
 {
     $type_filter = ProjectUsers::getVisibleTypesFilter($user, array(PROJECT_STATUS_ACTIVE));
     if ($type_filter) {
         $objects_table = TABLE_PREFIX . 'project_objects';
         $logs_table = TABLE_PREFIX . 'activity_logs';
         $count = (int) $count;
         if ($count < 1) {
             $count = 30;
         }
         // if
         return ActivityLogs::findBySQL("SELECT {$logs_table}.* FROM {$logs_table}, {$objects_table} WHERE {$logs_table}.object_id = {$objects_table}.id AND {$type_filter} AND {$objects_table}.state >= ? AND {$objects_table}.visibility >= ? ORDER BY {$logs_table}.created_on DESC LIMIT 0, {$count}", array(STATE_DELETED, $user->getVisibility()));
     } else {
         return null;
     }
     // if
 }
 /**
  * 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;
 }
 /**
  * Paginate attachments by project
  *
  * @param Project $project
  * @param User $user
  * @param integer $page
  * @param integer $per_page
  * @param integer $min_state
  * @return array
  */
 function paginateByProject($project, $user, $page = 1, $per_page = 30, $min_state = STATE_VISIBLE)
 {
     $attachments_table = TABLE_PREFIX . 'attachments';
     $project_objects_table = TABLE_PREFIX . 'project_objects';
     $type_filter = ProjectUsers::getVisibleTypesFilterByProject($user, $project);
     if ($type_filter) {
         $total = array_var(db_execute_one("SELECT COUNT({$attachments_table}.id) AS 'row_count' FROM {$attachments_table}, {$project_objects_table} WHERE {$attachments_table}.attachment_type = ? AND {$attachments_table}.parent_id = {$project_objects_table}.id AND {$type_filter} AND {$project_objects_table}.state >= ? AND {$project_objects_table}.visibility >= ?", ATTACHMENT_TYPE_ATTACHMENT, $min_state, $user->getVisibility()), 'row_count');
         if ($total) {
             $offset = ($page - 1) * $per_page;
             $attachments = Attachments::findBySQL("SELECT {$attachments_table}.* FROM {$attachments_table}, {$project_objects_table} WHERE {$attachments_table}.attachment_type = ? AND {$attachments_table}.parent_id = {$project_objects_table}.id AND {$type_filter} AND {$project_objects_table}.state >= ? AND {$project_objects_table}.visibility >= ? ORDER BY `created_on` DESC LIMIT {$offset}, {$per_page}", array(ATTACHMENT_TYPE_ATTACHMENT, $min_state, $user->getVisibility()));
             if ($attachments) {
                 return array($attachments, new Pager($page, $total, $per_page));
             }
             // if
         }
         // if
     }
     // if
     return array(null, new Pager(1, 0, $per_page));
 }
 /**
  * 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;
 }
 /**
  * Delete project - company relation
  * 
  * This function needs to remove relation from the database and all user - project relations
  *
  * @param void
  * @return boolean
  */
 function delete()
 {
     $company = $this->getCompany();
     $project = $this->getProject();
     if ($company instanceof Company && $project instanceof Project) {
         $users = $company->getUsers();
         if (is_array($users)) {
             foreach ($users as $user) {
                 $relation = ProjectUsers::findById(array('project_id' => $project->getId(), 'user_id' => $user->getId()));
                 //findById
                 if ($relation instanceof ProjectUser) {
                     $relation->delete();
                 }
                 // if
             }
             // foreach
         }
         // if
     }
     // if
     return parent::delete();
 }
 /**
  * Return array of company users on specific project
  *
  * @access public
  * @param Project $project
  * @return array
  */
 function getUsersOnProject(Project $project)
 {
     return ProjectUsers::getCompanyUsersByProject($this, $project);
 }
 function createWorkspace($ws_name, $parentWS_ids = null)
 {
     try {
         DB::beginWork();
         $color = rand(0, 24);
         $project_data = array('name' => $ws_name, 'description' => '', 'show_description_in_overview' => false, 'color' => $color);
         $project = new Project();
         $project->setFromAttributes($project_data);
         $project->save();
         $permission_columns = ProjectUsers::getPermissionColumns();
         $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
         $project->clearUsers();
         foreach ($auto_assign_users as $user) {
             $project_user = new ProjectUser();
             $project_user->setProjectId($project->getId());
             $project_user->setUserId($user->getId());
             if (is_array($permission_columns)) {
                 foreach ($permission_columns as $permission) {
                     $project_user->setColumnValue($permission, true);
                 }
             }
             // if
             $project_user->save();
         }
         // foreach
         $this->setParents($project, $parentWS_ids);
         $id_parent = $project->getPID($project->getDepth() - 1);
         $proj_id = $project->getId();
         ImportLogger::instance()->log("Workspace created: {$proj_id} {$ws_name} [{$id_parent}]");
         print "Workspace created: {$proj_id} {$ws_name} [{$id_parent}]\r\n";
         DB::commit();
     } catch (Exception $e) {
         print "ERROR: {$e}\r\n";
         DB::rollback();
     }
     return $proj_id;
 }
 /**
  * Delete from database
  *
  * @param void
  * @return boolean
  */
 function delete()
 {
     db_begin_work();
     $delete = parent::delete();
     if ($delete && !is_error($delete)) {
         unlink($this->getAvatarPath());
         unlink($this->getAvatarPath(true));
         ProjectUsers::deleteByUser($this);
         Assignments::deleteByUser($this);
         Subscriptions::deleteByUser($this);
         StarredObjects::deleteByUser($this);
         PinnedProjects::deleteByUser($this);
         UserConfigOptions::deleteByUser($this);
         Reminders::deleteByUser($this);
         search_index_remove($this->getId(), 'User');
         $cleanup = array();
         event_trigger('on_user_cleanup', array(&$cleanup));
         if (is_foreachable($cleanup)) {
             foreach ($cleanup as $table_name => $fields) {
                 foreach ($fields as $field) {
                     $condition = '';
                     if (is_array($field)) {
                         $id_field = array_var($field, 'id');
                         $name_field = array_var($field, 'name');
                         $email_field = array_var($field, 'email');
                         $condition = array_var($field, 'condition');
                     } else {
                         $id_field = $field . '_id';
                         $name_field = $field . '_name';
                         $email_field = $field . '_email';
                     }
                     // if
                     if ($condition) {
                         db_execute('UPDATE ' . TABLE_PREFIX . "{$table_name} SET {$id_field} = 0, {$name_field} = ?, {$email_field} = ? WHERE {$id_field} = ? AND {$condition}", $this->getName(), $this->getEmail(), $this->getId());
                     } else {
                         db_execute('UPDATE ' . TABLE_PREFIX . "{$table_name} SET {$id_field} = 0, {$name_field} = ?, {$email_field} = ? WHERE {$id_field} = ?", $this->getName(), $this->getEmail(), $this->getId());
                     }
                     // if
                 }
                 // foreach
             }
             // foreach
         }
         // if
         db_commit();
         return true;
     } else {
         db_rollback();
         return $delete;
     }
     // if
 }
 /**
  * Return project day data
  *
  * @param User $user
  * @param Project $project
  * @param DateValue $day
  * @return array
  */
 function getProjectDayData($user, $project, $day)
 {
     $types = get_completable_project_object_types();
     $filter = ProjectUsers::getVisibleTypesFilterByproject($user, $project, $types);
     if ($filter) {
         $filter .= db_prepare_string(' AND (state >= ? AND visibility >= ?)', array(STATE_VISIBLE, $user->getVisibility()));
         return Calendar::getDayData($day, $filter);
     } else {
         return null;
     }
     // if
 }
Beispiel #11
0
 /**
  * Delete this object
  *
  * @param void
  * @return boolean
  */
 function delete()
 {
     if ($this->isAccountOwner()) {
         return false;
     }
     // if
     if ($this->isTaggable()) {
         $this->clearTags();
     }
     // if
     // TODO check all things that need to be deleted
     // ticket subscriptions
     // message subscriptions
     // project-user association
     $this->deleteAvatar();
     $this->clearImValues();
     if ($this->hasUserAccount()) {
         ProjectUsers::clearByUser($this->getUserAccount());
         MessageSubscriptions::clearByUser($this->getUserAccount());
         $this->getUserAccount()->delete();
     }
     // if
     return parent::delete();
 }
 /**
  * Show update permissions page
  *
  * @param void
  * @return null
  */
 function update_permissions()
 {
     $user = Users::findById(get_id());
     if (!$user instanceof User) {
         flash_error(lang('user dnx'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     if (!$user->canUpdatePermissions(logged_user())) {
         flash_error(lang('no access permissions'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     $company = $user->getCompany();
     if (!$company instanceof Company) {
         flash_error(lang('company dnx'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     $projects = $company->getProjects();
     if (!is_array($projects) || !count($projects)) {
         flash_error(lang('no projects owned by company'));
         $this->redirectToReferer($company->getViewUrl());
     }
     // if
     $permissions = PermissionManager::getPermissionsText();
     $redirect_to = array_var($_GET, 'redirect_to');
     if (trim($redirect_to) == '' || !is_valid_url($redirect_to)) {
         $redirect_to = $user->getCardUrl();
     }
     // if
     tpl_assign('user', $user);
     tpl_assign('company', $company);
     tpl_assign('projects', $projects);
     tpl_assign('permissions', $permissions);
     tpl_assign('redirect_to', $redirect_to);
     if (array_var($_POST, 'submitted') == 'submitted') {
         DB::beginWork();
         ProjectUsers::clearByUser($user);
         foreach ($projects as $project) {
             $permission_count = 0;
             $permission_all = array_var($_POST, 'project_permissions_' . $project->getId() . '_all') == 'checked';
             foreach ($permissions as $permission_name => $permission_text) {
                 $permission_value = $permission_all || array_var($_POST, 'project_permission_' . $project->getId() . '_' . $permission_name) == 'checked';
                 if ($permission_value) {
                     $permission_count++;
                 }
                 $user->setProjectPermission($project, $permission_name, $permission_value);
             }
             // foreach
             if ($permission_count > 0) {
                 $relation = new ProjectUser();
                 $relation->setProjectId($project->getId());
                 $relation->setUserId($user->getId());
                 $relation->save();
             }
         }
         // if
         DB::commit();
         flash_success(lang('success user permissions updated'));
         $this->redirectToUrl($redirect_to);
     }
     // if
 }
Beispiel #13
0
 /**
  * Clear project level permissions
  *
  * @param void
  * @return null
  */
 function clearPermissions()
 {
     ProjectCompanies::clearByProject($this);
     ProjectUsers::clearByProject($this);
 }
 /**
  * Add user
  *
  * @access public
  * @param void
  * @return null
  */
 function add()
 {
     $this->setTemplate('add_user');
     $company = Companies::findById(get_id('company_id'));
     if (!$company instanceof Company) {
         flash_error(lang('company dnx'));
         $this->redirectTo('administration');
     }
     // if
     if (!User::canAdd(logged_user(), $company)) {
         flash_error(lang('no access permissions'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     $user = new User();
     $user_data = array_var($_POST, 'user');
     if (!is_array($user_data)) {
         $user_data = array('password_generator' => 'random', 'company_id' => $company->getId(), 'timezone' => $company->getTimezone());
         // array
     }
     // if
     $projects = $company->getProjects();
     $permissions = ProjectUsers::getNameTextArray();
     tpl_assign('user', $user);
     tpl_assign('company', $company);
     tpl_assign('projects', $projects);
     tpl_assign('permissions', $permissions);
     tpl_assign('user_data', $user_data);
     if (is_array(array_var($_POST, 'user'))) {
         $user->setFromAttributes($user_data);
         $user->setCompanyId($company->getId());
         try {
             // Generate random password
             if (array_var($user_data, 'password_generator') == 'random') {
                 $password = substr(sha1(uniqid(rand(), true)), rand(0, 25), 13);
                 // Validate user input
             } else {
                 $password = array_var($user_data, 'password');
                 if (trim($password) == '') {
                     throw new Error(lang('password value required'));
                 }
                 // if
                 if ($password != array_var($user_data, 'password_a')) {
                     throw new Error(lang('passwords dont match'));
                 }
                 // if
             }
             // if
             $user->setPassword($password);
             DB::beginWork();
             $user->save();
             ApplicationLogs::createLog($user, null, ApplicationLogs::ACTION_ADD);
             if (is_array($projects)) {
                 foreach ($projects as $project) {
                     if (array_var($user_data, 'project_permissions_' . $project->getId()) == 'checked') {
                         $relation = new ProjectUser();
                         $relation->setProjectId($project->getId());
                         $relation->setUserId($user->getId());
                         foreach ($permissions as $permission => $permission_text) {
                             $permission_value = array_var($user_data, 'project_permission_' . $project->getId() . '_' . $permission) == 'checked';
                             $setter = 'set' . Inflector::camelize($permission);
                             $relation->{$setter}($permission_value);
                         }
                         // foreach
                         $relation->save();
                     }
                     // if
                 }
                 // forech
             }
             // if
             DB::commit();
             // Send notification...
             try {
                 if (array_var($user_data, 'send_email_notification')) {
                     Notifier::newUserAccount($user, $password);
                 }
                 // if
             } catch (Exception $e) {
             }
             // try
             flash_success(lang('success add user', $user->getDisplayName()));
             $this->redirectToUrl($company->getViewUrl());
             // Translate to profile page
         } catch (Exception $e) {
             DB::rollback();
             tpl_assign('error', $e);
         }
         // try
     }
     // if
 }
 /**
  * Manage repository users
  *
  * @param void
  * @return null
  */
 function repository_users()
 {
     if ($this->active_repository->isNew()) {
         flash_error('Repository does not exist');
         $this->redirectToReferer(SOURCE_MODULE_PATH);
     }
     // if
     if (!$this->active_repository->canEdit($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     $this->wireframe->addPageAction(lang('Browse repository'), $this->active_repository->getBrowseUrl(), null);
     $this->wireframe->addPageAction(lang('Commit History'), $this->active_repository->getHistoryUrl());
     $source_users = SourceUsers::findByRepository($this->active_repository);
     $distinct_repository_users = $this->active_repository->getDistinctUsers();
     // loop through already mapped users and remove them from repository users
     foreach ($source_users as $source_user) {
         $mapped_user_key = array_search($source_user->getRepositoryUser(), $distinct_repository_users);
         if ($mapped_user_key !== false) {
             unset($distinct_repository_users[$mapped_user_key]);
         }
         // if
     }
     // foreach
     $this->smarty->assign(array('source_users' => $source_users, 'repository_users' => $distinct_repository_users, 'system_users' => ProjectUsers::findByProject($this->active_project), 'repository_user_add_url' => assemble_url('repository_user_add', array('project_id' => $this->active_project->getId(), 'repository_id' => $this->active_repository->getId()))));
 }
Beispiel #16
0
/**
 * Tells whether a user can assign a task to another user or company in a workspace.
 * 
 * @param $user User to which to check permissions
 * @param $workspace
 * @param $assignee
 * @return boolean
 */
function can_assign_task(User $user, Project $workspace, $assignee)
{
    if (!$assignee instanceof User && !$assignee instanceof Company) {
        return true;
    }
    if ($assignee instanceof Company) {
        $company = $assignee;
    } else {
        if ($assignee->getId() == $user->getId()) {
            return true;
        }
        // alow user to assign to himself
        $company = $assignee->getCompany();
    }
    $is_owner = $company->getId() == Companies::getOwnerCompany()->getId();
    $permissions = ProjectUsers::getByUserAndProject($workspace, $user);
    if ($permissions instanceof ProjectUser) {
        if ($is_owner) {
            if ($permissions->getCanAssignToOwners()) {
                return true;
            }
        } else {
            if ($permissions->getCanAssignToOther()) {
                return true;
            }
        }
    }
    $groups = GroupUsers::getGroupsByUser($user->getId());
    if (is_array($groups) && count($groups) > 0) {
        //user belongs to at least one group
        foreach ($groups as $group) {
            $permissions = ProjectUsers::getByUserAndProject($workspace, $group);
            if ($permissions instanceof ProjectUser) {
                if ($is_owner) {
                    if ($permissions->getCanAssignToOwners()) {
                        return true;
                    }
                } else {
                    if ($permissions->getCanAssignToOther()) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}
 /**
  * Return manager instance
  *
  * @access protected
  * @param void
  * @return ProjectUsers 
  */
 function manager()
 {
     if (!$this->manager instanceof ProjectUsers) {
         $this->manager = ProjectUsers::instance();
     }
     return $this->manager;
 }
 /**
  * Serve iCal data
  *
  * @param void
  * @return null
  */
 function ical()
 {
     if ($this->active_project->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     $filter = ProjectUsers::getVisibleTypesFilterByProject($this->logged_user, $this->active_project, get_completable_project_object_types());
     if ($filter) {
         $objects = ProjectObjects::find(array('conditions' => array($filter . ' AND completed_on IS NULL AND state >= ? AND visibility >= ?', STATE_VISIBLE, $this->logged_user->getVisibility()), 'order' => 'priority DESC'));
         render_icalendar($this->active_project->getName() . ' ' . lang('calendar'), $objects);
         die;
     } else {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
 }
 function getByUserAndProject($project, $user)
 {
     return ProjectUsers::findOne(array('conditions' => array('`user_id` = ? AND `project_id` = ? ', $user->getId(), $project->getId())));
 }
 /**
  * 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
 }
 /**
  * Show update permissions page
  *
  * @param void
  * @return null
  */
 function update_permissions()
 {
     $user = Users::findById(get_id());
     if (!$user instanceof User) {
         flash_error(lang('user dnx'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     if (!$user->canUpdatePermissions(logged_user())) {
         flash_error(lang('no access permissions'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     $company = $user->getCompany();
     if (!$company instanceof Company) {
         flash_error(lang('company dnx'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     $projects = $company->getProjects();
     if (!is_array($projects) || !count($projects)) {
         flash_error(lang('no projects owned by company'));
         $this->redirectToReferer($company->getViewUrl());
     }
     // if
     $permissions = ProjectUsers::getNameTextArray();
     $redirect_to = array_var($_GET, 'redirect_to');
     if (trim($redirect_to) == '' || !is_valid_url($redirect_to)) {
         $redirect_to = $user->getCardUrl();
     }
     // if
     tpl_assign('user', $user);
     tpl_assign('company', $company);
     tpl_assign('projects', $projects);
     tpl_assign('permissions', $permissions);
     tpl_assign('redirect_to', $redirect_to);
     if (array_var($_POST, 'submitted') == 'submitted') {
         DB::beginWork();
         foreach ($projects as $project) {
             $relation = ProjectUsers::findById(array('project_id' => $project->getId(), 'user_id' => $user->getId()));
             // findById
             if (array_var($_POST, 'project_permissions_' . $project->getId()) == 'checked') {
                 if (!$relation instanceof ProjectUser) {
                     $relation = new ProjectUser();
                     $relation->setProjectId($project->getId());
                     $relation->setUserId($user->getId());
                 }
                 // if
                 foreach ($permissions as $permission => $permission_text) {
                     $permission_value = array_var($_POST, 'project_permission_' . $project->getId() . '_' . $permission) == 'checked';
                     $setter = 'set' . Inflector::camelize($permission);
                     $relation->{$setter}($permission_value);
                 }
                 // foreach
                 $relation->save();
             } else {
                 if ($relation instanceof ProjectUser) {
                     $relation->delete();
                 }
                 // if
             }
             // if
         }
         // if
         DB::commit();
         flash_success(lang('success user permissions updated'));
         $this->redirectToUrl($redirect_to);
     }
     // if
 }
 /**
  * Returns array of companies that are involved in project
  * @param Project $project
  * @return array
  */
 function findByProject($project)
 {
     $people = ProjectUsers::findUsersByProject($project);
     if (is_foreachable($people)) {
         $company_ids = array();
         foreach ($people as $person) {
             if (!in_array($person->getCompanyId(), $company_ids)) {
                 $company_ids[] = $person->getCompanyId();
             }
             // if
         }
         // foreach
         return Companies::findByIds($company_ids);
     } else {
         return null;
     }
     // if
 }
 /**
  * Remove company from project
  *
  * @param void
  * @return null
  */
 function remove_company()
 {
     if (!active_project()->canChangePermissions(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $project = Projects::findById(get_id('project_id'));
     if (!$project instanceof Project) {
         flash_error(lang('project dnx'));
         ajx_current("empty");
         return;
     }
     // if
     $company = Companies::findById(get_id('company_id'));
     if (!$company instanceof Company) {
         flash_error(lang('company dnx'));
         ajx_current("empty");
         return;
     }
     // if
     $project_company = ProjectCompanies::findById(array('project_id' => $project->getId(), 'company_id' => $company->getId()));
     if (!$project_company instanceof ProjectCompany) {
         flash_error(lang('company not on project'));
         ajx_current("empty");
         return;
     }
     // if
     try {
         DB::beginWork();
         $project_company->delete();
         $users = ProjectUsers::getCompanyUsersByProject($company, $project);
         if (is_array($users)) {
             foreach ($users as $user) {
                 $project_user = ProjectUsers::findById(array('project_id' => $project->getId(), 'user_id' => $user->getId()));
                 if ($project_user instanceof ProjectUser) {
                     $project_user->delete();
                 }
             }
             // foreach
         }
         // if
         DB::commit();
         flash_success(lang('success remove company from project'));
         ajx_current("reload");
     } catch (Exception $e) {
         DB::rollback();
         flash_error(lang('error remove company from project'));
         ajx_current("empty");
     }
     // try
 }
 function search($search_for, $type, $user, $page = 1, $per_page = 30, $search_object_type = '', $search_under_project_id = '', $datesort = '')
 {
     //EOF:mod 20120711
     $page = (int) $page;
     $per_page = (int) $per_page;
     $search_index_table = TABLE_PREFIX . 'search_index';
     $offset = ($page - 1) * $per_page;
     // Search in projects
     if ($type == 'ProjectObject') {
         $type_filter = ProjectUsers::getVisibleTypesFilter($user, array(PROJECT_STATUS_ACTIVE, PROJECT_STATUS_PAUSED, PROJECT_STATUS_COMPLETED, PROJECT_STATUS_CANCELED));
         if (empty($type_filter)) {
             return array(null, new Pager(1, 0, $per_page));
         }
         // if
         if (strlen($search_for) <= 2) {
             return array(null, new Pager(1, 0, $per_page));
         }
         //BOF:mod 20111102
         // $search_for = str_replace(' ', '% %', $search_for);
         //EOF:mod 20111102
         $project_objects_table = TABLE_PREFIX . 'project_objects';
         //$total_items = (integer) array_var(db_execute_one("SELECT COUNT($project_objects_table.id) AS 'row_count' FROM $project_objects_table, $search_index_table WHERE $type_filter AND MATCH ($search_index_table.content) AGAINST (? IN BOOLEAN MODE) AND $project_objects_table.id = $search_index_table.object_id AND $search_index_table.type = ? AND state >= ? AND visibility >= ?", $search_for, $type, STATE_VISIBLE, $user->getVisibility()), 'row_count');
         /*if (empty($search_object_type)){
           	$total_items = (integer) array_var(db_execute_one("SELECT COUNT($project_objects_table.id) AS 'row_count' FROM $project_objects_table, $search_index_table WHERE $type_filter AND MATCH ($search_index_table.content) AGAINST (? IN BOOLEAN MODE) AND $project_objects_table.id = $search_index_table.object_id AND $search_index_table.type = ? AND state >= ? AND visibility >= ?", $search_for, $type, STATE_VISIBLE, $user->getVisibility()), 'row_count');
           } else {
           	$total_items = (integer) array_var(db_execute_one("SELECT COUNT($project_objects_table.id) AS 'row_count' FROM $project_objects_table, $search_index_table WHERE $type_filter AND MATCH ($search_index_table.content) AGAINST (? IN BOOLEAN MODE) AND $project_objects_table.id = $search_index_table.object_id AND $search_index_table.type = ? AND state >= ? AND visibility >= ? AND $project_objects_table.type = ?", $search_for, $type, STATE_VISIBLE, $user->getVisibility(), $search_object_type), 'row_count');
           }*/
         $complete_str = '';
         if ($_GET['complete'] != '1') {
             $complete_str = " and healingcrystals_project_objects.completed_on is null and (healingcrystals_project_objects.completed_by_id is null or healingcrystals_project_objects.completed_by_id='0') and healingcrystals_project_objects.boolean_field_1 is null ";
         }
         $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
         mysql_select_db(DB_NAME);
         $query_main = "(select healingcrystals_sort_order_for_search.sort_order, if(healingcrystals_project_objects.completed_on is null, '0', '1'), '0' as new_order, healingcrystals_project_objects.* \n\t\t  \t\t from healingcrystals_project_objects " . (!empty($search_under_project_id) ? " inner join healingcrystals_projects on (healingcrystals_project_objects.project_id=healingcrystals_projects.id and  healingcrystals_project_objects.project_id='" . (int) $search_under_project_id . "') " : " ") . " inner join healingcrystals_search_index on healingcrystals_project_objects.id=healingcrystals_search_index.object_id \n\t\t  \t\t left join healingcrystals_sort_order_for_search on healingcrystals_sort_order_for_search.type=healingcrystals_project_objects.type \n\t\t\t\t where " . $type_filter . $complete_str . " \n\t\t\t\t and (healingcrystals_project_objects.name is not null) \n\t\t\t\t and (healingcrystals_project_objects.name like '%" . addslashes($search_for) . "%') \n\t\t\t\t and healingcrystals_search_index.type='" . $type . "' \n\t\t\t\t and healingcrystals_project_objects.state='" . STATE_VISIBLE . "' " . (empty($search_object_type) ? "" : " and healingcrystals_project_objects.type='" . $search_object_type . "' ") . " )\n\t\t\t\t UNION \n\t\t\t\t (select healingcrystals_sort_order_for_search.sort_order, if(healingcrystals_project_objects.completed_on is null, '0', '1'), '0' as new_order, healingcrystals_project_objects.* \n\t\t  \t\t from healingcrystals_project_objects " . (!empty($search_under_project_id) ? " inner join healingcrystals_projects on (healingcrystals_project_objects.project_id=healingcrystals_projects.id and  healingcrystals_project_objects.project_id='" . (int) $search_under_project_id . "') " : " ") . " inner join healingcrystals_search_index on healingcrystals_project_objects.id=healingcrystals_search_index.object_id \n\t\t  \t\t left join healingcrystals_sort_order_for_search on healingcrystals_sort_order_for_search.type=healingcrystals_project_objects.type \n\t\t\t\t where " . $type_filter . $complete_str . " \n\t\t\t\t and (healingcrystals_project_objects.body like '%" . addslashes($search_for) . "%') and \n\t\t\t\t (healingcrystals_project_objects.name is null or healingcrystals_project_objects.name='') \n\t\t\t\t and healingcrystals_search_index.type='" . $type . "' \n\t\t\t\t and healingcrystals_project_objects.state='" . STATE_VISIBLE . "' " . (empty($search_object_type) ? "" : " and healingcrystals_project_objects.type='" . $search_object_type . "' ") . " ) ";
         $count_query_main = "(select * \n\t\t  \t\t from healingcrystals_project_objects " . (!empty($search_under_project_id) ? " inner join healingcrystals_projects on (healingcrystals_project_objects.project_id=healingcrystals_projects.id and  healingcrystals_project_objects.project_id='" . (int) $search_under_project_id . "') " : " ") . " inner join healingcrystals_search_index on healingcrystals_project_objects.id=healingcrystals_search_index.object_id \n\t\t  \t\t left join healingcrystals_sort_order_for_search on healingcrystals_sort_order_for_search.type=healingcrystals_project_objects.type \n\t\t\t\t where " . $type_filter . $complete_str . " and (healingcrystals_project_objects.name is not null) \n\t\t\t\t and (healingcrystals_project_objects.name like '%" . addslashes($search_for) . "%') \n\t\t\t\t and healingcrystals_search_index.type='" . $type . "' \n\t\t\t\t and healingcrystals_project_objects.state='" . STATE_VISIBLE . "' " . (empty($search_object_type) ? "" : " and healingcrystals_project_objects.type='" . $search_object_type . "' ") . " )\n\t\t\t\t UNION \n\t\t\t\t (select * from healingcrystals_project_objects " . (!empty($search_under_project_id) ? " inner join healingcrystals_projects on (healingcrystals_project_objects.project_id=healingcrystals_projects.id and  healingcrystals_project_objects.project_id='" . (int) $search_under_project_id . "') " : " ") . " inner join healingcrystals_search_index on healingcrystals_project_objects.id=healingcrystals_search_index.object_id \n\t\t  \t\t left join healingcrystals_sort_order_for_search on healingcrystals_sort_order_for_search.type=healingcrystals_project_objects.type \n\t\t\t\t where " . $type_filter . $complete_str . " \n\t\t\t\t and (healingcrystals_project_objects.body like '%" . addslashes($search_for) . "%')  and \n\t\t\t\t (healingcrystals_project_objects.name is null or healingcrystals_project_objects.name='') \n\t\t\t\t and healingcrystals_search_index.type='" . $type . "' \n\t\t\t\t and healingcrystals_project_objects.state='" . STATE_VISIBLE . "' " . (empty($search_object_type) ? "" : " and healingcrystals_project_objects.type='" . $search_object_type . "' ") . " ) ";
         //BOF-20120216
         if (strpos($search_for, ' ') !== false) {
             $all_parts_in_name_string = '';
             $all_parts_in_body_string = '';
             $few_parts_in_name_string = '';
             $string_parts = explode(' ', $search_for);
             $query_parts_name = array();
             $query_parts_description = array();
             foreach ($string_parts as $part) {
                 $query_parts_name[] = "healingcrystals_project_objects.name like '%" . addslashes($part) . "%'";
                 $query_parts_description[] = "healingcrystals_project_objects.body like '%" . addslashes($part) . "%'";
             }
             $all_parts_in_name_string = implode(" and ", $query_parts_name);
             $all_parts_in_body_string = implode(" and ", $query_parts_description);
             $few_parts_in_name_string = implode(" or ", $query_parts_name);
             $few_parts_in_body_string = implode(" or ", $query_parts_description);
             $query_main = "(select distinct(healingcrystals_project_objects.id), healingcrystals_sort_order_for_search.sort_order, if(healingcrystals_project_objects.completed_on is null, '0', '1'), if(healingcrystals_project_objects.name like '%" . addslashes($search_for) . "%','1', if(" . $all_parts_in_name_string . ",'3',if(" . $few_parts_in_name_string . ",'5','99'))) as new_order, healingcrystals_project_objects.* \n\t\t  \t\t from healingcrystals_project_objects " . (!empty($search_under_project_id) ? " inner join healingcrystals_projects on (healingcrystals_project_objects.project_id=healingcrystals_projects.id and  healingcrystals_project_objects.project_id='" . (int) $search_under_project_id . "') " : " ") . " inner join healingcrystals_search_index on healingcrystals_project_objects.id=healingcrystals_search_index.object_id \n\t\t  \t\t left join healingcrystals_sort_order_for_search on healingcrystals_sort_order_for_search.type=healingcrystals_project_objects.type \n\t\t\t\t where " . $type_filter . $complete_str . " \n\t\t\t\t and (healingcrystals_project_objects.name is not null) \n\t\t\t\t and ( (healingcrystals_project_objects.name like '%" . addslashes($search_for) . "%') or ( " . $all_parts_in_name_string . " )  or ( " . $few_parts_in_name_string . " ) ) \n\t\t\t\t and healingcrystals_search_index.type='" . $type . "' \n\t\t\t\t and healingcrystals_project_objects.state='" . STATE_VISIBLE . "' " . (empty($search_object_type) ? "" : " and healingcrystals_project_objects.type='" . $search_object_type . "' ") . " )\n\t\t\t\t UNION \n\t\t\t\t (select distinct(healingcrystals_project_objects.id), healingcrystals_sort_order_for_search.sort_order, if(healingcrystals_project_objects.completed_on is null, '0', '1'), if(healingcrystals_project_objects.body like '%" . addslashes($search_for) . "%','2', if(" . $all_parts_in_body_string . ",'4',if(" . $few_parts_in_body_string . ",'6','99'))) as new_order, healingcrystals_project_objects.* \n\t\t  \t\t from healingcrystals_project_objects " . (!empty($search_under_project_id) ? " inner join healingcrystals_projects on (healingcrystals_project_objects.project_id=healingcrystals_projects.id and  healingcrystals_project_objects.project_id='" . (int) $search_under_project_id . "') " : " ") . " inner join healingcrystals_search_index on healingcrystals_project_objects.id=healingcrystals_search_index.object_id \n\t\t  \t\t left join healingcrystals_sort_order_for_search on healingcrystals_sort_order_for_search.type=healingcrystals_project_objects.type \n\t\t\t\t where " . $type_filter . $complete_str . " \n\t\t\t\t and ( (healingcrystals_project_objects.body like '%" . addslashes($search_for) . "%') or ( " . $all_parts_in_body_string . " ) or ( " . $few_parts_in_body_string . " ) ) \n\t\t\t\t and (healingcrystals_project_objects.name is null or healingcrystals_project_objects.name='') \n\t\t\t\t and healingcrystals_search_index.type='" . $type . "' \n\t\t\t\t and healingcrystals_project_objects.state='" . STATE_VISIBLE . "' " . (empty($search_object_type) ? "" : " and healingcrystals_project_objects.type='" . $search_object_type . "' ") . " )";
             $count_query_main = "(select * from healingcrystals_project_objects " . (!empty($search_under_project_id) ? " inner join healingcrystals_projects on (healingcrystals_project_objects.project_id=healingcrystals_projects.id and  healingcrystals_project_objects.project_id='" . (int) $search_under_project_id . "') " : " ") . " inner join healingcrystals_search_index on healingcrystals_project_objects.id=healingcrystals_search_index.object_id \n\t\t  \t\t left join healingcrystals_sort_order_for_search on healingcrystals_sort_order_for_search.type=healingcrystals_project_objects.type \n\t\t\t\t where " . $type_filter . $complete_str . " and (healingcrystals_project_objects.name is not null) \n\t\t\t\t and ( (healingcrystals_project_objects.name like '%" . addslashes($search_for) . "%' ) or ( " . $all_parts_in_name_string . " ) or ( " . $few_parts_in_name_string . " ) ) \n\t\t\t\t and healingcrystals_search_index.type='" . $type . "' \n\t\t\t\t and healingcrystals_project_objects.state='" . STATE_VISIBLE . "' " . (empty($search_object_type) ? "" : " and healingcrystals_project_objects.type='" . $search_object_type . "' ") . " )\n\t\t\t\t UNION \n\t\t\t\t (select * from healingcrystals_project_objects " . (!empty($search_under_project_id) ? " inner join healingcrystals_projects on (healingcrystals_project_objects.project_id=healingcrystals_projects.id and  healingcrystals_project_objects.project_id='" . (int) $search_under_project_id . "') " : " ") . " inner join healingcrystals_search_index on healingcrystals_project_objects.id=healingcrystals_search_index.object_id \n\t\t  \t\t left join healingcrystals_sort_order_for_search on healingcrystals_sort_order_for_search.type=healingcrystals_project_objects.type \n\t\t\t\t where " . $type_filter . $complete_str . "\n\t\t\t\t and ( (healingcrystals_project_objects.body like '%" . addslashes($search_for) . "%' ) or ( " . $all_parts_in_body_string . " ) or ( " . $few_parts_in_body_string . " ) ) \n\t\t\t\t and (healingcrystals_project_objects.name is null or healingcrystals_project_objects.name='')  \n\t\t\t\t and healingcrystals_search_index.type='" . $type . "' \n\t\t\t\t and healingcrystals_project_objects.state='" . STATE_VISIBLE . "' " . (empty($search_object_type) ? "" : " and healingcrystals_project_objects.type='" . $search_object_type . "' ") . " )";
         }
         $result = mysql_query($query_main, $link);
         $count_result = mysql_query($count_query_main, $link);
         $count = mysql_num_rows($count_result);
         $total_items = mysql_num_rows($result);
         //mysql_query("insert into testing (content, date_added) values ('" . mysql_real_escape_string($query_main) . "', now())");
         if ($total_items) {
             $rows = array();
             $items = array();
             //$items = ProjectObjects::findBySQL("SELECT $project_objects_table.* FROM $project_objects_table, $search_index_table WHERE $type_filter AND MATCH ($search_index_table.content) AGAINST (? IN BOOLEAN MODE) AND $project_objects_table.id = $search_index_table.object_id AND $search_index_table.type = ? AND state >= ? AND visibility >= ? LIMIT $offset, $per_page", array($search_for, $type, STATE_VISIBLE, $user->getVisibility()));
             $ids = array();
             //BOF:mod 20110706 ticketid222
             /*
             //EOF:mod 20110706 ticketid222
             $query = $query_main . " order by 2, 1 LIMIT " . $offset . " ," . $per_page;
             //BOF:mod 20110706 ticketid222
             */
             //BOF:mod 20120711
             if (empty($datesort)) {
                 //EOF:mod 20120711
                 $query = $query_main . " order by new_order ASC, 2, 1, created_on desc LIMIT " . $offset . " ," . $per_page;
                 //BOF:mod 20120711
             } elseif ($datesort == 'a') {
                 $query = $query_main . " order by created_on, new_order ASC, 2, 1 LIMIT " . $offset . " ," . $per_page;
             } elseif ($datesort == 'd') {
                 $query = $query_main . " order by created_on desc, new_order ASC, 2, 1 LIMIT " . $offset . " ," . $per_page;
             }
             //EOF:mod 20120711
             //EOF:mod 20110706 ticketid222
             $result = mysql_query($query, $link);
             while ($info = mysql_fetch_assoc($result)) {
                 $ids[] = $info['id'];
                 $rows[] = $info;
             }
             foreach ($rows as $row) {
                 $item_class = array_var($row, 'type');
                 $item = new $item_class();
                 $item->loadFromRow($row);
                 $add_item = true;
                 if ($_GET['complete'] != '1') {
                     if ($item->getParentType() == 'Page') {
                         $temp_page = new Page($item->getParentId());
                         $is_archived = $temp_page->getIsArchived();
                         if ($is_archived) {
                             $add_item = false;
                         }
                     }
                     if ($add_item) {
                         $temp_obj = new ProjectObject($item->getParentId());
                         if ($temp_obj->isCompleted()) {
                             $add_item = false;
                         }
                     }
                 }
                 if ($add_item) {
                     $items[] = $item;
                 }
             }
             if (empty($search_object_type)) {
                 //$items = ProjectObjects::findBySQL("SELECT $project_objects_table.* FROM $project_objects_table, $search_index_table WHERE $type_filter AND MATCH ($search_index_table.content) AGAINST (? IN BOOLEAN MODE) AND $project_objects_table.id = $search_index_table.object_id AND $search_index_table.type = ? AND state >= ? AND visibility >= ? LIMIT $offset, $per_page", array($search_for, $type, STATE_VISIBLE, $user->getVisibility()));
             } else {
                 //$items = ProjectObjects::findBySQL("SELECT $project_objects_table.* FROM $project_objects_table, $search_index_table WHERE $type_filter AND MATCH ($search_index_table.content) AGAINST (? IN BOOLEAN MODE) AND $project_objects_table.id = $search_index_table.object_id AND $search_index_table.type = ? AND state >= ? AND visibility >= ? AND $project_objects_table.type = ? LIMIT $offset, $per_page", array($search_for, $type, STATE_VISIBLE, $user->getVisibility(), $search_object_type));
             }
             //mysql_query("insert into healingcrystals_testing (query, fired_at) values ('" . mysql_real_escape_string($query) . "', now())", $link);
         } else {
             $items = null;
         }
         // if
         mysql_close($link);
         return array($items, new Pager($page, $total_items, $per_page), $count);
         // Search for projects
     } elseif ($type == 'Project') {
         $project_ids = Projects::findProjectIdsByUser($user, null, true);
         if (!is_foreachable($project_ids)) {
             return array(null, new Pager(1, 0, $per_page));
         }
         // if
         $projects_table = TABLE_PREFIX . 'projects';
         $total_items = (int) array_var(db_execute_one("SELECT COUNT({$projects_table}.id) AS 'row_count' FROM {$projects_table}, {$search_index_table} WHERE {$projects_table}.id IN (?) AND MATCH ({$search_index_table}.content) AGAINST (? IN BOOLEAN MODE) AND {$projects_table}.id = {$search_index_table}.object_id AND {$search_index_table}.type = ?", $project_ids, $search_for, 'Project'), 'row_count');
         if ($total_items) {
             $items = Projects::findBySQL("SELECT * FROM {$projects_table}, {$search_index_table} WHERE {$projects_table}.id IN (?) AND MATCH ({$search_index_table}.content) AGAINST (? IN BOOLEAN MODE) AND {$projects_table}.id = {$search_index_table}.object_id AND {$search_index_table}.type = ? LIMIT {$offset}, {$per_page}", array($project_ids, $search_for, 'Project'));
         } else {
             $items = null;
         }
         // if
         return array($items, new Pager($page, $total_items, $per_page));
         // Search for users
     } elseif ($type == 'User') {
         $user_ids = $user->visibleUserIds();
         if (!is_foreachable($user_ids)) {
             return array(null, new Pager(1, 0, $per_page));
         }
         // if
         $users_table = TABLE_PREFIX . 'users';
         $total_items = (int) array_var(db_execute_one("SELECT COUNT({$users_table}.id) AS 'row_count' FROM {$users_table}, {$search_index_table} WHERE {$users_table}.id IN (?) AND MATCH ({$search_index_table}.content) AGAINST (? IN BOOLEAN MODE) AND {$users_table}.id = {$search_index_table}.object_id AND {$search_index_table}.type = ?", $user_ids, $search_for, 'User'), 'row_count');
         if ($total_items) {
             $items = Users::findBySQL("SELECT * FROM {$users_table}, {$search_index_table} WHERE {$users_table}.id IN (?) AND MATCH ({$search_index_table}.content) AGAINST (? IN BOOLEAN MODE) AND {$users_table}.id = {$search_index_table}.object_id AND {$search_index_table}.type = ? LIMIT {$offset}, {$per_page}", array($user_ids, $search_for, 'User'));
         } else {
             $items = null;
         }
         // if
         return array($items, new Pager($page, $total_items, $per_page));
         // Unknown search type
     } else {
         return array(null, new Pager(1, 0, $per_page));
     }
     // if
 }
 /**
  * Paginate trashed objects
  *
  * @param User $user
  * @param integer $page
  * @param integer $per_page
  * @return null
  */
 function paginateTrashed($user, $page = 1, $per_page = 30)
 {
     if ($user->isAdministrator() || $user->isProjectManager()) {
         return ProjectObjects::paginate(array('conditions' => array("state = ? AND visibility >= ?", STATE_DELETED, $user->getVisibility()), 'order' => 'updated_on'), $page, $per_page);
     } else {
         $type_filter = ProjectUsers::getVisibleTypesFilter($user, array(PROJECT_STATUS_ACTIVE, PROJECT_STATUS_PAUSED, PROJECT_STATUS_CANCELED, PROJECT_STATUS_COMPLETED));
         if ($type_filter) {
             return ProjectObjects::paginate(array('conditions' => array($type_filter . ' AND state = ? AND visibility >= ?', STATE_DELETED, $user->getVisibility()), 'order' => 'updated_on'), $page, $per_page);
         } else {
             return array(null, new Pager(1, 0, $per_page));
         }
         // if
     }
     // if
 }
 function do_unclassify($main_email)
 {
     $conv_emails = MailContents::getMailsFromConversation($main_email);
     foreach ($conv_emails as $email) {
         try {
             DB::beginWork();
             //only get workspaces with R&W permissions
             $all_workspaces = ProjectUsers::getProjectsByUser(logged_user());
             $ws_ids = array();
             foreach ($all_workspaces as $ws) {
                 $has_ws_perm = logged_user()->hasProjectPermission($ws, ProjectUsers::CAN_WRITE_MAILS);
                 $has_gr_perm = false;
                 if (!$has_ws_perm) {
                     $groups = logged_user()->getGroups();
                     foreach ($groups as $group) {
                         $has_gr_perm = $group->getProjectPermission($ws, ProjectUsers::CAN_WRITE_MAILS);
                     }
                 }
                 if ($has_ws_perm || $has_gr_perm) {
                     $ws_ids[] = $ws->getId();
                 }
             }
             $ws_ids = implode(',', $ws_ids);
             // remove workspaces
             $email->removeFromWorkspaces($ws_ids);
             // unclassify attachments, remove all allowed ws, then if file has no ws -> delete it
             if ($email->getHasAttachments()) {
                 MailUtilities::parseMail($email->getContent(), $decoded, $parsedEmail, $warnings);
                 if (isset($parsedEmail['Attachments'])) {
                     $files = ProjectFiles::findAll(array('conditions' => 'mail_id = ' . $email->getId()));
                     foreach ($files as $file) {
                         $file->removeFromWorkspaces($ws_ids);
                         $current_wss = $file->getWorkspaces();
                         if (!is_array($current_wss) || count($current_wss) == 0) {
                             $file->delete();
                         }
                     }
                 }
             }
             DB::commit();
             return true;
         } catch (Exception $e) {
             DB::rollback();
             return false;
         }
     }
 }
Beispiel #27
0
 /**
 * Delete this object
 *
 * @param void
 * @return boolean
 */
 function delete() {
   if ($this->isAccountOwner()) {
     return false;
   } // if
   
   ProjectUsers::clearByUser($this);
   MessageSubscriptions::clearByUser($this);
   return parent::delete();
 } // delete
 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);
 }
 /**
  * Edit group
  *
  * @param void
  * @return null
  */
 function edit_group()
 {
     $this->setTemplate('add_group');
     if (!can_manage_security(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $group = Groups::findById(get_id());
     if (!$group instanceof Group) {
         flash_error(lang('group dnx'));
         $this->redirectTo('administration', 'groups');
     }
     // if
     if (logged_user()->isAdministrator()) {
         $projects = Projects::getAll();
     } else {
         $projects = null;
     }
     $permissions = ProjectUsers::getNameTextArray();
     $group_data = array_var($_POST, 'group');
     if (!is_array($group_data)) {
         $group_data = array('name' => $group->getName(), 'can_edit_company_data' => $group->getCanEditCompanyData(), 'can_manage_security' => $group->getCanManageSecurity(), 'can_manage_workspaces' => $group->getCanManageWorkspaces(), 'can_manage_configuration' => $group->getCanManageConfiguration(), 'can_manage_contacts' => $group->getCanManageContacts(), 'can_manage_templates' => $group->getCanManageTemplates(), 'can_manage_reports' => $group->getCanManageReports(), 'can_manage_time' => $group->getCanManageTime(), 'can_add_mail_accounts' => $group->getCanAddMailAccounts());
         // array
     }
     // if
     $users = GroupUsers::getUsersByGroup($group->getId());
     if ($users) {
         foreach ($users as $usr) {
             $group_data['user[' . $usr->getId() . ']'] = true;
         }
     }
     tpl_assign('group', $group);
     tpl_assign('group_data', $group_data);
     tpl_assign('permissions', $permissions);
     tpl_assign('projects', $projects);
     if (is_array(array_var($_POST, 'group'))) {
         $group->setFromAttributes($group_data);
         if (array_var($group_data, "can_edit_company_data") != 'checked') {
             $group->setCanEditCompanyData(false);
         }
         if (array_var($group_data, "can_manage_security") != 'checked') {
             $group->setCanManageSecurity(false);
         }
         if (array_var($group_data, "can_manage_configuration") != 'checked') {
             $group->setCanManageConfiguration(false);
         }
         if (array_var($group_data, "can_manage_workspaces") != 'checked') {
             $group->setCanManageWorkspaces(false);
         }
         if (array_var($group_data, "can_manage_contacts") != 'checked') {
             $group->setCanManageContacts(false);
         }
         if (array_var($group_data, "can_manage_templates") != 'checked') {
             $group->setCanManageTemplates(false);
         }
         if (array_var($group_data, "can_manage_reports") != 'checked') {
             $group->setCanManageReports(false);
         }
         if (array_var($group_data, "can_manage_time") != 'checked') {
             $group->setCanManageTime(false);
         }
         if (array_var($group_data, "can_add_mail_accounts") != 'checked') {
             $group->setCanAddMailAccounts(false);
         }
         try {
             DB::beginWork();
             //set permissions
             $permissionsString = array_var($_POST, 'permissions');
             if ($permissionsString && $permissionsString != '') {
                 $permissions = json_decode($permissionsString);
             }
             if (is_array($permissions) && count($permissions) > 0) {
                 //Clear old modified permissions
                 $ids = array();
                 foreach ($permissions as $perm) {
                     $ids[] = $perm->wsid;
                 }
                 ProjectUsers::clearByUser($group, implode(',', $ids));
                 //Add new permissions
                 //TODO - Make batch update of these permissions
                 foreach ($permissions as $perm) {
                     if (ProjectUser::hasAnyPermissions($perm->pr, $perm->pc)) {
                         $relation = new ProjectUser();
                         $relation->setProjectId($perm->wsid);
                         $relation->setUserId($group->getId());
                         $relation->setCheckboxPermissions($perm->pc);
                         $relation->setRadioPermissions($perm->pr);
                         $relation->save();
                     }
                     //endif
                     //else if the user has no permissions at all, he is not a project_user. ProjectUser is not created
                 }
                 //end foreach
             }
             // if
             $group->save();
             GroupUsers::clearByGroup($group);
             if (array_var($_POST, 'user')) {
                 foreach (array_var($_POST, 'user') as $user_id => $val) {
                     if ($val == 'checked' && is_numeric($user_id) && Users::findById($user_id) instanceof User) {
                         $gu = new GroupUser();
                         $gu->setGroupId($group->getId());
                         $gu->setUserId($user_id);
                         $gu->save();
                     }
                 }
             }
             ApplicationLogs::createLog($group, null, ApplicationLogs::ACTION_EDIT);
             DB::commit();
             flash_success(lang('success edit group', $group->getName()));
             ajx_current("back");
         } catch (Exception $e) {
             DB::rollback();
             tpl_assign('error', $e);
         }
         // try
     }
     // if
 }
 /**
  * Delete relations by $user
  *
  * @param User $user
  * @return boolean
  */
 function deleteByUser($user)
 {
     return ProjectUsers::delete(array('user_id = ?', $user->getId()));
 }