public function rebuild($start_date = null, $end_date = null) { if (!$start_date) { $start_date = config_option('last_sharing_table_rebuild'); } if ($start_date instanceof DateTimeValue) { $start_date = $start_date->toMySQL(); } if ($end_date instanceof DateTimeValue) { $end_date = $end_date->toMySQL(); } if ($end_date) { $end_cond = "AND updated_on <= '{$end_date}'"; } try { $object_ids = Objects::instance()->findAll(array('id' => true, "conditions" => "updated_on >= '{$start_date}' {$end_cond}")); $obj_count = 0; DB::beginWork(); foreach ($object_ids as $id) { $obj = Objects::findObject($id); if ($obj instanceof ContentDataObject) { $obj->addToSharingTable(); $obj_count++; } } set_config_option('last_sharing_table_rebuild', DateTimeValueLib::now()->toMySQL()); DB::commit(); } catch (Exception $e) { DB::rollback(); Logger::log("Failed to rebuild sharing table: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString()); } return $obj_count; }
function purge_trash() { Env::useHelper("permissions"); $days = config_option("days_on_trash", 0); $count = 0; if ($days > 0) { $date = DateTimeValueLib::now()->add("d", -$days); $objects = Objects::findAll(array("conditions" => array("`trashed_by_id` > 0 AND `trashed_on` < ?", $date), "limit" => 100)); foreach ($objects as $object) { $concrete_object = Objects::findObject($object->getId()); if (!$concrete_object instanceof ContentDataObject) { continue; } if ($concrete_object instanceof MailContent && $concrete_object->getIsDeleted() > 0) { continue; } try { DB::beginWork(); if ($concrete_object instanceof MailContent) { $concrete_object->delete(false); } else { $concrete_object->delete(); } ApplicationLogs::createLog($concrete_object, ApplicationLogs::ACTION_DELETE); DB::commit(); $count++; } catch (Exception $e) { DB::rollback(); Logger::log("Error delting object in purge_trash: " . $e->getMessage(), Logger::ERROR); } } } return $count; }
function console_create_user($args) { $fname = array_shift($args); $lname = array_shift($args); $email = array_shift($args); $admin = array_shift($args) == 'true'; if (is_null($fname) || is_null($lname) || is_null($email)) { throw new Exception('create_user: Missing arguments. Expected: (fname, lname, email, admin)'); } $display_name = $fname . " " . $lname; $username = str_replace(" ", "_", strtolower($display_name)); $user_data = array('username' => $username, 'display_name' => $display_name, 'email' => $email, 'password_generator' => 'random', 'timezone' => 0, 'autodetect_time_zone' => 1, 'create_contact' => false, 'company_id' => owner_company()->getId(), 'send_email_notification' => true, 'personal_project' => 0); // array try { DB::beginWork(); $user = create_user($user_data, $admin, ''); if (!$user->getContact() instanceof Contact) { $contact = new Contact(); $contact->setFirstName($fname); $contact->setLastName($lname); $contact->setEmail($email); $contact->setUserId($user->getId()); $contact->save(); } DB::commit(); } catch (Exception $e) { DB::rollback(); throw $e; } }
function add() { $pt = DB::escape(array_var($_GET, 'pt')); $t = DB::escape(array_var($_GET, 't')); $dep = ProjectTaskDependencies::findOne(array('conditions' => "`previous_task_id` = {$pt} AND `task_id` = {$t}")); if (!$dep instanceof ProjectTaskDependency) { try { DB::beginWork(); $dep = new ProjectTaskDependency(); $dep->setPreviousTaskId(array_var($_GET, 'pt')); $dep->setTaskId(array_var($_GET, 't')); $dep->save(); DB::commit(); } catch (Exception $e) { flash_error($e->getMessage()); DB::rollback(); } } flash_success(lang('success add task dependency')); $reload = array_var($_GET, 'reload', true); if ($reload) { ajx_current("reload"); } else { ajx_current("empty"); } }
function &logUserIn(User $user, $settings = null) { $existing_session_id = isset($settings['existing_session_id']) && $settings['existing_session_id'] ? $settings['existing_session_id'] : null; try { DB::beginWork('Logging user in @ ' . __CLASS__); $users_table = TABLE_PREFIX . 'users'; $user_sessions_table = TABLE_PREFIX . 'user_sessions'; $remember = (bool) array_var($settings, 'remember', false); $new_visit = (bool) array_var($settings, 'new_visit', false); // Some initial data $session_id = null; $new_expires_on = $remember ? time() + 1209600 : time() + 1800; // 30 minutes or 2 weeks? // Existing session if ($existing_session_id) { $existing_session_data = DB::executeFirstRow("SELECT remember, session_key, interface FROM {$user_sessions_table} WHERE id = ?", $existing_session_id); if ($existing_session_data && isset($existing_session_data['remember']) && isset($existing_session_data['session_key'])) { if ($existing_session_data['remember']) { $new_expires_on = time() + 1209600; } // if $session_key = $existing_session_data['session_key']; DB::execute("UPDATE {$user_sessions_table} SET user_ip = ?, user_agent = ?, last_activity_on = UTC_TIMESTAMP(), expires_on = ?, visits = visits + 1 WHERE id = ?", AngieApplication::getVisitorIp(), AngieApplication::getVisitorUserAgent(), date(DATETIME_MYSQL, $new_expires_on), $existing_session_id); $session_id = $existing_session_id; AngieApplication::setPreferedInterface($existing_session_data['interface']); } // if } // if // New session? if ($session_id === null) { AngieApplication::setPreferedInterface(array_var($settings, 'interface')); do { $session_key = make_string(40); } while (DB::executeFirstCell("SELECT COUNT(id) AS 'row_count' FROM {$user_sessions_table} WHERE session_key = ?", $session_key) > 0); DB::execute("INSERT INTO {$user_sessions_table} (user_id, user_ip, user_agent, visits, remember, interface, created_on, last_activity_on, expires_on, session_key) VALUES (?, ?, ?, ?, ?, ?, UTC_TIMESTAMP(), ?, ?, ?)", $user->getId(), AngieApplication::getVisitorIp(), AngieApplication::getVisitorUserAgent(), 1, (int) $remember, AngieApplication::getPreferedInterface(), date(DATETIME_MYSQL), date(DATETIME_MYSQL, $new_expires_on), $session_key); $session_id = DB::lastInsertId(); } // if // Update last visit time if ($new_visit) { DB::execute("UPDATE {$users_table} SET last_visit_on = last_login_on, last_login_on = ?, last_activity_on = ? WHERE id = ?", date(DATETIME_MYSQL), date(DATETIME_MYSQL), $user->getId()); } else { DB::execute("UPDATE {$users_table} SET last_activity_on = ? WHERE id = ?", date(DATETIME_MYSQL), $user->getId()); } // if DB::commit('User logged in @ ' . __CLASS__); $this->session_id = $session_id; // remember it, for logout Cookies::setVariable($this->session_id_var_name, "{$session_id}/{$session_key}/" . date(DATETIME_MYSQL)); return parent::logUserIn($user); } catch (Exception $e) { DB::rollback('Failed to log user in @ ' . __CLASS__); throw $e; } // try }
static function createDefaultUserPermissionsAllDimension(Contact $user, $dimension_id, $remove_previous = true) { $role_id = $user->getUserType(); $permission_group_id = $user->getPermissionGroupId(); $dimension = Dimensions::getDimensionById($dimension_id); if (!$dimension instanceof Dimension || !$dimension->getDefinesPermissions()) { return; } try { DB::beginWork(); $shtab_permissions = array(); $new_permissions = array(); $role_permissions = self::findAll(array('conditions' => 'role_id = ' . $role_id)); $members = Members::findAll(array('conditions' => 'dimension_id = ' . $dimension_id)); foreach ($members as $member) { $member_id = $member->getId(); if ($remove_previous) { ContactMemberPermissions::delete("permission_group_id = {$permission_group_id} AND member_id = {$member_id}"); } foreach ($role_permissions as $role_perm) { if ($member->canContainObject($role_perm->getObjectTypeId())) { $cmp = new ContactMemberPermission(); $cmp->setPermissionGroupId($permission_group_id); $cmp->setMemberId($member_id); $cmp->setObjectTypeId($role_perm->getObjectTypeId()); $cmp->setCanDelete($role_perm->getCanDelete()); $cmp->setCanWrite($role_perm->getCanWrite()); $cmp->save(); $new_permissions[] = $cmp; $perm = new stdClass(); $perm->m = $member_id; $perm->r = 1; $perm->w = $role_perm->getCanWrite(); $perm->d = $role_perm->getCanDelete(); $perm->o = $role_perm->getObjectTypeId(); $shtab_permissions[] = $perm; } } } if (count($shtab_permissions)) { $stCtrl = new SharingTableController(); $stCtrl->afterPermissionChanged($permission_group_id, $shtab_permissions); } DB::commit(); return $new_permissions; } catch (Exception $e) { DB::rollback(); throw $e; } }
function healPermissionGroup(SharingTableFlag $flag) { if ($flag->getObjectId() > 0) { try { $obj = Objects::findObject($flag->getObjectId()); if (!$obj instanceof ContentDataObject) { $flag->delete(); // if object does not exists then delete the flag return; } DB::beginWork(); // update sharing table $obj->addToSharingTable(); DB::commit(); } catch (Exception $e) { DB::rollback(); Logger::log("Failed to heal object permissions for object " . $flag->getObjectId() . " (flag_id = " . $flag->getId() . ")"); return false; } // delete flag $flag->delete(); return true; } else { // heal $controller = new SharingTableController(); $permissions_string = $flag->getPermissionString(); $permission_group_id = $flag->getPermissionGroupId(); $permissions = json_decode($permissions_string); if ($flag->getMemberId() > 0) { foreach ($permissions as $p) { if (!isset($p->m)) { $p->m = $flag->getMemberId(); } } } try { DB::beginWork(); // update sharing table $controller->afterPermissionChanged($permission_group_id, $permissions); DB::commit(); } catch (Exception $e) { DB::rollback(); Logger::log("Failed to heal permission group {$permission_group_id} (flag_id = " . $flag->getId() . ")\n" . $e->getTraceAsString()); return false; } // delete flag $flag->delete(); return true; } }
/** * Delete specific user * * @access public * @param void * @return null */ function delete() { $this->setTemplate('del_user'); $user = Users::findById(get_id()); if (!$user instanceof User) { flash_error(lang('user dnx')); $this->redirectTo('administration'); } // if if (!$user->canDelete(logged_user())) { flash_error(lang('no access permissions')); $this->redirectToReferer(get_url('dashboard')); } // if $delete_data = array_var($_POST, 'deleteUser'); tpl_assign('user', $user); tpl_assign('delete_data', $delete_data); if (!is_array($delete_data)) { $delete_data = array('really' => 0, 'password' => ''); // array tpl_assign('delete_data', $delete_data); } else { if ($delete_data['really'] == 1) { $password = $delete_data['password']; if (trim($password) == '') { tpl_assign('error', new Error(lang('password value missing'))); return $this->render(); } if (!logged_user()->isValidPassword($password)) { tpl_assign('error', new Error(lang('invalid login data'))); return $this->render(); } try { DB::beginWork(); $user->delete(); ApplicationLogs::createLog($user, null, ApplicationLogs::ACTION_DELETE); DB::commit(); flash_success(lang('success delete user', $user->getDisplayName())); } catch (Exception $e) { DB::rollback(); flash_error(lang('error delete user')); } // try $this->redirectToUrl($user->getCompany()->getViewUrl()); } else { flash_error(lang('error delete user')); $this->redirectToUrl($user->getCompany()->getViewUrl()); } } }
/** * Contact member cache * */ function core_dimensions_update_7_8() { //UPDATE depth for all members //update root members DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = 1 WHERE parent_member_id = 0;"); //clean root members DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = 2 WHERE parent_member_id != 0 AND depth = 1;"); $members_depth = DB::executeAll("SELECT id FROM " . TABLE_PREFIX . "members WHERE parent_member_id =0 ORDER BY id"); $members_depth = array_flat($members_depth); $members_depth = implode(",", $members_depth); $depth = 2; $max_depth = DB::executeOne("SELECT MAX(depth) AS depth FROM `" . TABLE_PREFIX . "members`"); //update all depths for ($i = $depth; $i <= $max_depth['depth']; $i++) { //update members depth DB::execute("UPDATE " . TABLE_PREFIX . "members SET depth = " . $depth . " WHERE parent_member_id IN (" . $members_depth . ");"); //Get member from next depth $members_depth = DB::executeAll("SELECT id FROM " . TABLE_PREFIX . "members WHERE depth= " . $depth . " ORDER BY id"); $members_depth = array_flat($members_depth); $members_depth = implode(",", $members_depth); $depth++; } //END UPDATE depth for all members //Load the contact member cache set_time_limit(0); ini_set('memory_limit', '512M'); $users = Contacts::getAllUsers(); $dimensions = Dimensions::findAll(); $dimensions_ids = array(); foreach ($dimensions as $dimension) { if ($dimension->getDefinesPermissions()) { $dimensions_ids[] = $dimension->getId(); } } $dimensions_ids = implode(",", $dimensions_ids); $root_members = DB::executeAll("SELECT * FROM " . TABLE_PREFIX . "members WHERE dimension_id IN (" . $dimensions_ids . ") AND parent_member_id=0 ORDER BY id"); foreach ($users as $user) { try { DB::beginWork(); foreach ($root_members as $member) { ContactMemberCaches::updateContactMemberCache($user, $member['id'], $member['parent_member_id']); } DB::commit(); } catch (Exception $e) { DB::rollback(); throw $e; } } //END Load the contact member cache }
function purge_trash() { Env::useHelper("permissions"); $days = config_option("days_on_trash", 0); $count = 0; if ($days > 0) { $date = DateTimeValueLib::now()->add("d", -$days); $managers = array('Comments', 'Companies', 'Contacts', 'MailContents', 'ProjectCharts', 'ProjectEvents', 'ProjectFiles', 'ProjectFileRevisions', 'ProjectForms', 'ProjectMessages', 'ProjectMilestones', 'ProjectTasks', 'ProjectWebpages'); foreach ($managers as $manager_class) { $manager = new $manager_class(); $prevcount = -1; while ($prevcount != $count) { $prevcount = $count; if ($manager_class == 'MailContents') { $objects = $manager->findAll(array("include_trashed" => true, "conditions" => array("`trashed_by_id` > 0 AND `trashed_on` < ? AND `is_deleted` = 0", $date), "limit" => 100)); } else { $objects = $manager->findAll(array("include_trashed" => true, "conditions" => array("`trashed_by_id` > 0 AND `trashed_on` < ?", $date), "limit" => 100)); } if (is_array($objects)) { // delete one by one because each one knows what else to delete foreach ($objects as $o) { try { DB::beginWork(); $ws = $o->getWorkspaces(); if ($o instanceof MailContent) { $o->delete(false); } else { $o->delete(); } ApplicationLogs::createLog($o, $ws, ApplicationLogs::ACTION_DELETE); DB::commit(); $count++; } catch (Exception $e) { DB::rollback(); Logger::log("Error deleting object in purge_trash: " . $e->getMessage(), Logger::ERROR); } } } } } } return $count; }
function store() { ob_end_clean(); if (isset($_POST['message'])) { DB::beginWork(); $user = $_POST['from']; //$sql = "insert into " . DB_PREFIX . "`email_in` (created_by, raw) values ("; $sql = "insert into `PP086_email_in` (created_by, raw) values ("; $sql .= "'{$user}', '" . mysql_real_escape_string($_POST['message']) . "')"; DB::execute($sql); //ApplicationLogs::createLog('new email received', null, ApplicationLogs::ACTION_ADD); DB::commit(); //header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK'); //header('Status: 200'); echo 'ok'; die; } header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found'); header('Status: 404 Not Found'); die; }
static function createLog($title, $log_data, $category = null) { if(is_null($category)) { $category = self::ADM_LOG_CATEGORY_SYSTEM; } // if if(!self::isValidCategory($category)) { throw new Error("'$category' is not valid administration log category"); } // if $log = new AdministrationLog(); try { DB::beginWork(); $log->setTitle($title); $log->setLogData($log_data); $log->setCategory($category); $log->save(); DB::commit(); } catch (Exception $e) { DB::rollback(); } return $log; } // createLog
static function createLog($num, $log_data, $category = null) { if (is_null($category)) { $category = self::SMS_LOG_CATEGORY_FAILURE; } // if if (!self::isValidCategory($category)) { throw new Error("'{$category}' is not valid sms log category"); } // if $log = new SmsLog(); try { DB::beginWork(); $log->setNumber($num); $log->setLogData($log_data); $log->setCategory($category); $log->save(); DB::commit(); } catch (Exception $e) { DB::rollback(); } return $log; }
function update_unset_billing_values() { ajx_current("empty"); if (!logged_user()->isAdministrator()) { flash_error(lang("no access permissions")); return; } try { DB::beginWork(); $count = Timeslots::updateBillingValues(); DB::commit(); flash_success(lang("success update billing values", $count)); } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); } }
function addToStatus($amount) { try { DB::beginWork(); $state = -1; $saved = "false"; $state = $this->getState(); $this->setState($state + $amount); $this->save(); $saved = "true"; DB::commit(); return true; } catch (Exception $e) { Logger::log("Could not advance email state, email skipped: ".$e->getMessage()."\nmail_id=".$this->getId()."\nstate=$state\nsaved=$saved"); DB::rollback(); } return false; }
/** * Open specific milestone * * @access public * @param void * @return null */ function open() { $milestone = ProjectMilestones::findById(get_id()); if (!$milestone instanceof ProjectMilestone) { flash_error(lang('milestone dnx')); $this->redirectTo('milestone'); } // if if (!$milestone->canChangeStatus(logged_user())) { flash_error(lang('no access permissions')); $this->redirectToReferer(get_url('milestone')); } // if try { $milestone->setCompletedOn(null); $milestone->setCompletedById(0); DB::beginWork(); $milestone->save(); ApplicationLogs::createLog($milestone, active_project(), ApplicationLogs::ACTION_OPEN); DB::commit(); flash_success(lang('success open milestone', $milestone->getName())); } catch (Exception $e) { DB::rollback(); flash_error(lang('error open milestone')); } // try $this->redirectToReferer($milestone->getViewUrl()); }
/** * Delete company logo * * @param void * @return null */ function delete_logo() { if (!logged_user()->isAdministrator(owner_company())) { flash_error(lang('no access permissions')); $this->redirectTo('dashboard'); } // if $company = Companies::findById(get_id()); if (!$company instanceof Company) { flash_error(lang('company dnx')); $this->redirectToReferer(get_url('administration', 'clients')); } // if try { DB::beginWork(); $company->deleteLogo(); $company->save(); ApplicationLogs::createLog($company, null, ApplicationLogs::ACTION_EDIT); DB::commit(); flash_success(lang('success delete company logo')); } catch (Exception $e) { DB::rollback(); flash_error(lang('error delete company logo')); } // try $this->redirectToUrl($company->getEditLogoUrl()); }
/** * Save milestone record to the database * * @return boolean */ function save() { // hack DB::beginWork('Saving Milestone @ ' . __CLASS__); // if($this->isNew()){ DB::execute('UPDATE ' . TABLE_PREFIX . 'object_contexts SET parent_type = ? WHERE parent_id = ?', 'RemediaMilestone', $this->getId()); // } $result = parent::save(); // hack DB::execute('UPDATE ' . TABLE_PREFIX . 'object_contexts SET parent_type = ? WHERE parent_id = ?', 'Milestone', $this->getId()); DB::execute('UPDATE ' . TABLE_PREFIX . 'project_objects SET type = ? WHERE type = ?', 'Milestone', 'RemediaMilestone'); DB::execute('UPDATE ' . TABLE_PREFIX . 'modification_logs SET parent_type = ? WHERE parent_type = ?', 'Milestone', 'RemediaMilestone'); DB::execute('UPDATE ' . TABLE_PREFIX . 'activity_logs SET subject_type = ? WHERE subject_type = ?', 'Milestone', 'RemediaMilestone'); DB::execute('UPDATE ' . TABLE_PREFIX . 'activity_logs SET action = ? WHERE action = ?', 'milestone/created', 'remedia_milestone/created'); // DB::execute('DELETE FROM ' . TABLE_PREFIX . 'subscriptions WHERE parent_type = \'RemediaMilestone\' AND parent_id IN (SELECT parent_id FROM ' . TABLE_PREFIX . 'subscriptions WHERE parent_type = \'Milestone\')'); // DB::execute('UPDATE ' . TABLE_PREFIX . 'subscriptions SET parent_type = ? WHERE parent_type = ?', 'Milestone', 'RemediaMilestone'); DB::commit('Milestone saved @ ' . __CLASS__); return $result; }
/** * Delete specific comment * * @param void * @return null */ function delete() { $comment = Comments::findById(get_id()); if (!$comment instanceof Comment) { flash_error(lang('comment dnx')); ajx_current("empty"); return; } // if $object = $comment->getRelObject(); if (!$object instanceof ContentDataObject) { flash_error(lang('object dnx')); ajx_current("empty"); return; } // if if (trim($object->getObjectUrl())) { $redirect_to = $object->getObjectUrl(); } if (!$comment->canDelete(logged_user())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } // if try { DB::beginWork(); $comment->trash(); ApplicationLogs::createLog($comment, ApplicationLogs::ACTION_TRASH); DB::commit(); flash_success(lang('success delete comment')); ajx_current("reload"); } catch (Exception $e) { DB::rollback(); flash_error(lang('error delete comment')); ajx_current("empty"); } // try }
/** * @author Ignacio Vazquez - elpepe.uy@gmail.com * @param array of string $pluginNames * TODO avoid using mysql functions - (copied from installer) */ static function executeInstaller($name) { $table_prefix = TABLE_PREFIX; tpl_assign('table_prefix', $table_prefix); $default_charset = 'DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'; tpl_assign('default_charset', $default_charset); $default_collation = 'collate utf8_unicode_ci'; tpl_assign('default_collation', $default_collation); $engine = DB_ENGINE; tpl_assign('engine', $engine); $path = ROOT . "/plugins/{$name}/info.php"; if (file_exists($path)) { DB::beginWork(); $pluginInfo = (include_once $path); //0. Check if exists in plg table $sql = "SELECT id FROM " . TABLE_PREFIX . "plugins WHERE name = '{$name}' "; $res = @mysql_query($sql); if (!$res) { DB::rollback(); return false; } $plg_obj = mysql_fetch_object($res); if (!$plg_obj) { //1. Insert into PLUGIN TABLE $cols = "name, is_installed, is_activated, version"; $values = "'{$name}', 1, 1 ,'" . array_var($pluginInfo, 'version') . "'"; if (is_numeric(array_var($pluginInfo, 'id'))) { $cols = "id, " . $cols; $values = array_var($pluginInfo, 'id') . ", " . $values; } $sql = "INSERT INTO " . TABLE_PREFIX . "plugins ({$cols}) VALUES ({$values}) "; if (@mysql_query($sql)) { $id = @mysql_insert_id(); $pluginInfo['id'] = $id; } else { echo "ERROR: " . mysql_error(); @mysql_query('ROLLBACK'); return false; } } else { $id = $plg_obj->id; $pluginInfo['id'] = $id; } //2. IF Plugin defines types, INSERT INTO ITS TABLE if (count(array_var($pluginInfo, 'types'))) { foreach ($pluginInfo['types'] as $k => $type) { if (isset($type['name'])) { $sql = "\n\t\t\t\t\t\t\tINSERT INTO " . TABLE_PREFIX . "object_types (name, handler_class, table_name, type, icon, plugin_id)\n\t\t\t\t\t\t\t \tVALUES (\n\t\t\t\t\t\t\t \t'" . array_var($type, "name") . "', \n\t\t\t\t\t\t\t \t'" . array_var($type, "handler_class") . "', \n\t\t\t\t\t\t\t \t'" . array_var($type, "table_name") . "', \n\t\t\t\t\t\t\t \t'" . array_var($type, "type") . "', \n\t\t\t\t\t\t\t \t'" . array_var($type, "icon") . "', \n\t\t\t\t\t\t\t\t{$id}\n\t\t\t\t\t\t\t)"; if (@mysql_query($sql)) { $pluginInfo['types'][$k]['id'] = @mysql_insert_id(); $type['id'] = @mysql_insert_id(); } else { echo $sql . "<br/>"; echo mysql_error() . "<br/>"; DB::rollback(); return false; } } } } //2. IF Plugin defines tabs, INSERT INTO ITS TABLE if (count(array_var($pluginInfo, 'tabs'))) { foreach ($pluginInfo['tabs'] as $k => $tab) { if (isset($tab['title'])) { $type_id = array_var($type, "id"); $sql = "\n\t\t\t\t\t\t\tINSERT INTO " . TABLE_PREFIX . "tab_panels (\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\ttitle, \n\t\t\t\t\t\t\t\ticon_cls, \n\t\t\t\t\t\t\t\trefresh_on_context_change, \n\t\t\t\t\t\t\t\tdefault_controller, \n\t\t\t\t\t\t\t\tdefault_action, \n\t\t\t\t\t\t\t\tinitial_controller, \n\t\t\t\t\t\t\t\tinitial_action, \n\t\t\t\t\t\t\t\tenabled, \n\t\t\t\t\t\t\t\ttype, \n\t\t\t\t\t\t\t\tplugin_id, \n\t\t\t\t\t\t\t\tobject_type_id )\n\t\t\t\t\t\t \tVALUES (\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'id') . "', \n\t\t\t\t\t\t \t\t'" . array_var($tab, 'title') . "', \n\t\t\t\t\t\t \t\t'" . array_var($tab, 'icon_cls') . "',\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'refresh_on_context_change') . "',\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'default_controller') . "',\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'default_action') . "',\n\t\t\t\t\t\t\t\t'" . array_var($tab, 'initial_controller') . "',\n\t\t\t\t\t\t\t\t'" . array_var($tab, 'initial_action') . "',\n\t\t\t\t\t\t\t\t'" . array_var($tab, 'enabled', 1) . "',\n\t\t\t\t\t\t\t\t'" . array_var($tab, 'type') . "',\n\t\t\t\t\t\t\t\t{$id},\n\t\t\t\t\t\t\t\t" . array_var($tab, 'object_type_id') . "\n\t\t\t\t\t\t\t)"; if (!@mysql_query($sql)) { echo $sql; echo mysql_error(); DB::rollback(); return false; } // INSERT INTO TAB PANEL PERMISSSION $sql = "\n\t\t\t\t\t\t\tINSERT INTO " . TABLE_PREFIX . "tab_panel_permissions (\n\t\t\t\t\t\t\t\tpermission_group_id,\n\t\t\t\t\t\t\t\ttab_panel_id \n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t \tVALUES ( 1,'" . array_var($tab, 'id') . "' ), ( 2,'" . array_var($tab, 'id') . "' ) ON DUPLICATE KEY UPDATE permission_group_id = permission_group_id "; if (!@mysql_query($sql)) { echo $sql; echo mysql_error(); @mysql_query('ROLLBACK'); DB::rollback(); return false; } } } } // Create schema sql query $schema_creation = ROOT . "/plugins/{$name}/install/sql/mysql_schema.php"; if (file_exists($schema_creation)) { $total_queries = 0; $executed_queries = 0; if (executeMultipleQueries(tpl_fetch($schema_creation), $total_queries, $executed_queries)) { logger::log("Schema created for plugin {$name} "); } else { //echo tpl_fetch ( $schema_creation ); echo mysql_error(); echo "llega <br>"; DB::rollback(); return false; } } // Create schema sql query $schema_query = ROOT . "/plugins/{$name}/install/sql/mysql_initial_data.php"; if (file_exists($schema_query)) { $total_queries = 0; $executed_queries = 0; if (executeMultipleQueries(tpl_fetch($schema_query), $total_queries, $executed_queries)) { logger::log("Initial data loaded for plugin '{$name}'." . mysql_error()); } else { echo mysql_error(); DB::rollback(); return false; } } $install_script = ROOT . "/plugins/{$name}/install/install.php"; if (file_exists($install_script)) { include_once $install_script; } DB::commit(); return true; } return false; }
/** * @author Ignacio Vazquez <elpepe.uy at gmail dot com> * Handle quick add submit */ function quick_add() { if (array_var($_GET, 'current') == 'overview-panel') { ajx_current("reload"); }else { ajx_current("empty"); } //---------- REQUEST PARAMS -------------- // $_POST = Array ( // [member] => Array ( // [name] => pepe 333 // [dimension_id] => 1 // [parent_member_id] => 0 // [dimension_id] => 19 // ) // [contact] => Array ( // [email] => slkdjflksjdflksdf@kldsjflkdf.com // [user] => Array ( // [create-user]=>on // [type] => 25 // [first_name] => // [surname] => // ) //---------------------------------------- // Init variables $max_users = config_option('max_users'); if ($max_users && (Contacts::count() >= $max_users)) { flash_error(lang('maximum number of users reached error')); ajx_current("empty"); return; } if (!can_manage_security(logged_user())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $email = trim(array_var(array_var($_POST, 'contact'),'email')) ; $member = array_var($_POST, 'member'); $name = array_var($member, 'name'); $firstName = trim(array_var(array_var($_POST, 'contact'),'first_name')); $surname = trim(array_var(array_var($_POST, 'contact'),'surname')); $parentMemberId = array_var($member, 'parent_member_id'); $objectType = ObjectTypes::findById(array_var($member, 'object_type_id'))->getName(); // 'person', 'company' $dimensionId = array_var($member, 'dimension_id'); $company = array_var(array_var(array_var($_POST, 'contact'),'user'),'company_id'); // Create new instance of Contact and set the basic fields $contact = new Contact(); $contact->setObjectName($name); if ($firstName) { $contact->setFirstName($firstName); }else{ $contact->setFirstName($name); } if ($surname) { $contact->setSurname($surname); } $contact->setCompanyId($company); $contact->setIsCompany($objectType == "company"); if ($parentMemberId){ if ( $companyId = Members::findById($parentMemberId)->getObjectId()) { $contact->setCompanyId($companyId); } } // Save Contact try { DB::beginWork(); $contact->save(); if ($email && is_valid_email($email)) { if (!Contacts::validateUniqueEmail($email)) { DB::rollback(); flash_error(lang("email address must be unique")); return false; }else{ if (!array_var (array_var(array_var($_POST, 'contact'),'user'), 'create-user')) { $contact->addEmail($email, 'personal', true); } flash_success(lang("success add contact", $contact->getObjectName())); } } // User settings $user = array_var(array_var($_POST, 'contact'),'user'); $user['username'] = str_replace(" ","",strtolower($name)) ; $this->createUserFromContactForm($user, $contact->getId(), $email); // Reload contact again due to 'createUserFromContactForm' changes Hook::fire("after_contact_quick_add", Contacts::instance()->findById($contact->getId()), $ret); DB::commit(); }catch (Exception $e){ DB::rollback(); flash_error($e->getMessage()); } // Reload evt_add("reload dimension tree", array('dim_id' => $dimensionId)); }
function unarchive() { if (!can_manage_dimension_members(logged_user())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $member = Members::findById(get_id()); if (!$member instanceof Member) { flash_error(lang('member dnx')); ajx_current("empty"); return; } if (get_id('user')) { $user = Contacts::findById($get_id('user')); } else { $user = logged_user(); } if (!$user instanceof Contact) { ajx_current("empty"); return; } try { DB::beginWork(); set_time_limit(0); $count = $member->unarchive($user); evt_add("reload dimension tree", $member->getDimensionId()); ajx_current("back"); flash_success(lang('success unarchive member', $member->getName(), $count)); DB::commit(); } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); } }
/** * Show permission update form * * @param void * @return null */ function permissions() { if (!active_project()->canChangePermissions(logged_user())) { flash_error(lang('no access permissions')); $this->redirectToUrl(active_project()->getOverviewUrl()); } // if $project_init = array_var($_GET, 'project_init'); tpl_assign('project_init', $project_init); tpl_assign('project_users', active_project()->getUsers(false)); tpl_assign('project_companies', active_project()->getCompanies()); tpl_assign('user_projects', logged_user()->getProjects()); $permissions = PermissionManager::getPermissionsText(); 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(); active_project()->clearCompanies(); active_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(active_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(active_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')); if ($project_init) { $this->redirectToUrl(active_project()->getEditUrl(active_project()->getOverviewUrl())); } else { $this->redirectTo('project_settings', 'users'); } // if } catch (Exception $e) { DB::rollback(); flash_error(lang('error update project permissions')); $this->redirectTo('project_settings', 'permissions'); } // try } // if }
/** * Delete comment * * @access public * @param void * @return null */ function delete_comment() { $comment = MessageComments::findById(get_id()); if (!$comment instanceof MessageComment) { flash_error(lang('comment dnx')); $this->redirectTo('message'); } // if $message = $comment->getMessage(); if (!$message instanceof ProjectMessage) { flash_error(lang('message dnx')); $this->redirectTo('message'); } // if if (!$comment->canDelete(logged_user())) { flash_error(lang('no access permissions')); $this->redirectToUrl($message->getViewUrl()); } // if try { DB::beginWork(); $comment->delete(); ApplicationLogs::createLog($comment, active_project(), ApplicationLogs::ACTION_DELETE); DB::commit(); flash_success(lang('success delete comment')); } catch (Exception $e) { DB::rollback(); flash_error(lang('error delete comment')); } // try $this->redirectToUrl($message->getViewUrl()); }
/** * Delete specific category * * @access public * @param void * @return null */ function delete_category() { $category = ProjectCategories::findById(get_id()); if (!$category instanceof ProjectCategory) { flash_error(lang('category dnx')); $this->redirectTo('tickets', 'categories'); } // if if (!$category->canDelete(logged_user())) { flash_error(lang('no access permissions')); $this->redirectToReferer(get_url('tickets', 'categories')); } // if try { DB::beginWork(); $category->delete(); ApplicationLogs::createLog($category, $category->getProject(), ApplicationLogs::ACTION_DELETE); DB::commit(); flash_success(lang('success deleted category', $category->getName())); } catch (Exception $e) { DB::rollback(); flash_error(lang('error delete category')); } // try $this->redirectTo('tickets', 'categories'); }
/** * 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 }
/** * Edit existing project form * * @param void * @return null */ function edit() { $this->setTemplate('add_project_form'); $project_form = ProjectForms::findById(get_id()); if (!$project_form instanceof ProjectForm) { flash_error(lang('project form dnx')); if (ProjectForm::canAdd(logged_user(), active_project())) { $this->redirectTo('form'); } else { $this->redirectToUrl(active_project()->getOverviewUrl()); } // if } // if if (!$project_form->canEdit(logged_user())) { flash_error(lang('no access permissions')); if (ProjectForm::canAdd(logged_user(), active_project())) { $this->redirectTo('form'); } else { $this->redirectToUrl(active_project()->getOverviewUrl()); } // if } // if $project_form_data = array_var($_POST, 'project_form'); if (!is_array($project_form_data)) { $project_form_data = array('name' => $project_form->getName(), 'description' => $project_form->getDescription(), 'success_message' => $project_form->getSuccessMessage(), 'action' => $project_form->getAction(), 'is_enabled' => $project_form->getIsEnabled(), 'is_visible' => $project_form->getIsVisible()); // array if ($project_form->getAction() == ProjectForm::ADD_COMMENT_ACTION) { $project_form_data['message_id'] = $project_form->getInObjectId(); } else { $project_form_data['task_list_id'] = $project_form->getInObjectId(); } // if } // if tpl_assign('project_form', $project_form); tpl_assign('project_form_data', $project_form_data); if (is_array(array_var($_POST, 'project_form'))) { $project_form->setFromAttributes($project_form_data); if ($project_form->getAction() == ProjectForm::ADD_COMMENT_ACTION) { $in_object = ProjectMessages::findById(get_id('message_id', $project_form_data)); $relation_error_message = lang('project form select message'); } else { $in_object = ProjectTaskLists::findById(get_id('task_list_id', $project_form_data)); $relation_error_message = lang('project form select task lists'); } // if if (!$in_object instanceof ProjectDataObject) { tpl_assign('error', new Error($relation_error_message)); $this->render(); } // if $project_form->setInObjectId($in_object->getObjectId()); // set related object ID try { DB::beginWork(); $project_form->save(); ApplicationLogs::createLog($project_form, active_project(), ApplicationLogs::ACTION_EDIT, true); DB::commit(); flash_success(lang('success edit project form', $project_form->getName())); $this->redirectTo('form'); } catch (Exception $e) { DB::rollback(); tpl_assign('error', $e); } // try } // if }
/** * Delete avatar * * @param void * @return null */ function delete_avatar() { $user = Users::findById(get_id()); if (!$user instanceof User) { flash_error(lang('user dnx')); $this->redirectTo('dashboard'); } // if if (!$user->canUpdateProfile(logged_user())) { flash_error(lang('no access permissions')); $this->redirectTo('dashboard'); } // if $redirect_to = array_var($_GET, 'redirect_to'); if (trim($redirect_to) == '' || !is_valid_url($redirect_to)) { $redirect_to = $user->getUpdateAvatarUrl(); } // if tpl_assign('redirect_to', $redirect_to); if (!$user->hasAvatar()) { flash_error(lang('avatar dnx')); $this->redirectToUrl($redirect_to); } // if try { DB::beginWork(); $user->deleteAvatar(); $user->save(); ApplicationLogs::createLog($user, null, ApplicationLogs::ACTION_EDIT); DB::commit(); flash_success(lang('success delete avatar')); } catch (Exception $e) { DB::rollback(); flash_error(lang('error delete avatar')); } // try $this->redirectToUrl($redirect_to); }
/** * Delete locale logo * * @param void * @return null */ function delete_logo() { $locale = I18nLocales::findById(get_id()); if (!$locale instanceof I18nLocale) { flash_error(lang('locale dnx')); $this->redirectToReferer(get_url('i18n', 'index')); } // if if (!$locale->canEdit(logged_user())) { flash_error(lang('no access permissions')); $this->redirectTo('i18n', 'index'); } // if try { DB::beginWork(); $locale->deleteLogo(); $locale->save(); ApplicationLogs::createLog($locale, 0, ApplicationLogs::ACTION_EDIT); DB::commit(); flash_success(lang('success delete logo')); } catch (Exception $e) { DB::rollback(); flash_error(lang('error delete logo', $e)); } // try $this->redirectToUrl($locale->getEditLogoUrl()); }
/** * Detach file from related object * * @param void * @return null */ function detach_from_object() { $manager_class = array_var($_GET, 'manager'); $object_id = get_id('object_id'); $file_id = get_id('file_id'); $object = get_object_by_manager_and_id($object_id, $manager_class); if (!$object instanceof ProjectDataObject) { flash_error(lang('no access permissions')); $this->redirectToReferer(get_url('dashboard')); } // if $file = ProjectFiles::findById($file_id); if (!$file instanceof ProjectFile) { flash_error(lang('file dnx')); $this->redirectToReferer(get_url('dashboard')); } // if $attached_file = AttachedFiles::findById(array('rel_object_manager' => $manager_class, 'rel_object_id' => $object_id, 'file_id' => $file_id)); // findById if (!$attached_file instanceof AttachedFile) { flash_error(lang('file not attached to object')); $this->redirectToReferer(get_url('dashboard')); } // if try { DB::beginWork(); $attached_file->delete(); DB::commit(); flash_success(lang('success detach file')); } catch (Exception $e) { flash_error(lang('error detach file')); DB::rollback(); } // try $this->redirectToReferer($object->getObjectUrl()); }