/**
  * Show permission update form
  *
  * @param void
  * @return null
  */
 function permissions()
 {
     $project = active_or_personal_project();
     if (!$project->canChangePermissions(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     tpl_assign('project_users', $project->getUsers(false));
     tpl_assign('project_companies', $project->getCompanies());
     tpl_assign('user_projects', logged_user()->getProjects());
     $permissions = ProjectUsers::getNameTextArray();
     tpl_assign('permissions', $permissions);
     $companies = array(owner_company());
     $clients = owner_company()->getClientCompanies();
     if (is_array($clients)) {
         $companies = array_merge($companies, $clients);
     }
     // if
     tpl_assign('companies', $companies);
     if (array_var($_POST, 'process') == 'process') {
         try {
             DB::beginWork();
             $project->clearCompanies();
             $project->clearUsers();
             $companies = array(owner_company());
             $client_companies = owner_company()->getClientCompanies();
             if (is_array($client_companies)) {
                 $companies = array_merge($companies, $client_companies);
             }
             // if
             foreach ($companies as $company) {
                 // Company is selected!
                 if (array_var($_POST, 'project_company_' . $company->getId()) == 'checked') {
                     // Owner company is automaticly included so it does not need to be in project_companies table
                     if (!$company->isOwner()) {
                         $project_company = new ProjectCompany();
                         $project_company->setProjectId($project->getId());
                         $project_company->setCompanyId($company->getId());
                         $project_company->save();
                     }
                     // if
                     $users = $company->getUsers();
                     if (is_array($users)) {
                         $counter = 0;
                         foreach ($users as $user) {
                             $user_id = $user->getId();
                             $counter++;
                             if (array_var($_POST, "project_user_{$user_id}") == 'checked') {
                                 $project_user = new ProjectUser();
                                 $project_user->setProjectId($project->getId());
                                 $project_user->setUserId($user_id);
                                 foreach ($permissions as $permission => $permission_text) {
                                     // Owner company members have all permissions
                                     $permission_value = $company->isOwner() ? true : array_var($_POST, 'project_user_' . $user_id . '_' . $permission) == 'checked';
                                     $setter = 'set' . Inflector::camelize($permission);
                                     $project_user->{$setter}($permission_value);
                                 }
                                 // if
                                 $project_user->save();
                             }
                             // if
                         }
                         // foreach
                     }
                     // if
                 }
                 // if
             }
             // foreach
             DB::commit();
             flash_success(lang('success update project permissions'));
             ajx_current("back");
         } catch (Exception $e) {
             DB::rollback();
             flash_error(lang('error update project permissions'));
             ajx_current("empty");
         }
         // try
     }
     // 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
 }
 /**
  * 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
 }
 /**
  * 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
 }
 /**
  * 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'));
         ajx_current("empty");
         return;
     }
     // if
     if (!$user->canUpdatePermissions(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $company = $user->getCompany();
     if (!$company instanceof Company) {
         flash_error(lang('company dnx'));
         ajx_current("empty");
         return;
     }
     // if
     if (logged_user()->isAdministrator()) {
         $projects = Projects::getAll();
     } else {
         $projects = null;
     }
     $permissions = ProjectUsers::getNameTextArray();
     $redirect_to = array_var($_GET, 'redirect_to');
     if (trim($redirect_to) == '' || !is_valid_url($redirect_to)) {
         $redirect_to = $user->getCardUrl();
     }
     // if
     $user_data = array_var($_POST, 'user');
     if (!is_array($user_data)) {
         $user_data = array('can_edit_company_data' => $user->getCanEditCompanyData(), 'can_manage_security' => $user->getCanManageSecurity(), 'can_manage_workspaces' => $user->getCanManageWorkspaces(), 'can_manage_configuration' => $user->getCanManageConfiguration(), 'can_manage_contacts' => $user->getCanManageContacts(), 'can_manage_templates' => $user->getCanManageTemplates(), 'can_manage_reports' => $user->getCanManageReports(), 'can_manage_time' => $user->getCanManageTime(), 'can_add_mail_accounts' => $user->getCanAddMailAccounts());
         // array
         Hook::fire('add_user_permissions', $user, $user_data);
     }
     // if
     tpl_assign('user_data', $user_data);
     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') {
         $user_data = array_var($_POST, 'user');
         if (!is_array($user_data)) {
             $user_data = array();
         }
         try {
             DB::beginWork();
             $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($user, 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($user->getId());
                         $relation->setCheckboxPermissions($perm->pc, $user->isGuest() ? false : true);
                         $relation->setRadioPermissions($perm->pr, $user->isGuest() ? false : true);
                         $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
             $user->setCanEditCompanyData(false);
             $user->setCanManageSecurity(false);
             $user->setCanManageConfiguration(false);
             $user->setCanManageWorkspaces(false);
             $user->setCanManageContacts(false);
             $user->setCanManageTemplates(false);
             $user->setCanManageReports(false);
             $user->setCanManageTime(false);
             $user->setCanAddMailAccounts(false);
             $other_permissions = array();
             Hook::fire('add_user_permissions', $user, $other_permissions);
             foreach ($other_permissions as $k => $v) {
                 $user->setColumnValue($k, false);
             }
             $user->setFromAttributes($user_data);
             $user->setUpdatedOn(DateTimeValueLib::now());
             $user->save();
             DB::commit();
             flash_success(lang('success user permissions updated'));
             ajx_current("back");
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
     }
     // if
 }
 /**
  * Add user
  *
  * @access public
  * @param void
  * @return null
  */
 function add()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $max_users = config_option('max_users');
     if ($max_users && Users::count() >= $max_users) {
         flash_error(lang('maximum number of users reached error'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('add_user');
     $company = Companies::findById(get_id('company_id'));
     if (!$company instanceof Company) {
         $company = owner_company();
     }
     // if
     if (!User::canAdd(logged_user(), $company)) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $user = new User();
     $user_data = array_var($_POST, 'user');
     if (!is_array($user_data)) {
         //if it is a new user
         $contact_id = get_id('contact_id');
         $contact = Contacts::findById($contact_id);
         if ($contact instanceof Contact) {
             //if it will be created from a contact
             $user_data = array('username' => $this->generateUserNameFromContact($contact), 'display_name' => $contact->getFirstname() . $contact->getLastname(), 'email' => $contact->getEmail(), 'contact_id' => $contact->getId(), 'password_generator' => 'random', 'company_id' => $company->getId(), 'timezone' => $contact->getTimezone(), 'create_contact' => false, 'type' => 'normal', 'can_manage_time' => true);
             // array
         } else {
             // if it is new, and created from admin interface
             $user_data = array('password_generator' => 'random', 'company_id' => $company->getId(), 'timezone' => $company->getTimezone(), 'create_contact' => true, 'send_email_notification' => true, 'type' => 'normal', 'can_manage_time' => true);
             // array
         }
     }
     // if
     $permissions = ProjectUsers::getNameTextArray();
     tpl_assign('user', $user);
     tpl_assign('company', $company);
     tpl_assign('permissions', $permissions);
     tpl_assign('user_data', $user_data);
     tpl_assign('billing_categories', BillingCategories::findAll());
     if (is_array(array_var($_POST, 'user'))) {
         if (!array_var($user_data, 'createPersonalProject')) {
             $user_data['personal_project'] = 0;
         }
         try {
             DB::beginWork();
             $user = $this->createUser($user_data, array_var($_POST, 'permissions'));
             $object_controller = new ObjectController();
             $object_controller->add_custom_properties($user);
             DB::commit();
             flash_success(lang('success add user', $user->getDisplayName()));
             ajx_current("back");
         } catch (Exception $e) {
             DB::rollback();
             ajx_current("empty");
             flash_error($e->getMessage());
         }
         // try
     }
     // if
 }