static function findAllowed() { $ctxMembers = active_context_members(); $permissionGroups = ContactPermissionGroups::getPermissionGroupIdsByContactCSV(logged_user()->getId()); // Find members where user can add tasks $sql = "\r\n\t\t\tSELECT distinct(member_id) \r\n\t\t\tFROM " . TABLE_PREFIX . "contact_member_permissions o \r\n\t\t\tWHERE object_type_id = " . ProjectTasks::instance()->getObjectTypeId() . " \r\n\t\t\tAND permission_group_id IN ( {$permissionGroups} ) AND can_write= 1 \r\n\t\t\t\r\n\t\t\tUNION (\r\n\t\t\t\tSELECT DISTINCT id from " . TABLE_PREFIX . "members m WHERE m.dimension_id IN\r\n\t\t\t\t(\r\n\t\t\t\t\tSELECT DISTINCT dimension_id FROM " . TABLE_PREFIX . "contact_dimension_permissions WHERE permission_group_id IN ({$permissionGroups}) AND permission_type ='allow all'\r\n\t\t\t\t)\t\r\n\t\t\t)"; $res = DB::execute($sql); $members = array(); while ($row = $res->fetchRow()) { $members[] = $row['member_id']; } if (!count($members)) { return; } // Find templates that belongs to any $member $sql = "\r\n\t\t\tSELECT distinct(id) AS id\r\n\t\t\tFROM " . TABLE_PREFIX . "object_members om\r\n\t\t\tINNER JOIN " . TABLE_PREFIX . "templates t ON t.object_id = om.object_id\r\n\t\t\tINNER JOIN " . TABLE_PREFIX . "objects o ON om.object_id = o.id\r\n\t\t\tWHERE\r\n\t\t\t member_id IN (" . implode(',', $members) . ")\r\n\t\t\tAND is_optimization = 0\r\n\t\t\tGROUP BY om.object_id\t\t\r\n\t\t"; $res = DB::execute($sql); $tpls = array(); // Iterate on the results and make som filtering while ($row = $res->fetchRow()) { $tpl = COTemplates::instance()->findById($row['id']); $templateMembers = $tpl->getMemberIds(); if (!count(array_intersect($templateMembers, $ctxMembers))) { //array_intersect($templateMembers, $ctxMembers) continue; } // Chcheck if all template members are included in $mebers // TODO: PERFORMENCE This should be done in one sql instead of filtering here if (!count(array_diff($templateMembers, $members))) { $tpls[] = $tpl; } else { } } return $tpls; }
function list_all() { ajx_current("empty"); // Get all variables from request $start = array_var($_GET, 'start', 0); $limit = array_var($_GET, 'limit', config_option('files_per_page')); $order = 'name'; $order_dir = array_var($_GET, 'dir'); $action = array_var($_GET, 'action'); $attributes = array("ids" => explode(',', array_var($_GET, 'ids'))); if (!$order_dir) { switch ($order) { case 'name': $order_dir = 'ASC'; break; default: $order_dir = 'DESC'; } } $dim_controller = new DimensionController(); $members = $dim_controller->initial_list_dimension_members(Dimensions::findByCode('workspaces')->getId(), ObjectTypes::findByName('workspace')->getId(), $context, true); $ids = array(); foreach ($members as $m) { $ids[] = $m['object_id']; } $members = active_context_members(false); // Context Members Ids $members_sql = ""; if (count($members) > 0) { $members_sql .= " AND parent_member_id IN (" . implode(',', $members) . ")"; } else { $members_sql .= " AND parent_member_id = 0"; } $res = Members::findAll(array("conditions" => "object_id IN (" . implode(',', $ids) . ") " . $members_sql, 'offset' => $start, 'limit' => $limit, 'order' => "{$order} {$order_dir}")); $object = $this->prepareObject($res, $start, $limit, count($res)); ajx_extra_data($object); tpl_assign("listing", $object); }
/** * Add single mail * * @access public * @param void * @return null */ function add_mail() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $this->addHelper('textile'); $mail_accounts = MailAccounts::getMailAccountsByUser(logged_user()); if (count($mail_accounts) < 1) { flash_error(lang('no mail accounts set')); ajx_current("empty"); return; } $this->setTemplate('add_mail'); $mail_data = array_var($_POST, 'mail'); $sendBtnClick = array_var($mail_data, 'sendBtnClick', '') == 'true' ? true : false; $isDraft = array_var($mail_data, 'isDraft', '') == 'true' ? true : false; $isUpload = array_var($mail_data, 'isUpload', '') == 'true' ? true : false; $autosave = array_var($mail_data, 'autosave', '') == 'true'; $id = array_var($mail_data, 'id'); $mail = MailContents::findById($id); $isNew = false; if (!$mail) { $isNew = true; $mail = new MailContent(); } tpl_assign('mail_to', urldecode(array_var($_GET, 'to'))); tpl_assign('link_to_objects', array_var($_GET, 'link_to_objects')); $def_acc_id = $this->getDefaultAccountId(); if ($def_acc_id > 0) { $def_acc = MailAccounts::getAccountById($def_acc_id); if ($def_acc instanceof MailAccount) { tpl_assign('default_account', $def_acc); } } tpl_assign('mail', $mail); tpl_assign('mail_data', $mail_data); tpl_assign('mail_accounts', $mail_accounts); Hook::fire('send_to', array_var($_GET, 'ids'), array_var($_GET, 'me')); // Form is submited if (is_array($mail_data)) { $account = MailAccounts::findById(array_var($mail_data, 'account_id')); if (!$account instanceof MailAccount) { flash_error(lang('mail account dnx')); ajx_current("empty"); return; } $accountUser = MailAccountContacts::getByAccountAndContact($account, logged_user()); if (!$accountUser instanceof MailAccountContact) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } if ($account->getOutgoingTrasnportType() == 'ssl' || $account->getOutgoingTrasnportType() == 'tls') { $available_transports = stream_get_transports(); if (array_search($account->getOutgoingTrasnportType(), $available_transports) === FALSE) { flash_error('The server does not support SSL.'); ajx_current("empty"); return; } } $cp_errs = $this->checkRequiredCustomPropsBeforeSave(array_var($_POST, 'object_custom_properties', array())); if (is_array($cp_errs) && count($cp_errs) > 0) { foreach ($cp_errs as $err) { flash_error($err); } ajx_current("empty"); return; } $subject = array_var($mail_data, 'subject'); $body = array_var($mail_data, 'body'); if (($pre_body_fname = array_var($mail_data, 'pre_body_fname')) != "") { $body = str_replace(lang('content too long not loaded'), '', $body, $count = 1); $tmp_filename = ROOT . "/tmp/{$pre_body_fname}"; if (is_file($tmp_filename)) { $body .= file_get_contents($tmp_filename); if (!$isDraft) { @unlink($tmp_filename); } } } if (array_var($mail_data, 'format') == 'html') { $css = "font-family:sans-serif,Arial,Verdana; font-size:14px; line-height:1.6; color:#222;"; Hook::fire('email_base_css', null, $css); str_replace(array("\r", "\n"), "", $css); $body = '<div style="' . $css . '">' . $body . '</div>'; $body = str_replace('<blockquote>', '<blockquote style="border-left:1px solid #987ADD;padding-left:10px;">', $body); } $type = 'text/' . array_var($mail_data, 'format'); $to = trim(array_var($mail_data, 'to')); if (str_ends_with($to, ",") || str_ends_with($to, ";")) { $to = substr($to, 0, strlen($to) - 1); } $mail_data['to'] = $to; $cc = trim(array_var($mail_data, 'cc')); if (str_ends_with($cc, ",") || str_ends_with($cc, ";")) { $cc = substr($cc, 0, strlen($cc) - 1); } $mail_data['cc'] = $cc; $bcc = trim(array_var($mail_data, 'bcc')); if (str_ends_with($bcc, ",") || str_ends_with($bcc, ";")) { $bcc = substr($bcc, 0, strlen($bcc) - 1); } $mail_data['bcc'] = $bcc; if (!$isDraft && trim($to . $cc . $bcc) == '') { flash_error(lang('recipient must be specified')); ajx_current("empty"); return; } $invalid_to = MailUtilities::validate_email_addresses($to); if (is_array($invalid_to)) { flash_error(lang('error invalid recipients', lang('mail to'), implode(", ", $invalid_to))); ajx_current("empty"); return; } $invalid_cc = MailUtilities::validate_email_addresses($cc); if (is_array($invalid_cc)) { flash_error(lang('error invalid recipients', lang('mail CC'), implode(", ", $invalid_cc))); ajx_current("empty"); return; } $invalid_bcc = MailUtilities::validate_email_addresses($bcc); if (is_array($invalid_bcc)) { flash_error(lang('error invalid recipients', lang('mail BCC'), implode(", ", $invalid_bcc))); ajx_current("empty"); return; } $last_mail_in_conversation = array_var($mail_data, 'last_mail_in_conversation'); $conversation_id = array_var($mail_data, 'conversation_id'); if ($last_mail_in_conversation && $conversation_id) { $new_mail_in_conversation = MailContents::getLastMailIdInConversation($conversation_id, true); if ($new_mail_in_conversation != $last_mail_in_conversation) { ajx_current("empty"); evt_add("new email in conversation", array('id' => $new_mail_in_conversation, 'genid' => array_var($_POST, 'instanceName'))); return; } } $mail->setFromAttributes($mail_data); $mail->setTo($to); $mail->setCc($cc); $mail->setBcc($bcc); $mail->setSubject($mail_data['subject']); $utils = new MailUtilities(); // attachment $linked_attachments = array(); $attachments = array(); $project_files_attachments = array(); $objects = array_var($_POST, 'linked_objects'); $attach_contents = array_var($_POST, 'attach_contents', array()); $original_email = isset($mail_data['original_id']) ? MailContents::findById($mail_data['original_id']) : null; if (is_array($objects)) { $err = 0; $count = -1; foreach ($objects as $objid) { $count++; $split = explode(":", $objid); if (count($split) == 2) { $object = Objects::instance()->findObject($split[1]); } else { if (count($split) == 4) { if ($split[0] == 'FwdMailAttach') { $tmp_filename = ROOT . "/tmp/" . logged_user()->getId() . "_" . ($original_email ? $original_email->getAccountId() : $mail_data['account_id']) . "_FwdMailAttach_" . $split[3]; if (is_file($tmp_filename)) { $attachments[] = array("data" => file_get_contents($tmp_filename), "name" => $split[1], "type" => $split[2]); continue; } } } } if (!isset($object) || !$object) { flash_error(lang('file dnx')); $err++; } else { if (isset($attach_contents[$count])) { if ($split[0] == 'ProjectFiles') { $file = ProjectFiles::findById($object->getId()); if (!$file instanceof ProjectFile) { flash_error(lang('file dnx')); $err++; } // if // if(!$file->canDownload(logged_user())) { // flash_error(lang('no access permissions')); // $err++; // } // if $project_files_attachments[] = $file; $attachments[] = array("data" => $file->getFileContent(), "name" => $file->getFilename(), "type" => $file->getTypeString()); } else { if ($split[0] == 'MailContents') { $email = MailContents::findById($object->getId()); if (!$email instanceof MailContent) { flash_error(lang('email dnx')); $err++; } // if if (!$email->canView(logged_user())) { flash_error(lang('no access permissions')); $err++; } // if $attachments[] = array("data" => $email->getContent(), "name" => $email->getSubject() . ".eml", "type" => 'message/rfc822'); } } } else { $linked_attachments[] = array("data" => $object->getViewUrl(), "name" => clean($object->getObjectName()), "type" => lang($object->getObjectTypeName()), "id" => $object->getId()); } } } if ($err > 0) { flash_error(lang('some objects could not be linked', $err)); ajx_current('empty'); return; } } $to = preg_split('/;|,/', $to); $to = $utils->parse_to($to); if ($body == '') { $body .= ' '; } try { $linked_users = array(); //create contacts from recipients of email if (user_config_option('create_contacts_from_email_recipients') || can_manage_contacts(logged_user())) { foreach ($to as $to_user) { $linked_user = Contacts::getByEmail($to_user[1]); if (!$linked_user instanceof Contact) { try { DB::beginWork(); $linked_user = create_user_from_email($to_user[1], $to_user[0], null, false); DB::commit(); } catch (Exception $e) { Logger::log($e->getMessage()); DB::rollback(); } } if ($linked_user instanceof Contact) { $linked_users[] = $linked_user; } } } if (count($linked_attachments)) { $linked_atts = $type == 'text/html' ? '<div style="font-family:arial;"><br><br><br><span style="font-size:12pt;font-weight:bold;color:#777">' . lang('linked attachments') . '</span><ul>' : "\n\n\n-----------------------------------------\n" . lang('linked attachments') . "\n\n"; foreach ($linked_attachments as $att) { $linked_atts .= $type == 'text/html' ? '<li><a href="' . $att['data'] . '">' . $att['name'] . ' (' . $att['type'] . ')</a></li>' : $att['name'] . ' (' . $att['type'] . '): ' . $att['data'] . "\n"; foreach ($linked_users as $linked_user) { try { $linked_user->giveAccessToObject(Objects::findObject($att['id'])); } catch (Exception $e) { //Logger::log($e->getMessage()); } } } $linked_atts .= $type == 'text/html' ? '</ul></div>' : ''; } else { $linked_atts = ''; } $body .= $linked_atts; if (count($attachments) > 0) { $i = 0; $str = ""; /* foreach ($attachments as $att) { $str .= "--000000000000000000000000000$i\n"; $str .= "Name: ".$att['name'] .";\n"; $str .= "Type: ".$att['type'] .";\n"; //$str .= "Encoding: ".$att['type'] .";\n"; $str .= base64_encode($att['data']) ."\n"; $str .= "--000000000000000000000000000$i--\n"; $i++; } */ $str = "#att_ver 2\n"; foreach ($attachments as $att) { $rep_id = $utils->saveContent($att['data']); if (str_starts_with($att['name'], "#")) { $att['name'] = str_replace_first("#", "@@sharp@@", $att['name']); } $str .= $att['name'] . "|" . $att['type'] . "|" . $rep_id . "\n"; } // save attachments, when mail is sent this file is deleted and full content is saved $repository_id = $utils->saveContent($str); if (!$isNew) { if (FileRepository::isInRepository($mail->getContentFileId())) { // delete old attachments $content = FileRepository::getFileContent($mail->getContentFileId()); if (str_starts_with($content, "#att_ver")) { $lines = explode("\n", $content); foreach ($lines as $line) { if (!str_starts_with($line, "#") && trim($line) !== "") { $data = explode("|", $line); if (isset($data[2]) && FileRepository::isInRepository($data[2])) { FileRepository::deleteFile($data[2]); } } } } FileRepository::deleteFile($mail->getContentFileId()); } } $mail->setContentFileId($repository_id); } $mail->setHasAttachments(is_array($attachments) && count($attachments) > 0 ? 1 : 0); $mail->setAccountEmail($account->getEmailAddress()); $mail->setSentDate(DateTimeValueLib::now()); $mail->setReceivedDate(DateTimeValueLib::now()); DB::beginWork(); $msg_id = MailUtilities::generateMessageId($account->getEmailAddress()); $conversation_id = array_var($mail_data, 'conversation_id'); $in_reply_to_id = array_var($mail_data, 'in_reply_to_id'); if ($conversation_id) { $in_reply_to = MailContents::findById(array_var($mail_data, 'original_id')); if ($in_reply_to instanceof MailContent && $in_reply_to->getSubject() && strpos(strtolower($mail->getSubject()), strtolower($in_reply_to->getSubject())) === false) { $conversation_id = null; $in_reply_to_id = ''; } } if (!$conversation_id) { $conversation_id = MailContents::getNextConversationId($account->getId()); } $mail->setMessageId($msg_id); $mail->setConversationId($conversation_id); $mail->setInReplyToId($in_reply_to_id); $mail->setUid(gen_id()); $mail->setState($isDraft && !$sendBtnClick ? 2 : 200); set_user_config_option('last_mail_format', array_var($mail_data, 'format', 'plain'), logged_user()->getId()); $body = utf8_safe($body); if (array_var($mail_data, 'format') == 'html') { $body = preg_replace("/<body*[^>]*>/i", '<body>', $body); // commented because sometimes brokes the html and leaves the body in blank //$body = convert_to_links(preg_replace("/<body*[^>]*>/i",'<body>', $body)); $mail->setBodyHtml($body); $mail->setBodyPlain(utf8_safe(html_to_text($body))); } else { $mail->setBodyPlain($body); $mail->setBodyHtml(''); } $mail->setFrom($account->getEmailAddress()); if ($accountUser->getIsDefault() && $accountUser->getSenderName() == "") { $mail->setFromName(logged_user()->getObjectName()); } else { $mail->setFromName($accountUser->getSenderName()); } $mail->save(); //$mail->setIsRead(logged_user()->getId(), true); if (Plugins::instance()->isActivePlugin('mail_rules')) { if (array_var($mail_data, 'format') == 'html') { $img = MailTracks::get_track_mark_img($mail->getId()); $body = $body . $img; $mail->setBodyHtml($body); $mail->setBodyPlain(utf8_safe(html_to_text($body))); $mail->save(); } } foreach ($project_files_attachments as $pfatt) { if ($pfatt instanceof ProjectFile) { $pfatt->setMailId($mail->getId()); $pfatt->save(); $pfatt->addToSharingTable(); } } $member_ids = active_context_members(false); // if replying a classified email classify on same workspace $classified_with_conversation = false; if (array_var($mail_data, 'original_id')) { $in_reply_to = MailContents::findById(array_var($mail_data, 'original_id')); if ($in_reply_to instanceof MailContent) { $member_ids = array_merge($member_ids, $in_reply_to->getMemberIds()); $classified_with_conversation = true; } } // autoclassify sent email if not classified if (!$classified_with_conversation) { $acc_mem_ids = explode(',', $account->getMemberId()); foreach ($acc_mem_ids as $acc_mem_id) { $member_ids[] = $acc_mem_id; } } $object_controller = new ObjectController(); foreach ($member_ids as $k => &$mem_id) { if ($mem_id == "") { unset($member_ids[$k]); } } if (count($member_ids) > 0) { //$object_controller->add_to_members($mail, $member_ids); $members = Members::instance()->findAll(array('conditions' => 'id IN (' . implode(',', $member_ids) . ')')); $mail->addToMembers($members, true); $mail->addToSharingTable(); } $object_controller->link_to_new_object($mail); $object_controller->add_subscribers($mail); /* if (array_var($mail_data, 'link_to_objects') != ''){ $lto = explode('|', array_var($mail_data, 'link_to_objects')); foreach ($lto as $object_string){ $split_object = explode('-', $object_string); $object = Objects::findObject($split_object[1]); if ($object instanceof ContentDataObject){ $mail->linkObject($object); } } }*/ //subscribe user $user = Contacts::findById($account->getContactId()); if ($user instanceof Contact) { $mail->subscribeUser($user); } /*if (user_config_option('create_contacts_from_email_recipients') && can_manage_contacts(logged_user())) { // automatically create contacts foreach ($to as $recipient) { $recipient_name = trim($recipient[0]); $recipient_address = trim($recipient[1]); if (!$recipient_address) continue; $contact = Contacts::getByEmail($recipient_address); if (!$contact instanceof Contact) { try { $contact = new Contact(); $contact->addEmail($recipient_address, 'personal'); if ($recipient_name && $recipient_name != $recipient_address) { $contact->setFirstName($recipient_name); } else { $index = strpos($recipient_address, "@"); $recipient_name = substr($recipient_address, 0, $index); $contact->setFirstName($recipient_name); } $contact->save(); } catch (Exception $e) { Logger::log($e->getMessage()); } } } }*/ $mail->addToSharingTable(); $mail->orderConversation(); DB::commit(); ApplicationLogs::createLog($mail, ApplicationLogs::ACTION_ADD, false, true); $mail->setIsRead(logged_user()->getId(), true); if (!$autosave) { if ($isDraft && !$sendBtnClick) { flash_success(lang('success save mail')); ajx_current("empty"); } else { evt_add("must send mails", array("account" => $mail->getAccountId())); //flash_success(lang('mail is being sent')); ajx_current("back"); } evt_add("email saved", array("id" => $mail->getId(), "instance" => array_var($_POST, 'instanceName'))); } else { evt_add("draft mail autosaved", array("id" => $mail->getId(), "hf_id" => $mail_data['hf_id'])); flash_success(lang('success autosave draft')); ajx_current("empty"); } } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); } // try } // if }
$currentday = $today->format("j"); $currentmonth = $today->format("n"); $currentyear = $today->format("Y"); $drawHourLine = $day == $currentday && $month == $currentmonth && $year == $currentyear; $dtv = DateTimeValueLib::make(0, 0, 0, $month, $day, $year); $result = ProjectEvents::getDayProjectEvents($dtv, active_context(), $user_filter, $status_filter); if (!$result) { $result = array(); } $alldayevents = array(); $milestones = ProjectMilestones::getRangeMilestones($dtv, $dtv); if ($task_filter != "hide") { $tasks = ProjectTasks::getRangeTasksByUser($dtv, $dtv, $user_filter != -1 ? $user : null, $task_filter); } if (user_config_option('show_birthdays_in_calendar')) { $birthdays = Contacts::instance()->getRangeContactsByBirthday($dtv, $dtv, active_context_members(false)); } else { $birthdays = array(); } foreach ($result as $key => $event) { if ($event->getTypeId() > 1) { $alldayevents[] = $event; unset($result[$key]); } } if ($milestones) { $alldayevents = array_merge($alldayevents, $milestones); } if (isset($tasks)) { $tmp_tasks = array(); $dtv_end = new DateTimeValue($dtv->getTimestamp() + 60 * 60 * 24);
function quick_add_task() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $notAllowedMember = ''; if (!ProjectTask::canAdd(logged_user(), active_context(), $notAllowedMember)) { if (str_starts_with($notAllowedMember, '-- req dim --')) { flash_error(lang('must choose at least one member of', str_replace_first('-- req dim --', '', $notAllowedMember, $in))); } else { flash_error(lang('no context permissions to add', lang("tasks"), $notAllowedMember)); } ajx_current("empty"); return; } ajx_current("empty"); $task = new ProjectTask(); $task_data = array_var($_POST, 'task'); $parent_id = array_var($task_data, 'parent_id', 0); $parent = ProjectTasks::findById($parent_id); if (is_array($task_data)) { $task_data['due_date'] = getDateValue(array_var($task_data, 'task_due_date')); $task_data['start_date'] = getDateValue(array_var($task_data, 'task_start_date')); if ($task_data['due_date'] instanceof DateTimeValue) { $duetime = getTimeValue(array_var($task_data, 'task_due_time')); if (is_array($duetime)) { $task_data['due_date']->setHour(array_var($duetime, 'hours')); $task_data['due_date']->setMinute(array_var($duetime, 'mins')); } $task_data['due_date']->advance(logged_user()->getTimezone() * -3600); $task_data['use_due_time'] = is_array($duetime); } if ($task_data['start_date'] instanceof DateTimeValue) { $starttime = getTimeValue(array_var($task_data, 'task_start_time')); if (is_array($starttime)) { $task_data['start_date']->setHour(array_var($starttime, 'hours')); $task_data['start_date']->setMinute(array_var($starttime, 'mins')); } $task_data['start_date']->advance(logged_user()->getTimezone() * -3600); $task_data['use_start_time'] = is_array($starttime); } if (config_option("wysiwyg_tasks")) { $task_data['type_content'] = "html"; $task_data['text'] = preg_replace("/[\n|\r|\n\r]/", '', array_var($task_data, 'text')); } else { $task_data['type_content'] = "text"; } $task_data['object_type_id'] = $task->getObjectTypeId(); $task->setFromAttributes($task_data); if (array_var($task_data, 'is_completed', false) == 'true') { $task->setCompletedOn(DateTimeValueLib::now()); $task->setCompletedById(logged_user()->getId()); } try { DB::beginWork(); $task->save(); $totalMinutes = array_var($task_data, 'hours') * 60 + array_var($task_data, 'minutes'); $task->setTimeEstimate($totalMinutes); $task->save(); $gb_member_id = array_var($task_data, 'member_id'); $member_ids = array(); $persons_dim = Dimensions::findByCode('feng_persons'); $persons_dim_id = $persons_dim instanceof Dimension ? $persons_dim->getId() : 0; if ($parent) { if (count($parent->getMembers()) > 0) { foreach ($parent->getMembers() as $member) { if ($member->getDimensionId() != $persons_dim_id) { $member_ids[] = $member->getId(); } } } $task->setMilestoneId($parent->getMilestoneId()); $task->save(); } if (count($member_ids) == 0) { $member_ids = active_context_members(false); } if ($gb_member_id && is_numeric($gb_member_id)) { $member_ids[] = $gb_member_id; } $object_controller = new ObjectController(); $object_controller->add_to_members($task, $member_ids); //Add new work timeslot for this task // if (array_var($task_data,'hours') != '' && array_var($task_data,'hours') > 0){ // $hours = array_var($task_data, 'hours'); // $hours = - $hours; // // $timeslot = new Timeslot(); // $dt = DateTimeValueLib::now(); // $dt2 = DateTimeValueLib::now(); // $timeslot->setEndTime($dt); // $dt2 = $dt2->add('h', $hours); // $timeslot->setStartTime($dt2); // $timeslot->setContactId(logged_user()->getId()); // $timeslot->setObjectId($task->getId()); // $timeslot->save(); // } ApplicationLogs::createLog($task, ApplicationLogs::ACTION_ADD); $assignee = $task->getAssignedToContact(); if ($assignee instanceof Contact) { $task->subscribeUser($assignee); } // create default reminder $reminder = new ObjectReminder(); $reminder->setMinutesBefore(1440); $reminder->setType("reminder_email"); $reminder->setContext("due_date"); $reminder->setObject($task); $reminder->setUserId(0); $date = $task->getDueDate(); if (!isset($minutes)) { $minutes = 0; } if ($date instanceof DateTimeValue) { $rdate = new DateTimeValue($date->getTimestamp() - $minutes * 60); $reminder->setDate($rdate); } $reminder->save(); $subs = array(); if (config_option('multi_assignment') && Plugins::instance()->isActivePlugin('crpm')) { $json_subtasks = json_decode(array_var($_POST, 'multi_assignment')); $line = 0; foreach ($json_subtasks as $json_subtask) { $subtasks[$line]['assigned_to_contact_id'] = $json_subtask->assigned_to_contact_id; $subtasks[$line]['name'] = $json_subtask->name; $subtasks[$line]['time_estimate_hours'] = $json_subtask->time_estimate_hours; $subtasks[$line]['time_estimate_minutes'] = $json_subtask->time_estimate_minutes; $line++; } Hook::fire('save_subtasks', $task, $subtasks); $subtasks = ProjectTasks::findAll(array('conditions' => '`parent_id` = ' . DB::escape($task->getId()))); // findAll foreach ($subtasks as $sub) { $subs[] = $sub->getArrayInfo(); } } // subscribe $task->subscribeUser(logged_user()); DB::commit(); // notify asignee if (array_var($task_data, 'notify') == 'true') { try { Notifier::taskAssigned($task); } catch (Exception $e) { } // try } ajx_extra_data(array("task" => $task->getArrayInfo(), 'subtasks' => $subs)); flash_success(lang('success add task', $task->getObjectName())); } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); } // try } // if }
function get_rendered_member_selectors() { $object_members = array(); $objectId = 0; if (get_id()) { $object = Objects::findObject(get_id()); $object_type_id = $object->manager()->getObjectTypeId(); $object_members = $object->getMemberIds(); $objectId = get_id(); } else { $object_type_id = array_var($_GET, 'objtypeid'); if (array_var($_GET, 'members')) { $object_members = explode(',', array_var($_GET, 'members')); } } if (count($object_members) == 0) { $object_members = active_context_members(false); } $genid = array_var($_GET, 'genid'); $listeners = array(); //ob_start — Turn on output buffering //no output is sent from the script (other than headers), instead the output is stored in an internal buffer. ob_start(); //get skipped dimensions for this view $view_name = array_var($_GET, 'view_name'); $dimensions_to_show = explode(",", user_config_option($view_name . "_view_dimensions_combos")); $dimensions_to_skip = array_diff(get_user_dimensions_ids(), $dimensions_to_show); render_member_selectors($object_type_id, $genid, $object_members, array('listeners' => $listeners), $dimensions_to_skip, null, false); ajx_current("empty"); //Gets the current buffer contents and delete current output buffer. //ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean(). ajx_extra_data(array("htmlToAdd" => ob_get_clean())); ajx_extra_data(array("objectId" => $objectId)); }
<?php $members = implode(',', active_context_members(false)); $ws_dim = Dimensions::findByCode('workspaces'); ?> <div class="ws-widget widget"> <div class="widget-header" onclick="og.dashExpand('<?php echo $genid; ?> ');"> <?php echo lang('workspaces'); ?> <div class="dash-expander ico-dash-expanded" id="<?php echo $genid; ?> expander"></div> </div> <div class="widget-body" id="<?php echo $genid; ?> _widget_body" > <div class="project-list"> <?php foreach ($data_ws as $ws) { ?> <div class="project-row-container">
<?php // Render only when no context is selected if (!count(active_context_members(false))) { // Make calcs, call models, controllers $limit = 5; $result = Contacts::instance()->listing(array("order" => "name", "order_dir" => "asc", "extra_conditions" => " AND `is_company` = 0 AND disabled = 0 ", "start" => 0, "limit" => $limit)); $total = $result->total; $contacts = $result->objects; $render_add = can_manage_security(logged_user()); $genid = gen_id(); include_once 'template.php'; }
/** * Return user config option value * * @access public * @param string $name Option name * @param mixed $default Default value that is returned in case of any error * @param int $user_id User Id, if null logged user is taken * @return mixed */ function user_config_option($option, $default = null, $user_id = null, $options_members = false) { if (is_null($user_id)) { if (logged_user() instanceof Contact) { $user_id = logged_user()->getId(); } else if (is_null($default)) { $def_value = null; // check the cache for the option default value if (GlobalCache::isAvailable()) { $def_value = GlobalCache::get('user_config_option_def_'.$option, $success); if ($success) return $def_value; } // default value not found in cache $def_value = ContactConfigOptions::getDefaultOptionValue($option, $default); if (GlobalCache::isAvailable()) { GlobalCache::update('user_config_option_def_'.$option, $def_value); } return $def_value; } else { return $default; } } // check the cache for the option value if (GlobalCache::isAvailable()) { $option_value = GlobalCache::get('user_config_option_'.$user_id.'_'.$option, $success); if ($success) return $option_value; } if($options_members){ $members = implode ( ',',active_context_members(false)); // default value not found in cache $option_value = ContactConfigOptions::getOptionValue($option, $user_id, $default, $members); }else{ $option_value = ContactConfigOptions::getOptionValue($option, $user_id, $default); } if (GlobalCache::isAvailable()) { GlobalCache::update('user_config_option_'.$user_id.'_'.$option, $option_value); } return $option_value; } // user_config_option
function render_member_selectors($content_object_type_id, $genid = null, $selected_member_ids = null, $options = array(), $skipped_dimensions = null, $simulate_required = null, $default_view = true) { if (is_numeric($content_object_type_id)) { if (is_null($genid)) { $genid = gen_id(); } $user_dimensions = get_user_dimensions_ids(); // User allowed dimensions $dimensions = array(); // Diemsions for this content type if ($all_dimensions = Dimensions::getAllowedDimensions($content_object_type_id)) { foreach ($all_dimensions as $dimension) { if (isset($user_dimensions[$dimension['dimension_id']])) { $custom_name = DimensionOptions::getOptionValue($dimension['dimension_id'], 'custom_dimension_name'); $dimension['dimension_name'] = $custom_name && trim($custom_name) != "" ? $custom_name : lang($dimension['dimension_code']); $dimensions[] = $dimension; } } } if ($dimensions != null && count($dimensions)) { if (is_null($selected_member_ids) && array_var($options, 'select_current_context')) { $context = active_context(); $selected_member_ids = array(); foreach ($context as $selection) { if ($selection instanceof Member) { $selected_member_ids[] = $selection->getId(); } } } if (is_null($selected_member_ids)) { $selected_member_ids = array(); } $skipped_dimensions_cond = ""; if (is_array($skipped_dimensions) && count($skipped_dimensions) > 0) { $skipped_dimensions_cond = " AND dimension_id NOT IN (" . implode(',', $skipped_dimensions) . ")"; } // Set view variables $manageable_conds = ' AND dimension_id IN (SELECT id from ' . TABLE_PREFIX . 'dimensions WHERE is_manageable=1)' . $skipped_dimensions_cond; $selected_members = count($selected_member_ids) > 0 ? Members::findAll(array('conditions' => 'id IN (' . implode(',', $selected_member_ids) . ') ' . $manageable_conds)) : array(); $selected_member_ids = array(); foreach ($selected_members as $sm) { $selected_member_ids[] = $sm->getId(); } $selected_members_json = "[" . implode(',', $selected_member_ids) . "]"; $component_id = "{$genid}-member-selectors-panel-{$content_object_type_id}"; $object_is_new = is_null($selected_members); $listeners = array_var($options, 'listeners', array()); $allowed_member_type_ids = array_var($options, 'allowedMemberTypes', null); $initial_selected_members = $selected_members; if (count($initial_selected_members) == 0) { $selected_context_member_ids = active_context_members(false); if (count($selected_context_member_ids) > 0) { $initial_selected_members = Members::findAll(array('conditions' => 'id IN (' . implode(',', $selected_context_member_ids) . ')')); } } $tmp = array(); foreach ($initial_selected_members as $ism) { if ($ism->getDimension()->getIsManageable()) { $tmp[] = $ism; } } $initial_selected_members = $tmp; // Render view include get_template_path("components/multiple_dimension_selector", "dimension"); } } }
/** * Execute search * TODO: Performance gus: * Fetch only ids and execute a select statement by pk (fer each result) * @param void * @return null */ function search() { // Init vars $search_for = array_var($_GET, 'search_for'); $search_dimension = array_var($_GET, 'search_dimension'); $advanced = array_var($_GET, 'advanced'); $minWordLength = $this->minWordLength($search_for); $useLike = ( $minWordLength && ($this->ignoreMinWordLength) && ($minWordLength < self::$MYSQL_MIN_WORD_LENGHT) ); $search_pieces= explode(" ", $search_for); $search_string = ""; if (!$useLike){ // Prepare MATCH AGAINST string foreach ($search_pieces as $word ) { if (( strpos($word, "@") || strpos($word, ".") || strpos($word, ",")) === false ) { // STRING Dont containt special characheters that mysql use as separator. Noramal flow if ($this->wildCardSearch) { $word.="*"; } }else{ $word = str_replace($this->mysqlWordSeparator, " +", $word) ; } if ( !str_starts_with($word, " ") ) { $word = " +".$word; } $search_string .= mysql_real_escape_string( $word ). " "; } $search_string = substr($search_string, 0 , -1); }else{ // USE Like Query $search_string = mysql_real_escape_string($search_for, DB::connection()->getLink()); } $this->search_for = $search_for; $limit = $this->limit; $start = array_var($_REQUEST, 'start' , $this->start); $this->start = $start; $limitTest = max( $this->limitTest , $this->limit); $filteredResults = 0; $uid = logged_user()->getId(); if(!isset($search_dimension)){ $members = active_context_members(false); }else{ if($search_dimension == 0){ $members = array(); }else{ $members = array($search_dimension); } } // click on search everywhere if (array_var($_REQUEST, 'search_all_projects')) { $members = array(); } $revisionObjectTypeId = ObjectTypes::findByName("file revision")->getId(); $members_sql = ""; if(count($members) > 0){ $members_sql = "AND (rel_object_id IN (SELECT object_id FROM " . TABLE_PREFIX . "object_members om WHERE member_id IN (" . implode ( ',', $members ) . ") GROUP BY object_id HAVING count(member_id) = ".count($members).") OR o.object_type_id = $revisionObjectTypeId AND rel_object_id IN (SELECT fr.object_id FROM " . TABLE_PREFIX . "object_members om INNER JOIN ".TABLE_PREFIX."project_file_revisions fr ON om.object_id=fr.file_id WHERE member_id IN (" . implode ( ',', $members ) . ") GROUP BY object_id HAVING count(member_id) = ".count($members)."))"; $this->search_dimension = implode ( ',', $members ); }else{ $this->search_dimension = 0; } $listableObjectTypeIds = implode(",",ObjectTypes::getListableObjectTypeIds()); if($_POST) { $conditions = array_var($_POST, 'conditions'); $search = array_var($_POST, 'search'); $type_object = array_var($search, 'search_object_type_id'); if(!is_array($conditions)) $conditions = array(); $where_condiition = ''; $conditions_view = array(); $cont = 0; $joincp =""; foreach($conditions as $condition){ $condValue = array_key_exists('value', $condition) ? $condition['value'] : ''; if($condition['field_type'] == 'boolean'){ $value = array_key_exists('value', $condition); }else if($condition['field_type'] == 'date'){ if ($condValue != '') { $dtFromWidget = DateTimeValueLib::dateFromFormatAndString(user_config_option('date_format'), $condValue); $value = date("m/d/Y", $dtFromWidget->getTimestamp()); } }else{ $value = mysql_real_escape_string($condValue, DB::connection()->getLink()); } $condition_condition = mysql_real_escape_string(array_var($condition, 'condition'), DB::connection()->getLink()); $condition_field_name = mysql_real_escape_string(array_var($condition, 'field_name'), DB::connection()->getLink()); $conditionLocal = "like"; tpl_assign('type_object', $type_object); if (isset($condition['custom_property_id']) and is_numeric($condition['custom_property_id'])){ $condition_field_name = 'value'; $joincp = 'JOIN fo_custom_property_values cp ON cp.object_id = so.rel_object_id'; }; if ($condition_condition == "=" or $condition_condition == ">" or $condition_condition == "<" or $condition_condition == "<>" or $condition_condition == ">=" or $condition_condition == "<="){ $conditionLocal = $condition_condition; }; if($condition_field_name == "id"){ $condition_field_name = "o`.`id" ; }; if($condition_condition == "like"){ $where_condiition .= " AND `" . $condition_field_name . "` " . "like" . " '%" . $value . "%' "; }else if($condition_condition == "ends with"){ $where_condiition .= " AND `" . $condition_field_name . "` " . "like" . " '%" . $value . "' "; }else if($condition_condition == "start with"){ $where_condiition .= " AND `" . $condition_field_name . "` " . "like" . " '" . $value . "%' "; }else if($condition_condition == "not like"){ $where_condiition .= " AND `" . $condition_field_name . "` " . "not like" . " '%" . $value . "%' "; }else{ $where_condiition .= " AND `" . $condition_field_name . "` " . $conditionLocal . " '" . $value . "' "; } $conditions_view[$cont]['id'] = $condition['id']; $conditions_view[$cont]['custom_property_id'] = $custom_prop_id; $conditions_view[$cont]['field_name'] = $condition['field_name']; $conditions_view[$cont]['condition'] = $condition['condition']; $conditions_view[$cont]['value'] = $value; $cont++; } tpl_assign('conditions', $conditions_view); if($type_object){ $object_table = ObjectTypes::findById($type_object); $table = $object_table->getTableName(); } $sql = " SELECT distinct(so.rel_object_id) AS id FROM ".TABLE_PREFIX."searchable_objects so ".$joincp." INNER JOIN ".TABLE_PREFIX.$table." nto ON nto.object_id = so.rel_object_id INNER JOIN ".TABLE_PREFIX."objects o ON o.id = so.rel_object_id WHERE ( ( so.rel_object_id IN ( SELECT object_id FROM ".TABLE_PREFIX."sharing_table WHERE group_id IN ( SELECT permission_group_id FROM ".TABLE_PREFIX."contact_permission_groups WHERE contact_id = $uid ) ) ) ) " . $where_condiition . $members_sql . " ORDER by o.updated_on DESC LIMIT $start, $limitTest "; } else { $type_object = ''; $sql = " SELECT distinct(so.rel_object_id) AS id FROM ".TABLE_PREFIX."searchable_objects so INNER JOIN ".TABLE_PREFIX."objects o ON o.id = so.rel_object_id WHERE ( ( o.object_type_id = $revisionObjectTypeId AND EXISTS ( SELECT id FROM ".TABLE_PREFIX."sharing_table WHERE object_id = ( SELECT file_id FROM ".TABLE_PREFIX."project_file_revisions WHERE object_id = o.id ) AND group_id IN (SELECT permission_group_id FROM ".TABLE_PREFIX."contact_permission_groups WHERE contact_id = $uid ) ) ) OR ( so.rel_object_id IN ( SELECT object_id FROM ".TABLE_PREFIX."sharing_table WHERE group_id IN ( SELECT permission_group_id FROM ".TABLE_PREFIX."contact_permission_groups WHERE contact_id = $uid ) ) ) )" . (($useLike) ? "AND so.content LIKE '%$search_string%' " : "AND MATCH (so.content) AGAINST ('$search_string' IN BOOLEAN MODE) ") . " AND o.object_type_id IN ($listableObjectTypeIds) " . $members_sql . " ORDER by o.updated_on DESC LIMIT $start, $limitTest "; } tpl_assign('type_object', $type_object); $db_search_results = array(); $search_results_ids = array(); $timeBegin = time(); $res = DB::execute($sql); $timeEnd = time(); while ($row = $res->fetchRow() ) { $search_results_ids[] = $row['id'] ; } // Prepare results for view to avoid processing at presentation layer $search_results = $this->prepareResults($search_results_ids, $null, $limit); // Calculate or approximate total for pagination $total = count($search_results_ids) + $start ; if ( count ( $search_results_ids ) < $limitTest ) { $total = count($search_results_ids) + $start ; }else{ $total = "Many" ; } //$total -= $filteredResults ; $this->total = $total ; // Pagination $this->buildPagination($search_results, $search_for); // Extra data $extra = new stdClass() ; if ($this->showQueryTime) { $extra->time = $timeEnd-$timeBegin ; } //$extra->filteredResults = $filteredResults ; // Template asigns tpl_assign('pagination', $this->pagination); tpl_assign('search_string', $search_for); tpl_assign('search_dimension', $this->search_dimension); tpl_assign('search_results', $search_results); tpl_assign('advanced', $advanced); tpl_assign('extra', $extra ); $types = array(array("", lang("select one"))); $object_types = ObjectTypes::getAvailableObjectTypes(); foreach ($object_types as $ot) { $types[] = array($ot->getId(), lang($ot->getName())); } // if ($selected_type != '') // tpl_assign('allowed_columns', $this->get_allowed_columns($selected_type)); tpl_assign('object_types', $types); //Ajax if (!$total && !$advanced){ if($_POST && count($search_results < 0)){ tpl_assign('msg_advanced', true); }else{ $this->setTemplate('no_results'); } } ajx_set_no_toolbar(true); }
<?php $genid = gen_id(); $typeId = ObjectTypes::instance()->findByName("workspace")->getId(); //Check if There is a workspace in the active context /* @var $member Member */ foreach (active_context_members(false) as $memberId) { $member = Members::instance()->findById($memberId); if ($member->getObjectTypeId() == $typeId) { $id = $member->getObjectId(); if ($workspace = Workspaces::instance()->findById($id) && trim($member->getDescription()) != "") { $description = $member->getDescription(); include_once 'template.php'; break; } } }
function general_search() { // Init vars $search_dimension = array_var($_GET, 'search_dimension'); $filteredResults = 0; $uid = logged_user()->getId(); if (!isset($search_dimension)) { $members = active_context_members(false); } else { if ($search_dimension == 0) { $members = array(); } else { $members = array($search_dimension); } } // click on search everywhere if (array_var($_REQUEST, 'search_all_projects')) { $members = array(); } $revisionObjectTypeId = ObjectTypes::findByName("file revision")->getId(); $members_sql = ""; if (count($members) > 0) { $context_condition = "(EXISTS\r\n\t\t\t\t\t\t\t\t\t\t(SELECT om.object_id\r\n\t\t\t\t\t\t\t\t\t\t\tFROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\t\t\t\t\t\t\tWHERE\tom.member_id IN (" . implode(',', $members) . ") AND so.rel_object_id = om.object_id\r\n\t\t\t\t\t\t\t\t\t\t\tGROUP BY object_id\r\n\t\t\t\t\t\t\t\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t)"; $context_condition_rev = "(EXISTS\r\n\t\t\t\t\t\t\t\t\t\t(SELECT fr.object_id FROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "project_file_revisions fr ON om.object_id=fr.file_id\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "objects ob ON fr.object_id=ob.id\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE fr.file_id = so.rel_object_id AND ob.object_type_id = {$revisionObjectTypeId} AND member_id IN (" . implode(',', $members) . ")\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tGROUP BY object_id\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t)"; $members_sql = "AND ( " . $context_condition . " OR " . $context_condition_rev . ")"; $this->search_dimension = implode(',', $members); } else { $this->search_dimension = 0; } $listableObjectTypeIds = implode(",", ObjectTypes::getListableObjectTypeIds()); $can_see_all_tasks_cond = ""; if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $can_see_all_tasks_cond = " AND IF((SELECT ot.name FROM " . TABLE_PREFIX . "object_types ot WHERE ot.id=o.object_type_id)='task',\r\n\t\t\t (SELECT t.assigned_to_contact_id FROM " . TABLE_PREFIX . "project_tasks t WHERE t.object_id=o.id) = " . logged_user()->getId() . ",\r\n\t\t\t true)"; } $search_string = trim(array_var($_REQUEST, 'query', '')); $search_string = mysql_real_escape_string($search_string, DB::connection()->getLink()); $start = array_var($_REQUEST, 'start', 0); $orig_limit = array_var($_REQUEST, 'limit'); $limit = $orig_limit + 1; $useLike = false; if (user_config_option("search_engine") == 'like') { $useLike = true; } if (strlen($search_string) < 4) { $useLike = true; } if (strlen($search_string) > 0) { $this->search_for = $search_string; $logged_user_pgs = implode(',', logged_user()->getPermissionGroupIds()); $sql = "\r\n\t\t\tSELECT DISTINCT so.rel_object_id AS id, so.content AS text_match, so.column_name AS field_match\r\n\t\t\tFROM " . TABLE_PREFIX . "searchable_objects so\r\n\t\t\tWHERE " . ($useLike ? " so.content LIKE '%{$search_string}%' " : " MATCH (so.content) AGAINST ('\"{$search_string}\"' IN BOOLEAN MODE) ") . "\r\n\t\t\tAND (EXISTS\r\n\t\t\t\t(SELECT o.id\r\n\t\t\t\t FROM " . TABLE_PREFIX . "objects o\r\n\t\t\t\t\t\t\t WHERE\to.id = so.rel_object_id AND (\r\n\t\t\t\t\t\t\t (o.object_type_id = {$revisionObjectTypeId} AND\r\n\t\t\t\t\t\t\t EXISTS (\r\n\t\t\t\t\t\t\t SELECT group_id FROM " . TABLE_PREFIX . "sharing_table WHERE object_id = ( SELECT file_id FROM " . TABLE_PREFIX . "project_file_revisions WHERE object_id = o.id )\r\n\t\t\t\t\t\t\t\t\tAND group_id IN ({$logged_user_pgs})\r\n\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tOR (\r\n\t\t\t\t\t\t\t\t\t\t\t\t(EXISTS\r\n\t\t\t\t\t\t\t\t\t\t\t\t(SELECT object_id\r\n\t\t\t\t\t\t\t\t\t\t\t\tFROM " . TABLE_PREFIX . "sharing_table sh\r\n\t\t\t\t\t\t\t\t\t\tWHERE o.id = sh.object_id\r\n\t\t\t\t\t\t\t\t\t\tAND sh.group_id IN (\r\n\t\t\t\t\t\t\t\t\t\t\t{$logged_user_pgs}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t) AND o.object_type_id IN ({$listableObjectTypeIds}) " . $members_sql . $can_see_all_tasks_cond . "\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tGROUP BY(id)\t\r\n\t\t\t\t\t\tORDER BY(id) DESC\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tLIMIT {$start}, {$limit}"; $rows = DB::executeAll($sql); if (!is_array($rows)) { $rows = array(); } // show more $show_more = false; if (count($rows) > $orig_limit) { array_pop($rows); $show_more = true; } if ($show_more) { ajx_extra_data(array('show_more' => $show_more)); } $search_results = array(); $object_ids = array(); foreach ($rows as $ob_data) { // basic data $data = array('id' => $ob_data['id'], 'text_match' => $this->highlightOneResult($ob_data['text_match']), 'field_match' => $ob_data['field_match']); $object_ids[] = $ob_data['id']; $search_results[] = $data; } if (count($object_ids) > 0) { $result = ContentDataObjects::listing(array("extra_conditions" => " AND o.id IN (" . implode(",", $object_ids) . ") ", "include_deleted" => true)); $objects = $result->objects; foreach ($objects as $object) { foreach ($search_results as $key => $search_result) { if ($search_result['id'] == $object->getId()) { $search_results[$key]['name'] = $object->getObjectName(); $class = 'ico-' . $object->getObjectTypeName(); $search_results[$key]['iconCls'] = $class; $search_results[$key]['url'] = $object->getViewUrl(); continue; } } } } $row = "search-result-row-medium"; ajx_extra_data(array('row_class' => $row)); ajx_extra_data(array('search_results' => $search_results)); } ajx_current("empty"); }
function index() { $tasksUserId = array_var($_GET, 'tu'); if (is_null($tasksUserId)) { $tasksUserId = user_config_option('TM tasks user filter', logged_user()->getId()); } else { if (user_config_option('TM tasks user filter') != $tasksUserId) { set_user_config_option('TM tasks user filter', $tasksUserId, logged_user()->getId()); } } $timeslotsUserId = array_var($_GET, 'tsu'); if (is_null($timeslotsUserId)) { $timeslotsUserId = user_config_option('TM user filter', 0); } else { if (user_config_option('TM user filter') != $timeslotsUserId) { set_user_config_option('TM user filter', $timeslotsUserId, logged_user()->getId()); } } if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $timeslotsUserId = logged_user()->getId(); } $showTimeType = array_var($_GET, 'stt'); if (is_null($showTimeType)) { $showTimeType = user_config_option('TM show time type', 0); } else { if (user_config_option('TM show time type') != $showTimeType) { set_user_config_option('TM show time type', $showTimeType, logged_user()->getId()); } } $start = array_var($_GET, 'start', 0); $limit = 20; $tasksUser = Contacts::findById($tasksUserId); $timeslotsUser = Contacts::findById($timeslotsUserId); //Active tasks view $open_timeslots = Timeslots::instance()->listing(array("extra_conditions" => " AND end_time = '" . EMPTY_DATETIME . "' AND contact_id = " . $tasksUserId))->objects; $tasks = array(); foreach ($open_timeslots as $open_timeslot) { $task = ProjectTasks::findById($open_timeslot->getRelObjectId()); if ($task instanceof ProjectTask && !$task->isCompleted() && !$task->isTrashed() && !$task->isArchived()) { $tasks[] = $task; } } ProjectTasks::populateTimeslots($tasks); //Timeslots view $total = 0; switch ($showTimeType) { case 0: //Show only timeslots added through the time panel $result = Timeslots::getGeneralTimeslots(active_context(), $timeslotsUser, $start, $limit); $timeslots = $result->objects; $get_total = Timeslots::getGeneralTimeslots(active_context(), $timeslotsUser, $start, $limit, true); $total = $get_total->total; break; default: throw new Error('Unrecognised TM show time type: ' . $showTimeType); } //Get Users Info $users = array(); $context = active_context(); if (!can_manage_time(logged_user())) { if (can_add(logged_user(), $context, Timeslots::instance()->getObjectTypeId())) { $users = array(logged_user()); } } else { if (logged_user()->isMemberOfOwnerCompany()) { $users = Contacts::getAllUsers(); } else { $users = logged_user()->getCompanyId() > 0 ? Contacts::getAllUsers(" AND `company_id` = " . logged_user()->getCompanyId()) : array(logged_user()); } // filter users by permissions only if any member is selected. $selected_members = active_context_members(false); if (count($selected_members) > 0) { $tmp_users = array(); foreach ($users as $user) { if (can_add($user, $context, Timeslots::instance()->getObjectTypeId())) { $tmp_users[] = $user; } } $users = $tmp_users; } } //Get Companies Info if (logged_user()->isMemberOfOwnerCompany() || logged_user()->isAdminGroup()) { $companies = Contacts::getCompaniesWithUsers(); } else { $companies = array(); if (logged_user()->getCompanyId() > 0) { $companies[] = logged_user()->getCompany(); } } $required_dimensions = DimensionObjectTypeContents::getRequiredDimensions(Timeslots::instance()->getObjectTypeId()); $draw_inputs = !$required_dimensions || count($required_dimensions) == 0; if (!$draw_inputs) { $ts_ots = DimensionObjectTypeContents::getDimensionObjectTypesforObject(Timeslots::instance()->getObjectTypeId()); $context = active_context(); foreach ($context as $sel) { if ($sel instanceof Member) { foreach ($ts_ots as $ts_ot) { if ($sel->getDimensionId() == $ts_ot->getDimensionId() && $sel->getObjectTypeId() == $ts_ot->getDimensionObjectTypeId()) { $draw_inputs = true; break; } } if ($draw_inputs) { break; } } } } tpl_assign('draw_inputs', $draw_inputs); tpl_assign('selected_user', logged_user()->getId()); tpl_assign('timeslots', $timeslots); tpl_assign('tasks', $tasks); if (count($tasks) > 0) { tpl_assign('all_users', Contacts::getAllUsers()); } tpl_assign('users', $users); tpl_assign('start', $start); tpl_assign('limit', $limit); tpl_assign('total', $total); tpl_assign('companies', $companies); ajx_set_no_toolbar(true); }
/** * quick_add_multiple_files * Use this function to upload multiple files * @access public * @param null */ function quick_add_multiple_files() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $file_data = array_var($_POST, 'file'); $file = new ProjectFile(); tpl_assign('file', $file); tpl_assign('file_data', $file_data); tpl_assign('genid', array_var($_GET, 'genid')); tpl_assign('object_id', array_var($_GET, 'object_id')); tpl_assign('composing_mail', array_var($_GET, 'composing_mail')); if (is_array(array_var($_POST, 'file'))) { //$this->setLayout("html"); $upload_option = array_var($file_data, 'upload_option', -1); try { //members $member_ids = array(); $object_controller = new ObjectController(); if (count(active_context_members(false)) > 0) { $member_ids = active_context_members(false); } elseif (array_var($file_data, 'member_ids')) { $member_ids = explode(',', array_var($file_data, 'member_ids')); if (is_numeric($member_ids) && $member_ids > 0) { $member_ids = array($member_ids); } } elseif (array_var($file_data, 'object_id')) { $object = Objects::findObject(array_var($file_data, 'object_id')); if ($object instanceof ContentDataObject) { $member_ids = $object->getMemberIds(); } else { // add only to logged_user's person member } } else { // add only to logged_user's person member } $upload_id = array_var($file_data, 'upload_id'); $uploaded_file = array_var($_SESSION, $upload_id, array()); //files ids to return $file_ids = array(); if (isset($uploaded_file['name']) && is_array($uploaded_file['name'])) { foreach ($uploaded_file['name'] as $key => $file_name) { if (count($uploaded_file['name']) == 1 && array_var($file_data, 'name') != "" && array_var($file_data, 'name') != $file_name) { $file_name = array_var($file_data, 'name'); } $file_data_mult = $file_data; $file_data_mult['name'] = $file_name; $uploaded_file_mult['name'] = $file_name; $uploaded_file_mult['size'] = $uploaded_file['size'][$key]; $uploaded_file_mult['type'] = $uploaded_file['type'][$key]; $uploaded_file_mult['tmp_name'] = $uploaded_file['tmp_name'][$key]; $uploaded_file_mult['error'] = $uploaded_file['error'][$key]; if (count($uploaded_file['name']) != 1) { $upload_option = -1; } $file_ids[] = $this->add_file_from_multi($file_data_mult, $uploaded_file_mult, $member_ids, $upload_option); } } unset($_SESSION[$upload_id]); //data to return $files_data_to_return = array(); foreach ($file_ids as $file_id) { $file_to_ret = ProjectFiles::findById($file_id); if (!$file_to_ret instanceof ProjectFile) { continue; } $file_data = array(); $file_data["file_id"] = $file_to_ret->getId(); $file_data["file_name"] = $file_to_ret->getFilename(); $file_data["icocls"] = 'ico-file ico-' . str_replace(".", "_", str_replace("/", "-", $file_to_ret->getTypeString())); $files_data_to_return[] = $file_data; } ajx_extra_data(array("files_data" => $files_data_to_return)); ajx_current("empty"); } catch (Exception $e) { flash_error($e->getMessage()); ajx_current("empty"); } // try } // if }
static function getLastActivities() { $members = active_context_members(false); // Context Members Ids $options = explode(",", user_config_option("filters_dashboard", null, null, true)); $extra_conditions = "action <> 'login' AND action <> 'logout' AND action <> 'subscribe' AND created_by_id > '0'"; if ($options[1] == 0) { //do not show timeslots $extra_conditions .= "AND action <> 'open' AND action <> 'close' AND ((action <> 'add' OR action <> 'edit' OR action <> 'delete') AND object_name NOT LIKE 'Time%')"; } // task assignment conditions if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $extra_conditions .= " AND IF((SELECT o.object_type_id FROM " . TABLE_PREFIX . "objects o WHERE o.id=rel_object_id)=(SELECT ot.id FROM " . TABLE_PREFIX . "object_types ot WHERE ot.name='task'),\r\n\t\t\t\t(SELECT t.assigned_to_contact_id FROM " . TABLE_PREFIX . "project_tasks t WHERE t.object_id=rel_object_id) = " . logged_user()->getId() . ",\r\n\t\t\t\ttrue)"; } //do not display template tasks logs $extra_conditions .= " AND IF((SELECT o.object_type_id FROM " . TABLE_PREFIX . "objects o WHERE o.id=rel_object_id)=(SELECT ot.id FROM " . TABLE_PREFIX . "object_types ot WHERE ot.name='template_task'), false, true)"; // if logged user is guest dont show other users logs if (logged_user()->isGuest()) { $extra_conditions .= " AND `created_by_id`=" . logged_user()->getId(); } $members_sql = ""; $is_member_child = ""; if (count($members) > 0) { $members_sql = "(EXISTS(\r\n\t\t\t\tSELECT om.object_id FROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\tWHERE om.member_id IN (" . implode(',', $members) . ") AND rel_object_id = om.object_id\r\n\t\t\t\tGROUP BY object_id\r\n\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t))"; $is_member_child = "AND mem.parent_member_id IN (" . implode(',', $members) . ")"; } //permissions $logged_user_pgs = implode(',', logged_user()->getPermissionGroupIds()); $permissions_condition = "al.rel_object_id IN (\r\n\t\tSELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh\r\n\t\tWHERE al.rel_object_id = sh.object_id AND sh.object_id > 0\r\n\t\tAND sh.group_id IN ({$logged_user_pgs})\r\n\t\t)"; $sql = "SELECT al.id FROM " . TABLE_PREFIX . "application_logs al \r\n\t\t\t\tWHERE {$permissions_condition} AND {$extra_conditions}"; if ($members_sql != "") { $sql .= " AND {$members_sql}"; //do not display users logs $sql .= " AND NOT EXISTS(SELECT con.object_id FROM " . TABLE_PREFIX . "contacts con WHERE con.object_id=rel_object_id AND user_type > 0)"; } $sql .= " ORDER BY created_on DESC LIMIT 100"; $id_rows = array_flat(DB::executeAll($sql)); // if logged user is guest dont show other users logs $user_condition = ""; if (logged_user()->isGuest()) { $user_condition .= " AND `created_by_id`=" . logged_user()->getId(); } $member_logs_sql = "SELECT al.id FROM " . TABLE_PREFIX . "application_logs al\r\n\t\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members mem ON mem.id=al.member_id \r\n\t\t\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "contact_member_cache cmcache ON cmcache.member_id=mem.id AND cmcache.contact_id = " . logged_user()->getId() . "\r\n\t\t\t\t\t\t\t\t\t\t\tWHERE al.member_id>0\r\n\t\t\t\t\t\t\t\t\t\t\t{$user_condition}\r\n\t\t\t\t\t\t\t\t\t\t\t{$is_member_child}\r\n\t\t\t\t\t\t\tORDER BY created_on DESC LIMIT 100"; $m_id_rows = array_flat(DB::executeAll($member_logs_sql)); $id_rows = array_filter(array_merge($id_rows, $m_id_rows)); $logs = array(); if (count($id_rows) > 0) { $logs = ApplicationLogs::findAll(array("condition" => "id IN (" . implode(',', $id_rows) . ")", "order" => "created_on DESC")); } return $logs; }
} ?> <th id="ie_scrollbar_adjust" style="display:none;width:15px;padding:0px;margin:0px;"></th> </tr> <?php $date_start = new DateTimeValue($fd_ts); $date_start->advance(-24 * 3600 * $firstday); $ld_dow = date('w', $ld_ts); $date_end = new DateTimeValue($ld_ts); $date_end->advance(24 * 3600 * (6 - $ld_dow)); $milestones = ProjectMilestones::getRangeMilestones($date_start, $date_end); if ($task_filter != "hide") { $tasks = ProjectTasks::getRangeTasksByUser($date_start, $date_end, $user_filter != -1 ? $user : null, $task_filter); } if (user_config_option('show_birthdays_in_calendar')) { $birthdays = Contacts::instance()->getRangeContactsByBirthday($date_start, $date_end, active_context_members(false)); } else { $birthdays = array(); } $result = array(); if ($milestones) { $result = array_merge($result, $milestones); } if (isset($tasks)) { foreach ($tasks as $task) { $result = array_merge($result, replicateRepetitiveTaskForCalendar($task, $date_start, $date_end)); } } if (is_array($birthdays) && count($birthdays) > 0) { $result = array_merge($result, $birthdays); }
/** * @author Ignacio Vazquez elpepe.uy at gmail.com * Fermormance FIX: getContentObjects replacement * @param array $args * order = null - may be performance killer depending on the order criteria * order_dir = null * extra_conditions = null : extra sql 'inyection' - may be performance killer depending on the injected query * join_params = null : extra join table * trashed = false * archived = false * start = 0 * limit = null * ignore_context * include_deleted * count_results : if true calc found rows else show 'many' * extra_member_ids : Search also objects in this slist of members * member_ids : force to search objects in this list of members (strinct) * */ public function listing($args = array()) { if ( defined('DEBUG_TIME') && DEBUG_TIME ) { $start_time = microtime(1); } $result = new stdClass ; $result->objects =array(); $result->total =array(); $type_id = self::getObjectTypeId(); $SQL_BASE_JOIN = ''; $SQL_EXTRA_JOINS = ''; $SQL_TYPE_CONDITION = 'true'; if (isset($args['count_results'])) { $count_results = $args['count_results']; } else { $count_results = !( defined('INFINITE_PAGING') && INFINITE_PAGING ); } $return_raw_data = array_var($args,'raw_data'); $start = array_var($args,'start'); $limit = array_var($args,'limit'); $member_ids = array_var($args, 'member_ids'); $extra_member_ids = array_var($args,'extra_member_ids'); $ignore_context = array_var($args,'ignore_context'); $include_deleted = (bool) array_var($args,'include_deleted'); $select_columns = array_var($args, 'select_columns', array('*')); if ($count_results) { $SQL_FOUND_ROWS = "SQL_CALC_FOUND_ROWS"; }else{ $SQL_FOUND_ROWS = ""; } $handler_class = "Objects"; if ($type_id){ // If isset type, is a concrete instance linsting. Otherwise is a generic listing of objects $type = ObjectTypes::findById($type_id); /* @var $object_type ObjectType */ $handler_class = $type->getHandlerClass(); $table_name = self::getTableName(); // Extra Join statements if ($this instanceof ContentDataObjects && $this->object_type_name == 'timeslot') { // if object is a timeslot and is related to a content object => check for members of the related content object. $SQL_BASE_JOIN = " INNER JOIN $table_name e ON IF(e.rel_object_id > 0, e.rel_object_id, e.object_id) = o.id "; $SQL_TYPE_CONDITION = "object_type_id = IF(e.rel_object_id > 0, (SELECT z.object_type_id FROM ".TABLE_PREFIX."objects z WHERE z.id = e.rel_object_id), $type_id)"; } else { $SQL_BASE_JOIN = " INNER JOIN $table_name e ON e.object_id = o.id "; $SQL_TYPE_CONDITION = "o.object_type_id = $type_id"; } $SQL_EXTRA_JOINS = self::prepareJoinConditions(array_var($args,'join_params')); } if (!$ignore_context && !$member_ids) { $members = active_context_members(false); // Context Members Ids } elseif ( count($member_ids) ) { $members = $member_ids; } if (is_array($extra_member_ids)) { if (isset($members)) { $members = array_merge($members, $extra_member_ids); } else { $members = $extra_member_ids; } } $uid = logged_user()->getId() ; // Order statement $SQL_ORDER = self::prepareOrderConditions(array_var($args,'order'), array_var($args,'order_dir')); // Prepare Limit SQL if (is_numeric(array_var($args,'limit')) && is_numeric(array_var($args,'start')) && array_var($args,'limit')>0){ $SQL_LIMIT = "LIMIT ".array_var($args,'start',0)." , ".array_var($args,'limit'); }else{ $SQL_LIMIT = '' ; } $SQL_CONTEXT_CONDITION = " true "; if (!empty($members) && count($members)) { $object_ids = array (); $members_sql = " SELECT object_id FROM " . TABLE_PREFIX . "object_members om WHERE member_id IN (" . implode ( ',', $members ) . ") GROUP BY object_id HAVING count(member_id) = ".count($members); $db_result = DB::execute ( $members_sql ); $rows = $db_result->fetchAll(); if (is_array($rows)){ foreach ( $rows as $row ) { $object_ids [$row ['object_id']] = $row ['object_id']; } } if (count( $object_ids )) { $object_ids = implode ( ",", $object_ids ); $SQL_CONTEXT_CONDITION = "o.id IN ($object_ids)"; }else{ $SQL_CONTEXT_CONDITION = ' false ' ; } } // Trash && Archived CONDITIONS $trashed_archived_conditions = self::prepareTrashandArchivedConditions(array_var($args,'trashed'), array_var($args,'archived')); $SQL_TRASHED_CONDITION = ($include_deleted) ? ' TRUE ' : $trashed_archived_conditions[0]; $SQL_ARCHIVED_CONDITION =($include_deleted) ? ' AND TRUE ' : $trashed_archived_conditions[1]; // Extra CONDITIONS if (array_var($args,'extra_conditions')) { $SQL_EXTRA_CONDITIONS = array_var($args,'extra_conditions') ; }else{ $SQL_EXTRA_CONDITIONS = ''; } $SQL_COLUMNS = implode(',', $select_columns); // Build Main SQL $sql = " SELECT $SQL_FOUND_ROWS $SQL_COLUMNS FROM ".TABLE_PREFIX."objects o $SQL_BASE_JOIN $SQL_EXTRA_JOINS WHERE o.id IN ( SELECT object_id FROM ".TABLE_PREFIX."sharing_table WHERE group_id IN ( SELECT permission_group_id FROM ".TABLE_PREFIX."contact_permission_groups WHERE contact_id = $uid ) ) AND $SQL_CONTEXT_CONDITION AND $SQL_TYPE_CONDITION AND $SQL_TRASHED_CONDITION $SQL_ARCHIVED_CONDITION $SQL_EXTRA_CONDITIONS $SQL_ORDER $SQL_LIMIT"; // Execute query and build the resultset $rows = DB::executeAll($sql); if ($return_raw_data) { $result->objects = $rows; } else { if($rows && is_array($rows)) { foreach ($rows as $row) { if ($handler_class) { $phpCode = '$co = '.$handler_class.'::instance()->loadFromRow($row);'; eval($phpCode); } if ( $co ) { $result->objects[] = $co ; } } } } if ($count_results) { $total = DB::executeOne("SELECT FOUND_ROWS() as total"); $result->total = $total['total']; }else{ if ( count($result->objects) == $limit ) { $result->total = 10000000; }else{ $result->total = $start + count($result->objects) ; } } if ( defined('DEBUG_TIME') && DEBUG_TIME ) { Logger::log("Query time: ". (microtime(1) - $start_time) ) ; } return $result; }
function quick_add_files() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $file_data = array_var($_POST, 'file'); $file = new ProjectFile(); tpl_assign('file', $file); tpl_assign('file_data', $file_data); tpl_assign('genid', array_var($_GET, 'genid')); tpl_assign('object_id', array_var($_GET, 'object_id')); if (is_array(array_var($_POST, 'file'))) { //$this->setLayout("html"); $upload_option = array_var($file_data, 'upload_option'); try { DB::beginWork(); $type = array_var($file_data, 'type'); $file->setType($type); $file->setFilename(array_var($file_data, 'name')); $file->setFromAttributes($file_data); $file->setIsVisible(true); $file->save(); $file->subscribeUser(logged_user()); if($file->getType() == ProjectFiles::TYPE_DOCUMENT){ // handle uploaded file $upload_id = array_var($file_data, 'upload_id'); $uploaded_file = array_var($_SESSION, $upload_id, array()); $revision = $file->handleUploadedFile($uploaded_file, true); // handle uploaded file @unlink($uploaded_file['tmp_name']); unset($_SESSION[$upload_id]); } else if ($file->getType() == ProjectFiles::TYPE_WEBLINK) { $url = array_var($file_data, 'url', ''); if ($url && strpos($url, ':') === false) { $url = $this->protocol . $url; $file->setUrl($url); $file->save(); } $revision = new ProjectFileRevision(); $revision->setFileId($file->getId()); $revision->setRevisionNumber($file->getNextRevisionNumber()); $revision->setFileTypeId(FileTypes::getByExtension('webfile')->getId()); $revision->setTypeString($file->getUrl()); $revision->setRepositoryId('webfile'); $revision_comment = array_var($file_data, 'revision_comment', lang('initial versions')); $revision->setComment($revision_comment); $revision->save(); } $member_ids = array(); $object_controller = new ObjectController(); if(count(active_context_members(false)) > 0 ){ $object_controller->add_to_members($file, active_context_members(false)); }elseif(array_var($file_data, 'object_id')){ $object = Objects::findObject(array_var($file_data, 'object_id')); if ($object instanceof ContentDataObject) { $member_ids = $object->getMemberIds(); $object_controller->add_to_members($file, $member_ids); } else { // add only to logged_user's person member $object_controller->add_to_members($file, array()); } } else { // add only to logged_user's person member $object_controller->add_to_members($file, array()); } DB::commit(); ajx_extra_data(array("file_id" => $file->getId())); ajx_extra_data(array("file_name" => $file->getFilename())); ajx_extra_data(array("icocls" => 'ico-file ico-' . str_replace(".", "_", str_replace("/", "-", $file->getTypeString())))); if (!array_var($_POST, 'no_msg')) { flash_success(lang('success add file', $file->getFilename())); } ajx_current("empty"); } catch(Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); // If we uploaded the file remove it from repository if(isset($revision) && ($revision instanceof ProjectFileRevision) && FileRepository::isInRepository($revision->getRepositoryId())) { FileRepository::deleteFile($revision->getRepositoryId()); } // if } // try } // if } // quick_add_files
private function getActiveContextConditions($include_and = true) { $members = active_context_members(false); $context_condition = ""; if (count($members) > 0) { $context_condition = ($include_and ? " AND" : "") . " (EXISTS\r\n\t\t\t\t(SELECT om.object_id\r\n\t\t\t\t\tFROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\tWHERE\tom.member_id IN (" . implode(',', $members) . ") AND e.object_id = om.object_id\r\n\t\t\t\t\tGROUP BY object_id\r\n\t\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t\t)\r\n\t\t\t)"; } return $context_condition; }
$not_overdue_limit = 5; $overdue_limit = 20; $show_more = false; // Not due tasks $not_due_tasks = ProjectTasks::getUpcomingWithoutDate($not_overdue_limit + 1); if (count($not_due_tasks) > $not_overdue_limit) { $show_more = true; array_pop($not_due_tasks); } // Due Tasks $overdue_upcoming_objects = ProjectTasks::getOverdueAndUpcomingObjects($overdue_limit + 1); // FIXME: performance Killer if (count($overdue_upcoming_objects) > $overdue_limit) { $show_more = true; array_pop($overdue_upcoming_objects); } $overdue_upcoming_objects = array_merge($not_due_tasks, $overdue_upcoming_objects); $users = array(); // Render only when the context isnt 'all' and you have perms $render_add = active_context_members(false) && ProjectTask::canAdd(logged_user(), active_context()); if ($render_add) { $users[] = array(0, lang('dont assign')); foreach (allowed_users_to_assign() as $company) { foreach ($company['users'] as $user) { $name = logged_user()->getId() == $user['id'] ? lang('me') : $user['name']; $users[] = array($user['id'], $name); } } } include_once 'template.php';
static function getLastActivities() { $members = active_context_members(false); // Context Members Ids $options = explode(",",user_config_option("filters_dashboard",null,null,true)); $extra_conditions = "action <> 'login' AND action <> 'logout' AND action <> 'subscribe' "; if($options[1] == 0){//do not show timeslots $extra_conditions .= "AND action <> 'open' AND action <> 'close' AND ((action <> 'add' OR action <> 'edit' OR action <> 'delete') AND object_name NOT LIKE 'Time%')"; } // task assignment conditions if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { $extra_conditions .= " AND IF((SELECT o.object_type_id FROM ".TABLE_PREFIX."objects o WHERE o.id=rel_object_id)=(SELECT ot.id FROM ".TABLE_PREFIX."object_types ot WHERE ot.name='task'), (SELECT t.assigned_to_contact_id FROM ".TABLE_PREFIX."project_tasks t WHERE t.object_id=rel_object_id) = ".logged_user()->getId().", true)"; } $members_sql = ""; if(count($members) > 0){ $object_ids_rows = DB::executeAll("SELECT object_id FROM " . TABLE_PREFIX . "object_members om WHERE member_id IN (" . implode ( ',', $members ) . ") GROUP BY object_id HAVING count(member_id) = ".count($members).""); $object_ids = implode(',', array_flat($object_ids_rows)); if ($object_ids == "") $object_ids = "0"; $members_sql = "rel_object_id IN ($object_ids)"; } $permissions_sql = "AND rel_object_id IN ( SELECT object_id FROM ".TABLE_PREFIX."sharing_table WHERE group_id IN (SELECT permission_group_id FROM ".TABLE_PREFIX."contact_permission_groups WHERE contact_id = ".logged_user()->getId().") )"; $condition = ($members_sql != "" ? $members_sql . " AND " : "") . $extra_conditions . $permissions_sql; return ApplicationLogs::findAll(array( "condition" => $condition, "order" => "created_on DESC", "limit" => "100" )); }
/** * Same that getContentObjects but reading from sahring table * @deprecated by parent::listing() **/ static function findByContext( $options = array () ) { // Initialize method result $result = new stdClass(); $result->total = 0 ; $result->objects = array() ; // Read arguments and Init Vars $limit = array_var($options,'limit'); $members = active_context_members(false); // 70 $type_id = self::instance()->getObjectTypeId(); if (!count($members)) return $res ; $uid = logged_user()->getId() ; if ($limit>0){ $limit_sql = "LIMIT $limit"; }else{ $limit_sql = '' ; } // Build Main SQL $sql = " SELECT distinct(id) FROM ".TABLE_PREFIX."objects WHERE id IN ( SELECT object_id FROM ".TABLE_PREFIX."sharing_table WHERE group_id IN ( SELECT permission_group_id FROM ".TABLE_PREFIX."contact_permission_groups WHERE contact_id = $uid ) ) AND id IN ( SELECT object_id FROM ".TABLE_PREFIX."object_members WHERE member_id IN (".implode(',', $members).") GROUP BY object_id HAVING count(member_id) = ".count($members)." ) AND object_type_id = $type_id AND ".SQL_NOT_DELETED." $limit_sql"; // Execute query and build the resultset $rows = DB::executeAll($sql); foreach ($rows as $row) { $task = ProjectTasks::findById($row['id']); if ( ( $task && $task instanceof ProjectTask ) && !$task->isTemplate() ) { if($task->getDueDate()){ $k = "#".$task->getDueDate()->getTimestamp().$task->getId(); $result->objects[$k] = $task ; }else{ $result->objects[] = $task ; } $result->total++; } } // Sort by key ksort($result->objects); // Remove keys $result->objects = array_values($result->objects); return $result; }
function render_member_selectors($content_object_type_id, $genid = null, $selected_member_ids = null, $options = array(), $skipped_dimensions = null, $simulate_required = null) { if (is_numeric($content_object_type_id)) { if (is_null($genid)) $genid = gen_id(); $user_dimensions = get_user_dimensions_ids(); // User allowed dimensions $dimensions = array(); // Diemsions for this content type if ( $all_dimensions = Dimensions::getAllowedDimensions($content_object_type_id) ) { foreach ($all_dimensions as $dimension){ if ( isset($user_dimensions[$dimension['dimension_id']] ) ){ if( $dimension_options = json_decode($dimension['dimension_options'])){ if (isset($dimension_options->useLangs) && $dimension_options->useLangs ) { $dimension['dimension_name'] = lang($dimension['dimension_code']); } } $dimensions[] = $dimension; } } } if ($dimensions != null && count($dimensions)) { if (is_null($selected_member_ids) && array_var($options, 'select_current_context')) { $context = active_context(); $selected_member_ids = array(); foreach ($context as $selection) { if ($selection instanceof Member) $selected_member_ids[] = $selection->getId(); } } 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"; $object_is_new = is_null($selected_members); $listeners = array_var($options, 'listeners', array()); $allowed_member_type_ids = array_var($options, 'allowedMemberTypes', null); $initial_selected_members = $selected_members; if (count($initial_selected_members) == 0) { $selected_context_member_ids = active_context_members(false); if (count($selected_context_member_ids) > 0) { $initial_selected_members = Members::findAll(array('conditions' => 'id IN ('.implode(',', $selected_context_member_ids).')')); } } $tmp = array(); foreach ($initial_selected_members as $ism) { if ($ism->getDimension()->getIsManageable()) $tmp[] = $ism; } $initial_selected_members = $tmp; // Render view include get_template_path("components/multiple_dimension_selector", "dimension"); } } }
/** * Fermormance FIX: getContentObjects replacement * @param array $args * order = null - may be performance killer depending on the order criteria * order_dir = null * extra_conditions = null : extra sql 'inyection' - may be performance killer depending on the injected query * join_params = null : extra join table * trashed = false * archived = false * start = 0 * limit = null * ignore_context * include_deleted * count_results : if true calc found rows else show 'many' * extra_member_ids : Search also objects in this slist of members * member_ids : force to search objects in this list of members (strinct) * */ public function listing($args = array()) { $result = new stdClass(); $result->objects = array(); $result->total = array(); $type_id = self::getObjectTypeId(); $SQL_BASE_JOIN = ''; $SQL_EXTRA_JOINS = ''; $SQL_TYPE_CONDITION = 'true'; $SQL_FOUND_ROWS = ''; if (isset($args['count_results'])) { $count_results = $args['count_results']; } else { $count_results = defined('INFINITE_PAGING') ? !INFINITE_PAGING : false; } //get only the number of results without limit not data if (isset($args['only_count_results'])) { $only_count_results = $args['only_count_results']; } else { $only_count_results = false; } $return_raw_data = array_var($args, 'raw_data'); $start = array_var($args, 'start'); $limit = array_var($args, 'limit'); $member_ids = array_var($args, 'member_ids'); $extra_member_ids = array_var($args, 'extra_member_ids'); $ignore_context = array_var($args, 'ignore_context'); $include_deleted = (bool) array_var($args, 'include_deleted'); $select_columns = array_var($args, 'select_columns'); if (empty($select_columns)) { $select_columns = array('*'); } //template objects $template_objects = (bool) array_var($args, 'template_objects', false); $handler_class = "Objects"; if ($type_id) { // If isset type, is a concrete instance linsting. Otherwise is a generic listing of objects $type = ObjectTypes::findById($type_id); /* @var $object_type ObjectType */ $handler_class = $type->getHandlerClass(); $table_name = self::getTableName(); // Extra Join statements if ($this instanceof ContentDataObjects && $this->object_type_name == 'timeslot') { // if object is a timeslot and is related to a content object => check for members of the related content object. $SQL_BASE_JOIN = " INNER JOIN {$table_name} e ON IF(e.rel_object_id > 0, e.rel_object_id, e.object_id) = o.id "; $SQL_TYPE_CONDITION = "o.object_type_id = IF(e.rel_object_id > 0, (SELECT z.object_type_id FROM " . TABLE_PREFIX . "objects z WHERE z.id = e.rel_object_id), {$type_id})"; } else { $SQL_BASE_JOIN = " INNER JOIN {$table_name} e ON e.object_id = o.id "; $SQL_TYPE_CONDITION = "o.object_type_id = {$type_id}"; } $SQL_EXTRA_JOINS = self::prepareJoinConditions(array_var($args, 'join_params')); } if (!$ignore_context && !$member_ids) { $members = active_context_members(false); // Context Members Ids } elseif (count($member_ids)) { $members = $member_ids; } if (is_array($extra_member_ids)) { if (isset($members)) { $members = array_merge($members, $extra_member_ids); } else { $members = $extra_member_ids; } } // Order statement $SQL_ORDER = self::prepareOrderConditions(array_var($args, 'order'), array_var($args, 'order_dir')); // Prepare Limit SQL if (is_numeric(array_var($args, 'limit')) && array_var($args, 'limit') > 0) { $SQL_LIMIT = "LIMIT " . array_var($args, 'start', 0) . " , " . array_var($args, 'limit'); } else { $SQL_LIMIT = ''; } // Prepare Group By SQL $group_by = array_var($args,'group_by'); if (array_var($args, 'group_by')) { $SQL_GROUP_BY = "GROUP BY " . array_var($args, 'group_by'); } else { $SQL_GROUP_BY = ''; } $SQL_CONTEXT_CONDITION = " true "; //show only objects that are on this members by classification not by hierarchy $show_only_member_objects = array_var($args, 'show_only_member_objects', false); $exclusive_in_member = ''; if ($show_only_member_objects) { $exclusive_in_member = " AND om.`is_optimization` = 0"; } if (!empty($members) && count($members)) { $SQL_CONTEXT_CONDITION = "(EXISTS (SELECT om.object_id\r\n\t\t\t\t\tFROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\tWHERE\tom.member_id IN (" . implode(',', $members) . ") AND o.id = om.object_id {$exclusive_in_member}\r\n\t\t\t\t\tGROUP BY object_id\r\n\t\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t))"; } else { //show only objects that are on root if ($show_only_member_objects) { if (is_array(active_context())) { $active_dims_ids = array(); foreach (active_context() as $ctx) { if ($ctx instanceof Dimension) { $active_dims_ids[] = $ctx->getId(); } } if (count($active_dims_ids) > 0) { $SQL_CONTEXT_CONDITION = "(NOT EXISTS (SELECT om.object_id\r\n\t\t\t\t\t\t\tFROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members mem ON mem.id = om.member_id AND mem.dimension_id IN (" . implode(",", $active_dims_ids) . ")\r\n\t\t\t\t\t\t\tWHERE\to.id = om.object_id\r\n\t\t\t\t\t\t\t))"; } } } } // Trash && Archived CONDITIONS $trashed_archived_conditions = self::prepareTrashandArchivedConditions(array_var($args, 'trashed'), array_var($args, 'archived')); $SQL_TRASHED_CONDITION = $include_deleted ? ' TRUE ' : $trashed_archived_conditions[0]; $SQL_ARCHIVED_CONDITION = $include_deleted ? ' AND TRUE ' : $trashed_archived_conditions[1]; // Extra CONDITIONS if (array_var($args, 'extra_conditions')) { $SQL_EXTRA_CONDITIONS = array_var($args, 'extra_conditions'); } else { $SQL_EXTRA_CONDITIONS = ''; } $SQL_COLUMNS = implode(',', $select_columns); if (logged_user() instanceof Contact) { $uid = logged_user()->getId(); // Build Main SQL $logged_user_pgs = implode(',', logged_user()->getPermissionGroupIds()); $permissions_condition = "o.id IN (\r\n\t\t\t\t\tSELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh\r\n\t\t\t\t\tWHERE o.id = sh.object_id\r\n\t\t\t\t\tAND sh.group_id IN ({$logged_user_pgs})\r\n\t\t\t)"; /* * Check that the objects to list does not belong only to a non-manageable dimension that defines permissions * Object can be shown if: * 1 - It belongs to at least a member in a dimension that defines permissions and is manageable * 2 - Or it belongs to at least a member in a dimension that does not defines permissions * 3 - Or user has permissions to read objects without classification */ if (!$type instanceof ObjectType || !$type->getName() == 'mail') { $without_perm_dim_ids = Dimensions::findAll(array('id' => true, 'conditions' => "defines_permissions=0")); $no_perm_dims_cond = ""; if (count($without_perm_dim_ids) > 0) { $no_perm_dims_cond = " OR EXISTS (\r\n\t\t\t\t\tselect * from " . TABLE_PREFIX . "object_members omems\r\n\t\t\t\t\t inner join " . TABLE_PREFIX . "members mems on mems.id = omems.member_id\r\n\t\t\t\t\t WHERE omems.object_id=o.id AND mems.dimension_id IN (" . implode(',', $without_perm_dim_ids) . ")\r\n\t\t\t\t)"; } $permissions_condition .= " AND (\r\n\t\t\t\tEXISTS (\r\n\t\t\t\t\tSELECT cmp.permission_group_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp \r\n\t\t\t\t\tWHERE cmp.member_id=0 AND cmp.permission_group_id=" . logged_user()->getPermissionGroupId() . " AND cmp.object_type_id = o.object_type_id\r\n\t\t\t\t)\r\n\t\t\t\tOR\r\n\t\t\t\tEXISTS (\r\n\t\t\t\t\tselect * from " . TABLE_PREFIX . "object_members omems\r\n\t\t\t\t\t\tinner join " . TABLE_PREFIX . "members mems on mems.id = omems.member_id\r\n\t\t\t\t\t\tinner join " . TABLE_PREFIX . "dimensions dims on dims.id = mems.dimension_id\r\n\t\t\t\t\tWHERE omems.object_id=o.id and dims.defines_permissions=1 and dims.is_manageable=1\r\n\t\t\t\t) {$no_perm_dims_cond}\r\n\t\t\t)"; } /********************************************************************************************************/ if (!$this instanceof MailContents && logged_user()->isAdministrator() || $this instanceof Contacts && $this->object_type_name == 'contact' && can_manage_contacts(logged_user())) { $permissions_condition = "true"; } if ($this instanceof ProjectFiles && logged_user()->isAdministrator() && Plugins::instance()->isActivePlugin('mail')) { $permissions_condition = "IF(e.mail_id > 0,\r\n\t\t\t\t\t e.mail_id IN (\r\n\t\t\t\t\t\t\t\t\t\tSELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh\r\n\t\t\t\t\t\t\t\t\t\tWHERE e.mail_id = sh.object_id\r\n\t\t\t\t\t\t\t\t\t\tAND sh.group_id IN ({$logged_user_pgs})\r\n\t\t\t\t\t ),\r\n\t\t\t\t\t true\r\n\t\t\t\t\t)"; } if ($template_objects) { $permissions_condition = "true"; $SQL_BASE_JOIN .= " INNER JOIN " . TABLE_PREFIX . "template_tasks temob ON temob.object_id = o.id "; } $sql = "\r\n\t\t\t\tSELECT {$SQL_FOUND_ROWS} {$SQL_COLUMNS} FROM " . TABLE_PREFIX . "objects o\r\n\t\t\t\t{$SQL_BASE_JOIN}\r\n\t\t\t\t{$SQL_EXTRA_JOINS}\r\n\t\t\t\tWHERE\r\n\t\t\t\t\t{$permissions_condition}\r\n\t\t\t\t\tAND\t{$SQL_CONTEXT_CONDITION}\r\n\t\t\t\t\tAND {$SQL_TYPE_CONDITION}\r\n\t\t\t\t\tAND {$SQL_TRASHED_CONDITION} {$SQL_ARCHIVED_CONDITION} {$SQL_EXTRA_CONDITIONS}\r\n\t\t\t\t{$SQL_GROUP_BY}\r\n\t\t\t\t{$SQL_ORDER}\r\n\t\t\t\t{$SQL_LIMIT}"; if (isset($args['query_wraper_start'])) { $query_wraper_start = $args['query_wraper_start']; $query_wraper_end = $args['query_wraper_end']; $sql = $query_wraper_start . $sql . $query_wraper_end; } $sql_total = "\r\n\t\t\t\tSELECT count(o.id) as total FROM " . TABLE_PREFIX . "objects o\r\n\t\t\t\t{$SQL_BASE_JOIN}\r\n\t\t\t\t{$SQL_EXTRA_JOINS}\r\n\t\t\t\tWHERE\r\n\t\t\t\t\t{$permissions_condition}\r\n\t\t\t\t\tAND\t{$SQL_CONTEXT_CONDITION}\r\n\t\t\t\t\tAND {$SQL_TYPE_CONDITION}\r\n\t\t\t\t\tAND {$SQL_TRASHED_CONDITION} {$SQL_ARCHIVED_CONDITION} {$SQL_EXTRA_CONDITIONS}\r\n\t\t\t\t{$SQL_GROUP_BY}\t\t\t\r\n\t\t\t"; if (!$only_count_results) { // Execute query and build the resultset $rows = DB::executeAll($sql); if ($return_raw_data) { $result->objects = $rows; } else { if ($rows && is_array($rows)) { foreach ($rows as $row) { if ($handler_class) { $phpCode = '$co = ' . $handler_class . '::instance()->loadFromRow($row);'; eval($phpCode); } if ($co) { $result->objects[] = $co; } } } } if ($count_results) { $total = DB::executeOne($sql_total); $result->total = $total['total']; } else { if (count($result->objects) >= $limit) { $result->total = 10000000; } else { $result->total = $start + count($result->objects); } } } else { $total = DB::executeOne($sql_total); $result->total = $total['total']; } } else { $result->objects = array(); $result->total = 0; } return $result; }
if ($end_time instanceof DateTimeValue) $end_time->advance(-3600*logged_user()->getTimezone(), true); } if ($start_time instanceof DateTimeValue) { ?> <span class="bold"><?php echo lang('from')?></span>: <?php echo $start_time->format($date_format) ?> <?php } if ($end_time instanceof DateTimeValue) { ?> <span class="bold" style="padding-left:10px"><?php echo lang('to date')?></span>: <?php echo $end_time->format($date_format) ?> <?php } ?> <?php if ($user instanceof Contact) { ?> <br /> <span class="bold"><?php echo lang('reporting user')?></span>: <?php echo clean($user->getObjectName()); ?> <?php } ?> <?php if (count(active_context_members(false)) > 0) : ?> <div class="clear"></div> <div style="margin-bottom: 10px; padding-bottom: 5px; float:left;"> <h5><?php echo lang('showing information for')?>:</h5> <ul> <?php $context = active_context(); foreach ($context as $selection) : if ($selection instanceof Member) : ?> <li><span class="coViewAction <?php echo $selection->getIconClass()?>"><?php echo $selection->getName()?></span></li> <?php endif; endforeach; ?> </ul> </div> <div class="clear"></div>
function import_from_csv_file() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } @set_time_limit(0); ini_set('auto_detect_line_endings', '1'); if (isset($_GET['from_menu']) && $_GET['from_menu'] == 1) unset($_SESSION['history_back']); if (isset($_SESSION['history_back'])) { unset($_SESSION['history_back']); ajx_current("start"); } else { if(!Contact::canAdd(logged_user(), active_context())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $this->setTemplate('csv_import'); $type = array_var($_GET, 'type', array_var($_SESSION, 'import_type', 'contact')); //type of import (contact - company) if (!isset($_SESSION['import_type']) || ($type != $_SESSION['import_type'] && $type != '')) $_SESSION['import_type'] = $type; tpl_assign('import_type', $type); $filedata = array_var($_FILES, 'csv_file'); if (is_array($filedata) && !is_array(array_var($_POST, 'select_contact'))) { $filename = $filedata['tmp_name'].'.csv'; copy($filedata['tmp_name'], $filename); $first_record_has_names = array_var($_POST, 'first_record_has_names', false); $delimiter = array_var($_POST, 'delimiter', ''); if ($delimiter == '') $delimiter = $this->searchForDelimiter($filename); $_SESSION['delimiter'] = $delimiter; $_SESSION['csv_import_filename'] = $filename; $_SESSION['first_record_has_names'] = $first_record_has_names; $titles = $this->read_csv_file($filename, $delimiter, true); tpl_assign('titles', $titles); } if (array_var($_GET, 'calling_back', false)) { $filename = $_SESSION['csv_import_filename']; $delimiter = $_SESSION['delimiter']; $first_record_has_names = $_SESSION['first_record_has_names']; $titles = $this->read_csv_file($filename, $delimiter, true); unset($_GET['calling_back']); tpl_assign('titles', $titles); } if (is_array(array_var($_POST, 'select_contact')) || is_array(array_var($_POST, 'select_company'))) { $type = $_SESSION['import_type']; $filename = $_SESSION['csv_import_filename']; $delimiter = $_SESSION['delimiter']; $first_record_has_names = $_SESSION['first_record_has_names']; $registers = $this->read_csv_file($filename, $delimiter); $import_result = array('import_ok' => array(), 'import_fail' => array()); $i = $first_record_has_names ? 1 : 0; $object_controller = new ObjectController(); while ($i < count($registers)) { try { DB::beginWork(); if ($type == 'contact') { $contact_data = $this->buildContactData(array_var($_POST, 'select_contact'), array_var($_POST, 'check_contact'), $registers[$i]); $contact_data['import_status'] = '('.lang('updated').')'; $fname = DB::escape(array_var($contact_data, "first_name")); $lname = DB::escape(array_var($contact_data, "surname")); $email_cond = array_var($contact_data, "email") != '' ? " OR email_address = '".array_var($contact_data, "email")."'" : ""; $contact = Contacts::findOne(array( "conditions" => "first_name = ".$fname." AND surname = ".$lname." $email_cond", 'join' => array( 'table' => ContactEmails::instance()->getTableName(), 'jt_field' => 'contact_id', 'e_field' => 'object_id', ))); $log_action = ApplicationLogs::ACTION_EDIT; if (!$contact) { $contact = new Contact(); $contact_data['import_status'] = '('.lang('new').')'; $log_action = ApplicationLogs::ACTION_ADD; $can_import = $contact->canAdd(logged_user(), active_context()); } else { $can_import = $contact->canEdit(logged_user()); } if ($can_import) { $comp_name = DB::escape(array_var($contact_data, "company_id")); if ($comp_name != '') { $company = Contacts::findOne(array("conditions" => "first_name = $comp_name AND is_company = 1")); if ($company) { $contact_data['company_id'] = $company->getId(); } $contact_data['import_status'] .= " " . lang("company") . " $comp_name"; } else { $contact_data['company_id'] = 0; } $contact_data['birthday'] = $contact_data["o_birthday"]; $contact_data['name'] = $contact_data['first_name']." ".$contact_data['surname']; $contact->setFromAttributes($contact_data); $contact->save(); //Home form if($contact_data['h_address'] != ""){ $contact->addAddress($contact_data['h_address'], $contact_data['h_city'], $contact_data['h_state'], $contact_data['h_country'], $contact_data['h_zipcode'], 'home'); } if($contact_data['h_phone_number'] != "") $contact->addPhone($contact_data['h_phone_number'], 'home', true); if($contact_data['h_phone_number2'] != "") $contact->addPhone($contact_data['h_phone_number2'], 'home'); if($contact_data['h_mobile_number'] != "") $contact->addPhone($contact_data['h_mobile_number'], 'mobile'); if($contact_data['h_fax_number'] != "") $contact->addPhone($contact_data['h_fax_number'], 'fax'); if($contact_data['h_pager_number'] != "") $contact->addPhone($contact_data['h_pager_number'], 'pager'); if($contact_data['h_web_page'] != "") $contact->addWebpage($contact_data['h_web_page'], 'personal'); //Work form if($contact_data['w_address'] != ""){ $contact->addAddress($contact_data['w_address'], $contact_data['w_city'], $contact_data['w_state'], $contact_data['w_country'], $contact_data['w_zipcode'], 'work'); } if($contact_data['w_phone_number'] != "") $contact->addPhone($contact_data['w_phone_number'], 'work', true); if($contact_data['w_phone_number2'] != "") $contact->addPhone($contact_data['w_phone_number2'], 'work'); if($contact_data['w_assistant_number'] != "") $contact->addPhone($contact_data['w_assistant_number'], 'assistant'); if($contact_data['w_callback_number'] != "") $contact->addPhone($contact_data['w_callback_number'], 'callback'); if($contact_data['w_fax_number'] != "") $contact->addPhone($contact_data['w_fax_number'], 'fax', true); if($contact_data['w_web_page'] != "") $contact->addWebpage($contact_data['w_web_page'], 'work'); //Other form if($contact_data['o_address'] != ""){ $contact->addAddress($contact_data['o_address'], $contact_data['o_city'], $contact_data['o_state'], $contact_data['o_country'], $contact_data['o_zipcode'], 'other'); } if($contact_data['o_phone_number'] != "") $contact->addPhone($contact_data['o_phone_number'], 'other', true); if($contact_data['o_phone_number2'] != "") $contact->addPhone($contact_data['o_phone_number2'], 'other'); if($contact_data['o_web_page'] != "") $contact->addWebpage($contact_data['o_web_page'], 'other'); //Emails and instant messaging form if($contact_data['email'] != "") $contact->addEmail($contact_data['email'], 'personal', true); if($contact_data['email2'] != "") $contact->addEmail($contact_data['email2'], 'personal'); if($contact_data['email3'] != "") $contact->addEmail($contact_data['email3'], 'personal'); if(count(active_context_members(false)) > 0 ){ $object_controller->add_to_members($contact, active_context_members(false)); } ApplicationLogs::createLog($contact, null, $log_action); $import_result['import_ok'][] = $contact_data; } else { throw new Exception(lang('no access permissions')); } }else if ($type == 'company') { $contact_data = $this->buildCompanyData(array_var($_POST, 'select_company'), array_var($_POST, 'check_company'), $registers[$i]); $contact_data['import_status'] = '('.lang('updated').')'; $comp_name = DB::escape(array_var($contact_data, "first_name")); $company = Contacts::findOne(array("conditions" => "first_name = $comp_name AND is_company = 1")); $log_action = ApplicationLogs::ACTION_EDIT; if (!$company) { $company = new Contact(); $contact_data['import_status'] = '('.lang('new').')'; $log_action = ApplicationLogs::ACTION_ADD; $can_import = $company->canAdd(logged_user(), active_context()); } else { $can_import = $company->canEdit(logged_user()); } if ($can_import) { $contact_data['name'] = $contact_data['first_name']; $contact_data['is_company'] = 1; $company->setFromAttributes($contact_data); $company->save(); if(count(active_context_members(false)) > 0 ){ $object_controller->add_to_members($company, active_context_members(false)); } ApplicationLogs::createLog($company, null, $log_action); $import_result['import_ok'][] = $contact_data; } else { throw new Exception(lang('no access permissions')); } } DB::commit(); } catch (Exception $e) { DB::rollback(); $contact_data['fail_message'] = substr_utf($e->getMessage(), strpos_utf($e->getMessage(), "\r\n")); $import_result['import_fail'][] = $contact_data; } $i++; } unlink($_SESSION['csv_import_filename']); unset($_SESSION['csv_import_filename']); unset($_SESSION['delimiter']); unset($_SESSION['first_record_has_names']); unset($_SESSION['import_type']); $_SESSION['history_back'] = true; tpl_assign('import_result', $import_result); } } } // import_from_csv_file
function quick_add_task() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $notAllowedMember = ''; if (!ProjectTask::canAdd(logged_user(), active_context(), $notAllowedMember)) { if (str_starts_with($notAllowedMember, '-- req dim --')) { flash_error(lang('must choose at least one member of', str_replace_first('-- req dim --', '', $notAllowedMember, $in))); } else { trim($notAllowedMember) == "" ? flash_error(lang('you must select where to keep', lang('the task'))) : flash_error(lang('no context permissions to add', lang("tasks"), $notAllowedMember)); } ajx_current("empty"); return; } ajx_current("empty"); $task = new ProjectTask(); $task_data = array_var($_POST, 'task'); $parent_id = array_var($task_data, 'parent_id', 0); $parent = ProjectTasks::findById($parent_id); if (is_array($task_data)) { $task_data['due_date'] = getDateValue(array_var($task_data, 'task_due_date')); $task_data['start_date'] = getDateValue(array_var($task_data, 'task_start_date')); if ($task_data['due_date'] instanceof DateTimeValue) { $duetime = getTimeValue(array_var($task_data, 'task_due_time')); if (is_array($duetime)) { $task_data['due_date']->setHour(array_var($duetime, 'hours')); $task_data['due_date']->setMinute(array_var($duetime, 'mins')); $task_data['due_date']->advance(logged_user()->getTimezone() * -3600); } $task_data['use_due_time'] = is_array($duetime); } if ($task_data['start_date'] instanceof DateTimeValue) { $starttime = getTimeValue(array_var($task_data, 'task_start_time')); if (is_array($starttime)) { $task_data['start_date']->setHour(array_var($starttime, 'hours')); $task_data['start_date']->setMinute(array_var($starttime, 'mins')); $task_data['start_date']->advance(logged_user()->getTimezone() * -3600); } $task_data['use_start_time'] = is_array($starttime); } if (config_option("wysiwyg_tasks")) { $task_data['type_content'] = "html"; $task_data['text'] = str_replace(array("\r", "\n", "\r\n"), array('', '', ''), array_var($task_data, 'text')); } else { $task_data['type_content'] = "text"; } $task_data['object_type_id'] = $task->getObjectTypeId(); $task->setFromAttributes($task_data); if (array_var($task_data, 'is_completed', false) == 'true') { $task->setCompletedOn(DateTimeValueLib::now()); $task->setCompletedById(logged_user()->getId()); } try { DB::beginWork(); $task->save(); $totalMinutes = array_var($task_data, 'hours') * 60 + array_var($task_data, 'minutes'); $task->setTimeEstimate($totalMinutes); $task->save(); $gb_member_ids = array_var($task_data, 'members'); $member_ids = array(); $persons_dim = Dimensions::findByCode('feng_persons'); $persons_dim_id = $persons_dim instanceof Dimension ? $persons_dim->getId() : 0; if ($parent) { if (count($parent->getMembers()) > 0) { foreach ($parent->getMembers() as $member) { if ($member->getDimensionId() != $persons_dim_id) { $member_ids[] = $member->getId(); } } } $task->setMilestoneId($parent->getMilestoneId()); $task->save(); } if (count($member_ids) == 0) { $member_ids = active_context_members(false); } // get member ids if ($gb_member_ids && !empty($gb_member_ids)) { $member_ids = json_decode(array_var($task_data, 'members')); } $object_controller = new ObjectController(); $object_controller->add_to_members($task, $member_ids); $assignee = $task->getAssignedToContact(); $assignee_to_me = false; if ($assignee instanceof Contact) { $task->subscribeUser($assignee); //do not notify my self if ($assignee->getId() == logged_user()->getId()) { $assignee_to_me = true; } } // create default reminder by user config option if ($task->getDueDate() != null && user_config_option("add_task_default_reminder")) { $reminder = new ObjectReminder(); $def = explode(",", user_config_option("reminders_tasks")); $minutes = $def[2] * $def[1]; $reminder->setMinutesBefore($minutes); $reminder->setType($def[0]); $reminder->setContext("due_date"); $reminder->setObject($task); $reminder->setUserId(0); $date = $task->getDueDate(); if ($date instanceof DateTimeValue) { $rdate = new DateTimeValue($date->getTimestamp() - $minutes * 60); $reminder->setDate($rdate); } $reminder->save(); } $subs = array(); if (config_option('multi_assignment') && Plugins::instance()->isActivePlugin('crpm')) { $json_subtasks = json_decode(array_var($_POST, 'multi_assignment'), true); $subtasks = array(); $line = 0; if (is_array($json_subtasks)) { foreach ($json_subtasks as $json_subtask) { $subtasks[$line]['assigned_to_contact_id'] = $json_subtask['assigned_to_contact_id']; $subtasks[$line]['name'] = $json_subtask['name']; $subtasks[$line]['time_estimate_hours'] = $json_subtask['time_estimate_hours']; $subtasks[$line]['time_estimate_minutes'] = $json_subtask['time_estimate_minutes']; $line++; } } Hook::fire('save_subtasks', $task, $subtasks); $subtasks = ProjectTasks::findAll(array('conditions' => '`parent_id` = ' . DB::escape($task->getId()))); // findAll foreach ($subtasks as $sub) { $subs[] = $sub->getArrayInfo(); } } // subscribe $task->subscribeUser(logged_user()); //for calculate member status we save de task again after the object have the members $task->save(); DB::commit(); $isSailent = true; // notify asignee if ((array_var($task_data, 'notify') == 'true' || user_config_option("can notify from quick add") && !user_config_option("show_notify_checkbox_in_quick_add")) && !$assignee_to_me) { $isSailent = false; try { Notifier::taskAssigned($task); } catch (Exception $e) { Logger::log($e->getMessage()); Logger::log($e->getTraceAsString()); } // try } ApplicationLogs::createLog($task, ApplicationLogs::ACTION_ADD, null, $isSailent); ajx_extra_data(array("task" => $task->getArrayInfo(), 'subtasks' => $subs)); flash_success(lang('success add task', $task->getObjectName())); } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); } // try } // if }
static function findByContext($options = array()) { // Initialize method result $result = new stdClass(); $result->total = 0; $result->objects = array(); // Read arguments and Init Vars $limit = array_var($options, 'limit'); $offset = array_var($options, 'offset'); $trashed = array_var($options, 'trashed'); $archived = array_var($options, 'archived'); $members = active_context_members(false); $type_id = self::instance()->getObjectTypeId(); $uid = logged_user()->getId(); if ($limit > 0) { $limit_sql = "LIMIT " . ($offset ? "{$offset}, " : "") . "{$limit}"; } else { $limit_sql = ''; } $member_conditions = count($members) > 0 ? "id IN (SELECT object_id FROM " . TABLE_PREFIX . "object_members WHERE member_id IN (" . implode(',', $members) . "))" : "true"; $trashed_conditions = "AND o.trashed_on " . ($trashed ? ">" : "=") . " 0"; $archived_conditions = "AND o.archived_on " . ($archived ? ">" : "=") . " 0"; $extra_conditions = array_var($options, 'extra_conditions', ""); // Build Main SQL $template_sql = "\r\n\t \tSELECT <selection> FROM " . TABLE_PREFIX . "objects o\r\n\t \tINNER JOIN " . TABLE_PREFIX . "mail_contents m ON m.object_id = o.id\r\n\t \tWHERE \r\n\t \t\to.id IN ( \r\n\t \t\t\tSELECT object_id FROM " . TABLE_PREFIX . "sharing_table\r\n\t \t\t\tWHERE group_id IN (\r\n\t\t \t\t\tSELECT permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups WHERE contact_id = {$uid}\r\n\t\t\t\t\t)\r\n\t\t\t\t) \r\n\t\t\t\tAND {$member_conditions}\r\n\t\t\t\tAND o.object_type_id = {$type_id}\r\n\t\t\t\tAND m.is_deleted = 0 {$trashed_conditions} {$archived_conditions} {$extra_conditions}"; $count_sql = str_replace_first("<selection>", "COUNT(distinct(o.id)) as total", $template_sql); $sql = str_replace_first("<selection>", "distinct(o.id)", $template_sql) . " {$limit_sql}"; // count all emails $res = DB::execute($count_sql); $result->total = array_var($res->fetchRow(), 'total'); if ($result->total == 0) { return $result; } // Execute query and build the resultset $rows = DB::executeAll($sql); $mail_ids = array(); foreach ($rows as $row) { $mail_ids[] = $row['id']; } $result->objects = MailContents::findAll(array("conditions" => "object_id IN (" . implode(",", $mail_ids) . ")", "order" => array_var($options, 'order'))); return $result; }
function list_objects() { /* get query parameters */ $filesPerPage = config_option('files_per_page'); $start = array_var($_GET, 'start') ? (int) array_var($_GET, 'start') : 0; $limit = array_var($_GET, 'limit') ? array_var($_GET, 'limit') : $filesPerPage; $order = array_var($_GET, 'sort'); $id_no_select = array_var($_GET, 'id_no_select', "undefined"); $ignore_context = (bool) array_var($_GET, 'ignore_context'); $member_ids = json_decode(array_var($_GET, 'member_ids')); $extra_member_ids = json_decode(array_var($_GET, 'extra_member_ids')); $orderdir = array_var($_GET, 'dir'); if (!in_array(strtoupper($orderdir), array('ASC', 'DESC'))) { $orderdir = 'ASC'; } if ($order == "dateUpdated") { $order = "updated_on"; } elseif ($order == "dateArchived") { $order = "archived_on"; } elseif ($order == "dateDeleted") { $order = "trashed_on"; } elseif ($order == "name") { $order = "name"; } else { $order = ""; $orderdir = ""; } $extra_list_params = array_var($_GET, 'extra_list_params'); $extra_list_params = json_decode($extra_list_params); $page = (int) ($start / $limit) + 1; $hide_private = !logged_user()->isMemberOfOwnerCompany(); $typeCSV = array_var($_GET, 'type'); $types = null; if ($typeCSV) { $types = explode(",", $typeCSV); } $name_filter = mysql_real_escape_string(array_var($_GET, 'name')); $linked_obj_filter = array_var($_GET, 'linkedobject'); $object_ids_filter = ''; $show_all_linked_objects = false; if (!is_null($linked_obj_filter)) { $show_all_linked_objects = true; $linkedObject = Objects::findObject($linked_obj_filter); $objs = $linkedObject->getLinkedObjects(); foreach ($objs as $obj) { $object_ids_filter .= ($object_ids_filter == '' ? '' : ',') . $obj->getId(); } } $filters = array(); if (!is_null($types)) { $filters['types'] = $types; } if (!is_null($name_filter)) { $filters['name'] = $name_filter; } if ($object_ids_filter != '') { $filters['object_ids'] = $object_ids_filter; } $user = array_var($_GET, 'user'); $trashed = array_var($_GET, 'trashed', false); $archived = array_var($_GET, 'archived', false); /* if there's an action to execute, do so */ if (!$show_all_linked_objects) { $this->processListActions(); } $filterName = array_var($_GET, 'name'); $template_object_names = ""; $template_extra_condition = "true"; $template_objects = false; if (in_array("template_task", array_var($filters, 'types', array())) || in_array("template_milestone", array_var($filters, 'types', array()))) { $template_id = 0; $template_objects = true; if (isset($extra_list_params->template_id)) { $template_id = $extra_list_params->template_id; } $tmpl_task = TemplateTasks::findById(intval($id_no_select)); if ($tmpl_task instanceof TemplateTask) { $template_extra_condition = "o.id IN (SELECT object_id from " . TABLE_PREFIX . "template_tasks WHERE `template_id`=" . $tmpl_task->getTemplateId() . " OR `template_id`=0 AND `session_id`=" . logged_user()->getId() . " )"; } else { $template_extra_condition = "o.id IN (SELECT object_id from " . TABLE_PREFIX . "template_tasks WHERE `template_id`=" . intval($template_id) . " OR `template_id`=0 AND `session_id`=" . logged_user()->getId() . " )"; } } else { $template_object_names = "AND name <> 'template_task' AND name <> 'template_milestone'"; } $result = null; $context = active_context(); $obj_type_types = array('content_object', 'dimension_object'); if (array_var($_GET, 'include_comments')) { $obj_type_types[] = 'comment'; } $type_condition = ""; if ($types) { $type_condition = " AND name IN ('" . implode("','", $types) . "')"; } $extra_conditions = array(); // user filter if (in_array("contact", array_var($filters, 'types', array())) && isset($extra_list_params->is_user)) { $joins[] = "\r\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "contacts c on c.object_id=o.id"; $extra_conditions[] = "\r\n\t\t\t\tc.user_type " . ($extra_list_params->is_user == 1 ? ">" : "=") . " 0"; if (isset($extra_list_params->has_permissions) && $extra_list_params->has_permissions > 0) { $mem_id = $extra_list_params->has_permissions; $extra_conditions[] = " EXISTS (\r\n\t\t\t\t\tSELECT cmp.permission_group_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp\r\n\t\t\t\t\tWHERE cmp.permission_group_id IN (SELECT x.permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups x WHERE x.contact_id=o.id)\r\n\t\t\t\t\tAND cmp.member_id='{$mem_id}' \r\n\t\t\t\t\tAND cmp.object_type_id NOT IN (SELECT tp.object_type_id FROM " . TABLE_PREFIX . "tab_panels tp WHERE tp.enabled=0)\r\n\t\t\t\t\tAND cmp.object_type_id NOT IN (SELECT oott.id FROM " . TABLE_PREFIX . "object_types oott WHERE oott.name IN ('comment','template'))\r\n\t\t\t\t\tAND cmp.object_type_id IN (SELECT oott2.id FROM " . TABLE_PREFIX . "object_types oott2 WHERE oott2.type IN ('content_object','dimension_object'))\r\n\t\t\t\t)"; } } // Object type filter - exclude template types (if not template picker), filter by required type names (if specified) and match value with objects table $extra_object_type_conditions = "\r\n\t\t\tAND name <> 'file revision' {$template_object_names} {$type_condition} AND o.object_type_id = ot.id"; $extra_conditions[] = ObjectTypes::getListableObjectsSqlCondition($extra_object_type_conditions); // -- // logged user permission group ids $logged_user_pg_ids = implode(',', logged_user()->getPermissionGroupIds()); // used in template object picker $extra_conditions[] = $template_extra_condition; // when filtering by name if ($name_filter) { $extra_conditions[] = "\r\n\t\t\t\tname LIKE '%{$name_filter}%'"; } // when excluding some object in particular if ($id_no_select != "undefined") { $extra_conditions[] = "\r\n\t\t\t\tid <> '{$id_no_select}'"; } // when filtering by some group of objects, for example in the linked objects view if ($object_ids_filter != "") { $extra_conditions[] = "\r\n\t\t\t\tid in ({$object_ids_filter})"; } $joins[] = "\r\n\t\t\tLEFT JOIN " . TABLE_PREFIX . "project_tasks pt on pt.object_id=o.id"; if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) { // exclude other users' tasks if cannot see them $extra_conditions[] = "\r\n\t\t\t\t( pt.assigned_to_contact_id IS NULL OR pt.assigned_to_contact_id= " . logged_user()->getId() . ")"; } // don't include tasks which have is_template=1 $extra_conditions[] = "\r\n\t\t\t( pt.is_template IS NULL OR pt.is_template=0)"; // trashed conditions $extra_conditions[] = "\r\n\t\t\to.trashed_on" . ($trashed ? "<>" : "=") . "0"; // archived conditions $extra_conditions[] = "\r\n\t\t\to.archived_on" . ($archived ? "<>" : "=") . "0"; // don't include unclassified mails from other accounts if (Plugins::instance()->isActivePlugin('mail')) { $accounts_of_loggued_user = MailAccountContacts::getByContact(logged_user()); $account_ids = array(0); foreach ($accounts_of_loggued_user as $acc) { $account_ids[] = $acc->getAccountId(); } $joins[] = "\r\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "mail_contents mc on mc.object_id=o.id\r\n\t\t\t"; $extra_conditions[] = "\r\n\t\t\t\tIF( mc.account_id IS NULL, true, mc.account_id IN (" . implode(',', $account_ids) . ") OR EXISTS (\r\n\t\t\t\t\tSELECT om1.object_id FROM " . TABLE_PREFIX . "object_members om1 \r\n\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members m1 ON m1.id=om1.member_id \r\n\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "dimensions d1 ON d1.id=m1.dimension_id \r\n\t\t\t\t\tWHERE om1.object_id=o.id AND d1.is_manageable=1)\r\n\t\t\t\t)"; } // don't show attached files of emails that cannot be viewed if (logged_user()->isAdministrator() && Plugins::instance()->isActivePlugin('mail')) { $joins[] = "LEFT JOIN " . TABLE_PREFIX . "project_files pf on pf.object_id=o.id"; $extra_conditions[] = "IF(pf.mail_id IS NULL OR pf.mail_id = 0, true, \r\n\t\t\t\tpf.mail_id IN (SELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh WHERE pf.mail_id = sh.object_id AND sh.group_id IN ({$logged_user_pg_ids})))"; } $only_count_result = array_var($_GET, 'only_result', false); $count_results = array_var($_GET, 'count_results', false); // Members filter $sql_members = ""; if (!$ignore_context && !$member_ids) { $members = active_context_members(false); // Context Members Ids } elseif (count($member_ids)) { $members = $member_ids; } else { // get members from context if (!$ignore_context) { $members = active_context_members(false); } } if (is_array($extra_member_ids)) { if (isset($members)) { $members = array_merge($members, $extra_member_ids); } else { $members = $extra_member_ids; } } if (isset($members) && is_array($members) && count($members) > 0 && !(isset($template_id) && $template_id > 0)) { $sql_members = "\r\n\t\t\t\tAND (EXISTS (SELECT om.object_id\r\n\t\t\t\t\tFROM " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\tWHERE om.member_id IN (" . implode(',', $members) . ") AND o.id = om.object_id \r\n\t\t\t\t\tGROUP BY object_id\r\n\t\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t\t))\r\n\t\t\t"; } // -- // Permissions filter if (isset($template_id) && $template_id > 0) { // editing template items do not check permissions $sql_permissions = ""; } else { $sql_permissions = "\r\n\t\t\t\tAND EXISTS (SELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh WHERE sh.object_id=o.id AND sh.group_id IN ({$logged_user_pg_ids}))\r\n\t\t\t"; } // Main select $sql_select = "SELECT * FROM " . TABLE_PREFIX . "objects o "; // Joins $sql_joins = implode(" ", $joins); // Where $sql_where = "\r\n\t\t\tWHERE " . implode(" AND ", $extra_conditions) . $sql_permissions . $sql_members; // Order $sql_order = ""; if ($order) { $sql_order = "\r\n\t\t\t\tORDER BY {$order} {$orderdir}\r\n\t\t\t"; } // Limit $sql_limit = ""; if ($start >= 0 && $limit > 0) { $sql_limit = " LIMIT {$start}, {$limit}"; } // Full SQL $sql = "{$sql_select} {$sql_joins} {$sql_where} {$sql_order} {$sql_limit}"; // Execute query if (!$only_count_result) { $rows = DB::executeAll($sql); } // get total items if ($count_results) { $sql_count = "SELECT count(o.id) as total_items FROM " . TABLE_PREFIX . "objects o {$sql_joins} {$sql_where}"; $rows_count = DB::executeAll($sql_count); $total_items = $rows_count[0]['total_items']; } else { if (isset($rows) && is_array($rows)) { $total_items = count($rows) < $filesPerPage ? count($rows) : 1000000; } else { $total_items = 0; } } // prepare response object $info = array(); // get objects if (isset($rows) && is_array($rows)) { foreach ($rows as $row) { $instance = Objects::findObject($row['id']); if (!$instance instanceof ContentDataObject) { continue; } $info_elem = $instance->getObject()->getArrayInfo(); $info_elem['url'] = $instance->getViewUrl(); $info_elem['isRead'] = $instance->getIsRead(logged_user()->getId()); $info_elem['manager'] = get_class($instance->manager()); $info_elem['memPath'] = json_encode($instance->getMembersIdsToDisplayPath()); if ($instance instanceof Contact) { if ($instance->isCompany()) { $info_elem['icon'] = 'ico-company'; $info_elem['type'] = 'company'; } else { $info_elem['memPath'] = json_encode($instance->getUserType() ? "" : $instance->getMembersIdsToDisplayPath()); } } else { if ($instance instanceof ProjectFile) { $info_elem['mimeType'] = $instance->getTypeString(); } } $info[] = $info_elem; } } $listing = array("totalCount" => $total_items, "start" => $start, "objects" => $info); ajx_extra_data($listing); tpl_assign("listing", $listing); if (isset($reload) && $reload) { ajx_current("reload"); } else { ajx_current("empty"); } }