Exemple #1
0
 public function body($arg = null, $rb = null, $uid = null)
 {
     if (isset($arg) && isset($rb)) {
         $this->group = $rb->tab . '/' . $arg['id'];
         if (Utils_WatchdogCommon::get_category_id($rb->tab) !== null) {
             $this->watchdog_category = $rb->tab;
             $this->watchdog_id = $arg['id'];
         }
         $this->set_view_func(array('Utils_RecordBrowserCommon', 'create_default_linked_label'), array($rb->tab, $arg['id']));
     }
     if (!isset($this->group) && !$uid) {
         trigger_error('Key not given to attachment module', E_USER_ERROR);
     }
     $_SESSION['client']['utils_attachment_group'] = $this->group;
     load_js('modules/Utils/Attachment/attachments.js');
     Base_ThemeCommon::load_css('Utils_Attachment', 'browse');
     $this->rb = $this->init_module(Utils_RecordBrowser::module_name(), 'utils_attachment', 'utils_attachment');
     $defaults = array('permission' => Base_User_SettingsCommon::get('CRM_Common', 'default_record_permission'), 'func' => serialize($this->func), 'args' => serialize($this->args));
     $rb_cols = array();
     $single_group = is_string($this->group) || count($this->group) == 1;
     if ($this->force_multiple) {
         $single_group = false;
     }
     if ($single_group) {
         $group = is_string($this->group) ? $this->group : reset($this->group);
         $defaults['local'] = $group;
     } else {
         // force attached to display
         $rb_cols['attached_to'] = true;
         $this->rb->set_button(false);
     }
     $this->rb->set_defaults($defaults);
     $this->rb->set_additional_actions_method(array($this, 'add_actions'));
     $this->rb->set_header_properties(array('sticky' => array('width' => 1, 'display' => false), 'attached_to' => array('width' => "16em"), 'edited_on' => array('width' => "12em"), 'title' => array('width' => "20em")));
     if ($uid) {
         $this->rb->set_button(false);
         $this->rb->disable_actions(array('delete'));
         $this->display_module($this->rb, array(array(':Created_by' => $uid), $rb_cols, array('sticky' => 'DESC', 'edited_on' => 'DESC')), 'show_data');
     } else {
         $crits = array();
         if (!is_array($this->group)) {
             $this->group = array($this->group);
         }
         if (isset($_SESSION['attachment_copy']) && count($this->group) == 1 && $_SESSION['attachment_copy']['group'] != $this->group) {
             $this->rb->new_button(Base_ThemeCommon::get_template_file(Utils_Attachment::module_name(), 'link.png'), __('Paste'), Utils_TooltipCommon::open_tag_attrs($_SESSION['attachment_copy']['text']) . ' ' . $this->create_callback_href(array($this, 'paste')));
         }
         if ($this->group) {
             $g = array_map(array('DB', 'qstr'), $this->group);
             $crits['id'] = DB::GetCol('SELECT attachment FROM utils_attachment_local WHERE local IN (' . implode(',', $g) . ')');
         } else {
             $crits['id'] = 0;
         }
         $this->display_module($this->rb, array($crits, $rb_cols, array('sticky' => 'DESC', 'edited_on' => 'DESC')), 'show_data');
     }
 }
 public static function watchdog_label($tab, $cat, $rid, $events = array(), $label = null, $details = true)
 {
     $ret = array('category' => $cat);
     if ($rid !== null) {
         $r = self::get_record($tab, $rid);
         if ($r === null) {
             return null;
         }
         if (!self::get_access($tab, 'view', $r)) {
             return null;
         }
         if (is_array($label)) {
             $label = Utils_RecordBrowserCommon::record_link_open_tag_r($tab, $r) . call_user_func($label, $r, true) . Utils_RecordBrowserCommon::record_link_close_tag();
             $label = self::create_default_record_tooltip_ajax($label, $tab, $rid);
         } elseif ($label) {
             $label = Utils_RecordBrowserCommon::create_linked_label_r($tab, $label, $r);
             $label = self::create_default_record_tooltip_ajax($label, $tab, $rid);
         } else {
             $label = Utils_RecordBrowserCommon::create_default_linked_label($tab, $rid, false, false);
         }
         $ret['title'] = $label;
         $ret['view_href'] = Utils_RecordBrowserCommon::create_record_href($tab, $rid);
         $events_display = array();
         $events = array_reverse($events);
         $other_events = array();
         $header = false;
         foreach ($events as $v) {
             if (count($events_display) > 20) {
                 $other_events[__('And more...')] = 1;
                 break;
             }
             $param = explode('_', $v);
             switch ($param[0]) {
                 case 'C':
                     $what = 'Created';
                     $event_display = array('who' => Base_UserCommon::get_user_label($r['created_by'], true), 'when' => Base_RegionalSettingsCommon::time2reg($r['created_on']), 'what' => _V($what));
                     break;
                 case 'D':
                     if (!isset($what)) {
                         $what = 'Deleted';
                     }
                 case 'R':
                     if (!isset($what)) {
                         $what = 'Restored';
                     }
                     if (!isset($param[1])) {
                         $event_display = array('who' => '', 'when' => '', 'what' => _V($what));
                         break;
                     }
                 case 'E':
                     $event_display = self::get_edit_details_modify_record($tab, $r['id'], $param[1], $details);
                     if (isset($event_display['what']) && !empty($event_display['what'])) {
                         $header = true;
                     }
                     break;
                 case 'N':
                     $event_display = false;
                     switch ($param[1]) {
                         case '+':
                             $action = __('Note linked');
                             break;
                         case '-':
                             $action = __('Note unlinked');
                             break;
                         default:
                             if (!isset($other_events[$param[1]])) {
                                 $other_events[$param[1]] = 0;
                             }
                             $other_events[$param[1]]++;
                             $event_display = null;
                             break;
                     }
                     if ($event_display === false) {
                         $date = isset($param[3]) ? Base_RegionalSettingsCommon::time2reg($param[3]) : '';
                         $who = isset($param[4]) ? Base_UserCommon::get_user_label($param[4], true) : '';
                         $action .= ' - ' . self::create_default_linked_label('utils_attachment', $param[2]);
                         $event_display = array('what' => $action, 'who' => $who, 'when' => $date);
                     }
                     break;
                 default:
                     $event_display = array('what' => _V($v));
             }
             if ($event_display) {
                 $events_display[] = $event_display;
             }
         }
         foreach ($other_events as $k => $v) {
             $events_display[] = array('what' => _V($k) . ($v > 1 ? ' [' . $v . ']' : ''));
         }
         if ($events_display) {
             $theme = Base_ThemeCommon::init_smarty();
             if ($header) {
                 $theme->assign('header', array(__('Field'), __('Old value'), __('New value')));
             }
             $theme->assign('events', $events_display);
             $tpl = 'changes_list';
             if (Utils_WatchdogCommon::email_mode()) {
                 $record_data = self::get_record_tooltip_data($tab, $rid);
                 $theme->assign('record', $record_data);
                 $tpl = 'changes_list_email';
             }
             ob_start();
             Base_ThemeCommon::display_smarty($theme, 'Utils_RecordBrowser', $tpl);
             $output = ob_get_clean();
             $ret['events'] = $output;
         } else {
             // if we've generated empty events for certain record, then
             // it's possible that some of the fields, that have changed,
             // are hidden so we have to check if there are any other events
             // If all events are the same and output is empty we can safely
             // mark all as notified.
             $all_events = Utils_WatchdogCommon::check_if_notified($tab, $rid);
             if (count($all_events) == count($events)) {
                 Utils_WatchdogCommon::notified($tab, $rid);
             }
             $ret = null;
         }
     }
     return $ret;
 }
Exemple #3
0
 public static function submit_task($values, $mode)
 {
     $me = CRM_ContactsCommon::get_my_record();
     switch ($mode) {
         case 'display':
             $values['title'] = __('Follow-up') . ': ' . $values['title'];
             $values['status'] = 0;
             $values['deadline'] = date('Y-m-d', strtotime('+1 day'));
             $ret = array();
             $cus = reset($values['customers']);
             if (ModuleManager::is_installed('CRM/Meeting') >= 0) {
                 $ret['new']['event'] = '<a ' . Utils_TooltipCommon::open_tag_attrs(__('New Meeting')) . ' ' . Utils_RecordBrowserCommon::create_new_record_href('crm_meeting', array('title' => $values['title'], 'permission' => $values['permission'], 'priority' => $values['priority'], 'description' => $values['description'], 'date' => date('Y-m-d'), 'time' => date('H:i:s'), 'duration' => 3600, 'employees' => $values['employees'], 'customers' => $values['customers'], 'status' => 0), 'none', false) . '><img border="0" src="' . Base_ThemeCommon::get_template_file('CRM_Calendar', 'icon-small.png') . '" /></a>';
             }
             $ret['new']['task'] = '<a ' . Utils_TooltipCommon::open_tag_attrs(__('New Task')) . ' ' . Utils_RecordBrowserCommon::create_new_record_href('task', $values) . '><img border="0" src="' . Base_ThemeCommon::get_template_file('CRM_Tasks', 'icon-small.png') . '" /></a>';
             if (ModuleManager::is_installed('CRM/PhoneCall') >= 0) {
                 $ret['new']['phonecall'] = '<a ' . Utils_TooltipCommon::open_tag_attrs(__('New Phonecall')) . ' ' . Utils_RecordBrowserCommon::create_new_record_href('phonecall', array('subject' => $values['title'], 'permission' => $values['permission'], 'priority' => $values['priority'], 'description' => $values['description'], 'date_and_time' => date('Y-m-d H:i:s'), 'employees' => $values['employees'], 'customer' => $cus, 'status' => 0), 'none', false) . '><img border="0" src="' . Base_ThemeCommon::get_template_file('CRM_PhoneCall', 'icon-small.png') . '" /></a>';
             }
             $ret['new']['note'] = Utils_RecordBrowser::$rb_obj->add_note_button('task/' . $values['id']);
             return $ret;
         case 'adding':
             $values['deadline_time'] = strtotime(date('Y-m-d') . ' 23:59:59');
             $values['permission'] = Base_User_SettingsCommon::get('CRM_Common', 'default_record_permission');
             break;
         case 'add':
             break;
         case 'edit':
             $old_values = Utils_RecordBrowserCommon::get_record('task', $values['id']);
             $old_related = array_merge($old_values['employees'], $old_values['customers']);
         case 'added':
             if (isset($values['follow_up'])) {
                 CRM_FollowupCommon::add_tracing_notes($values['follow_up'][0], $values['follow_up'][1], $values['follow_up'][2], 'task', $values['id'], $values['title']);
             }
             self::subscribed_employees($values);
             $related = array_merge($values['employees'], $values['customers']);
             foreach ($related as $v) {
                 if ($mode === 'edit' && in_array($v, $old_related)) {
                     continue;
                 }
                 if (!is_numeric($v)) {
                     list($t, $id) = explode(':', $v);
                 } else {
                     $t = 'P';
                     $id = $v;
                 }
                 if ($t == 'P') {
                     $t = 'contact';
                 } else {
                     $t = 'company';
                 }
                 $subs = Utils_WatchdogCommon::get_subscribers($t, $id);
                 foreach ($subs as $s) {
                     Utils_WatchdogCommon::user_subscribe($s, 'task', $values['id']);
                 }
             }
             break;
     }
     return $values;
 }
Exemple #4
0
 public static function submit_meeting($values, $mode)
 {
     $me = CRM_ContactsCommon::get_my_record();
     switch ($mode) {
         case 'delete':
             Utils_MessengerCommon::delete_by_id('CRM_Calendar_Event:' . $values['id']);
             break;
         case 'display':
             $pdf = Utils_RecordBrowser::$rb_obj->pack_module('Libs/TCPDF', 'L');
             if ($pdf->prepare()) {
                 $pdf->set_title($values['title']);
                 $pdf->set_subject('');
                 $pdf->prepare_header();
                 $pdf->AddPage();
                 $v = CRM_Calendar_EventCommon::get(DB::GetOne('SELECT id FROM crm_calendar_custom_events_handlers WHERE group_name=%s', array('Meetings')) . '#' . $values['id']);
                 $ev_mod = Utils_RecordBrowser::$rb_obj->init_module('CRM/Calendar/Event');
                 $ev_mod->make_event_PDF($pdf, $v, true, 'view');
             }
             $pdf->add_actionbar_icon('Print');
             if (isset($_REQUEST['day'])) {
                 $values['date'] = $_REQUEST['day'];
             }
             $ret = array();
             if ($values['time']) {
                 // normal event
                 $start = $values['time'];
                 // time in unix timestamp UTC
                 $start_disp = strtotime(Base_RegionalSettingsCommon::time2reg($start, true, true, true, false));
             } else {
                 // when event is timeless - all day event
                 $time = $values['date'] . ' 00:00:01';
                 $start = Base_RegionalSettingsCommon::reg2time($time);
                 $start_disp = strtotime($time);
             }
             $end = strtotime('+' . $values['duration'] . ' seconds', $start);
             $ret['day_details'] = array('start' => array('day' => '<a ' . Base_BoxCommon::create_href(null, 'CRM/Calendar', 'body', array(array('default_view' => 'day', 'default_date' => strtotime($values['date']))), array()) . '>' . date('j', $start_disp) . '</a>', 'month' => '<a ' . Base_BoxCommon::create_href(null, 'CRM/Calendar', 'body', array(array('default_view' => 'month', 'default_date' => strtotime($values['date']))), array()) . '>' . __date('F', $start_disp) . '</a>', 'year' => '<a ' . Base_BoxCommon::create_href(null, 'CRM/Calendar', 'body', array(array('default_view' => 'year', 'default_date' => strtotime($values['date']))), array()) . '>' . date('Y', $start_disp) . '</a>', 'weekday' => '<a ' . Base_BoxCommon::create_href(null, 'CRM/Calendar', 'body', array(array('default_view' => 'week', 'default_date' => strtotime($values['date']))), array()) . '>' . __date('l', $start_disp) . '</a>'));
             if (!isset($values['timeless']) || !$values['timeless']) {
                 $ret['event_info'] = array('start_time' => Base_RegionalSettingsCommon::time2reg($start, 2, false), 'end_time' => Base_RegionalSettingsCommon::time2reg($end, 2, false), 'duration' => Base_RegionalSettingsCommon::seconds_to_words($values['duration']), 'start_date' => '-', 'end_date' => '-');
             }
             $ret['form_data']['timeless'] = array('label' => __('Timeless'), 'html' => 'value');
             $ret['toggle_duration'] = 'tog';
             $ret['duration_block_id'] = '1';
             $ret['event_end_block_id'] = '2';
             $values['title'] = __('Follow-up') . ': ' . $values['title'];
             $values['status'] = 0;
             $cus = reset($values['customers']);
             if (ModuleManager::is_installed('CRM/Meeting') >= 0) {
                 $ret['new']['event'] = '<a ' . Utils_TooltipCommon::open_tag_attrs(__('New Meeting')) . ' ' . Utils_RecordBrowserCommon::create_new_record_href('crm_meeting', array('title' => $values['title'], 'permission' => $values['permission'], 'priority' => $values['priority'], 'description' => $values['description'], 'date' => date('Y-m-d'), 'time' => date('H:i:s'), 'duration' => 3600, 'employees' => $values['employees'], 'customers' => $values['customers'], 'status' => 0), 'none', false) . '><img border="0" src="' . Base_ThemeCommon::get_template_file('CRM_Calendar', 'icon-small.png') . '" /></a>';
             }
             if (ModuleManager::is_installed('CRM/Tasks') >= 0) {
                 $ret['new']['task'] = '<a ' . Utils_TooltipCommon::open_tag_attrs(__('New Task')) . ' ' . Utils_RecordBrowserCommon::create_new_record_href('task', array('title' => $values['title'], 'permission' => $values['permission'], 'priority' => $values['priority'], 'description' => $values['description'], 'employees' => $values['employees'], 'customers' => $values['customers'], 'status' => 0, 'deadline' => date('Y-m-d', strtotime('+1 day')))) . '><img border="0" src="' . Base_ThemeCommon::get_template_file('CRM_Tasks', 'icon-small.png') . '"></a>';
             }
             if (ModuleManager::is_installed('CRM/PhoneCall') >= 0) {
                 $ret['new']['phonecall'] = '<a ' . Utils_TooltipCommon::open_tag_attrs(__('New Phonecall')) . ' ' . Utils_RecordBrowserCommon::create_new_record_href('phonecall', array('subject' => $values['title'], 'permission' => $values['permission'], 'priority' => $values['priority'], 'description' => $values['description'], 'date_and_time' => date('Y-m-d H:i:s'), 'employees' => $values['employees'], 'customer' => $cus, 'status' => 0), 'none', false) . '><img border="0" src="' . Base_ThemeCommon::get_template_file('CRM_PhoneCall', 'icon-small.png') . '" /></a>';
             }
             $ret['new']['note'] = Utils_RecordBrowser::$rb_obj->add_note_button('crm_meeting/' . $values['id']);
             return $ret;
         case 'edit':
             self::subscribed_employees($values);
             $alarms = Utils_MessengerCommon::get_alarms('CRM_Calendar_Event:' . $values['id']);
             $old = Utils_RecordBrowserCommon::get_record('crm_meeting', $values['id']);
             $old_time = strtotime($old['date'] . ' ' . date('H:i:s', strtotime($old['time'])));
             $new_time = strtotime($values['date'] . ' ' . date('H:i:s', strtotime($values['time'])));
             foreach ($alarms as $id => $time) {
                 $time = strtotime($time);
                 $diff = $old_time - $time;
                 Utils_MessengerCommon::update_time($id, $new_time - $diff);
             }
         case 'add':
             if (isset($values['duration_switch']) && !$values['duration_switch']) {
                 $values['duration'] = strtotime($values['end_time']) - strtotime($values['time']);
                 if ($values['duration'] < 0) {
                     $values['duration'] += 60 * 60 * 24;
                 }
                 // failsafe
             }
             if (isset($values['timeless']) && $values['timeless']) {
                 $values['duration'] = -1;
             }
             $new = '';
             foreach (array(0 => 'Mon', 1 => 'Tue', 2 => 'Wed', 3 => 'Thu', 4 => 'Fri', 5 => 'Sat', 6 => 'Sun') as $k => $v) {
                 if (isset($values['recurrence_hash_' . $k]) && $values['recurrence_hash_' . $k]) {
                     $new .= '1';
                 } else {
                     $new .= '0';
                 }
             }
             if ($new != '0000000') {
                 $values['recurrence_hash'] = $new;
             }
             if ($values['duration'] != -1) {
                 if (isset($values['modded'])) {
                     $time = Base_RegionalSettingsCommon::time2reg($values['time'], true, true, true, false);
                     $reg_timestamp = $values['date'] . ' ' . date('H:i:s', strtotime($time));
                     $timestamp = Base_RegionalSettingsCommon::reg2time($reg_timestamp);
                     $values['date'] = date('Y-m-d', $timestamp);
                     $values['time'] = date('Y-m-d H:i:s', $timestamp);
                     if (isset($values['recurrence_end']) && $values['recurrence_end']) {
                         $values['recurrence_end'] = date('Y-m-d', Base_RegionalSettingsCommon::reg2time($values['recurrence_end'] . ' ' . date('H:i:s', strtotime($time))));
                         if ($values['recurrence_end'] < $values['date']) {
                             $values['recurrence_end'] = $values['date'];
                         }
                         if ($values['recurrence_type'] == 8) {
                             $date = date('Y-m-d', strtotime('+6 days', strtotime($values['date'])));
                             if ($values['recurrence_end'] < $date) {
                                 $values['recurrence_end'] = $date;
                             }
                         }
                     }
                 }
             } else {
                 $values['time'] = '';
             }
             break;
         case 'adding':
             $values['permission'] = Base_User_SettingsCommon::get('CRM_Common', 'default_record_permission');
         case 'editing':
         case 'view':
             $values['modded'] = 1;
             if (!isset($values['date'])) {
                 $values['date'] = date('Y-m-d');
             }
             if (!isset($values['time'])) {
                 $values['time'] = time();
             }
             if (!isset($values['duration'])) {
                 $values['duration'] = 3600;
             }
             if (!is_numeric($values['time'])) {
                 $values['time'] = strtotime($values['time']);
             }
             if ($values['duration'] != -1) {
                 if (isset($values['date']) && $values['date']) {
                     $values['date'] = Base_RegionalSettingsCommon::time2reg($values['date'] . ' ' . date('H:i:s', $values['time']), false, true, true, false);
                     $values['time'] = Base_RegionalSettingsCommon::time2reg($values['date'] . ' ' . date('H:i:s', $values['time']), true, false, true, false);
                     $values['time'] = Base_RegionalSettingsCommon::reg2time($values['date'] . ' ' . $values['time']);
                 }
                 if (isset($values['recurrence_end']) && $values['recurrence_end']) {
                     $values['recurrence_end'] = Base_RegionalSettingsCommon::time2reg($values['recurrence_end'] . ' ' . date('H:i:s', $values['time']), false, true, true, false);
                 }
             }
             break;
         case 'added':
             if (isset($values['follow_up'])) {
                 CRM_FollowupCommon::add_tracing_notes($values['follow_up'][0], $values['follow_up'][1], $values['follow_up'][2], 'meeting', $values['id'], $values['title']);
             }
             self::subscribed_employees($values);
             $related = array_merge($values['employees'], $values['customers']);
             foreach ($related as $v) {
                 if ($mode === 'edit' && in_array($v, $old_related)) {
                     continue;
                 }
                 if (!is_numeric($v)) {
                     list($t, $id) = explode(':', $v);
                 } else {
                     $t = 'P';
                     $id = $v;
                 }
                 if ($t == 'P') {
                     $t = 'contact';
                 } else {
                     $t = 'company';
                 }
                 $subs = Utils_WatchdogCommon::get_subscribers($t, $id);
                 foreach ($subs as $s) {
                     Utils_WatchdogCommon::user_subscribe($s, 'crm_meeting', $values['id']);
                 }
             }
             if (isset($values['messenger_on']) && $values['messenger_on'] != 'none') {
                 $start = strtotime($values['date'] . ' ' . date('H:i:s', strtotime($values['time'])));
                 if ($values['messenger_on'] == 'me') {
                     Utils_MessengerCommon::add('CRM_Calendar_Event:' . $values['id'], 'CRM_Meeting', $values['messenger_message'], $start - $values['messenger_before'], array('CRM_MeetingCommon', 'get_alarm'), array($values['id']));
                 } else {
                     $eee = array();
                     foreach ($values['employees'] as $v) {
                         $c = CRM_ContactsCommon::get_contact($v);
                         if (isset($c['login'])) {
                             $eee[] = $c['login'];
                         }
                     }
                     Utils_MessengerCommon::add('CRM_Calendar_Event:' . $values['id'], 'CRM_Meeting', $values['messenger_message'], $start - $values['messenger_before'], array('CRM_MeetingCommon', 'get_alarm'), array($values['id']), $eee);
                 }
             }
             break;
     }
     return $values;
 }
Exemple #5
0
<?php

/**
 *
 * @author Arkadiusz Bisaga <*****@*****.**>
 * @copyright Copyright &copy; 2008, Telaxus LLC
 * @license MIT
 * @version 1.0
 * @package epesi-utils
 * @subpackage Watchdog
 */
if (!isset($_POST['key']) || !isset($_POST['cid']) || !is_numeric($_POST['cid'])) {
    die('alert(\'Invalid request\')');
}
define('CID', $_POST['cid']);
define('READ_ONLY_SESSION', true);
require_once '../../../include.php';
ModuleManager::load_modules();
if (!Acl::is_user()) {
    die('Unauthorized access');
}
list($cat_id, $id) = explode('__', $_POST['key']);
if (!is_numeric($cat_id) || !is_numeric($id)) {
    die('Invalid use');
}
Utils_WatchdogCommon::notified($cat_id, $id);
Exemple #6
0
 protected function handle_special_field_crit(Utils_RecordBrowser_CritsSingle $crit)
 {
     $field = $crit->get_field();
     $operator = self::transform_meta_operators_to_sql($crit->get_operator());
     $value = $crit->get_value();
     $negation = $crit->get_negation();
     $special = $field[0] == ':' || $field == 'id';
     if ($special) {
         $sql = '';
         $vals = array();
         switch ($field) {
             case ':id':
             case 'id':
                 if (!is_array($value)) {
                     $sql = $this->tab_alias . ".id {$operator} %d";
                     $vals[] = $value;
                 } else {
                     if ($operator != '=' && $operator != '==') {
                         throw new Exception("Cannot use array values for id field operator '{$operator}'");
                     }
                     $clean_vals = array();
                     foreach ($value as $v) {
                         if (is_numeric($v)) {
                             $clean_vals[] = $v;
                         }
                     }
                     if (empty($clean_vals)) {
                         $sql = 'false';
                     } else {
                         $sql = $this->tab_alias . ".id IN (" . implode(',', $clean_vals) . ")";
                     }
                 }
                 if ($negation) {
                     $sql = "NOT ({$sql})";
                 }
                 break;
             case ':Fav':
                 $fav = $value == true;
                 if ($negation) {
                     $fav = !$fav;
                 }
                 if (!isset($this->applied_joins[$field])) {
                     $this->final_tab = '(' . $this->final_tab . ') LEFT JOIN ' . $this->tab . '_favorite AS ' . $this->tab_alias . '_fav ON ' . $this->tab_alias . '_fav.' . $this->tab . '_id=' . $this->tab_alias . '.id AND ' . $this->tab_alias . '_fav.user_id=' . Acl::get_user();
                     $this->applied_joins[$field] = true;
                 }
                 $rule = $fav ? 'IS NOT NULL' : 'IS NULL';
                 $sql = $this->tab_alias . "_fav.fav_id {$rule}";
                 break;
             case ':Sub':
                 $sub = $value == true;
                 if ($negation) {
                     $sub = !$sub;
                 }
                 if (!isset($this->applied_joins[$field])) {
                     $this->final_tab = '(' . $this->final_tab . ') LEFT JOIN utils_watchdog_subscription AS ' . $this->tab_alias . '_sub ON ' . $this->tab_alias . '_sub.internal_id=' . $this->tab_alias . '.id AND ' . $this->tab_alias . '_sub.category_id=' . Utils_WatchdogCommon::get_category_id($this->tab) . ' AND ' . $this->tab_alias . '_sub.user_id=' . Acl::get_user();
                     $this->applied_joins[$field] = true;
                 }
                 $rule = $sub ? 'IS NOT NULL' : 'IS NULL';
                 $sql = $this->tab_alias . "_sub.internal_id {$rule}";
                 break;
             case ':Recent':
                 $rec = $value == true;
                 if ($negation) {
                     $rec = !$rec;
                 }
                 if (!isset($this->applied_joins[$field])) {
                     $this->final_tab = '(' . $this->final_tab . ') LEFT JOIN ' . $this->tab . '_recent AS ' . $this->tab_alias . '_rec ON ' . $this->tab_alias . '_rec.' . $this->tab . '_id=' . $this->tab_alias . '.id AND ' . $this->tab_alias . '_rec.user_id=' . Acl::get_user();
                     $this->applied_joins[$field] = true;
                 }
                 $rule = $rec ? 'IS NOT NULL' : 'IS NULL';
                 $sql = $this->tab_alias . "_rec.user_id {$rule}";
                 break;
             case ':Created_on':
                 $vals[] = Base_RegionalSettingsCommon::reg2time($value, false);
                 $sql = $this->tab_alias . '.created_on ' . $operator . '%T';
                 if ($negation) {
                     $sql = "NOT ({$sql})";
                 }
                 break;
             case ':Created_by':
                 if (!is_array($value)) {
                     $value = array($value);
                 }
                 $sql = array();
                 foreach ($value as $v) {
                     $vals[] = $v;
                     $sql[] = $this->tab_alias . '.created_by = %d';
                 }
                 $sql = implode(' OR ', $sql);
                 if ($negation) {
                     $sql = "NOT ({$sql})";
                 }
                 break;
             case ':Edited_on':
                 $inj = $operator . '%T';
                 $sql = '(((SELECT MAX(edited_on) FROM ' . $this->tab . '_edit_history WHERE ' . $this->tab . '_id=' . $this->tab_alias . '.id) ' . $inj . ') OR ' . '((SELECT MAX(edited_on) FROM ' . $this->tab . '_edit_history WHERE ' . $this->tab . '_id=' . $this->tab_alias . '.id) IS NULL AND created_on ' . $inj . '))';
                 $timestamp = Base_RegionalSettingsCommon::reg2time($value, false);
                 if ($negation) {
                     $sql = "NOT (COALESCE({$sql}, FALSE))";
                 }
                 $vals[] = $timestamp;
                 $vals[] = $timestamp;
                 break;
         }
         return array($sql, $vals);
     }
     return false;
 }
Exemple #7
0
    public function view_entry($mode='view', $id = null, $defaults = array(), $show_actions=true) {
		Base_HelpCommon::screen_name('rb_'.$mode.'_'.$this->tab);
        if (isset($_SESSION['client']['recordbrowser']['admin_access'])) Utils_RecordBrowserCommon::$admin_access = true;
        self::$mode = $mode;
        if ($this->navigation_executed) {
            $this->navigation_executed = false;
            return true;
        }
        if ($this->check_for_jump()) return;
        $theme = $this->init_module('Base/Theme');
        if ($this->isset_module_variable('id')) {
            $id = $this->get_module_variable('id');
            $this->unset_module_variable('id');
        }
        self::$browsed_records = null;

        Utils_RecordBrowserCommon::$cols_order = array();
        $js = ($mode!='view');
        $time = microtime(true);
        if ($this->is_back()) {
            self::$clone_result = 'canceled';
            return $this->back();
        }

        $this->init();
		if (is_numeric($id)) {
	                $id = intVal($id);
			self::$last_record = $this->record = Utils_RecordBrowserCommon::get_record($this->tab, $id, $mode!=='edit');
		} else {
			self::$last_record = $this->record = $id;
			$id = intVal($this->record['id']);
		}
		if ($id===0) $id = null;
        if ($id!==null && is_numeric($id)) Utils_WatchdogCommon::notified($this->tab,$id);

        if($mode=='add') {
            foreach ($defaults as $k=>$v)
                $this->custom_defaults[$k] = $v;
            foreach($this->table_rows as $field => $args)
                if (!isset($this->custom_defaults[$args['id']]))
					$this->custom_defaults[$args['id']] = $args['type'] == 'multiselect' ? array() : '';
			$this->custom_defaults['created_by'] = Acl::get_user();
		}

        $access = $this->get_access($mode=='history'?'view':$mode, isset($this->record)?$this->record:$this->custom_defaults);
        if ($mode=='edit' || $mode=='add')
            $this->view_fields_permission = $this->get_access('view', isset($this->record)?$this->record:$this->custom_defaults);
        else
            $this->view_fields_permission = $access;

        if ($mode!='add' && (!$access || $this->record==null)) {
            if (Base_AclCommon::i_am_admin()) {
                Utils_RecordBrowserCommon::$admin_access = true;
                $access = $this->get_access($mode, isset($this->record)?$this->record:$this->custom_defaults);
                if ($mode=='edit' || $mode=='add')
                    $this->view_fields_permission = $this->get_access('view', isset($this->record)?$this->record:$this->custom_defaults);
                else
                    $this->view_fields_permission = $access;
            } else {
                print(__('You don\'t have permission to view this record.'));
                if ($show_actions===true || (is_array($show_actions) && (!isset($show_actions['back']) || $show_actions['back']))) {
                    Base_ActionBarCommon::add('back', __('Back'), $this->create_back_href());
                    //Utils_ShortcutCommon::add(array('esc'), 'function(){'.$this->create_back_href_js().'}');
                }
                return true;
            }
        }
        if ($mode=='add' && !$access) {
			print(__('You don\'t have permission to perform this action.'));
			if ($show_actions===true || (is_array($show_actions) && (!isset($show_actions['back']) || $show_actions['back']))) {
				Base_ActionBarCommon::add('back', __('Back'), $this->create_back_href());
				//Utils_ShortcutCommon::add(array('esc'), 'function(){'.$this->create_back_href_js().'}');
			}
			return true;
		}

        if($mode == 'add' || $mode == 'edit') {
            $theme -> assign('click2fill', '<div id="c2fBox"></div>');
            load_js('modules/Utils/RecordBrowser/click2fill.js');
            eval_js('initc2f("'.__('Scan/Edit').'","'.__('Paste data here with Ctrl-v, click button below, then click on separated words in specific order and click in text field where you want put those words. They will replace text in that field.').'")');
            Base_ActionBarCommon::add('clone', __('Click 2 Fill'), 'href="javascript:void(0)" onclick="c2f()"');
        }

//        if ($mode!='add' && !$this->record[':active'] && !Base_AclCommon::i_am_admin()) return $this->back();

        $tb = $this->init_module('Utils/TabbedBrowser', null, 'recordbrowser_addons');
		if ($mode=='history') $tb->set_inline_display();
        self::$tab_param = $tb->get_path();

        $form = $this->init_module('Libs/QuickForm',null, $mode);
        if(Base_User_SettingsCommon::get($this->get_type(), 'confirm_leave') && ($mode == 'add' || $mode == 'edit'))
        	$form->set_confirm_leave_page();
        
        $this->form = $form;

        if($mode!='add')
            Utils_RecordBrowserCommon::add_recent_entry($this->tab, Acl::get_user(),$id);

		$dp = Utils_RecordBrowserCommon::record_processing($this->tab, $mode!='add'?$this->record:$this->custom_defaults, ($mode=='view' || $mode=='history')?'view':$mode.'ing');
		if($dp===false) return false;
		if (is_array($dp))
			$defaults = $this->custom_defaults = self::$last_record = $this->record = $dp;

        if (self::$last_record===null) self::$last_record = $defaults;
        if($mode=='add')
            $form->setDefaults($defaults);

        switch ($mode) {
            case 'add':     $this->action = _M('New record'); break;
            case 'edit':    $this->action = _M('Edit record'); break;
            case 'view':    $this->action = _M('View record'); break;
            case 'history':    $this->action = _M('Record history view'); break;
        }

        $this->prepare_view_entry_details($this->record, $mode=='history'?'view':$mode, $id, $form);

        if ($mode==='edit' || $mode==='add')
            foreach($this->table_rows as $field => $args) {
                if (!$access[$args['id']])
                    $form->freeze($args['id']);
            }
        if ($form->exportValue('submited') && $form->validate()) {
            $values = $form->exportValues();
			
			foreach ($defaults as $k=>$v) {
				if (!isset($values[$k]) && isset($this->view_fields_permission[$k]) && !$this->view_fields_permission[$k]) $values[$k] = $v;
				if (isset($access[$k]) && !$access[$k]) $values[$k] = $v;
			}
            foreach ($this->table_rows as $v) {
                if ($v['type']=='checkbox' && !isset($values[$v['id']])) $values[$v['id']]=0;
            }
            $values['id'] = $id;
            foreach ($this->custom_defaults as $k=>$v)
                if (!isset($values[$k])) $values[$k] = $v;
            if ($mode=='add') {
                $id = Utils_RecordBrowserCommon::new_record($this->tab, $values);
                self::$clone_result = $id;
                self::$clone_tab = $this->tab;
                return $this->back();
            }
            $time_from = date('Y-m-d H:i:s', $this->get_module_variable('edit_start_time'));
            $ret = DB::Execute('SELECT * FROM '.$this->tab.'_edit_history WHERE edited_on>=%T AND edited_on<=%T AND '.$this->tab.'_id=%d',array($time_from, date('Y-m-d H:i:s'), $id));
            if ($ret->EOF) {
                $this->update_record($id,$values);
                return $this->back();
            }
            $this->dirty_read_changes($id, $time_from);
        }
		$form->add_error_closing_buttons();

        if (($mode=='edit' || $mode=='add') && $show_actions!==false) {
            Utils_ShortcutCommon::add(array('Ctrl','S'), 'function(){'.$form->get_submit_form_js().'}');
        }
        if ($mode=='edit') {
            $this->set_module_variable('edit_start_time',$time);
        }

        if ($show_actions!==false) {
            if ($mode=='view') {
                if ($this->get_access('edit',$this->record)) {
                    Base_ActionBarCommon::add('edit', __('Edit'), $this->create_callback_href(array($this,'navigate'), array('view_entry','edit',$id)));
                    Utils_ShortcutCommon::add(array('Ctrl','E'), 'function(){'.$this->create_callback_href_js(array($this,'navigate'), array('view_entry','edit',$id)).'}');
                }
                if ($this->get_access('delete',$this->record)) {
                    Base_ActionBarCommon::add('delete', __('Delete'), $this->create_confirm_callback_href(__('Are you sure you want to delete this record?'),array($this,'delete_record'),array($id)));
                }
                if ($this->get_access('add',$this->record)) {
                    Base_ActionBarCommon::add('clone',__('Clone'), $this->create_confirm_callback_href(__('You are about to create a copy of this record. Do you want to continue?'),array($this,'clone_record'),array($id)));
                }
                /** @var Base_Print_Printer $printer */
                $printer = Utils_RecordBrowserCommon::get_printer($this->tab);
                if ($printer) {
                    Base_ActionBarCommon::add('print', __('Print'), $printer->get_href(array('tab' => $this->tab, 'record_id' => $this->record['id'])));
                }
                if ($show_actions===true || (is_array($show_actions) && (!isset($show_actions['back']) || $show_actions['back'])))
                    Base_ActionBarCommon::add('back', __('Back'), $this->create_back_href());
            } elseif($mode!='history') {
                Base_ActionBarCommon::add('save', __('Save'), $form->get_submit_form_href());
                Base_ActionBarCommon::add('delete', __('Cancel'), $this->create_back_href());
            }
            //Utils_ShortcutCommon::add(array('esc'), 'function(){'.$this->create_back_href_js().'}');
        }

        if ($mode!='add') {
            $theme -> assign('info_tooltip', '<a '.Utils_TooltipCommon::open_tag_attrs(Utils_RecordBrowserCommon::get_html_record_info($this->tab, $id)).'><img border="0" src="'.Base_ThemeCommon::get_template_file('Utils_RecordBrowser','info.png').'" /></a>');
            $row_data= array();

			if ($mode!='history') {
				if ($this->favorites)
					$theme -> assign('fav_tooltip', Utils_RecordBrowserCommon::get_fav_button($this->tab, $id));
				if ($this->watchdog)
					$theme -> assign('subscription_tooltip', Utils_WatchdogCommon::get_change_subscription_icon($this->tab, $id));
				if ($this->full_history) {
					$info = Utils_RecordBrowserCommon::get_record_info($this->tab, $id);
					if ($info['edited_on']===null) $theme -> assign('history_tooltip', '<a '.Utils_TooltipCommon::open_tag_attrs(__('This record was never edited')).'><img border="0" src="'.Base_ThemeCommon::get_template_file('Utils_RecordBrowser','history_inactive.png').'" /></a>');
					else $theme -> assign('history_tooltip', '<a '.Utils_TooltipCommon::open_tag_attrs(__('Click to view edit history of currently displayed record')).' '.$this->create_callback_href(array($this,'navigate'), array('view_edit_history', $id)).'><img border="0" src="'.Base_ThemeCommon::get_template_file('Utils_RecordBrowser','history.png').'" /></a>');
				}
				if ($this->clipboard_pattern) {
					$theme -> assign('clipboard_tooltip', '<a '.Utils_TooltipCommon::open_tag_attrs(__('Click to export values to copy')).' '.Libs_LeightboxCommon::get_open_href('clipboard').'><img border="0" src="'.Base_ThemeCommon::get_template_file('Utils_RecordBrowser','clipboard.png').'" /></a>');
					$text = $this->clipboard_pattern;
					$record = Utils_RecordBrowserCommon::get_record($this->tab, $id);
					/* for every field name store its value */
					$data = array();
					foreach($this->table_rows as $val) {
						$fval = Utils_RecordBrowserCommon::get_val($this->tab, $val['id'], $record, true);
						if(strlen($fval)) $data[$val['id']] = $fval;
					}
					/* some complicate preg match to find every occurence
					 * of %{ .. {f_name} .. } pattern
					 */
                    if (preg_match_all('/%\{(([^%\}\{]*?\{[^%\}\{]+?\}[^%\}\{]*?)+?)\}/', $text, $match)) { // match for all patterns %{...{..}...}
                        foreach ($match[0] as $k => $matched_string) {
                            $text_replace = $match[1][$k];
                            $changed = false;
                            while(preg_match('/\{(.+?)\}/', $text_replace, $second_match)) { // match for keys in braces {key}
                                $replace_value = '';
                                if(array_key_exists($second_match[1], $data)) {
                                    $replace_value = $data[$second_match[1]];
                                    $changed = true;
                                }
                                $text_replace = str_replace($second_match[0], $replace_value, $text_replace);
                            }
                            if(! $changed ) $text_replace = '';
                            $text = str_replace($matched_string, $text_replace, $text);
                        }
                    }
					load_js("modules/Utils/RecordBrowser/selecttext.js");
					/* remove all php new lines, replace <br>|<br/> to new lines and quote all special chars */
					$ftext = htmlspecialchars(preg_replace('#<[bB][rR]/?>#', "\n", str_replace("\n", '', $text)));
					$flash_copy = '<object width="60" height="20">'.
								'<param name="FlashVars" value="txtToCopy='.$ftext.'">'.
								'<param name="movie" value="'.$this->get_module_dir().'copyButton.swf">'.
								'<embed src="'.$this->get_module_dir().'copyButton.swf" flashvars="txtToCopy='.$ftext.'" width="60" height="20">'.
								'</embed>'.
								'</object>';
					$text = '<h3>'.__('Click Copy under the box or move mouse over box below to select text and hit Ctrl-c to copy it.').'</h3><div onmouseover="fnSelect(this)" style="border: 1px solid gray; margin: 15px; padding: 20px;">'.$text.'</div>'.$flash_copy;

					Libs_LeightboxCommon::display('clipboard',$text,__('Copy'));
				}
			}
        }

		if ($mode=='view') {
			$dp = Utils_RecordBrowserCommon::record_processing($this->tab, $this->record, 'display');
			if ($dp && is_array($dp))
				foreach ($dp as $k=>$v)
					$theme->assign($k, $v);
		}

        if ($mode=='view' || $mode=='history') $form->freeze();
        $renderer = new HTML_QuickForm_Renderer_TCMSArraySmarty();
        $form->accept($renderer);
        $data = $renderer->toArray();

        print($data['javascript'].'<form '.$data['attributes'].'>'.$data['hidden']."\n");

        $last_page = DB::GetOne('SELECT MIN(position) FROM '.$this->tab.'_field WHERE type = \'page_split\' AND field != \'General\'');
		if (!$last_page) $last_page = DB::GetOne('SELECT MAX(position) FROM '.$this->tab.'_field')+1;
        $label = DB::GetRow('SELECT field, param FROM '.$this->tab.'_field WHERE position=%s', array($last_page));
		if ($label) {
			$cols = $label['param'];
			$label = $label['field'];
		} else $cols = false;

        $this->view_entry_details(1, $last_page, $data, $theme, true);
        $ret = DB::Execute('SELECT position, field, param FROM '.$this->tab.'_field WHERE type = \'page_split\' AND position > %d ORDER BY position', array($last_page));
        $row = true;
        if ($mode=='view')
            print("</form>\n");
        $tab_counter=-1;
		$additional_tabs = 0;
		$default_tab = null;
        while ($row) {
            $row = $ret->FetchRow();
            if ($row) $pos = $row['position'];
            else $pos = DB::GetOne('SELECT MAX(position) FROM '.$this->tab.'_field WHERE active=1')+1;

            $valid_page = false;
			$hide_page = ($mode=='view' && Base_User_SettingsCommon::get('Utils/RecordBrowser','hide_empty'));
            foreach($this->table_rows as $field => $args) {
                if (!isset($data[$args['id']]) || $data[$args['id']]['type']=='hidden') continue;
                if ($args['position'] >= $last_page && ($pos+1 == -1 || $args['position'] < $pos+1)) {
                    $valid_page = true;
					if ($hide_page && !$this->field_is_empty($this->record, $args['id'])) $hide_page = false;
                    break;
                }
            }
            if ($valid_page && $pos - $last_page>1 && !isset($this->hide_tab[$label])) {
				$tb->set_tab(_V($label),array($this,'view_entry_details'), array($last_page, $pos+1, $data, null, false, $cols, _V($label)), $js); // TRSL
				if ($hide_page) {
					eval_js('$("'.$tb->get_tab_id(_V($label)).'").style.display="none";');
					if ($default_tab===($tab_counter+1) || $tb->get_tab()==($tab_counter+1)) $default_tab = $tab_counter+2;
				} else
					$additional_tabs++;
			}
            $cols = $row['param'];
            $last_page = $pos;
            if ($row) $label = $row['field'];
            $tab_counter++;
        }
		if ($default_tab!==null) $tb->set_default_tab($default_tab);
        if ($mode!='history') {
            $ret = DB::Execute('SELECT * FROM recordbrowser_addon WHERE tab=%s AND enabled=1 ORDER BY pos', array($this->tab));
            $addons_mod = array();
            while ($row = $ret->FetchRow()) {
                if (ModuleManager::is_installed($row['module'])==-1) continue;
                if (is_callable(explode('::',$row['label']))) {
                    $result = call_user_func(explode('::',$row['label']), $this->record, $this);
                    if (!isset($result['show'])) $result['show']=true;
					if (($mode=='add' || $mode=='edit') && (!isset($result['show_in_edit']) || !$result['show_in_edit'])) continue;
                    if ($result['show']==false) continue;
                    if (!isset($result['label'])) $result['label']='';
                    $row['label'] = $result['label'];
                } else {
					if ($mode=='add' || $mode=='edit') continue;
					$labels = explode('#',$row['label']);
					foreach($labels as $i=>$label) $labels[$i] = _V($label); // translate labels from database
					$row['label'] = implode('#',$labels);
				}
                $mod_id = md5(serialize($row));
				if (method_exists($row['module'].'Common',$row['func'].'_access') && !call_user_func(array($row['module'].'Common',$row['func'].'_access'), $this->record, $this)) continue;
                $addons_mod[$mod_id] = $this->init_module($row['module']);
                if (!method_exists($addons_mod[$mod_id],$row['func'])) $tb->set_tab($row['label'],array($this, 'broken_addon'), array(), $js);
                else $tb->set_tab($row['label'],array($this, 'display_module'), array(& $addons_mod[$mod_id], array($this->record, $this), $row['func']), $js);
            }
        }
        if ($additional_tabs==0 && ($mode=='add' || $mode=='edit' || $mode=='history'))
            print("</form>\n");
        $this->display_module($tb);
        $tb->tag();
		
		foreach ($this->fields_in_tabs as $label=>$fields) {
			$highlight = false;
			foreach ($fields as $f) {
				$err = $form->getElementError($f);
				if ($err) {
					$highlight = true;
					break;
				}
			}
			if ($highlight)
				$tb->tab_icon($label, Base_ThemeCommon::get_template_file('Utils_RecordBrowser','notify_error.png'));
		}
		
        if ($this->switch_to_addon) {
    	    $this->set_module_variable('switch_to_addon',false);
            if($tab_counter<0) $tab_counter=0;
            $ret = DB::Execute('SELECT * FROM recordbrowser_addon WHERE tab=%s AND enabled=1 ORDER BY pos', array($this->tab));
            while ($row = $ret->FetchRow()) {
                if (ModuleManager::is_installed($row['module'])==-1) continue;
                if (is_callable(explode('::',$row['label']))) {
                    $result = call_user_func(explode('::',$row['label']), $this->record,$this);
                    if (isset($result['show']) && $result['show']==false) continue;
                    $row['label'] = $result['label'];
                }
                if ($row['label']==$this->switch_to_addon) $this->switch_to_addon = $tab_counter;
                $tab_counter++;
            }
            $tb->switch_tab($this->switch_to_addon);
            location(array());
        }
        if ($additional_tabs!=0 && ($mode=='add' || $mode=='edit' || $mode=='history'))
            print("</form>\n");

        return true;
    } //view_entry
Exemple #8
0
/**
 * @author Arkadiusz Bisaga <*****@*****.**>
 * @copyright Copyright &copy; 2008, Telaxus LLC
 * @license MIT
 * @version 1.0
 * @package epesi-utils
 * @subpackage watchdog
 */
if (!isset($_POST['id']) || !isset($_POST['state']) || !isset($_POST['element']) || !isset($_POST['cat']) || !isset($_POST['cid'])) {
    die('Invalid request: ' . print_r($_POST, true));
}
define('JS_OUTPUT', 1);
define('CID', $_POST['cid']);
define('READ_ONLY_SESSION', true);
require_once '../../../include.php';
ModuleManager::load_modules();
$id = json_decode($_POST['id']);
$cat = json_decode($_POST['cat']);
$state = json_decode($_POST['state']);
$element = json_decode($_POST['element']);
if (!Acl::is_user()) {
    die('alert("Unauthorized access");');
}
if ($state) {
    Utils_WatchdogCommon::subscribe($cat, $id);
} else {
    Utils_WatchdogCommon::unsubscribe($cat, $id);
}
print 'jq("#' . $element . '").html("' . Epesi::escapeJS(Utils_WatchdogCommon::get_change_subscription_icon_tags($cat, $id)) . '");';
Exemple #9
0
 private function archive($uids, $verbose = true)
 {
     global $E_SESSION;
     $rcmail = rcmail::get_instance();
     $path = getcwd();
     chdir(str_replace(array('/modules/CRM/Roundcube/RC', '\\modules\\CRM\\Roundcube\\RC'), '', $path));
     $msgs = array();
     if (!is_array($uids)) {
         $uids = $uids->get();
     }
     foreach ($uids as $uid) {
         $msg = new rcube_message($uid);
         if ($msg === null || empty($msg->headers)) {
             if ($verbose) {
                 $rcmail->output->command('display_message', 'messageopenerror', 'error');
             }
             return false;
         } else {
             $msgs[$uid] = $msg;
         }
     }
     $map = array();
     foreach ($msgs as $k => $msg) {
         $sends = $rcmail->storage->decode_address_list($msg->headers->to);
         $map[$k] = array();
         foreach ($sends as $send) {
             $addr = $send['mailto'];
             $ret = $this->look_contact($addr);
             $map[$k] = array_merge($map[$k], $ret);
         }
         $addr = $rcmail->storage->decode_address_list($msg->headers->from);
         if ($addr) {
             $addr = array_shift($addr);
         }
         if (!isset($addr['mailto']) || !$addr['mailto']) {
             $map[$k] = false;
             continue;
         }
         $ret = $this->look_contact($addr['mailto']);
         $map[$k] = array_merge($map[$k], $ret);
     }
     if (!isset($_SESSION['force_archive'])) {
         $_SESSION['force_archive'] = array();
     }
     foreach ($map as $k => $ret) {
         if (!$ret && !isset($_SESSION['force_archive'][$k]) && $verbose) {
             $_SESSION['force_archive'][$k] = 1;
             $rcmail->output->command('display_message', $this->gettext('contactnotfound'), 'error');
             return false;
         }
     }
     $attachments_dir = DATA_DIR . '/CRM_Roundcube/attachments/';
     $epesi_mails = array();
     if (!file_exists($attachments_dir)) {
         mkdir($attachments_dir);
     }
     foreach ($msgs as $k => $msg) {
         $contacts = $map[$k];
         $mime_map = array();
         foreach ($msg->mime_parts as $mid => $m) {
             $mime_map[$m->mime_id] = md5($k . microtime(true) . $mid);
         }
         if ($msg->has_html_part()) {
             //            $body = $msg->first_html_part();
             foreach ($msg->mime_parts as $mime_id => $part) {
                 $mimetype = strtolower($part->ctype_primary . '/' . $part->ctype_secondary);
                 if ($mimetype == 'text/html') {
                     $body = $rcmail->storage->get_message_part($msg->uid, $mime_id, $part);
                     if (isset($part->replaces)) {
                         $cid_map = $part->replaces;
                     } else {
                         $cid_map = array();
                     }
                     break;
                 }
             }
             foreach ($cid_map as $k => &$v) {
                 if (preg_match('/_part=(.*?)&/', $v, $matches)) {
                     $mid = $matches[1];
                     if (isset($mime_map[$mid])) {
                         $v = 'get.php?' . http_build_query(array('mail_id' => '__MAIL_ID__', 'mime_id' => $mime_map[$mid]));
                     }
                 } else {
                     unset($cid_map[$k]);
                 }
             }
             $body = rcmail_wash_html($body, array('safe' => true, 'inline_html' => true), $cid_map);
         } else {
             $body = '<pre>' . $msg->first_text_part() . '</pre>';
         }
         $date = rcube_imap_generic::strToTime($msg->get_header('DATE'));
         $headers = array();
         foreach ($msg->headers as $k => $v) {
             if (is_string($v) && $k != 'from' && $k != 'to' && $k != 'body_structure') {
                 $headers[] = $k . ': ' . rcube_mime::decode_mime_string((string) $v);
             }
         }
         $message_id = str_replace(array('<', '>'), '', $msg->get_header('MESSAGE-ID'));
         if (Utils_RecordBrowserCommon::get_records_count('rc_mails', array('message_id' => $message_id)) > 0) {
             $rcmail->output->command('display_message', $this->gettext('archived_duplicate'), 'warning');
             return false;
         }
         $employee = DB::GetOne('SELECT id FROM contact_data_1 WHERE active=1 AND f_login=%d', array($E_SESSION['user']));
         $data = array('message_id' => $message_id, 'references' => $msg->get_header('REFERENCES'), 'contacts' => $contacts, 'date' => $date, 'subject' => substr($msg->subject, 0, 256), 'body' => $body, 'headers_data' => implode("\n", $headers), 'from' => $rcmail->storage->decode_header($msg->headers->from), 'to' => $rcmail->storage->decode_header($msg->headers->to), 'employee' => $employee);
         $id = Utils_RecordBrowserCommon::new_record('rc_mails', $data);
         $epesi_mails[] = $id;
         foreach ($contacts as $c) {
             list($rs, $con_id) = explode(':', $c);
             if ($rs == 'P') {
                 Utils_WatchdogCommon::new_event('contact', $con_id, 'N_New mail');
             } else {
                 Utils_WatchdogCommon::new_event('company', $con_id, 'N_New mail');
             }
         }
         Utils_WatchdogCommon::new_event('contact', $employee, 'N_New mail');
         /*DB::Execute('INSERT INTO rc_mails_data_1(created_on,created_by,f_contacts,f_date,f_employee,f_subject,f_body,f_headers_data,f_direction) VALUES(%T,%d,%s,%T,%d,%s,%s,%s,%b)',array(
                       time(),$E_SESSION['user'],$contacts,$date,$employee,substr($msg->subject,0,256),$body,implode("\n",$headers),$sent_mbox));
           $id = DB::Insert_ID('rc_mails_data_1','id');*/
         foreach ($msg->mime_parts as $mid => $m) {
             if (!$m->disposition) {
                 continue;
             }
             if (isset($cid_map['cid:' . $m->content_id])) {
                 $attachment = 0;
             } else {
                 $attachment = 1;
             }
             DB::Execute('INSERT INTO rc_mails_attachments(mail_id,type,name,mime_id,attachment) VALUES(%d,%s,%s,%s,%b)', array($id, $m->mimetype, $m->filename, $mime_map[$m->mime_id], $attachment));
             if (!file_exists($attachments_dir . $id)) {
                 mkdir($attachments_dir . $id);
             }
             $fp = fopen($attachments_dir . $id . '/' . $mime_map[$m->mime_id], 'w');
             $msg->get_part_content($m->mime_id, $fp);
             fclose($fp);
         }
     }
     //$rcmail->output->command('delete_messages');
     $E_SESSION['rc_mails_cp'] = $epesi_mails;
     chdir($path);
     return true;
 }
Exemple #10
0
 public static function display_contacts_with_notification($recordset, $record, $nolink, $desc)
 {
     $icon_on = Utils_TooltipCommon::open_tag_attrs(__('This person is up to date with all changes made to this record.')) . ' src="' . Base_ThemeCommon::get_template_file('Utils_Watchdog', 'watching_small.png') . '"';
     $icon_off = Utils_TooltipCommon::open_tag_attrs(__('This person has notifications pending about changes made to this record.')) . ' src="' . Base_ThemeCommon::get_template_file('Utils_Watchdog', 'watching_small_new_events.png') . '"';
     $icon_none = Utils_TooltipCommon::open_tag_attrs(__('This person is not watching this record.')) . ' src="' . Base_ThemeCommon::get_template_file('Utils_Watchdog', 'not_watching_small.png') . '"';
     $v = $record[$desc['id']];
     $def = '';
     $first = true;
     $param = explode(';', $desc['param']);
     if (!is_array($v) && !is_numeric($v)) {
         return $v;
     }
     if ($param[1] == '::') {
         $callback = array('CRM_ContactsCommon', 'contact_format_default');
     } else {
         $callback = explode('::', $param[1]);
     }
     if (!is_array($v)) {
         $v = array($v);
     }
     foreach ($v as $k => $w) {
         if ($w == '') {
             break;
         }
         if ($first) {
             $first = false;
         } else {
             $def .= '<br>';
         }
         $contact = CRM_ContactsCommon::get_contact($w);
         if (!$nolink) {
             if ($contact['login'] == '') {
                 $icon = $icon_none;
             } else {
                 $icon = Utils_WatchdogCommon::user_check_if_notified($contact['login'], $recordset, $record['id']);
                 if ($icon === null) {
                     $icon = $icon_none;
                 } elseif ($icon === true) {
                     $icon = $icon_on;
                 } else {
                     $icon = $icon_off;
                 }
             }
             $def .= '<img style="margin-right:4px;" ' . $icon . ' />';
         }
         $def .= Utils_RecordBrowserCommon::no_wrap(call_user_func($callback, $contact, $nolink));
     }
     if (!$def) {
         $def = '---';
     }
     return $def;
 }
Exemple #11
0
 public static function notification()
 {
     /*$methods = DB::GetAssoc('SELECT id,callback FROM utils_watchdog_category');
     		foreach ($methods as $k=>$v) { 
     			$methods[$k] = explode('::',$v);
     		}
             $time_sql = $time ? ' AND uwe.event_time > %T' : '';
     		$only_new = " AND last_seen_event<(SELECT MAX(id) FROM utils_watchdog_event AS uwe WHERE uwe.internal_id=uws.internal_id AND uwe.category_id=uws.category_id$time_sql)";
             $args = array(Acl::get_user());
             if ($time) {
                 $args[] = $time;
             }
             $records = DB::GetAll('SELECT internal_id,category_id,last_seen_event FROM utils_watchdog_subscription AS uws WHERE user_id=%d '.$only_new, $args);
     		$ret = array();
     		$tray = array();
             if ($records) {
                 $last_event_id = DB::GetOne('SELECT MAX(id) FROM utils_watchdog_event');
                 foreach ($records as $v) {
                     $changes = Utils_WatchdogCommon::check_if_notified($v['category_id'], $v['internal_id']);
                     if (!is_array($changes)) $changes = array();
                     $data = call_user_func($methods[$v['category_id']], $v['internal_id'], $changes, false);
                     if ($data==null) continue;
     
                     $msg = __("You've got unread notifications");
                     $ret['watchdog_'. $last_event_id] = '<b>'.__('Watchdog - %s', array($msg)).'</b> ';
                     $tray['watchdog_' . $last_event_id] = array('title'=>__('Watchdog'), 'body'=>$msg);
                     break;
                 }
             }*/
     $ret = array();
     $tray = array();
     $methods = DB::GetAssoc('SELECT id,callback FROM utils_watchdog_category');
     $only_new = ' AND last_seen_event<(SELECT MAX(id) FROM utils_watchdog_event AS uwe WHERE uwe.internal_id=uws.internal_id AND uwe.category_id=uws.category_id)';
     $records = DB::GetAll('SELECT internal_id,category_id FROM utils_watchdog_subscription AS uws WHERE user_id=%d ' . $only_new, array(Acl::get_user()));
     foreach ($records as $rec_key => $w) {
         $k = $w['internal_id'];
         $v = $w['category_id'];
         $changes = Utils_WatchdogCommon::check_if_notified($v, $k);
         if (!is_array($changes)) {
             $changes = array();
         }
         $data = call_user_func($methods[$v], $k, $changes);
         if ($data == null) {
             // mark events as seen when user can't see them
             Utils_WatchdogCommon::notified($v, $k);
             unset($records[$rec_key]);
             continue;
         }
         $ret['watchdog_' . $v . '_' . $k] = '<b>' . __('Watchdog - %s: %s', array($data['category'], $data['title'])) . '</b>' . (isset($data['events']) ? '<br />' . $data['events'] : '');
         $tray['watchdog_' . $v . '_' . $k] = array('title' => __('Watchdog - %s', array($data['category'])), 'body' => $data['title']);
     }
     return array('notifications' => $ret, 'tray' => $tray);
 }
Exemple #12
0
 /**
  * Create new watchdog event for record if $group denotes record.
  *
  * @param string $group   <Recordset>/<Id>
  * @param string $action  Action string
  * @param int    $note_id Note id
  *
  * @return bool True if events has been created, false otherwise
  */
 public static function new_watchdog_event($group, $action, $note_id)
 {
     $param = explode('/', $group);
     if (count($param)==2 && preg_match('/^[1-9][0-9]*$/', $param[1])) {
         Utils_WatchdogCommon::new_event($param[0], $param[1], implode('_', array('N', $action, $note_id, time(), Base_AclCommon::get_user())));
         return true;
     }
     return false;
 }
Exemple #13
0
 public function applet($conf, &$opts)
 {
     $categories = array();
     $methods = DB::GetAssoc('SELECT id,callback FROM utils_watchdog_category');
     foreach ($methods as $k => $v) {
         $methods[$k] = explode('::', $v);
         if (isset($conf['category_' . $k]) && $conf['category_' . $k] && is_numeric($k)) {
             $categories[] = $k;
         }
     }
     if (empty($categories)) {
         print __('No category selected');
         return;
     }
     $records_limit = isset($conf['records_limit']) ? $conf['records_limit'] : 15;
     if ($records_limit == '__all__') {
         $records_limit = null;
     }
     $header = array(array('name' => __('Cat.'), 'width' => 5), array('name' => __('Title'), 'width' => 15));
     if (count($categories) == 1) {
         $title = call_user_func($methods[$categories[0]]);
         $opts['title'] = __('Watchdog - %s', array($title['category']));
         $header = array(array('name' => __('Title')));
     } elseif (count($categories) == count($methods)) {
         $opts['title'] = __('Watchdog - All');
     } else {
         $opts['title'] = __('Watchdog - Selection');
     }
     $only_new = ' AND last_seen_event<(SELECT MAX(id) FROM utils_watchdog_event AS uwe WHERE uwe.internal_id=uws.internal_id AND uwe.category_id=uws.category_id)';
     $records = DB::GetAll('SELECT internal_id,category_id FROM utils_watchdog_subscription AS uws WHERE user_id=%d ' . $only_new . 'AND category_id IN (' . implode(',', $categories) . ')', array(Acl::get_user()));
     $gb = $this->init_module(Utils_GenericBrowser::module_name(), 'subscriptions', 'subscriptions');
     $gb->set_table_columns($header);
     $something_to_purge = false;
     $count = 0;
     foreach ($records as $rec_key => $w) {
         $k = $w['internal_id'];
         $v = $w['category_id'];
         $changes = Utils_WatchdogCommon::check_if_notified($v, $k);
         if (!is_array($changes)) {
             $changes = array();
         }
         $data = call_user_func($methods[$v], $k, $changes);
         if ($data == null) {
             // mark events as seen when user can't see them
             Utils_WatchdogCommon::notified($v, $k);
             unset($records[$rec_key]);
             continue;
         }
         $gb_row = $gb->get_new_row();
         if (count($categories) == 1) {
             $gb_row->add_data($data['title']);
         } else {
             $gb_row->add_data($data['category'], $data['title']);
         }
         $gb_row->add_action(Utils_WatchdogCommon::get_confirm_change_subscr_href($v, $k), 'Stop Watching', __('Click to stop watching this record for changes'), Base_ThemeCommon::get_template_file(Utils_Watchdog::module_name(), 'watching_small_new_events.png'));
         $gb_row->add_action($data['view_href'], 'View');
         if ($only_new || Utils_WatchdogCommon::check_if_notified($v, $k) !== true) {
             $gb_row->set_attrs('name="watchdog_table_row_' . $v . '__' . $k . '"');
             load_js('modules/Utils/Watchdog/applet_mark_as_read.js');
             $gb_row->add_action('href="javascript:void(0);" onclick="watchdog_applet_mark_as_read(\'' . $v . '__' . $k . '\')"', 'Mark as Read', __('Mark as read'), Base_ThemeCommon::get_template_file(Utils_Watchdog::module_name(), 'mark_as_read.png'));
             $something_to_purge = true;
         }
         if (isset($data['events']) && $data['events']) {
             $gb_row->add_info($data['events'], true);
         }
         $count++;
         if ($records_limit && $count >= $records_limit) {
             break;
         }
     }
     $records_qty = count($records);
     if ($records_limit && $count < $records_qty) {
         print __('Displaying %s of %s records', array($count, $records_qty));
     }
     $this->set_module_variable('display_at_time', time());
     if ($something_to_purge) {
         $opts['actions'][] = '<a ' . Utils_TooltipCommon::open_tag_attrs(__('Mark all entries as read')) . ' ' . $this->create_confirm_callback_href(__('This will mark all entries in selected categories as read, are you sure you want to continue?'), array($this, 'purge_subscriptions_applet'), array($categories)) . '><img src="' . Base_ThemeCommon::get_template_file('Utils_Watchdog', 'purge.png') . '" border="0"></a>';
     }
     $this->display_module($gb);
 }
Exemple #14
0
 public static function subscribe_users_to_record($record)
 {
     $employee = $record['employee'];
     $contacts = $record['contacts'];
     $subscribers = $employee ? Utils_WatchdogCommon::get_subscribers('contact', $employee) : array();
     foreach ($contacts as $c) {
         list($rs, $con_id) = explode(':', $c);
         $rs_full = $rs == 'P' ? 'contact' : 'company';
         $subscribers = array_merge($subscribers, Utils_WatchdogCommon::get_subscribers($rs_full, $con_id));
     }
     foreach (array_unique($subscribers) as $user_id) {
         Utils_WatchdogCommon::user_subscribe($user_id, 'rc_mails', $record['id']);
     }
 }
        $files_checkpoint->require_time(2);
        $row['aid'] = $map[$row['attach_id']];
        @mkdir(DATA_DIR . '/Utils_Attachment/' . $row['aid']);
        @rename(DATA_DIR . '/Utils_Attachment/' . $row['local'] . '/' . $row['id'], DATA_DIR . '/Utils_Attachment/' . $row['aid'] . '/' . $row['id']);
        DB::Execute('UPDATE utils_attachment_file SET attach_id=%d WHERE id=%d', array($row['aid'], $row['id']));
        $files_checkpoint->set('files', $files);
    }
    $files_checkpoint->done();
}
Patch::set_message('Updating database');
$new_fk_checkpoint = Patch::checkpoint('create_new_fk');
if (!$new_fk_checkpoint->is_done()) {
    Patch::require_time(5);
    if (DB::is_mysql()) {
        DB::Execute('ALTER TABLE utils_attachment_file ADD FOREIGN KEY (attach_id) REFERENCES utils_attachment_data_1(id)');
    } else {
        DB::Execute('ALTER TABLE utils_attachment_file ADD CONSTRAINT attach_id_fk FOREIGN KEY (attach_id) REFERENCES utils_attachment_data_1');
    }
    $new_fk_checkpoint->done();
}
Patch::set_message('Finishing');
$cleanup_checkpoint = Patch::checkpoint('cleanup');
if (!$cleanup_checkpoint->is_done()) {
    Patch::require_time(3);
    DB::DropTable('utils_attachment_note');
    DB::DropTable('utils_attachment_link');
    Utils_RecordBrowserCommon::enable_watchdog('utils_attachment', array('Utils_AttachmentCommon', 'watchdog_label'));
    $cleanup_checkpoint->done();
}
Utils_WatchdogCommon::dont_notify(false);
Exemple #16
0
	public static function tray_notification() {
		$methods = DB::GetAssoc('SELECT id,callback FROM utils_watchdog_category');
		foreach ($methods as $k=>$v) { 
			$methods[$k] = explode('::',$v);
		}
		$only_new = ' AND last_seen_event<(SELECT MAX(id) FROM utils_watchdog_event AS uwe WHERE uwe.internal_id=uws.internal_id AND uwe.category_id=uws.category_id)';
		$records = DB::GetAll('SELECT internal_id,category_id,last_seen_event FROM utils_watchdog_subscription AS uws WHERE user_id=%d '.$only_new, array(Acl::get_user()));
		$ret = array();
		$tray = array();
		foreach ($records as $v) {			
			$changes = Utils_WatchdogCommon::check_if_notified($v['category_id'], $v['internal_id']);
			if (!is_array($changes)) $changes = array();
			$data = call_user_func($methods[$v['category_id']], $v['internal_id'], $changes, false);
			if ($data==null) continue;
			$ret['watchdog_'.$v['internal_id'].'_'.$v['category_id'].'_'.$v['last_seen_event']] = '<b>'.__('Watchdog - %s', array($data['category'])).':</b> '.$data['title'];
			
			$tray['watchdog_'.$v['internal_id'].'_'.$v['category_id'].'_'.$v['last_seen_event']] = array('title'=>__('Watchdog - %s', array($data['category'])), 'body'=>$data['title']);			
			
			if (isset($data['events']) && $data['events']) {
				$ret['watchdog_'.$v['internal_id'].'_'.$v['category_id'].'_'.$v['last_seen_event']] .= '<br><font size=-5 color=gray>'.$data['events'].'</font>';
			}
		}
		return array('notifications'=>$ret, 'tray'=>$tray);
	}