static function getWorkspaces($limit = 10) { $ws_dim = Dimensions::findByCode('workspaces'); $ws_object_type = self::instance()->getObjectTypeId(); $sql = "dimension_id = " . $ws_dim->getId() . " AND object_type_id = {$ws_object_type}"; $allowed_members = array(); $add_ctx_members = true; $context = active_context(); foreach ($context as $selection) { if ($selection instanceof Dimension && $selection->getCode() == 'workspaces') { $add_ctx_members = false; } else { if ($selection instanceof Member && $selection->getObjectTypeId() == $ws_object_type) { $allowed_members[] = $selection->getId(); } } } if ($add_ctx_members && count($allowed_members) > 0) { $sql .= " AND parent_member_id IN (" . implode(",", $allowed_members) . ")"; } else { $sql .= " AND parent_member_id = 0"; } $members = Members::findAll(array('conditions' => $sql, 'order' => 'name')); $res = array(); foreach ($members as $mem) { // controlar permissos para cada f*****g miembro } return $members; }
function workspaces_update_5_6() { // create associations DB::execute("\n\t\t\tINSERT INTO `" . TABLE_PREFIX . "dimension_member_associations` (`dimension_id`,`object_type_id`,`associated_dimension_id`, `associated_object_type_id`, `is_required`,`is_multiple`, `keeps_record`) VALUES\n\t\t\t((SELECT id from " . TABLE_PREFIX . "dimensions WHERE code = 'workspaces'),(SELECT id FROM " . TABLE_PREFIX . "object_types WHERE name = 'workspace'),(SELECT id from " . TABLE_PREFIX . "dimensions WHERE code = 'feng_persons'),(SELECT id FROM " . TABLE_PREFIX . "object_types WHERE name = 'person' LIMIT 1),0,1,0),\n\t\t\t((SELECT id from " . TABLE_PREFIX . "dimensions WHERE code = 'workspaces'),(SELECT id FROM " . TABLE_PREFIX . "object_types WHERE name = 'workspace'),(SELECT id from " . TABLE_PREFIX . "dimensions WHERE code = 'feng_persons'),(SELECT id FROM " . TABLE_PREFIX . "object_types WHERE name = 'company' LIMIT 1),0,1,0);\n\t\t"); // instantiate actual associations $ws_dim = Dimensions::findByCode('workspaces'); $ws_ot = ObjectTypes::findByName('workspace'); $ws_members = Members::findAll(array('conditions' => 'dimension_id = ' . $ws_dim->getId() . ' AND object_type_id = ' . $ws_ot->getId())); foreach ($ws_members as $ws_mem) { // after saving permissions the associations are instantiated by 'core_dimensions' plugin save_member_permissions($ws_mem); } }
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 getAllChildren($recursive = false, $order = null) { $child_members = array(); $find_options = array('conditions' => '`parent_member_id` = ' . $this->getId()); if ($order != null) $find_options['order'] = $order; $members = Members::findAll($find_options); foreach ($members as $mem){ $child_members[] = $mem; if ($recursive) { $children = $mem->getAllChildren($recursive, $order); $child_members = array_merge($child_members, $children); } } return $child_members; }
function allowed_users_to_assign() { $members = array(); $member_ids = explode(',', array_var($_GET, 'member_ids')); if (count($member_ids) > 0) { $tmp_members = Members::findAll(array('conditions' => 'id IN (' . implode(',', $member_ids) . ')')); foreach ($tmp_members as $m) { if ($m->getDimension()->getIsManageable()) { $members[] = $m; } } } if (count($members) == 0) { $context_plain = array_var($_GET, 'context'); $context = null; if (!is_null($context_plain)) { $context = build_context_array($context_plain); } } else { $context = $members; } $comp_array = allowed_users_to_assign($context); $object = array("companies" => $comp_array); Hook::fire('modify_allowed_users_to_assign', array('params' => array_var($_REQUEST, 'extra_params')), $object); if (!can_manage_tasks(logged_user()) && can_task_assignee(logged_user())) { $object['only_me'] = "1"; } ajx_extra_data($object); ajx_current("empty"); }
function save_member_permissions($member) { $permissionsString = array_var($_POST, 'permissions'); if ($permissionsString && $permissionsString != '') { $permissions = json_decode($permissionsString); } $sharingTablecontroller = new SharingTableController(); $changed_pgs = array(); if (isset($permissions) && is_array($permissions)) { $allowed_pg_ids = array(); foreach ($permissions as &$perm) { $cmp = ContactMemberPermissions::findById(array('permission_group_id' => $perm->pg, 'member_id' => $member->getId(), 'object_type_id' => $perm->o)); if (!$cmp instanceof ContactMemberPermission) { $cmp = new ContactMemberPermission(); $cmp->setPermissionGroupId($perm->pg); $cmp->setMemberId($member->getId()); $cmp->setObjectTypeId($perm->o); } $cmp->setCanWrite($perm->w); $cmp->setCanDelete($perm->d); if ($perm->r) { $allowed_pg_ids[$perm->pg] = array(); if (isset($allowed_pg_ids[$perm->pg]['w'])) { if (!$allowed_pg_ids[$perm->pg]['w']) { $allowed_pg_ids[$perm->pg]['w'] = $perm->w; } } else { $allowed_pg_ids[$perm->pg]['w'] = $perm->w; } if (isset($allowed_pg_ids[$perm->pg]['d'])) { if (!$allowed_pg_ids[$perm->pg]['d']) { $allowed_pg_ids[$perm->pg]['d'] = $perm->d; } } else { $allowed_pg_ids[$perm->pg]['d'] = $perm->d; } $cmp->save(); } else { $cmp->delete(); } $perm->m = $member->getId(); $changed_pgs[] = $perm->pg; } foreach ($changed_pgs as $pg_id) { $sharingTablecontroller->afterPermissionChanged($pg_id, $permissions); } foreach ($allowed_pg_ids as $key => $mids) { $root_cmp = ContactMemberPermissions::findById(array('permission_group_id' => $key, 'member_id' => $member->getId(), 'object_type_id' => $member->getObjectTypeId())); if (!$root_cmp instanceof ContactMemberPermission) { $root_cmp = new ContactMemberPermission(); $root_cmp->setPermissionGroupId($key); $root_cmp->setMemberId($member->getId()); $root_cmp->setObjectTypeId($member->getObjectTypeId()); } $root_cmp->setCanWrite($mids['w'] == true ? 1 : 0); $root_cmp->setCanDelete($mids['d'] == true ? 1 : 0); $root_cmp->save(); } } // check the status of the dimension to set 'allow_all', 'deny_all' or 'check' $dimension = $member->getDimension(); $mem_ids = $dimension->getAllMembers(true); if (count($mem_ids) == 0) { $mem_ids[] = 0; } foreach ($changed_pgs as $pg_id) { $count = ContactMemberPermissions::count(array('conditions' => "`permission_group_id`={$pg_id} AND `member_id` IN (" . implode(",", $mem_ids) . ") AND `can_delete` = 0")); if ($count > 0) { $dimension->setContactDimensionPermission($pg_id, 'check'); } else { $count = ContactMemberPermissions::count(array('conditions' => "`permission_group_id`={$pg_id} AND `member_id` IN (" . implode(",", $mem_ids) . ")")); if ($count == 0) { $dimension->setContactDimensionPermission($pg_id, 'deny all'); } else { $allow_all = true; $dim_obj_types = $dimension->getAllowedObjectTypeContents(); $members = Members::findAll("`id` IN (" . implode(",", $mem_ids) . ")"); foreach ($dim_obj_types as $dim_obj_type) { $mem_ids_for_ot = array(); foreach ($members as $member) { if ($dim_obj_type->getDimensionObjectTypeId() == $member->getObjectTypeId()) { $mem_ids_for_ot[] = $member->getId(); } } if (count($mem_ids_for_ot) == 0) { $mem_ids_for_ot[] = 0; } $count = ContactMemberPermissions::count(array('conditions' => "`permission_group_id`={$pg_id} AND \n\t\t\t\t\t\t`object_type_id` = " . $dim_obj_type->getContentObjectTypeId() . " AND `can_delete` = 1 AND `member_id` IN (" . implode(",", $mem_ids_for_ot) . ")")); if ($count != count($mem_ids_for_ot)) { $allow_all = false; break; } } if ($allow_all) { $dimension->setContactDimensionPermission($pg_id, 'allow all'); } else { $dimension->setContactDimensionPermission($pg_id, 'check'); } } } } }
if ($show_widget) { $extra_conditions = " AND parent_member_id " . ($add_ctx_members && count($allowed_members) > 0 ? "IN (" . implode(",", $allowed_members) . ")" : "=0"); $parent = null; $context = active_context(); if (is_array($context)) { foreach ($context as $selection) { if ($selection instanceof Member && $selection->getDimensionId() == $ws_dimension->getId()) { $parent = $selection; break; } } } $ws_ot_id = ObjectTypes::findByName('workspace')->getId(); $pg_array = logged_user()->getPermissionGroupIds(); $current_member_cond = $parent instanceof Member ? "AND parent_member_id=" . $parent->getId() : ""; $members = Members::findAll(array('limit' => $limit, 'order' => "depth, name", 'conditions' => "object_type_id={$ws_ot_id} {$current_member_cond} AND archived_by_id=0 AND EXISTS (\r\n\t\t\tSELECT cmp.member_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp WHERE cmp.member_id=" . TABLE_PREFIX . "members.id AND cmp.permission_group_id IN (" . implode(',', $pg_array) . "))")); if ($parent instanceof Member && count($members) < $limit) { $tmp_ids = array(); foreach ($members as $m) { $tmp_ids[] = $m->getId(); } $extra_conds = "AND archived_by_id=0 AND EXISTS (\r\n\t\t\tSELECT cmp.member_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp WHERE cmp.member_id=" . TABLE_PREFIX . "members.id AND cmp.permission_group_id IN (" . implode(',', $pg_array) . "))"; $childs = $parent->getAllChildren(true, 'name', $extra_conds); foreach ($childs as $ch) { if (in_array($ch->getId(), $tmp_ids)) { continue; } if ($ch->getObjectTypeId() == $ws_ot_id && count($members) <= $limit) { $members[] = $ch; } if (count($members) >= $limit) {
private function getAssignableParents($dim_id, $otype_id) { $parents = Members::findAll(array("conditions" => array("`object_type_id` IN (\n\t\t\tSELECT `parent_object_type_id` FROM `" . DimensionObjectTypeHierarchies::instance()->getTableName() . "` WHERE `dimension_id` = ? AND `child_object_type_id` = ?\n\t\t)", $dim_id, $otype_id))); $parents_info = array(); foreach ($parents as $parent) { $parents_info[] = array('id' => $parent->getId(), 'name' => $parent->getName()); } $dim_obj_type = DimensionObjectTypes::findById(array('dimension_id' => $dim_id, 'object_type_id' => $otype_id)); if ($dim_obj_type && $dim_obj_type->getIsRoot()) { array_unshift($parents_info, array('id' => 0, 'name' => lang('none'))); } return $parents_info; }
function core_dim_add_to_person_user_dimensions($object, $user_ids) { if (logged_user() instanceof Contact) { $members = Members::findAll(array("conditions" => "`object_id` IN (" . implode(",", $user_ids) . ") AND `dimension_id` IN (SELECT `id` FROM `" . TABLE_PREFIX . "dimensions` WHERE `code` IN ('feng_persons'))")); if (is_array($members) && count($members) > 0) { $object->addToMembers($members); } } }
function add_to_members($object, $member_ids, $user = null, $check_allowed_members = true) { if (!$user instanceof Contact) { $user = logged_user(); } if ($user->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } if (isset($_POST['trees_not_loaded']) && $_POST['trees_not_loaded'] > 0) { return; } $required_dimension_ids = array(); $dimension_object_types = $object->getDimensionObjectTypes(); foreach ($dimension_object_types as $dot) { if ($dot->getIsRequired()) { $required_dimension_ids[] = $dot->getDimensionId(); } } $required_dimensions = Dimensions::findAll(array("conditions" => "id IN (" . implode(",", $required_dimension_ids) . ")")); // If not entered members if (!count($member_ids) > 0) { $throw_error = true; if (Plugins::instance()->isActivePlugin('core_dimensions')) { $personal_member = Members::findById($user->getPersonalMemberId()); if ($personal_member instanceof Member) { $member_ids[] = $user->getPersonalMemberId(); } } } if (count($member_ids) > 0) { $enteredMembers = Members::findAll(array('conditions' => 'id IN (' . implode(",", $member_ids) . ')')); } else { $enteredMembers = array(); } $object->removeFromMembers($user, $enteredMembers); /* @var $object ContentDataObject */ $validMembers = $check_allowed_members ? $object->getAllowedMembersToAdd($user, $enteredMembers) : $enteredMembers; foreach ($required_dimensions as $rdim) { $exists = false; foreach ($validMembers as $m) { if ($m->getDimensionId() == $rdim->getId()) { $exists = true; break; } } if (!$exists) { throw new Exception(lang('must choose at least one member of', $rdim->getName())); } } $object->addToMembers($validMembers); Hook::fire('after_add_to_members', $object, $null); $object->addToSharingTable(); return $validMembers; }
function instantiate() { $selected_members = array(); $id = get_id(); $template = COTemplates::findById($id); if (!$template instanceof COTemplate) { flash_error(lang("template dnx")); ajx_current("empty"); return; } $parameters = TemplateParameters::getParametersByTemplate($id); $parameterValues = array_var($_POST, 'parameterValues'); if (count($parameters) > 0 && !isset($parameterValues)) { ajx_current("back"); return; } if (array_var($_POST, 'members')) { $selected_members = json_decode(array_var($_POST, 'members')); } else { $context = active_context(); foreach ($context as $selection) { if ($selection instanceof Member) { $selected_members[] = $selection->getId(); } } } $objects = $template->getObjects(); $controller = new ObjectController(); if (count($selected_members > 0)) { $selected_members_instances = Members::findAll(array('conditions' => 'id IN (' . implode($selected_members) . ')')); } else { $selected_members_instances = array(); } DB::beginWork(); $active_context = active_context(); foreach ($objects as $object) { if (!$object instanceof ContentDataObject) { continue; } // copy object $copy = $object->copy(); if ($copy->columnExists('is_template')) { $copy->setColumnValue('is_template', false); } if ($copy instanceof ProjectTask) { // don't copy parent task and milestone $copy->setMilestoneId(0); $copy->setParentId(0); } $copy->save(); /* if (!can_write(logged_user(), $selected_members_instances, $copy->getObjectTypeId()) ) { flash_error(lang('no context permissions to add', $copy instanceof ProjectTask ? lang("tasks") : ($copy instanceof ProjectMilestone ? lang('milestones') : ''))); DB::rollback(); ajx_current("empty"); return; }*/ // Copy members from origial object, if it doesn't have then use active context members /* $template_object_members = $object->getMemberIds(); if (count($template_object_members) == 0) { $object_member_ids = active_context_members(false); if (count($object_member_ids) > 0) { $template_object_members = Members::findAll(array("id" => true, "conditions" => "id IN (".implode(",", $object_member_ids).")")); } }*/ /* Set instantiated object members: * foreach dimension: * if no member is active then the instantiated object is put in the same members as the original for current dimension * if a member is selected in current dimension then the instantiated object will be put in that member */ $template_object_members = $object->getMembers(); $object_members = array(); foreach ($active_context as $selection) { if ($selection instanceof Member) { // member selected $object_members[] = $selection->getId(); } else { if ($selection instanceof Dimension) { // no member selected foreach ($template_object_members as $tom) { if ($tom->getDimensionId() == $selection->getId()) { $object_members[] = $tom->getId(); } } } } } $controller->add_to_members($copy, $object_members); // copy linked objects $copy->copyLinkedObjectsFrom($object); // copy subtasks if applicable if ($copy instanceof ProjectTask) { ProjectTasks::copySubTasks($object, $copy, false); foreach ($copy->getOpenSubTasks(false) as $m_task) { $controller->add_to_members($m_task, $object_members); } $manager = $copy->manager(); } else { if ($copy instanceof ProjectMilestone) { ProjectMilestones::copyTasks($object, $copy, false); foreach ($copy->getTasks(false) as $m_task) { $controller->add_to_members($m_task, $object_members); } $manager = $copy->manager(); } } // copy custom properties $copy->copyCustomPropertiesFrom($object); // set property values as defined in template $objProp = TemplateObjectProperties::getPropertiesByTemplateObject($id, $object->getId()); foreach ($objProp as $property) { $propName = $property->getProperty(); $value = $property->getValue(); if ($manager->getColumnType($propName) == DATA_TYPE_STRING || $manager->getColumnType($propName) == DATA_TYPE_INTEGER) { if (is_array($parameterValues)) { foreach ($parameterValues as $param => $val) { if (strpos($value, '{' . $param . '}') !== FALSE) { $value = str_replace('{' . $param . '}', $val, $value); } } } } else { if ($manager->getColumnType($propName) == DATA_TYPE_DATE || $manager->getColumnType($propName) == DATA_TYPE_DATETIME) { $operator = '+'; if (strpos($value, '+') === false) { $operator = '-'; } $opPos = strpos($value, $operator); if ($opPos !== false) { // Is parametric $dateParam = substr($value, 1, strpos($value, '}') - 1); $date = $parameterValues[$dateParam]; $dateUnit = substr($value, strlen($value) - 1); // d, w or m (for days, weeks or months) if ($dateUnit == 'm') { $dateUnit = 'M'; // make month unit uppercase to call DateTimeValue::add with correct parameter } $dateNum = (int) substr($value, strpos($value, $operator), strlen($value) - 2); $date = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $date); $date = new DateTimeValue($date->getTimestamp() - logged_user()->getTimezone() * 3600); // set date to GMT 0 $value = $date->add($dateUnit, $dateNum); } else { $value = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $value); } } } if ($value != '') { if (!$copy->setColumnValue($propName, $value)) { $copy->object->setColumnValue($propName, $value); } $copy->save(); } } // subscribe assigned to if ($copy instanceof ProjectTask) { foreach ($copy->getOpenSubTasks(false) as $m_task) { if ($m_task->getAssignedTo() instanceof Contact) { $m_task->subscribeUser($copy->getAssignedTo()); } } if ($copy->getAssignedTo() instanceof Contact) { $copy->subscribeUser($copy->getAssignedTo()); } } else { if ($copy instanceof ProjectMilestone) { foreach ($copy->getTasks(false) as $m_task) { if ($m_task->getAssignedTo() instanceof Contact) { $m_task->subscribeUser($copy->getAssignedTo()); } } } } // copy reminders $reminders = ObjectReminders::getByObject($object); foreach ($reminders as $reminder) { $copy_reminder = new ObjectReminder(); $copy_reminder->setContext($reminder->getContext()); $reminder_date = $copy->getColumnValue($reminder->getContext()); if ($reminder_date instanceof DateTimeValue) { $reminder_date = new DateTimeValue($reminder_date->getTimestamp()); $reminder_date->add('m', -$reminder->getMinutesBefore()); } $copy_reminder->setDate($reminder_date); $copy_reminder->setMinutesBefore($reminder->getMinutesBefore()); $copy_reminder->setObject($copy); $copy_reminder->setType($reminder->getType()); $copy_reminder->setUserId($reminder->getUserId()); $copy_reminder->save(); } } DB::commit(); if (is_array($parameters) && count($parameters) > 0) { ajx_current("back"); } else { if (!$choose_ctx) { ajx_current("back"); } else { ajx_current("reload"); } } }
function import_google_calendar() { $users_cal = ExternalCalendarUsers::findAll(); if (count($users_cal) > 0) { foreach ($users_cal as $users) { $contact = Contacts::findById($users->getContactId()); $calendars = ExternalCalendars::findByExtCalUserId($users->getId()); require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Gdata'); Zend_Loader::loadClass('Zend_Gdata_AuthSub'); Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); Zend_Loader::loadClass('Zend_Gdata_Calendar'); $user = $users->getAuthUser(); $pass = $users->getAuthPass(); $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; try { $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service); $gdataCal = new Zend_Gdata_Calendar($client); //update or insert events for calendars foreach ($calendars as $calendar) { //check the deleted calendars $delete_calendar = true; $calFeed = $gdataCal->getCalendarListFeed(); foreach ($calFeed as $calF) { $cal_src = explode("/", $calF->content->src); array_pop($cal_src); $calendar_visibility = end($cal_src); array_pop($cal_src); $calendar_user = end($cal_src); if ($calendar_user == $calendar->getCalendarUser()) { $delete_calendar = false; } } if (!$delete_calendar) { $calendar_user = $calendar->getCalendarUser(); $calendar_visibility = $calendar->getCalendarVisibility(); $query = $gdataCal->newEventQuery(); $query->setUser($calendar_user); $query->setVisibility($calendar_visibility); $query->setSingleEvents(true); $query->setProjection('full'); // execute and get results $event_list = $gdataCal->getCalendarEventFeed($query); $array_events_google = array(); foreach ($event_list as $event) { $event_id = explode("/", $event->id->text); $special_id = end($event_id); $event_name = lang("untitle event"); if ($event->title->text != "") { $event_name = $event->title->text; } $array_events_google[] = $special_id; $new_event = ProjectEvents::findBySpecialId($special_id); if ($new_event) { if ($new_event->getUpdateSync() instanceof DateTimeValue && strtotime(ProjectEvents::date_google_to_sql($event->updated)) > $new_event->getUpdateSync()->getTimestamp()) { $start = strtotime(ProjectEvents::date_google_to_sql($event->when[0]->startTime)); $fin = strtotime(ProjectEvents::date_google_to_sql($event->when[0]->endTime)); if ($fin - $start == 86400) { $new_event->setStart(date("Y-m-d H:i:s", $start)); $new_event->setDuration(date("Y-m-d H:i:s", $start)); $new_event->setTypeId(2); } elseif ($fin - $start > 86400) { $t_s = explode(' ', date("Y-m-d H:i:s", $start)); $t_f = explode(' ', date("Y-m-d H:i:s", $fin)); $date_s = new DateTimeValue(strtotime($t_s[0] . "00:00:00") - $contact->getTimezone() * 3600); $date_f = new DateTimeValue(strtotime($t_f[0] . "23:59:59 -1 day") - $contact->getTimezone() * 3600); $new_event->setStart(date("Y-m-d H:i:s", $date_s->getTimestamp())); $new_event->setDuration(date("Y-m-d H:i:s", $date_f->getTimestamp())); $new_event->setTypeId(2); } else { $new_event->setStart(ProjectEvents::date_google_to_sql($event->when[0]->startTime)); $new_event->setDuration(ProjectEvents::date_google_to_sql($event->when[0]->endTime)); } $new_event->setObjectName($event_name); $new_event->setDescription($event->content->text); $new_event->setUpdateSync(ProjectEvents::date_google_to_sql($event->updated)); $new_event->setExtCalId($calendar->getId()); $new_event->save(); } } else { $new_event = new ProjectEvent(); $start = strtotime(ProjectEvents::date_google_to_sql($event->when[0]->startTime)); $fin = strtotime(ProjectEvents::date_google_to_sql($event->when[0]->endTime)); if ($fin - $start == 86400) { $new_event->setStart(date("Y-m-d H:i:s", $start)); $new_event->setDuration(date("Y-m-d H:i:s", $start)); $new_event->setTypeId(2); } elseif ($fin - $start > 86400) { $t_s = explode(' ', date("Y-m-d H:i:s", $start)); $t_f = explode(' ', date("Y-m-d H:i:s", $fin)); $date_s = new DateTimeValue(strtotime($t_s[0] . "00:00:00") - $contact->getTimezone() * 3600); $date_f = new DateTimeValue(strtotime($t_f[0] . "23:59:59 -1 day") - $contact->getTimezone() * 3600); $new_event->setStart(date("Y-m-d H:i:s", $date_s->getTimestamp())); $new_event->setDuration(date("Y-m-d H:i:s", $date_f->getTimestamp())); $new_event->setTypeId(2); } else { $new_event->setStart(ProjectEvents::date_google_to_sql($event->when[0]->startTime)); $new_event->setDuration(ProjectEvents::date_google_to_sql($event->when[0]->endTime)); $new_event->setTypeId(1); } $new_event->setObjectName($event_name); $new_event->setDescription($event->content->text); $new_event->setSpecialID($special_id); $new_event->setUpdateSync(ProjectEvents::date_google_to_sql($event->updated)); $new_event->setExtCalId($calendar->getId()); $new_event->save(); $conditions = array('event_id' => $new_event->getId(), 'contact_id' => $contact->getId()); //insert only if not exists if (EventInvitations::findById($conditions) == null) { $invitation = new EventInvitation(); $invitation->setEventId($new_event->getId()); $invitation->setContactId($contact->getId()); $invitation->setInvitationState($contact instanceof Contact && $contact->getId() == $contact->getId() ? 1 : 0); $invitation->save(); } //insert only if not exists if (ObjectSubscriptions::findBySubscriptions($new_event->getId(), $contact) == null) { $subscription = new ObjectSubscription(); $subscription->setObjectId($new_event->getId()); $subscription->setContactId($contact->getId()); $subscription->save(); } if ($users->getRelatedTo()) { $member = array(); $member_ids = explode(",", $users->getRelatedTo()); foreach ($member_ids as $member_id) { $member[] = $member_id; } $object_controller = new ObjectController(); $object_controller->add_to_members($new_event, $member); } else { $member_ids = array(); $context = active_context(); if (count($context) > 0) { foreach ($context as $selection) { if ($selection instanceof Member) { $member_ids[] = $selection->getId(); } } } if (count($member_ids) == 0 && $contact instanceof Contact) { $m = Members::findById($contact->getPersonalMemberId()); if (!$m instanceof Member) { $person_dim = Dimensions::findByCode('feng_persons'); if ($person_dim instanceof Dimension) { $member_ids = Members::findAll(array('id' => true, 'conditions' => array("object_id = ? AND dimension_id = ?", $contact->getId(), $person_dim->getId()))); } } else { $member_ids[] = $m->getId(); } } $object_controller = new ObjectController(); $object_controller->add_to_members($new_event, $member_ids, $contact); } } } // foreach event list //check the deleted events $events_delete = ProjectEvents::findByExtCalId($calendar->getId()); if ($events_delete) { foreach ($events_delete as $event_delete) { if (!in_array($event_delete->getSpecialID(), $array_events_google)) { $event_delete->trash(); $event_delete->setSpecialID(""); $event_delete->setExtCalId(0); $event_delete->save(); } } } } else { $events = ProjectEvents::findByExtCalId($calendar->getId()); if ($calendar->delete()) { if ($events) { foreach ($events as $event) { $event->trash(); $event->setSpecialID(""); $event->setExtCalId(0); $event->save(); } } } } } //foreach calendars } catch (Exception $e) { //Logger::log($e->getMessage()); } } } }
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 { $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)) { $cdp = ContactDimensionPermissions::instance()->findOne(array('conditions' => "permission_group_id = '$permission_group_id' AND dimension_id = $dimension_id")); if (!$cdp instanceof ContactDimensionPermission) { $cdp = new ContactDimensionPermission(); $cdp->setPermissionGroupId($permission_group_id); $cdp->setContactDimensionId($dimension_id); $cdp->setPermissionType('check'); $cdp->save(); } else { if ($cdp->getPermissionType() == 'deny all') { $cdp->setPermissionType('check'); $cdp->save(); } } $stCtrl = new SharingTableController(); $stCtrl->afterPermissionChanged($permission_group_id, $shtab_permissions); } return $new_permissions; } catch (Exception $e) { throw $e; } }
function render_single_member_selector(Dimension $dimension, $genid = null, $selected_member_ids = null, $options = array(), $default_view = true) { if (is_null($genid)) { $genid = gen_id(); } $dim_info = array('dimension_id' => $dimension->getId(), 'dimension_code' => $dimension->getCode(), 'dimension_name' => $dimension->getName(), 'is_manageable' => $dimension->getIsManageable(), 'is_required' => array_var($options, 'is_required'), 'is_multiple' => array_var($options, 'is_multiple')); $dimensions = array($dim_info); if (!is_array($selected_member_ids)) { $selected_member_ids = array(); } foreach ($selected_member_ids as $k => &$v) { if (!is_numeric($v)) { unset($selected_member_ids[$k]); } } if (count($selected_member_ids) > 0) { $sql = "SELECT m.id FROM " . TABLE_PREFIX . "members m WHERE m.id IN (" . implode(',', $selected_member_ids) . ") AND m.dimension_id=" . $dimension->getId(); $clean_sel_member_ids = array_flat(DB::executeAll($sql)); $selected_member_ids = $clean_sel_member_ids; } $content_object_type_id = array_var($options, 'content_object_type_id'); $initial_selected_members = $selected_member_ids; if (is_null($selected_member_ids)) { $selected_member_ids = array(); } // Set view variables $selected_members = count($selected_member_ids) > 0 ? Members::findAll(array('conditions' => 'id IN (' . implode(',', $selected_member_ids) . ')')) : array(); $selected_members_json = "[" . implode(',', $selected_member_ids) . "]"; $component_id = "{$genid}-member-selectors-panel-{$content_object_type_id}"; $listeners = array_var($options, 'listeners', array()); $allowed_member_type_ids = array_var($options, 'allowedMemberTypes', null); $hide_label = array_var($options, 'hide_label', false); if (isset($options['label'])) { $label = $options['label']; } // Render view include get_template_path("components/multiple_dimension_selector", "dimension"); }
function edit_timeslot() { ajx_current("empty"); $timeslot_data = array_var($_POST, 'timeslot'); $timeslot = Timeslots::findById(array_var($timeslot_data, 'id', 0)); if (!$timeslot instanceof Timeslot) { flash_error(lang('timeslot dnx')); return; } //context permissions or members $member_ids = json_decode(array_var($_POST, 'members', array())); // clean member_ids $tmp_mids = array(); foreach ($member_ids as $mid) { if (!is_null($mid) && trim($mid) != "") { $tmp_mids[] = $mid; } } $member_ids = $tmp_mids; if (empty($member_ids)) { if (!can_add(logged_user(), active_context(), Timeslots::instance()->getObjectTypeId())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } } else { if (count($member_ids) > 0) { $enteredMembers = Members::findAll(array('conditions' => 'id IN (' . implode(",", $member_ids) . ')')); } else { $enteredMembers = array(); } if (!can_add(logged_user(), $enteredMembers, Timeslots::instance()->getObjectTypeId())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } } try { $hoursToAdd = array_var($timeslot_data, 'hours', 0); $minutes = array_var($timeslot_data, 'minutes', 0); if (strpos($hoursToAdd, ',') && !strpos($hoursToAdd, '.')) { $hoursToAdd = str_replace(',', '.', $hoursToAdd); } if (strpos($hoursToAdd, ':') && !strpos($hoursToAdd, '.')) { $pos = strpos($hoursToAdd, ':') + 1; $len = strlen($hoursToAdd) - $pos; $minutesToAdd = substr($hoursToAdd, $pos, $len); if (!strlen($minutesToAdd) <= 2 || !strlen($minutesToAdd) > 0) { $minutesToAdd = substr($minutesToAdd, 0, 2); } $mins = $minutesToAdd / 60; $hours = substr($hoursToAdd, 0, $pos - 1); $hoursToAdd = $hours + $mins; } if ($minutes) { $min = str_replace('.', '', $minutes / 6); $hoursToAdd = $hoursToAdd + ("0." . $min); } if ($hoursToAdd <= 0) { flash_error(lang('time has to be greater than 0')); return; } $startTime = getDateValue(array_var($timeslot_data, 'date')); $startTime = $startTime->add('h', 8 - logged_user()->getTimezone()); $endTime = getDateValue(array_var($timeslot_data, 'date')); $endTime = $endTime->add('h', 8 - logged_user()->getTimezone() + $hoursToAdd); $timeslot_data['start_time'] = $startTime; $timeslot_data['end_time'] = $endTime; $timeslot_data['name'] = $timeslot_data['description']; //Only admins can change timeslot user if (!array_var($timeslot_data, 'contact_id') && !logged_user()->isAdministrator()) { $timeslot_data['contact_id'] = $timeslot->getContactId(); } $timeslot->setFromAttributes($timeslot_data); $user = Contacts::findById($timeslot_data['contact_id']); $billing_category_id = $user->getDefaultBillingId(); $bc = BillingCategories::findById($billing_category_id); if ($bc instanceof BillingCategory) { $timeslot->setBillingId($billing_category_id); $hourly_billing = $bc->getDefaultValue(); $timeslot->setHourlyBilling($hourly_billing); $timeslot->setFixedBilling($hourly_billing * $hoursToAdd); $timeslot->setIsFixedBilling(false); } DB::beginWork(); $timeslot->save(); $member_ids = json_decode(array_var($_POST, 'members', '')); $object_controller = new ObjectController(); $object_controller->add_to_members($timeslot, $member_ids); DB::commit(); ApplicationLogs::createLog($timeslot, ApplicationLogs::ACTION_EDIT); ajx_extra_data(array("timeslot" => $timeslot->getArrayInfo())); } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); } // try }
static function getArrayInfo($raw_data, $full = false) { $desc = ""; if ($full) { if (config_option("wysiwyg_tasks")) { if ($raw_data['type_content'] == "text") { $desc = nl2br(htmlspecialchars($raw_data['text'])); } else { $desc = purify_html(nl2br($raw_data['text'])); } } else { if ($raw_data['type_content'] == "text") { $desc = htmlspecialchars($raw_data['text']); } else { $desc = html_to_text(html_entity_decode(nl2br($raw_data['text']), null, "UTF-8")); } } } $member_ids = ObjectMembers::instance()->getCachedObjectMembers($raw_data['id']); $tmp_task = new ProjectTask(); $tmp_task->setObjectId($raw_data['id']); $tmp_task->setId($raw_data['id']); $tmp_task->setAssignedToContactId($raw_data['assigned_to_contact_id']); $result = array('id' => (int) $raw_data['id'], 'name' => $raw_data['name'], 'description' => $desc, 'members' => $member_ids, 'createdOn' => strtotime($raw_data['created_on']), 'createdById' => (int) $raw_data['created_by_id'], 'otype' => $raw_data['object_subtype'], 'percentCompleted' => (int) $raw_data['percent_completed'], 'memPath' => str_replace('"', "'", escape_character(json_encode($tmp_task->getMembersIdsToDisplayPath())))); if (isset($raw_data['isread'])) { $result['isread'] = $raw_data['isread']; } $result['multiAssignment'] = (int) array_var($raw_data, 'multi_assignment'); if ($raw_data['completed_by_id'] > 0) { $result['status'] = 1; } if ($raw_data['parent_id'] > 0) { $result['parentId'] = (int) $raw_data['parent_id']; } $result['subtasksIds'] = $tmp_task->getSubTasksIds(); //if ($this->getPriority() != 200) $result['priority'] = (int) $raw_data['priority']; if ($raw_data['milestone_id'] > 0) { $result['milestoneId'] = (int) $raw_data['milestone_id']; } if ($raw_data['assigned_by_id'] > 0) { $result['assignedById'] = (int) $raw_data['assigned_by_id']; } if ($raw_data['assigned_to_contact_id'] > 0) { $result['assignedToContactId'] = (int) $raw_data['assigned_to_contact_id']; } $result['atName'] = $tmp_task->getAssignedToName(); if ($raw_data['completed_by_id'] > 0) { $result['completedById'] = (int) $raw_data['completed_by_id']; $result['completedOn'] = strtotime($raw_data['completed_on']); } if ($raw_data['due_date'] != EMPTY_DATETIME) { $result['useDueTime'] = $raw_data['use_due_time'] ? 1 : 0; if ($result['useDueTime']) { $result['dueDate'] = strtotime($raw_data['due_date']) + logged_user()->getTimezone() * 3600; } else { $result['dueDate'] = strtotime($raw_data['due_date']); } } if ($raw_data['start_date'] != EMPTY_DATETIME) { $result['useStartTime'] = $raw_data['use_start_time'] ? 1 : 0; if ($result['useStartTime']) { $result['startDate'] = strtotime($raw_data['start_date']) + logged_user()->getTimezone() * 3600; } else { $result['startDate'] = strtotime($raw_data['start_date']); } } $time_estimate = $raw_data['time_estimate']; $result['timeEstimate'] = $raw_data['time_estimate']; if ($time_estimate > 0) { $result['timeEstimateString'] = str_replace(',', ',<br>', DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($time_estimate * 60), 'hm', 60)); } $result['timeZone'] = logged_user()->getTimezone() * 3600; $ot = $tmp_task->getOpenTimeslots(); if ($ot) { $users = array(); $time = array(); $paused = array(); foreach ($ot as $t) { if (!$t instanceof Timeslot) { continue; } $time[] = $t->getSeconds(); $users[] = $t->getContactId(); $paused[] = $t->isPaused() ? 1 : 0; if ($t->isPaused() && $t->getContactId() == logged_user()->getId()) { $result['pauseTime'] = $t->getPausedOn()->getTimestamp(); } } $result['workingOnTimes'] = $time; $result['workingOnIds'] = $users; $result['workingOnPauses'] = $paused; } $total_minutes = $tmp_task->getTotalMinutes(); if ($total_minutes > 0) { $result['worked_time'] = $total_minutes; $result['worked_time_string'] = str_replace(',', ',<br>', DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($total_minutes * 60), 'hm', 60)); } else { $result['worked_time'] = 0; } $pending_time = $time_estimate - $total_minutes; if ($pending_time > 0) { $result['pending_time'] = $pending_time; $result['pending_time_string'] = str_replace(',', ',<br>', DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($pending_time * 60), 'hm', 60)); } else { $result['pending_time'] = 0; } if ($raw_data['repeat_forever'] > 0 || $raw_data['repeat_num'] > 0 || $raw_data['repeat_end'] != EMPTY_DATETIME && $raw_data['repeat_end'] != '') { $result['repetitive'] = 1; } $tmp_members = array(); if (count($member_ids) > 0) { $tmp_members = Members::findAll(array("conditions" => "id IN (" . implode(',', $member_ids) . ")")); } $result['can_add_timeslots'] = can_add_timeslots(logged_user(), $tmp_members); //tasks dependencies if (config_option('use tasks dependencies')) { //get all dependant tasks ids, not completed yet $pending_tasks_ids = ProjectTaskDependencies::getDependenciesForTaskOnlyPendingIds($tmp_task->getId()); //get the total of previous tasks $result['dependants'] = $pending_tasks_ids; $result['previous_tasks_total'] = ProjectTaskDependencies::countPendingPreviousTasks($tmp_task->getId()); } return $result; }
/** * @param $email MailContent to classify * @param $members array of member ids in which the $email will be classified * @param $classification_data additional data needed for classification * @param $process_conversation boolean, if true all the conversation will be classified * @param $after_receiving boolean, indicates wheather the function was called after receiving the email or if only the user is classiffying the email */ function do_classify_mail($email, $members, $classification_data = null, $process_conversation = true, $after_receiving = false) { try { $ctrl = new ObjectController(); $create_task = false; //array_var($classification_data, 'create_task') == 'checked'; if (is_null($classification_data)) { $classification_data = array(); MailUtilities::parseMail($email->getContent(), $decoded, $parsedEmail, $warnings); for ($j = 0; $j < count(array_var($parsedEmail, "Attachments", array())); $j++) { $classification_data["att_" . $j] = true; } } foreach ($members as $k => &$mem_id) { if ($mem_id == "") { unset($members[$k]); } } $canWriteFiles = $this->checkFileWritability($classification_data, $parsedEmail); if ($canWriteFiles) { // if $after_receiving == true transaction has already been started, so dont start a new one if (!$after_receiving) { DB::beginWork(); } if (count($members) > 0) { $account_owner = logged_user() instanceof contact ? logged_user() : Contacts::findById($email->getAccount()->getContactId()); $ctrl->add_to_members($email, $members, $account_owner); if ($after_receiving && $email->getHasAttachments() && user_config_option('auto_classify_attachments') || !$after_receiving && $email->getHasAttachments() && (user_config_option('mail_drag_drop_prompt') == 'classify' || user_config_option('mail_drag_drop_prompt') == 'prompt' && intval(array_var($_REQUEST, 'classify_attachments')) > 0)) { if (count($members) > 0) { $member_instances = Members::findAll(array('conditions' => 'id IN (' . implode(',', $members) . ')')); MailUtilities::parseMail($email->getContent(), $decoded, $parsedEmail, $warnings); $this->classifyFile($classification_data, $email, $parsedEmail, $member_instances, false, !$after_receiving); } } } else { $email->removeFromMembers(logged_user() instanceof contact ? logged_user() : Contacts::findById($email->getAccount()->getContactId(), $email->getMembers())); } if ($process_conversation) { $conversation = MailContents::getMailsFromConversation($email); if (count($members) > 0) { $member_instances = Members::findAll(array('conditions' => 'id IN (' . implode(',', $members) . ')')); foreach ($conversation as $conv_email) { // dont process orignal email again if ($conv_email->getId() == $email->getId()) { continue; } $account_owner = logged_user() instanceof contact ? logged_user() : Contacts::findById($conv_email->getAccount()->getContactId()); $ctrl->add_to_members($conv_email, $members, $account_owner); MailUtilities::parseMail($conv_email->getContent(), $decoded, $parsedEmail, $warnings); if ($conv_email->getHasAttachments()) { if ($after_receiving && user_config_option('auto_classify_attachments') || !$after_receiving && (user_config_option('mail_drag_drop_prompt') == 'classify' || user_config_option('mail_drag_drop_prompt') == 'prompt' && intval(array_var($_REQUEST, 'classify_attachments')) > 0)) { $this->classifyFile($classification_data, $conv_email, $parsedEmail, $member_instances, false, !$after_receiving); } } } } else { if (!$after_receiving) { foreach ($conversation as $conv_email) { $conv_email->removeFromMembers(logged_user() instanceof contact ? logged_user() : Contacts::findById($email->getAccount()->getContactId(), $conv_email->getMembers())); } } } } if (!$after_receiving) { DB::commit(); } flash_success(lang('success classify email')); if ($create_task) { ajx_replace(true); $this->redirectTo('task', 'add_task', array('from_email' => $email->getId(), 'replace' => 1)); } else { ajx_current("back"); if (!$after_receiving) { evt_add("reload current panel", array()); } } } else { flash_error(lang("error classifying attachment cant open file")); ajx_current("empty"); } // If can write files // Error... } catch (Exception $e) { if (!$after_receiving) { DB::rollback(); } flash_error($e->getMessage()); ajx_current("empty"); } }
/** * Execute the script * * @param void * @return boolean */ function execute() { // --------------------------------------------------- // Check MySQL version // --------------------------------------------------- $mysql_version = mysql_get_server_info($this->database_connection); if ($mysql_version && version_compare($mysql_version, '4.1', '>=')) { $constants['DB_CHARSET'] = 'utf8'; @mysql_query("SET NAMES 'utf8'", $this->database_connection); tpl_assign('default_collation', $default_collation = 'collate utf8_unicode_ci'); tpl_assign('default_charset', $default_charset = 'DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'); } else { tpl_assign('default_collation', $default_collation = ''); tpl_assign('default_charset', $default_charset = ''); } // if $installed_version = installed_version(); $t_prefix = TABLE_PREFIX; if (version_compare($installed_version, '1.7.5') <= 0 && TABLE_PREFIX != "fo_") { $t_prefix = "fo_"; } tpl_assign('table_prefix', $t_prefix); if (defined('DB_ENGINE')) { tpl_assign('engine', DB_ENGINE); } else { tpl_assign('engine', 'InnoDB'); } // --------------------------------------------------- // Execute migration // --------------------------------------------------- $additional_upgrade_steps = array(); // RUN QUERIES $total_queries = 0; $executed_queries = 0; $upgrade_script = ""; // upgrading from version 1.x if (version_compare($installed_version, '2.0.0.0-beta') < 0) { ini_set('memory_limit', '1024M'); @set_time_limit(0); $upgrade_script .= tpl_fetch(get_template_path('db_migration/2_0_asado')); if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } $_SESSION['from_feng1'] = true; $upgrade_script = ""; @unlink(ROOT . '/cache/autoloader.php'); include ROOT . '/environment/classes/AutoLoader.class.php'; include ROOT . '/environment/constants.php'; if (!($callbacks = spl_autoload_functions())) { $callbacks = array(); } foreach ($callbacks as $callback) { spl_autoload_unregister($callback); } spl_autoload_register('feng_upg_autoload'); foreach ($callbacks as $callback) { spl_autoload_register($callback); } @(include ROOT . '/cache/autoloader.php'); define('DONT_LOG', true); define('FORCED_TABLE_PREFIX', 'fo_'); if (!defined('FILE_STORAGE_FILE_SYSTEM')) { define('FILE_STORAGE_FILE_SYSTEM', 'fs'); } if (!defined('FILE_STORAGE_MYSQL')) { define('FILE_STORAGE_MYSQL', 'mysql'); } if (!defined('MAX_SEARCHABLE_FILE_SIZE')) { define('MAX_SEARCHABLE_FILE_SIZE', 1048576); } try { DB::connect(DB_ADAPTER, array('host' => DB_HOST, 'user' => DB_USER, 'pass' => DB_PASS, 'name' => DB_NAME, 'persist' => DB_PERSIST)); if (defined('DB_CHARSET') && trim(DB_CHARSET)) { DB::execute("SET NAMES ?", DB_CHARSET); } } catch (Exception $e) { $this->printMessage("Error connecting to database: " . $e->getMessage() . "\n" . $e->getTraceAsString()); } try { $db_result = DB::execute("SELECT value FROM " . $t_prefix . "config_options WHERE name = 'file_storage_adapter'"); $db_result_row = $db_result->fetchRow(); if ($db_result_row['value'] == FILE_STORAGE_FILE_SYSTEM) { if (!defined('FILES_DIR')) { define('FILES_DIR', ROOT . '/upload'); } FileRepository::setBackend(new FileRepository_Backend_FileSystem(FILES_DIR, TABLE_PREFIX)); } else { FileRepository::setBackend(new FileRepository_Backend_DB(TABLE_PREFIX)); } PublicFiles::setRepositoryPath(ROOT . '/public/files'); if (!defined('PUBLIC_FOLDER')) { define('PUBLIC_FOLDER', 'public'); } if (trim(PUBLIC_FOLDER) == '') { PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'files'); } else { PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'public/files'); } $member_parents = array(); $members = Members::findAll(); foreach ($members as $member) { $member_parents[$member->getId()] = $member->getAllParentMembersInHierarchy(false, false); } $object_members = DB::executeAll('SELECT * FROM ' . $t_prefix . 'object_members WHERE is_optimization=0 and not exists (SELECT x.object_id FROM ' . $t_prefix . 'object_members x where x.object_id=fo_object_members.object_id and x.is_optimization=1)'); foreach ($object_members as $om) { $parents = isset($member_parents[$om['member_id']]) ? $member_parents[$om['member_id']] : array(); if (count($parents) > 0) { $sql_values = ""; foreach ($parents as $p) { $sql_values .= ($sql_values == "" ? "" : ",") . "(" . $om['object_id'] . "," . $p->getId() . ",1)"; } $sql = "INSERT INTO " . $t_prefix . "object_members (object_id, member_id, is_optimization) VALUES {$sql_values} ON DUPLICATE KEY UPDATE is_optimization=1;"; DB::execute($sql); } } $this->printMessage("Finished generating Object Members"); foreach ($members as $m) { if ($m->getParentMember() instanceof Member && $m->getDimensionId() != $m->getParentMember()->getDimensionId()) { $m->setDimensionId($m->getParentMember()->getDimensionId()); $m->save(); } } $app_move_logs = ApplicationLogs::findAll(array("conditions" => "action = 'move'")); foreach ($app_move_logs as &$app_log) { /* @var $app_log ApplicationLog */ $exp_log_data = explode(";", $app_log->getLogData()); if (count($exp_log_data) > 1) { $old_to = array_var($exp_log_data, 1); $old_from = array_var($exp_log_data, 0); } else { $old_to = array_var($exp_log_data, 0); $old_from = ""; } $to_id = str_replace("to:", "", $old_to); $new_to_id = Members::instance()->findOne(array("id" => true, "conditions" => "ws_id = '{$to_id}'")); if (count($new_to_id) > 0) { $new_to_id = $new_to_id[0]; } $new_from_ids = ""; $from_ids = str_replace("from:", "", $old_from); if ($from_ids != "") { $new_from_ids_array = Members::instance()->findAll(array("id" => true, "conditions" => "ws_id IN ({$from_ids})")); $new_from_ids = implode(",", $new_from_ids_array); } if ($new_to_id) { if ($new_from_ids) { $log_data = "from:{$new_from_ids};to:{$new_to_id}"; } else { $log_data = "to:{$new_to_id}"; } $app_log->setLogData($log_data); $app_log->save(); } } } catch (Exception $e) { die("\nError occurred:\n-----------------\n" . $e->getMessage() . "\n" . $e->getTraceAsString()); } //tpl_assign('install_inv_dw', true); $additional_upgrade_steps[] = array('url' => 'complete_migration.php?out=file', 'name' => 'Fill searchable objects and sharing table', 'filename' => dirname(__FILE__) . "/../complete_migration.php"); } else { // upgrading from a pre-release of this version (beta, rc, etc) if (version_compare($installed_version, '2.0.0.4') <= 0) { if (!$this->checkTableExists($t_prefix . 'role_object_type_permissions', $this->database_connection)) { $upgrade_script .= "\r\n\t\t\t\t\t\tCREATE TABLE `" . $t_prefix . "role_object_type_permissions` (\r\n\t\t\t\t\t\t `role_id` INTEGER UNSIGNED NOT NULL,\r\n\t\t\t\t\t\t `object_type_id` INTEGER UNSIGNED NOT NULL,\r\n\t\t\t\t\t\t `can_delete` BOOLEAN NOT NULL,\r\n\t\t\t\t\t\t `can_write` BOOLEAN NOT NULL,\r\n\t\t\t\t\t\t PRIMARY KEY (`role_id`, `object_type_id`)\r\n\t\t\t\t\t\t) ENGINE = InnoDB;\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 1, 1\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','task','milestone','event','contact','mail','timeslot','report','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Super Administrator','Administrator','Manager','Executive');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 1\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','task','milestone','event','contact','timeslot','report','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Collaborator Customer');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 1\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','task','milestone','event','timeslot','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Internal Collaborator','External Collaborator');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 0\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','event','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Guest Customer');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 0\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','event','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Guest');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 0\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','task','milestone','event','contact','timeslot','report','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Non-Exec Director');\r\n\t\t\t\t\t\tUPDATE " . $t_prefix . "role_object_type_permissions SET can_write = 1 WHERE object_type_id = (SELECT id FROM " . $t_prefix . "object_types WHERE name='comment');\r\n\t\t\t\t\t"; } if (!$this->checkTableExists($t_prefix . 'widgets', $this->database_connection)) { $upgrade_script .= "\r\n\t\t\t\t\t\tCREATE TABLE `" . $t_prefix . "widgets` (\r\n\t\t\t\t\t\t `name` varchar(64) NOT NULL,\r\n\t\t\t\t\t\t `title` varchar(255) NOT NULL,\r\n\t\t\t\t\t\t `plugin_id` int(10) unsigned NOT NULL,\r\n\t\t\t\t\t\t `path` varchar(512) NOT NULL,\r\n\t\t\t\t\t\t `default_options` text NOT NULL,\r\n\t\t\t\t\t\t `default_section` varchar(64) NOT NULL,\r\n\t\t\t\t\t\t `default_order` int(10) NOT NULL,\r\n\t\t\t\t\t\t PRIMARY KEY (`name`)\r\n\t\t\t\t\t\t) ENGINE = InnoDB;\r\n\t\t\t\t\t"; } if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } if (version_compare($installed_version, '2.0.0.5') <= 0) { if (!$this->checkColumnExists($t_prefix . 'contacts', 'default_billing_id', $this->database_connection)) { $upgrade_script = "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "contacts` ADD COLUMN `default_billing_id` INTEGER NOT NULL DEFAULT 0;\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_tasks`\r\n\t\t\t\t\t\t ADD COLUMN `use_due_time` BOOLEAN DEFAULT 0,\r\n\t\t\t\t\t\t ADD COLUMN `use_start_time` BOOLEAN DEFAULT 0;\r\n\t\t\t\t\t\tUPDATE " . $t_prefix . "project_tasks t SET\r\n\t\t\t\t\t\t t.due_date = ADDTIME(t.due_date, CONCAT(SUBSTRING_INDEX((SELECT c.timezone FROM " . $t_prefix . "contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM " . $t_prefix . "objects o WHERE o.id=t.object_id)), '.', 1), ':', SUBSTRING_INDEX(abs((SELECT c.timezone FROM " . $t_prefix . "contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM " . $t_prefix . "objects o WHERE o.id=t.object_id)) % 1)*60, '.', 1)))\r\n\t\t\t\t\t\t WHERE t.due_date > 0;\r\n\t\t\t\t\t\tUPDATE " . $t_prefix . "project_tasks t SET\r\n\t\t\t\t\t\t t.start_date = ADDTIME(t.start_date, CONCAT(SUBSTRING_INDEX((SELECT c.timezone FROM " . $t_prefix . "contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM " . $t_prefix . "objects o WHERE o.id=t.object_id)), '.', 1), ':', SUBSTRING_INDEX(abs((SELECT c.timezone FROM " . $t_prefix . "contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM " . $t_prefix . "objects o WHERE o.id=t.object_id)) % 1)*60, '.', 1)))\r\n\t\t\t\t\t\t WHERE t.start_date > 0;\r\n\t\t\t\t\t\tINSERT INTO `" . $t_prefix . "contact_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES\r\n\t\t\t\t\t\t ('general', 'work_day_end_time', '18:00', 'TimeConfigHandler', 0, 410, 'Work day end time');\t\t\t\t\t\t\r\n\t\t\t\t\t"; } if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } if (version_compare($installed_version, '2.0.0.6') <= 0) { //WS Widgets $upgrade_script = "\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "contact_config_options` SET `default_value` = '15' WHERE `" . $t_prefix . "contact_config_options`.`name` = 'noOfTasks' LIMIT 1 ;\r\n\t\t\t\t\tUPDATE " . $t_prefix . "widgets SET default_section = 'none' WHERE name = 'people' AND NOT EXISTS (SELECT id from " . $t_prefix . "plugins WHERE name = 'crpm');\r\n\t\t\t\t\tUPDATE " . $t_prefix . "dimensions SET options = '{\"defaultAjax\":{\"controller\":\"dashboard\", \"action\": \"main_dashboard\"}, \"quickAdd\":true,\"showInPaths\":true}' \r\n\t\t\t\t\t\tWHERE code='workspaces';\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "tab_panels` SET default_action = 'main_dashboard', initial_action = 'main_dashboard'\r\n\t\t\t\t\t\tWHERE id = 'overview-panel' ;\r\n\t\t\t\t\tUPDATE " . $t_prefix . "object_types SET type = 'dimension_object', handler_class='Workspaces', table_name = 'workpaces' WHERE name = 'workspace' ;\r\n\t\t\t\t\tUPDATE " . $t_prefix . "dimension_object_types SET OPTIONS = '{\"defaultAjax\":{\"controller\":\"dashboard\", \"action\": \"main_dashboard\"}}' \r\n\t\t\t\t\t\tWHERE dimension_id = (SELECT id FROM " . $t_prefix . "dimensions WHERE code = 'workspaces');\r\n\t\t\t\t\tCREATE TABLE IF NOT EXISTS `" . $t_prefix . "contact_widgets` (\r\n\t\t\t\t\t `widget_name` varchar(40) NOT NULL,\r\n\t\t\t\t\t `contact_id` int(11) NOT NULL,\r\n\t\t\t\t\t `section` varchar(40) NOT NULL,\r\n\t\t\t\t\t `order` int(11) NOT NULL,\r\n\t\t\t\t\t `options` varchar(255) NOT NULL,\r\n\t\t\t\t\t PRIMARY KEY (`widget_name`,`contact_id`) USING BTREE\r\n\t\t\t\t\t) ENGINE=InnoDB;\r\n\t\t\t\t\tINSERT INTO " . $t_prefix . "widgets(name, title, plugin_id, default_section,default_order) \r\n\t\t\t\t\t VALUES ('messages','notes',0,'none',1000)\r\n\t\t\t\t\t ON DUPLICATE KEY update name = name;\r\n\t\t\t\t\tINSERT INTO " . $t_prefix . "dimension_object_type_contents (dimension_id, dimension_object_type_id, content_object_type_id, is_required, is_multiple)\r\n\t\t\t\t\t SELECT d.id, ot.id, (SELECT tmp.id FROM " . $t_prefix . "object_types tmp WHERE tmp.name='contact'), 0, 1\r\n\t\t\t\t\t FROM " . $t_prefix . "dimensions d JOIN " . $t_prefix . "object_types ot\r\n\t\t\t\t\t WHERE d.code = 'customer_project' AND ot.name IN ('customer', 'project', 'folder', 'customer_folder', 'project_folder')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE dimension_id=dimension_id;\r\n\t\t\t\t\tUPDATE " . $t_prefix . "dimension_object_type_contents SET is_multiple = 1 WHERE content_object_type_id = (SELECT id FROM " . $t_prefix . "object_types WHERE name='mail');\r\n\t\t\t\t"; if (@mysql_fetch_row(@mysql_query("SELECT id from " . $t_prefix . "plugins WHERE name = 'workspaces'"))) { $upgrade_script .= "INSERT INTO " . $t_prefix . "widgets(name, title, plugin_id, default_section,default_order) \r\n\t\t\t\t\t\tVALUES ('ws_description', 'workspace description',(SELECT id from " . $t_prefix . "plugins WHERE name = 'workspaces'), 'left',-100)\r\n\t\t\t\t\t\tON DUPLICATE KEY update name = name ;"; } if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } if ($obj = @mysql_fetch_object(@mysql_query("SELECT id FROM " . $t_prefix . "object_types WHERE name = 'workspace' "))) { $wsTypeId = $obj->id; $res = @mysql_query("SELECT * FROM " . $t_prefix . "members WHERE dimension_id = (SELECT id FROM " . $t_prefix . "dimensions WHERE code='workspaces')"); while ($m = @mysql_fetch_object($res)) { @mysql_query("INSERT INTO " . $t_prefix . "objects (object_type_id, name) VALUES ({$wsTypeId}, '" . $m->name . "' )"); if ($id = @mysql_insert_id()) { @mysql_query("INSERT INTO " . $t_prefix . "workspaces (object_id) VALUES ({$id})"); @mysql_query("UPDATE " . $t_prefix . "members SET object_id={$id} WHERE id = {$m->id} "); } } } } if (version_compare($installed_version, '2.0.0.7') <= 0) { $upgrade_script = ""; if (!$this->checkTableExists($t_prefix . 'mail_spam_filters', $this->database_connection)) { $upgrade_script .= "\r\n CREATE TABLE IF NOT EXISTS `" . $t_prefix . "mail_spam_filters` (\r\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\r\n `account_id` int(10) unsigned NOT NULL,\r\n `text_type` enum('email_address','subject') COLLATE utf8_unicode_ci NOT NULL,\r\n `text` text COLLATE utf8_unicode_ci NOT NULL,\r\n `spam_state` enum('no spam','spam') COLLATE utf8_unicode_ci NOT NULL,\r\n PRIMARY KEY (`id`)\r\n ) ENGINE=InnoDB;\r\n "; } $upgrade_script .= "INSERT INTO `" . $t_prefix . "config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) \r\n\t\t\t\t\tVALUES ('general', 'untitled_notes', '0', 'BoolConfigHandler', '0', '0', NULL) ON DUPLICATE KEY UPDATE name=name;"; if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } if (version_compare($installed_version, '2.0.0.8') < 0) { $upgrade_script = ""; if (!$this->checkTableExists($t_prefix . 'external_calendar_users', $this->database_connection)) { $upgrade_script .= "\r\n CREATE TABLE IF NOT EXISTS `" . $t_prefix . "external_calendar_users` (\r\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\r\n `contact_id` int(10) unsigned NOT NULL,\r\n `auth_user` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\r\n `auth_pass` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\r\n `type` text COLLATE utf8_unicode_ci NOT NULL,\r\n `sync` TINYINT( 1 ) NULL DEFAULT '0',\r\n PRIMARY KEY (`id`)\r\n ) ENGINE = InnoDB;\r\n\t\t\t\t\t"; } if (!$this->checkTableExists($t_prefix . 'external_calendars', $this->database_connection)) { $upgrade_script .= "\r\n CREATE TABLE IF NOT EXISTS `" . $t_prefix . "external_calendars` (\r\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\r\n `ext_cal_user_id` int(10) unsigned NOT NULL,\r\n `calendar_user` varchar(255) COLLATE utf8_unicode_ci NOT NULL,\r\n `calendar_visibility` varchar(255) COLLATE utf8_unicode_ci NOT NULL,\r\n `calendar_name` text COLLATE utf8_unicode_ci NOT NULL,\r\n `calendar_feng` TINYINT( 1 ) NOT NULL DEFAULT '0',\r\n PRIMARY KEY (`id`)\r\n ) ENGINE = InnoDB;\r\n\t\t\t\t\t"; } if (!$this->checkColumnExists($t_prefix . 'project_events', 'ext_cal_id', $this->database_connection)) { $upgrade_script .= "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_events` ADD `ext_cal_id` INT(10) UNSIGNED NOT NULL;\r\n\t\t\t\t\t"; } $upgrade_script .= "\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_events` CHANGE `special_id` `special_id` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "file_types` SET `is_searchable` = '1' WHERE `extension` = 'docx';\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "file_types` SET `is_searchable` = '1' WHERE `extension` = 'pdf';\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`)\r\n\t\t\t\t\t\tVALUES ('general', 'repeating_task', '0', 'BoolConfigHandler', '0', '0', '')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "contact_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`)\r\n\t\t\t\t\t\tVALUES ('calendar panel', 'calendar task filter', 'pending', 'StringConfigHandler', '1', '0', NULL),\r\n\t\t\t\t\t\t\t('task panel', 'close timeslot open', '1', 'BoolConfigHandler', '0', '0', NULL),\r\n\t\t\t\t\t\t\t('calendar panel', 'reminders_events', 'reminder_email,1,60', 'StringConfigHandler', '0', '0', NULL)\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "cron_events` (`name`, `recursive`, `delay`, `is_system`, `enabled`, `date`)\r\n\t\t\t\t\t\tVALUES ('import_google_calendar', '1', '10', '0', '0', '0000-00-00 00:00:00'),\r\n\t\t\t\t\t\t\t('export_google_calendar', '1', '10', '0', '0', '0000-00-00 00:00:00')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t\t"; $upgrade_script .= "\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "config_options` WHERE `name`='use_time_in_task_dates' AND NOT EXISTS (SELECT id FROM `" . $t_prefix . "plugins` WHERE `name`='crpm' AND is_activated=1);\r\n\t\t\t\t\tINSERT INTO " . $t_prefix . "contact_config_options (category_name, name, default_value, config_handler_class, is_system, option_order) VALUES\r\n\t\t\t\t\t\t('general','show_object_direct_url',0,'BoolConfigHandler',0,0),\r\n\t\t\t\t\t\t('general','drag_drop_prompt','prompt','DragDropPromptConfigHandler',0,0)\r\n\t\t\t\t\t ON DUPLICATE KEY UPDATE name = name;\r\n\t\t\t\t"; $upgrade_script .= "\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "tab_panels` (`id`,`title`,`icon_cls`,`refresh_on_context_change`,`default_controller`,`default_action`,`initial_controller`,`initial_action`,`enabled`,`type`,`ordering`,`plugin_id`,`object_type_id`) VALUES \r\n\t\t\t\t\t('contacts-panel','contacts','ico-contacts',1,'contact','init','','',0,'system',7,0,16) ON DUPLICATE KEY UPDATE title=title;\r\n\t\t\t\t"; if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } if (version_compare($installed_version, '2.0.1') < 0) { $upgrade_script = ""; $upgrade_script .= "INSERT INTO `" . $t_prefix . "config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`)\r\n\t\t\t\t\tVALUES ('general', 'working_days', '1,2,3,4,5,6,7', 'StringConfigHandler', '0', '0', NULL);\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_tasks` ADD `original_task_id` INT( 10 ) UNSIGNED NULL DEFAULT '0';\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_tasks` ADD `type_content` ENUM( 'text', 'html' ) NOT NULL DEFAULT 'text';\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_events` ADD `original_event_id` INT( 10 ) UNSIGNED NULL DEFAULT '0';\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_messages` ADD `type_content` ENUM( 'text', 'html' ) NOT NULL DEFAULT 'text';\r\n\t\t\t\t"; $upgrade_script .= "INSERT INTO `" . $t_prefix . "config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`)\r\n\t\t\t\t\tVALUES ('general', 'wysiwyg_tasks', '0', 'BoolConfigHandler', '0', '0', NULL),\r\n\t\t\t\t\t('general', 'wysiwyg_messages', '0', 'BoolConfigHandler', '0', '0', NULL),\r\n\t\t\t\t\t('task panel', 'tasksShowTimeEstimates', '1', 'BoolConfigHandler', '1', '0', NULL)\r\n\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t"; $upgrade_script .= "UPDATE `" . $t_prefix . "widgets` SET plugin_id = (SELECT id FROM `" . $t_prefix . "plugins` WHERE name='workspaces') WHERE name='workspaces';\r\n\t\t\t\t"; // clean old users dimension $upgrade_script .= "DELETE FROM `" . $t_prefix . "object_members` WHERE member_id IN (SELECT `id` FROM `" . $t_prefix . "members` WHERE `dimension_id` IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users'));\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "contact_dimension_permissions` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "members` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "dimension_object_type_contents` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "dimension_object_type_hierarchies` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "dimension_object_types` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "dimensions` WHERE code='feng_users';\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "object_types` WHERE name='user';\r\n\t\t\t\t\tUPDATE " . $t_prefix . "contacts c SET c.personal_member_id = 0 WHERE c.user_type>0 AND NOT (SELECT count(m2.id) FROM " . $t_prefix . "members m2 WHERE m2.object_id=c.personal_member_id)=0;\r\n\t\t\t\t"; if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } // Plugin Version Support $upgrade_script = ''; if (!$this->checkColumnExists($t_prefix . "plugins", 'version', $this->database_connection)) { $upgrade_script = 'ALTER TABLE ' . $t_prefix . 'plugins ADD COLUMN `version` INTEGER NOT NULL DEFAULT 1 AFTER `name` '; if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } } $this->printMessage('Feng Office has been upgraded. You are now running Feng Office ' . $this->getVersionTo() . ' Enjoy!'); tpl_assign('additional_steps', $additional_upgrade_steps); }
$conditions[] = "membergroup_id=" . $vals['membergroup_id']; } /** $email_tos = array( array("*****@*****.**","ualink"), ); **/ $limit = null; if ($vals['all']) { } else { if ($vals['day'] > 0) { $day_timestamp = $vals['day'] * 86400; $day_timestamp = $time_stamp - $day_timestamp; $conditions[] = "last_login<" . $day_timestamp; } if ($vals['id']['from'] && $vals['id']['to']) { $conditions[] = "id BETWEEN " . $vals['id']['from'] . " AND " . $vals['id']['to']; } else { $limit = 100; } } $pdb->setFetchMode(ADODB_FETCH_ASSOC); $email_tos = $member->findAll("username,email", null, $conditions, null, $limit); $result = pb_sendmail($email_tos, $vals['subject'], null, $vals['content']); if ($result) { flash("email_sended_success"); } else { flash("email_sended_false"); } } template($tpl_file);
static function getByDimensionObjType($dimension_id, $object_type_id) { return Members::findAll(array("conditions" => array("`dimension_id` = ? AND `object_type_id` = ?", $dimension_id, $object_type_id))); }
/** * Add/edit Dimension Members * * @access public * @param void * @return null */ function edit_members() { if (!can_manage_dimension_members(logged_user())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } // if $dimensions = Dimensions::findAll(array('conditions' => '`is_manageable` = 1')); $members = array(); foreach ($dimensions as $dim) { $dimensions = Dimensions::findAll(array('conditions' => '`is_manageable` = 1')); $members = array(); foreach ($dimensions as $dim) { $root_members = Members::findAll(array('conditions' => array('`dimension_id`=? AND `parent_member_id`=0', $dim->getId()), 'order' => '`name` ASC')); foreach ($root_members as $mem) { $members[$dim->getId()][] = $mem; $members[$dim->getId()] = array_merge($members[$dim->getId()], $mem->getAllChildrenSorted()); } } } tpl_assign('members', $members); tpl_assign('dimensions', $dimensions); }
function initial_list_dimension_members_tree() { $dimension_id = array_var($_REQUEST, 'dimension_id'); $checkedField = (array_var($_REQUEST, 'checkboxes'))?"checked":"_checked"; $objectTypeId = array_var($_REQUEST, 'object_type_id', null ); $allowedMemberTypes = json_decode(array_var($_REQUEST, 'allowedMemberTypes', null )); if (!is_array($allowedMemberTypes)) { $allowedMemberTypes = null; } $only_names = array_var($_REQUEST, 'onlyname', false); $name = trim(array_var($_REQUEST, 'query', '')); $extra_cond = $name == "" ? "" : " AND name LIKE '".$name."%'"; $selected_member_ids = json_decode(array_var($_REQUEST, 'selected_ids', "[0]")); $selected_members = Members::findAll(array('conditions' => 'id IN ('.implode(',',$selected_member_ids).')')); $memberList = $this->initial_list_dimension_members($dimension_id, $objectTypeId, $allowedMemberTypes, false, $extra_cond, null, false, null, $only_names, $selected_members); $tree = buildTree($memberList, "parent", "children", "id", "name", $checkedField); ajx_current("empty"); ajx_extra_data(array('dimension_members' => $tree, 'dimension_id' => $dimension_id)); }
/** * Add/edit Dimension Members * * @access public * @param void * @return null */ function edit_members() { if (!can_manage_dimension_members(logged_user())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } // if $dimensions = Dimensions::findAll(array('conditions' => '`is_manageable` = 1')); $members = array(); $logged_user_pgs = implode(',', logged_user()->getPermissionGroupIds()); foreach ($dimensions as $dim) { //if ($dim->deniesAllForContact($logged_user_pgs)) continue; $allows_all = $dim->hasAllowAllForContact($logged_user_pgs); $root_members = Members::findAll(array('conditions' => array('`dimension_id`=? AND `parent_member_id`=0', $dim->getId()), 'order' => '`name` ASC')); foreach ($root_members as $mem) { if ($dim->getDefinesPermissions() && !$allows_all) { if (!$mem->canBeReadByContact($logged_user_pgs, logged_user())) { continue; } } $members[$dim->getId()][] = $mem; $members[$dim->getId()] = array_merge($members[$dim->getId()], $mem->getAllChildrenSorted()); } } tpl_assign('members', $members); tpl_assign('dimensions', $dimensions); }
function render_single_member_selector(Dimension $dimension, $genid = null, $selected_member_ids = null, $options = array()) { if (is_null($genid)) $genid = gen_id(); $dimension_options = $dimension->getOptions(true); $dim_info = array( 'dimension_id' => $dimension->getId(), 'dimension_code' => $dimension->getCode(), 'dimension_options' => $dimension_options, 'is_manageable' => $dimension->getIsManageable(), 'is_required' => array_var($options, 'is_required'), 'is_multiple' => array_var($options, 'is_multiple'), ); if($dimension_options && isset($dimension_options->useLangs) && $dimension_options->useLangs ) { $dim_info['dimension_name'] = lang($dimension->getCode()); } $dimensions = array($dim_info); if (is_null($selected_member_ids)) $selected_member_ids = array(); // Set view variables $selected_members = count($selected_member_ids) > 0 ? Members::findAll(array('conditions' => 'id IN ('.implode(',', $selected_member_ids).')')) : array(); $selected_members_json = "[".implode(',', $selected_member_ids)."]"; $component_id = "$genid-member-selectors-panel-$content_object_type_id"; $listeners = array_var($options, 'listeners', array()); $allowed_member_type_ids = array_var($options, 'allowedMemberTypes', null); // Render view include get_template_path("components/multiple_dimension_selector", "dimension"); }
function dimension_tree_for_permissions() { $dimension_id = array_var($_REQUEST, 'dimension_id'); $checkedField = array_var($_REQUEST, 'checkboxes') ? "checked" : "_checked"; $objectTypeId = array_var($_REQUEST, 'object_type_id', null); $allowedMemberTypes = json_decode(array_var($_REQUEST, 'allowedMemberTypes', null)); if (!is_array($allowedMemberTypes)) { $allowedMemberTypes = null; } $only_names = array_var($_REQUEST, 'onlyname', false); $name = trim(array_var($_REQUEST, 'query', '')); $extra_cond = $name == "" ? "" : " AND name LIKE '%" . $name . "%'"; if (array_var($_REQUEST, 'new_user')) { if (isset($_REQUEST['forced_members'])) { $forced_members = json_decode(array_var($_REQUEST, 'forced_members', '')); $fms = array(0); if (is_array($forced_members) && count($forced_members) > 0) { foreach ($forced_members as $fm) { if (is_numeric($fm)) { $fms[] = $fm; } } } if (count($fms) > 0) { $extra_cond .= " AND id IN (" . implode(',', $fms) . ")"; } } if (isset($_REQUEST['excluded_members'])) { $excluded_members = json_decode(array_var($_REQUEST, 'excluded_members', '')); $ems = array(0); if (is_array($excluded_members) && count($excluded_members) > 0) { foreach ($excluded_members as $em) { if (is_numeric($em)) { $ems[] = $em; } } } if (count($ems) > 0) { $extra_cond .= " AND id NOT IN (" . implode(',', $ems) . ")"; } } } else { // only use available object types $ots = ObjectTypes::getAvailableObjectTypes(); $available_ots_csv = ""; foreach ($ots as $ot) { $available_ots_csv .= ($available_ots_csv == "" ? "" : ",") . $ot->getId(); } if (trim($available_ots_csv) != "") { $ot_cond = " AND cmp.object_type_id IN ({$available_ots_csv})"; } else { $ot_cond = ""; } if (array_var($_REQUEST, 'only_with_perm')) { $extra_cond .= " AND EXISTS (SELECT cmp.member_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp WHERE cmp.member_id=id AND cmp.permission_group_id=" . array_var($_REQUEST, 'pg', '-1') . " {$ot_cond})"; } else { if (array_var($_REQUEST, 'only_without_perm')) { $extra_cond .= " AND NOT EXISTS (SELECT cmp.member_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp WHERE cmp.member_id=id AND cmp.permission_group_id=" . array_var($_REQUEST, 'pg', '-1') . " {$ot_cond})"; } } } $return_all_members = false; $selected_member_ids = json_decode(array_var($_REQUEST, 'selected_ids', "[0]")); $selected_members = Members::findAll(array('conditions' => 'id IN (' . implode(',', $selected_member_ids) . ')')); $memberList = $this->initial_list_dimension_members($dimension_id, $objectTypeId, $allowedMemberTypes, $return_all_members, $extra_cond, null, false, null, $only_names, $selected_members); // add missing parents $missing_parent_ids = array(); $all_members = array(); foreach ($memberList as $m) { $all_members[$m['id']] = $m['id']; } foreach ($memberList as $m) { if ($m['parent'] > 0 && !isset($all_members[$m['parent']])) { $missing_parent_ids[$m['parent']] = $m['parent']; } } while (count($missing_parent_ids) > 0) { $missing_members = DB::executeAll("SELECT m.*, ot.icon FROM " . TABLE_PREFIX . "members m INNER JOIN " . TABLE_PREFIX . "object_types ot ON ot.id=m.object_type_id WHERE m.id IN (" . implode(',', $missing_parent_ids) . ")"); $missing_parent_ids = array(); $new_missing = array(); foreach ($missing_members as $mem) { $m = array("id" => $mem['id'], "name" => clean($mem['name']), "parent" => $mem['parent_member_id'], "realParent" => $mem['parent_member_id'], "object_id" => $mem['object_id'], "depth" => $mem['depth'], "iconCls" => 'ico-' . $mem['icon'], "dimension_id" => $mem['dimension_id'], "object_type_id" => $mem['object_type_id'], "expandable" => true); $memberList[str_pad(array_var($m, 'parent'), 20, "0", STR_PAD_LEFT) . strtolower(array_var($m, 'name')) . array_var($m, 'id')] = $m; $new_missing[] = $m; $all_members[$m['id']] = $m; } foreach ($new_missing as $m) { if ($m['parent'] > 0 && !isset($all_members[$m['parent']])) { $missing_parent_ids[$m['parent']] = $m['parent']; } } } // -- $tree = buildTree($memberList, "parent", "children", "id", "name", $checkedField); ajx_current("empty"); ajx_extra_data(array('dimension_members' => $tree, 'dimension_id' => $dimension_id)); }
function getRootMembers() { $members = Members::findAll(array('conditions' => '`parent_member_id`=0 AND `dimension_id` = ' . $this->getId())); return $members; }
if (isset($_GET['member']['status']) && $_GET['member']['status'] >= 0) { $conditions[] = "Member.status='" . $_GET['member']['status'] . "'"; } if ($_GET['groupid'] > 0) { $conditions[] = "Member.membergroup_id=" . intval($_GET['groupid']); } } if ($do == "del" && !empty($id)) { $member->Delete($id); } } $fields = "id,username,CONCAT(mf.first_name,mf.last_name) AS NickName,mf.reg_ip,last_ip,points,credits,membergroup_id,status,created AS pubdate,last_login,trusttype_ids"; $amount = $member->findCount(null, $conditions); $page->setPagenav($amount); $joins[] = "LEFT JOIN {$tb_prefix}memberfields mf ON Member.id=mf.member_id"; $result = $member->findAll($fields, $joins, $conditions, "Member.id DESC ", $page->firstcount, $page->displaypg); if (!empty($result)) { for ($i = 0; $i < count($result); $i++) { $tmp_img = null; if ($result[$i]['id'] != $administrator_id) { $result[$i]['candelete'] = 1; } else { $result[$i]['candelete'] = 0; } if (!empty($result[$i]['trusttype_ids'])) { $tmp_str = explode(",", $result[$i]['trusttype_ids']); foreach ($tmp_str as $key => $val) { $tmp_img .= "<img src='" . URL . STATICURL . "images/icon/" . $G['trusttype'][$val]['avatar'] . "' alt='" . $G['trusttype'][$val]['name'] . "' />"; } $result[$i]['trust_image'] = $tmp_img; }
function edit_custom_report() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $report_id = array_var($_GET, 'id'); $report = Reports::getReport($report_id); if (!$report->canEdit(logged_user())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } // if if (is_array(array_var($_POST, 'report'))) { try { ajx_current("empty"); $report_data = array_var($_POST, 'report'); $member_ids = json_decode(array_var($_POST, 'members')); if (!is_array($member_ids) || count($member_ids) == 0) { flash_error(lang('must choose at least one member')); ajx_current("empty"); return; } $members = Members::findAll(array("conditions" => array("`id` IN(?)", $member_ids))); DB::beginWork(); $report->setObjectName($report_data['name']); $report->setDescription($report_data['description']); $report->setReportObjectTypeId($report_data['report_object_type_id']); $report->setOrderBy($report_data['order_by']); $report->setIsOrderByAsc($report_data['order_by_asc'] == 'asc'); $report->save(); $conditions = array_var($_POST, 'conditions'); if (!is_array($conditions)) { $conditions = array(); } foreach ($conditions as $condition) { $newCondition = new ReportCondition(); if ($condition['id'] > 0) { $newCondition = ReportConditions::getCondition($condition['id']); } if ($condition['deleted'] == "1") { $newCondition->delete(); continue; } $newCondition->setReportId($report_id); $custom_prop_id = isset($condition['custom_property_id']) ? $condition['custom_property_id'] : 0; $newCondition->setCustomPropertyId($custom_prop_id); $newCondition->setFieldName($condition['field_name']); $newCondition->setCondition($condition['condition']); if ($condition['field_type'] == 'boolean') { $newCondition->setValue(isset($condition['value']) && $condition['value']); } else { if ($condition['field_type'] == 'date') { if ($condition['value'] == '') { $newCondition->setValue(''); } else { $dtFromWidget = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $condition['value']); $newCondition->setValue(date("m/d/Y", $dtFromWidget->getTimestamp())); } } else { $newCondition->setValue(isset($condition['value']) ? $condition['value'] : ''); } } $newCondition->setIsParametrizable(isset($condition['is_parametrizable'])); $newCondition->save(); } ReportColumns::delete('report_id = ' . $report_id); $columns = array_var($_POST, 'columns'); asort($columns); //sort the array by column order foreach ($columns as $column => $order) { if ($order > 0) { $newColumn = new ReportColumn(); $newColumn->setReportId($report_id); if (is_numeric($column)) { $newColumn->setCustomPropertyId($column); } else { $newColumn->setFieldName($column); } $newColumn->save(); } } $object_controller = new ObjectController(); $object_controller->add_to_members($report, $member_ids); DB::commit(); flash_success(lang('custom report updated')); ajx_current('back'); } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); } // try } else { $this->setTemplate('add_custom_report'); tpl_assign('url', get_url('reporting', 'edit_custom_report', array('id' => $report_id))); if ($report instanceof Report) { tpl_assign('id', $report_id); $report_data = array('name' => $report->getObjectName(), 'description' => $report->getDescription(), 'report_object_type_id' => $report->getReportObjectTypeId(), 'order_by' => $report->getOrderBy(), 'order_by_asc' => $report->getIsOrderByAsc()); tpl_assign('report_data', $report_data); $conditions = ReportConditions::getAllReportConditions($report_id); tpl_assign('conditions', $conditions); $columns = ReportColumns::getAllReportColumns($report_id); $colIds = array(); foreach ($columns as $col) { if ($col->getCustomPropertyId() > 0) { $colIds[] = $col->getCustomPropertyId(); } else { $colIds[] = $col->getFieldName(); } } tpl_assign('columns', $colIds); } $selected_type = $report->getReportObjectTypeId(); $types = array(array("", lang("select one"))); $object_types = ObjectTypes::getAvailableObjectTypes(); foreach ($object_types as $ot) { $types[] = array($ot->getId(), lang($ot->getName())); } tpl_assign('object_types', $types); tpl_assign('selected_type', $selected_type); tpl_assign('object', $report); tpl_assign('allowed_columns', $this->get_allowed_columns($selected_type), true); } }
function instantiate($arguments = null) { $selected_members = array(); $id = array_var($arguments, 'id', get_id()); $template = COTemplates::findById($id); if (!$template instanceof COTemplate) { flash_error(lang("template dnx")); ajx_current("empty"); return; } $parameters = TemplateParameters::getParametersByTemplate($id); $parameterValues = array_var($arguments, 'parameterValues', array_var($_POST, 'parameterValues')); if (count($parameters) > 0 && !isset($parameterValues)) { ajx_current("back"); return; } $instantiation_id = 0; if (count($parameters) > 0) { $instantiation_id = $this->save_instantiated_parameters($template, $parameters, $parameterValues); } if (array_var($_POST, 'members') || array_var($arguments, 'members')) { $selected_members = array_var($arguments, 'members', json_decode(array_var($_POST, 'members'))); } else { $context = active_context(); foreach ($context as $selection) { if ($selection instanceof Member) { $selected_members[] = $selection->getId(); } } } if (array_var($_POST, 'additional_member_ids')) { $add_mem_ids = explode(',', array_var($_POST, 'additional_member_ids')); if (is_array($add_mem_ids)) { foreach ($add_mem_ids as $add_mem_id) { if (is_numeric($add_mem_id)) { $selected_members[] = $add_mem_id; } } } } $objects = $template->getObjects(); $controller = new ObjectController(); if (count($selected_members) > 0) { $selected_members_instances = Members::findAll(array('conditions' => 'id IN (' . implode($selected_members) . ')')); } else { $selected_members_instances = array(); } DB::beginWork(); $active_context = active_context(); $copies = array(); $copiesIds = array(); $dependencies = array(); Hook::fire("verify_objects_before_template_instantiation", $template, $objects); foreach ($objects as $object) { if (!$object instanceof ContentDataObject) { continue; } // copy object if ($object instanceof TemplateTask) { //dependencies $ptasks = ProjectTaskDependencies::getDependenciesForTemplateTask($object->getId()); if (!empty($ptasks)) { foreach ($ptasks as $d) { $dependencies[] = $d; } } $copy = $object->copyToProjectTask($instantiation_id); //if is subtask if ($copy->getParentId() > 0) { foreach ($copies as $c) { if ($c instanceof ProjectTask) { if ($c->getFromTemplateObjectId() == $object->getParentId()) { $copy->setParentId($c->getId()); } } } } } else { if ($object instanceof TemplateMilestone) { $copy = $object->copyToProjectMilestone(); } else { $copy = $object->copy(false); if ($copy->columnExists('from_template_id')) { $copy->setColumnValue('from_template_id', $object->getId()); } } } if ($copy->columnExists('is_template')) { $copy->setColumnValue('is_template', false); } $copy->save(); $copies[] = $copy; $copiesIds[$object->getId()] = $copy->getId(); $ret = null; Hook::fire('after_template_object_instantiation', array('template' => $template, 'original' => $object, 'copy' => $copy), $ret); /* Set instantiated object members: * if no member is active then the instantiated object is put in the same members as the original * if any members are selected then the instantiated object will be put in those members */ $template_object_members = $object->getMembers(); $object_members = array(); if (count($selected_members) == 0) { //change members according to context foreach ($active_context as $selection) { if ($selection instanceof Member) { // member selected foreach ($template_object_members as $i => $object_member) { if ($object_member instanceof Member && $object_member->getObjectTypeId() == $selection->getObjectTypeId()) { unset($template_object_members[$i]); } } $object_members[] = $selection->getId(); } } } else { $object_members = $selected_members; } foreach ($template_object_members as $object_member) { $object_members[] = $object_member->getId(); } $controller->add_to_members($copy, $object_members); // set property values as defined in template instantiate_template_task_parameters($object, $copy, $parameterValues); // subscribe assigned to if ($copy instanceof ProjectTask) { foreach ($copy->getOpenSubTasks(false) as $m_task) { if ($m_task->getAssignedTo() instanceof Contact) { $m_task->subscribeUser($m_task->getAssignedTo()); } } if ($copy->getAssignedTo() instanceof Contact) { $copy->subscribeUser($copy->getAssignedTo()); } } else { if ($copy instanceof ProjectMilestone) { foreach ($copy->getTasks(false) as $m_task) { if ($m_task->getAssignedTo() instanceof Contact) { $m_task->subscribeUser($m_task->getAssignedTo()); } } } } } foreach ($copies as $c) { if ($c instanceof ProjectTask) { if ($c->getMilestoneId() > 0) { // find milestone in copies foreach ($copies as $m) { if ($m instanceof ProjectMilestone && $m->getFromTemplateObjectId() == $c->getMilestoneId()) { $c->setMilestoneId($m->getId()); $c->save(); break; } } } } } //copy dependencies foreach ($dependencies as $dependencie) { if ($dependencie instanceof ProjectTaskDependency) { $dep = new ProjectTaskDependency(); $dep->setPreviousTaskId($copiesIds[$dependencie->getPreviousTaskId()]); $dep->setTaskId($copiesIds[$dependencie->getTaskId()]); $dep->save(); } } DB::commit(); foreach ($copies as $c) { if ($c instanceof ProjectTask) { ApplicationLogs::createLog($c, ApplicationLogs::ACTION_ADD); } } if (is_array($parameters) && count($parameters) > 0) { ajx_current("back"); } else { ajx_current("back"); } }
function do_classify_mail($email, $members, $classification_data = null) { try { $ctrl = new ObjectController(); $create_task = false;//array_var($classification_data, 'create_task') == 'checked'; if (is_null($classification_data)) { $classification_data = array(); MailUtilities::parseMail($email->getContent(), $decoded, $parsedEmail, $warnings); for ($j=0; $j < count(array_var($parsedEmail, "Attachments", array())); $j++) { $classification_data["att_".$j] = true; } } $canWriteFiles = $this->checkFileWritability($classification_data, $parsedEmail); if ($canWriteFiles) { DB::beginWork(); if ($members) { $account_owner = logged_user() instanceof contact ? logged_user() : Contacts::findById($email->getAccount()->getContactId()); $ctrl->add_to_members($email, $members, $account_owner); } $conversation = MailContents::getMailsFromConversation($email); if (count($members) > 0) { $member_instances = Members::findAll(array('conditions' => 'id IN ('.implode(',',$members).')')); foreach ($conversation as $conv_email) { $account_owner = logged_user() instanceof contact ? logged_user() : Contacts::findById($conv_email->getAccount()->getContactId()); $ctrl->add_to_members($conv_email, $members, $account_owner); MailUtilities::parseMail($conv_email->getContent(), $decoded, $parsedEmail, $warnings); if ($conv_email->getHasAttachments()) { $this->classifyFile($classification_data, $conv_email, $parsedEmail, $member_instances, true); } } } DB::commit(); flash_success(lang('success classify email')); if ($create_task) { ajx_replace(true); $this->redirectTo('task', 'add_task', array('from_email' => $email->getId(), 'replace' => 1)); } else { ajx_current("back"); evt_add("reload mails panel", array()); } } else { flash_error(lang("error classifying attachment cant open file")); ajx_current("empty"); } // If can write files // Error... } catch(Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); } }