Example #1
0
 public static function add_tracing_notes($dest_rset, $dest_id, $dest_label, $linkto_rset, $linkto_id, $linkto_label)
 {
     $after = __('Follow-up after') . ': ';
     $follow = __('Follow-up') . ': ';
     switch ($dest_rset) {
         case 'phonecall':
             $fwd_note_path = 'phonecall/' . $dest_id;
             $bck_note = $after . '[phone=' . $dest_id . ']' . $dest_label . '[/phone]';
             break;
         case 'meeting':
             $fwd_note_path = 'crm_meeting/' . $dest_id;
             $bck_note = $after . '[meeting=' . $dest_id . ']' . $dest_label . '[/meeting]';
             break;
         case 'task':
             $fwd_note_path = 'task/' . $dest_id;
             $bck_note = $after . '[task=' . $dest_id . ']' . $dest_label . '[/task]';
             break;
     }
     switch ($linkto_rset) {
         case 'phonecall':
             $bck_note_path = 'phonecall/' . $linkto_id;
             $fwd_note = $follow . '[phone=' . $linkto_id . ']' . $linkto_label . '[/phone]';
             break;
         case 'meeting':
             $bck_note_path = 'crm_meeting/' . $linkto_id;
             $fwd_note = $follow . '[meeting=' . $linkto_id . ']' . $linkto_label . '[/meeting]';
             break;
         case 'task':
             $bck_note_path = 'task/' . $linkto_id;
             $fwd_note = $follow . '[task=' . $linkto_id . ']' . $linkto_label . '[/task]';
             break;
     }
     Utils_AttachmentCommon::add($fwd_note_path, 0, Acl::get_user(), $fwd_note);
     Utils_AttachmentCommon::add($bck_note_path, 0, Acl::get_user(), $bck_note);
 }
Example #2
0
 public static function get_options()
 {
     static $user;
     if (isset(self::$options) && $user == Acl::get_user()) {
         return self::$options;
     }
     $user = Acl::get_user();
     self::$options = array();
     $modules_menu = array();
     $menus = Base_MenuCommon::get_menus();
     //ksort($menus);
     foreach ($menus as $name => $ret) {
         if ($name == 'Base_Admin') {
             continue;
         }
         if ($name == Base_Menu_QuickAccessCommon::module_name()) {
             continue;
         }
         Base_MenuCommon::add_default_menu($ret, $name);
         $modules_menu = array_merge($modules_menu, self::check_for_links('', $ret, $name));
     }
     usort($modules_menu, function ($a, $b) {
         return strcmp($a['label'], $b['label']);
     });
     self::$options =& $modules_menu;
     return self::$options;
 }
Example #3
0
 public static function get_trays()
 {
     static $trays;
     static $user;
     if (!isset($trays) || $user != Acl::get_user()) {
         $user = Acl::get_user();
         $trays = ModuleManager::call_common_methods('tray', false);
     }
     return $trays;
 }
Example #4
0
 public function applet()
 {
     $query = 'SELECT b.user_login_id, b.start_time, b.end_time, b.ip_address, b.host_name FROM base_login_audit b WHERE b.user_login_id=' . Acl::get_user() . ' ORDER BY b.start_time DESC';
     $ret = DB::SelectLimit($query, 1, 1);
     if ($row = $ret->FetchRow()) {
         $ok1 = $row['ip_address'] == get_client_ip_address();
         $ok2 = DB::GetOne('SELECT 1 FROM base_login_audit b WHERE (SELECT MIN(b2.start_time) FROM base_login_audit b2 WHERE b2.ip_address=%s)<b.start_time AND (SELECT MAX(b3.start_time) FROM base_login_audit b3 WHERE b3.ip_address=%s)>b.start_time AND b.ip_address!=%s', array($row['ip_address'], $row['ip_address'], $row['ip_address']));
         $ok = $ok1 || $ok2;
         print ($ok ? '<div style="padding:7px;">' : '<div style="padding:7px;background-color: red; color:white; font-weight:bold;">') . __('On: %s', array($row['start_time'])) . '<br />' . __('Host name: %s', array($row['host_name'])) . '<br />' . __('IP address: %s', array($row['ip_address'])) . '</div>';
     }
 }
Example #5
0
 public static function send_translation($lang, $org, $trans)
 {
     if (!self::allow_sending()) {
         return false;
     }
     $ip = gethostbyname($_SERVER['SERVER_NAME']);
     $r = DB::GetRow('SELECT * FROM base_lang_trans_contrib WHERE user_id=%d', array(Acl::get_user()));
     $q = array('first_name' => $r['first_name'], 'last_name' => $r['last_name'], 'lang' => $lang, 'ip' => $ip, 'original' => $org, 'translation' => $trans, 'credits' => $r['credits'], 'credits_website' => $r['credits_website'], 'contact_email' => $r['contact_email']);
     $ret = file_get_contents(self::translation_server_url . '/translations.php?' . http_build_query($q));
     $success = 'OK;' == $ret;
     return $success;
 }
Example #6
0
 public static function get_menus()
 {
     static $menus;
     static $user;
     if (!isset($menus) || $user != Acl::get_user()) {
         $user = Acl::get_user();
         $menus = ModuleManager::call_common_methods('menu', false);
         foreach ($menus as $m => $r) {
             if (!is_array($r)) {
                 unset($menus[$m]);
             }
         }
     }
     return $menus;
 }
Example #7
0
	public function add($def_date,$timeless=false) {
		if($this->is_back()) $this->back_to_calendar();

		$qf = $this->init_module('Libs/QuickForm',null,'addf');
		$qf->addElement('datepicker','start','Start Date');
		$qf->addElement('datepicker','end','End Date');
//		$qf->addElement('checkbox','timeless','Timeless'); //always
		$qf->addElement('text','title','Title');
		$qf->addElement('textarea','description','Description');
		$qf->addElement('select','color','Color',array('blue'=>'&bull; Blue', 'red'=>'&bull; Red', 'yellow'=>'&bull; Yellow', 'green'=>'&bull; Green', 'gray' => '&bull; Gray', 'cyan' => '&bull; Cyan', 'magenta' => '&bull; Magenta'));
		$qf->setDefaults(array('start'=>$def_date,'end'=>$def_date));
		if($qf->validate()) {
			$d = $qf->exportValues();
			DB::Execute('INSERT INTO tests_calendar_event(start,duration,timeless,title,description,created_on,created_by,color) VALUES(%d,%d,%b,%s,%s,%T,%d,%s)',
				array(strtotime($d['start']),strtotime($d['end'])-strtotime($d['start'])+86400,true,$d['title'],$d['description'],time(),Acl::get_user(),$d['color']));
			$this->back_to_calendar();
		} else {
			$qf->display();
			Base_ActionBarCommon::add('back',__('Cancel'),$this->create_back_href());
			Base_ActionBarCommon::add('save',__('Save'),$qf->get_submit_form_href());
		}
	}
Example #8
0
 /**
  * @param int  $account_id
  * @param bool $only_cached If true then only cached response will be retrieved
  * @param int  $cache_validity_in_minutes Provide 0 or false to force request
  *
  * @return array|null
  * @throws Exception
  */
 public static function get_unread_messages($account_id, $only_cached = false, $cache_validity_in_minutes = 3)
 {
     $return = null;
     $rec = Utils_RecordBrowserCommon::get_record('rc_accounts', $account_id);
     if ($rec['epesi_user'] !== Acl::get_user()) {
         throw new Exception('Invalid account id');
     }
     $port = $rec['security'] == 'ssl' ? 993 : 143;
     $server_str = '{' . $rec['server'] . '/imap/readonly/novalidate-cert' . ($rec['security'] ? '/' . $rec['security'] : '') . ':' . $port . '}';
     $cache_key = md5($server_str . ' # ' . $rec['login'] . ' # ' . $rec['password']);
     $cache = new FileCache(DATA_DIR . '/cache/roundcube_unread.php');
     if ($cache_validity_in_minutes) {
         $unread_messages = $cache->get($cache_key);
         if ($unread_messages && ($only_cached || $unread_messages['t'] > time() - $cache_validity_in_minutes * 60)) {
             $return = $unread_messages['val'];
         }
     }
     if ($return === null && $only_cached === false) {
         @set_time_limit(0);
         $mailbox = @imap_open(imap_utf7_encode($server_str), imap_utf7_encode($rec['login']), imap_utf7_encode($rec['password']), OP_READONLY || OP_SILENT);
         $err = imap_errors();
         $unseen = array();
         if (!$mailbox || $err) {
             $err = __('Connection error') . ": " . implode(', ', $err);
         } else {
             $uns = @imap_search($mailbox, 'UNSEEN ALL');
             if ($uns) {
                 $l = @imap_fetch_overview($mailbox, implode(',', $uns), 0);
                 $err = imap_errors();
                 if (!$l || $err) {
                     $error_info = $err ? ": " . implode(', ', $err) : "";
                     $err = __('Error reading messages overview') . $error_info;
                 } else {
                     foreach ($l as $msg) {
                         $from = isset($msg->from) ? imap_utf8($msg->from) : '<unknown>';
                         $subject = isset($msg->subject) ? imap_utf8($msg->subject) : '<no subject>';
                         $date = isset($msg->date) ? $msg->date : '';
                         $unseen[] = array('from' => $from, 'subject' => $subject, 'id' => $msg->uid, 'date' => $date, 'unix_timestamp' => $msg->udate);
                     }
                 }
             }
         }
         if (!is_bool($mailbox)) {
             imap_close($mailbox);
         }
         imap_errors();
         // called just to clean up errors.
         if ($err) {
             throw new Exception($err);
         } else {
             $return = $unseen;
             $cache->set($cache_key, array('val' => $return, 't' => time()));
         }
     }
     return $return;
 }
Example #9
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;
 }
Example #10
0
 /**
  * Add new record to recordset, when array is supplied and return it's object
  * or just returns empty data object to fill it with data and perform save()
  * method.
  * @param array|null $array_or_null associative array of data to or null.
  * @return RBO_Record|null
  */
 public function new_record($array_or_null = null)
 {
     if (is_array($array_or_null)) {
         $id = Utils_RecordBrowserCommon::new_record($this->tab, $array_or_null);
         if (!is_numeric($id)) {
             return null;
         }
         $array_or_null['id'] = $id;
         $array_or_null['created_by'] = Acl::get_user();
         $array_or_null[':active'] = true;
         return $this->record_to_object($array_or_null);
     }
     return $this->record_to_object(array());
 }
Example #11
0
 /**
  * Sets user setting to given value for currently logged in user.
  * Returns false if no user is logged in.
  *
  * @param string module name
  * @param string variable name
  * @param mixed value
  * @return bool true on success, false otherwise
  */
 public static function save($module, $name, $value, $user = null)
 {
     if (!Acl::is_user()) {
         return false;
     }
     //if ($value === null) $value = 0;
     $module = str_replace('/', '_', $module);
     $def = self::get_admin($module, $name);
     //		if (!isset($def)) return false;
     if (!Acl::is_user()) {
         return null;
     }
     if ($user === null) {
         $user = Acl::get_user();
     }
     if ($value == $def) {
         DB::Execute('DELETE FROM base_user_settings WHERE user_login_id=%d AND module=%s AND variable=%s', array(Acl::get_user(), $module, $name));
         if (isset(self::$user_variables[$user])) {
             unset(self::$user_variables[$user][$module][$name]);
         }
     } else {
         if (isset(self::$user_variables[$user])) {
             self::$user_variables[$user][$module][$name] = $value;
         }
         $value = serialize($value);
         $val = DB::GetOne('SELECT value FROM base_user_settings WHERE user_login_id=%d AND module=%s AND variable=%s', array(Acl::get_user(), $module, $name));
         if ($val === false || $val === null) {
             DB::Execute('INSERT INTO base_user_settings VALUES (%d,%s,%s,%s)', array(Acl::get_user(), $module, $name, $value));
         } else {
             DB::Execute('UPDATE base_user_settings SET value=%s WHERE user_login_id=%d AND module=%s AND variable=%s', array($value, Acl::get_user(), $module, $name));
         }
     }
     return true;
 }
Example #12
0
 public function account_manager($pushed_on_top = false)
 {
     if ($pushed_on_top) {
         if ($this->is_back()) {
             Base_BoxCommon::pop_main();
             return;
         }
         Base_ActionBarCommon::add('back', __('Back'), $this->create_back_href());
     } else {
         Base_ActionBarCommon::add('back', __('Back'), $this->create_main_href('Base_User_Settings'));
     }
     $this->rb = $this->init_module('Utils/RecordBrowser', 'rc_accounts', 'rc_accounts');
     $this->rb->set_defaults(array('epesi_user' => Acl::get_user()));
     $order = array(array('login' => 'DESC'), array('epesi_user' => Acl::get_user()), array('epesi_user' => false));
     $this->display_module($this->rb, $order);
     // other settings
     $qf = $this->init_module('Libs/QuickForm');
     $qf->addElement('advcheckbox', 'standard_mailto', __("Use standard mailto links"), null, array('onchange' => $qf->get_submit_form_js()));
     $use_standard_mailto = CRM_RoundcubeCommon::use_standard_mailto();
     $qf->setDefaults(array('standard_mailto' => $use_standard_mailto));
     if ($qf->validate()) {
         CRM_RoundcubeCommon::set_standard_mailto($qf->exportValue('standard_mailto'));
     }
     $qf->display_as_row();
 }
Example #13
0
 public static function display_status($record, $nolink, $desc)
 {
     $prefix = 'crm_tasks_leightbox';
     $v = $record[$desc['id']];
     if (!$v) {
         $v = 0;
     }
     $status = Utils_CommonDataCommon::get_translated_array('CRM/Status');
     if ($v >= 3 || $nolink) {
         return $status[$v];
     }
     CRM_FollowupCommon::drawLeightbox($prefix);
     if (!Utils_RecordBrowserCommon::get_access('task', 'edit', $record) && !Base_AclCommon::i_am_admin()) {
         return $status[$v];
     }
     if (isset($_REQUEST['form_name']) && $_REQUEST['form_name'] == $prefix . '_follow_up_form' && $_REQUEST['id'] == $record['id']) {
         unset($_REQUEST['form_name']);
         $v = $_REQUEST['closecancel'];
         $action = $_REQUEST['action'];
         $note = $_REQUEST['note'];
         if ($note) {
             if (get_magic_quotes_gpc()) {
                 $note = stripslashes($note);
             }
             $note = str_replace("\n", '<br />', $note);
             Utils_AttachmentCommon::add('task/' . $record['id'], 0, Acl::get_user(), $note);
         }
         if ($action == 'set_in_progress') {
             $v = 1;
         }
         Utils_RecordBrowserCommon::update_record('task', $record['id'], array('status' => $v));
         if ($action == 'set_in_progress') {
             location(array());
         }
         $values = $record;
         $values['date_and_time'] = date('Y-m-d H:i:s');
         $values['title'] = __('Follow-up') . ': ' . $values['title'];
         $values['status'] = 0;
         if ($action != 'none') {
             $x = ModuleManager::get_instance('/Base_Box|0');
             $values['follow_up'] = array('task', $record['id'], $record['title']);
             if ($action == 'new_task') {
                 $x->push_main('Utils/RecordBrowser', 'view_entry', array('add', null, $values), array('task'));
             }
             if ($action == 'new_meeting') {
                 $x->push_main('Utils/RecordBrowser', 'view_entry', array('add', null, 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, 'status' => 0, 'employees' => $values['employees'], 'customers' => $values['customers'], 'follow_up' => $values['follow_up'])), array('crm_meeting'));
             }
             if ($action == 'new_phonecall') {
                 $x->push_main('Utils/RecordBrowser', 'view_entry', array('add', null, 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'], 'status' => 0, 'customer' => !empty($values['customers']) ? array_pop($values['customers']) : '', 'follow_up' => $values['follow_up'])), array('phonecall'));
             }
             return false;
         }
         location(array());
     }
     if ($v == 0) {
         return '<a href="javascript:void(0)" onclick="' . $prefix . '_set_action(\'set_in_progress\');' . $prefix . '_set_id(\'' . $record['id'] . '\');' . $prefix . '_submit_form();">' . $status[$v] . '</a>';
     }
     return '<a href="javascript:void(0)" class="lbOn" rel="' . $prefix . '_followups_leightbox" onMouseDown="' . $prefix . '_set_id(' . $record['id'] . ');">' . $status[$v] . '</a>';
 }
Example #14
0
 public static function post_install_process($val)
 {
     $comp_id = Utils_RecordBrowserCommon::new_record('company', array('company_name' => $val['cname'], 'short_name' => isset($val['sname']) ? $val['sname'] : '', 'address_1' => isset($val['address1']) ? $val['address1'] : '', 'address_2' => isset($val['address2']) ? $val['address2'] : '', 'country' => isset($val['country']) ? $val['country'] : '', 'zone' => isset($val['state']) ? $val['state'] : '', 'city' => isset($val['city']) ? $val['city'] : '', 'postal_code' => isset($val['postal']) ? $val['postal'] : '', 'phone' => isset($val['phone']) ? $val['phone'] : '', 'fax' => isset($val['fax']) ? $val['fax'] : '', 'permission' => '0', 'web_address' => isset($val['web']) ? $val['web'] : '', 'group' => array('other')));
     if (Acl::is_user()) {
         $mail = DB::GetOne('SELECT up.mail FROM user_password up WHERE up.user_login_id=%d', array(Acl::get_user()));
         Utils_RecordBrowserCommon::new_record('contact', array('first_name' => $val['fname'], 'last_name' => $val['lname'], 'address_1' => isset($val['address1']) ? $val['address1'] : '', 'address_2' => isset($val['address2']) ? $val['address2'] : '', 'country' => isset($val['country']) ? $val['country'] : '', 'zone' => isset($val['state']) ? $val['state'] : '', 'city' => isset($val['city']) ? $val['city'] : '', 'postal_code' => isset($val['postal']) ? $val['postal'] : '', 'work_phone' => isset($val['phone']) ? $val['phone'] : '', 'fax' => isset($val['fax']) ? $val['fax'] : '', 'web_address' => isset($val['web']) ? $val['web'] : '', 'company_name' => $comp_id, 'login' => Acl::get_user(), 'permission' => '0', 'email' => $mail, 'group' => array('office', 'field')));
     }
 }
Example #15
0
$local = $rec['id'];
$fsid = $file['filestorage_id'];
$crypted = $rec['crypted'];
$meta = Utils_FileStorageCommon::meta($fsid);
require_once 'mime.php';
if (headers_sent()) {
    die('Some data has already been output to browser, can\'t send file');
}
$password = '';
if ($crypted) {
    $password = $_SESSION['client']['cp' . $rec['id']];
}
$t = time();
$remote_address = get_client_ip_address();
$remote_host = gethostbyaddr($remote_address);
DB::Execute('INSERT INTO utils_attachment_download(attach_file_id,created_by,created_on,download_on,description,ip_address,host_name) VALUES (%d,%d,%T,%T,%s,%s,%s)', array($id, Acl::get_user(), $t, $t, $disposition, $remote_address, $remote_host));
if (isset($_REQUEST['thumbnail'])) {
    $o_filename = $meta['file'];
    $f_filename = $o_filename . '_thumbnail';
    if (!file_exists($f_filename)) {
        if (!file_exists($o_filename)) {
            die('File doesn\'t exists');
        }
        $image_info = getimagesize($o_filename);
        $image_type = $image_info[2];
        $image = false;
        switch ($image_type) {
            case IMAGETYPE_JPEG:
                $image = imagecreatefromjpeg($o_filename);
                break;
            case IMAGETYPE_GIF:
Example #16
0
	public function applet() {

		$gb = $this->init_module('Utils/GenericBrowser', null, 'agenda');
		$columns = array(
			array('name'=>__('Done'), 'order'=>'done', 'width'=>5),
			array('name'=>__('Start'), 'order'=>'alert_on', 'width'=>15),
			array('name'=>__('Info'), 'width'=>80)
		);
		$gb->set_table_columns($columns);

		$gb->set_default_order(array(__('Start')=>'ASC'));

		$this->lp = $this->init_module('Utils_LeightboxPrompt');
		$this->lp->add_option('holdon_'.(5*60), __('5 minutes'),null);
		$this->lp->add_option('holdon_'.(15*60), __('15 minutes'),null);
		$this->lp->add_option('holdon_'.(30*60), __('30 minutes'),null);
		$this->lp->add_option('holdon_'.(60*60), __('1 hour'),null);
		$this->lp->add_option('holdon_'.(240*60), __('4 hours'),null);
		$this->lp->add_option('holdon_'.(12*3600), __('12 hours'),null);
		$this->lp->add_option('holdon_'.(24*3600), __('24 hours'),null);
    	$this->display_module($this->lp, array('Hold on', array('alert_id'), '', false));
		$vals = $this->lp->export_values();
		if ($vals) {
		    if(preg_match('/^holdon_([0-9]+)$/',$vals['option'],$reqs)) {
		        $_SESSION['utils_messenger_holdon'][$vals['params']['alert_id']] = time()+$reqs[1];
    		}
		}

		$t = time();
        // postgres compatible interval with type cast
        $interval = DB::is_postgresql() ? '::timestamp - interval \'1 hour\'' : '-INTERVAL 1 hour';
		$ret = DB::Execute('(SELECT u.done,m.* FROM utils_messenger_message m INNER JOIN utils_messenger_users u ON u.message_id=m.id WHERE u.user_login_id=%d AND u.done=0 AND m.alert_on<%T)'.
					' UNION '.
				'(SELECT u.done,m.* FROM utils_messenger_message m INNER JOIN utils_messenger_users u ON u.message_id=m.id WHERE u.user_login_id=%d AND m.alert_on<%T AND u.done_on>=%T'.$interval.' AND u.done=1 ORDER BY m.alert_on DESC LIMIT 3)'.
					' UNION '.
				'(SELECT 0 as done,m.* FROM utils_messenger_message m INNER JOIN utils_messenger_users u ON u.message_id=m.id WHERE u.user_login_id=%d AND m.alert_on>=%T ORDER BY m.alert_on ASC LIMIT 5)'.$gb->get_query_order(),array(Acl::get_user(),$t,Acl::get_user(),$t,$t,Acl::get_user(),$t));

		while($row = $ret->FetchRow()) {
			$info = call_user_func_array(unserialize($row['callback_method']),unserialize($row['callback_args']));
			$info = str_replace("\n",'<br>',$info);
			$alert_on = Base_RegionalSettingsCommon::time2reg($row['alert_on']);
			$gb->add_row(($row['done']?'<span class="checkbox_on" />':'<a '.Utils_TooltipCommon::open_tag_attrs(__('Turn off alarm')).' '.$this->create_confirm_callback_href(__('Are you sure you want to turn off the alarm?'),array('Utils_MessengerCommon','turn_off'),array($row['id'])).'><span class="checkbox_off" /></a>'),
			        (($row['done'] || $row['alert_on']>$t)?$alert_on:'<a '.Utils_TooltipCommon::open_tag_attrs(__('Hold on')).' '.$this->lp->get_href(array($row['id'])).'>'.$alert_on.'</a>'),
			        $info.'<br>'.($row['message']?__('Alarm comment: %s',array($row['message'])):''));
		}

		$this->display_module($gb);
	}
Example #17
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);
 }
Example #18
0
 public static function set_profile($prof)
 {
     if (preg_match('/^c([0-9,]+)$/', $prof, $reqs)) {
         $ret = $reqs[1];
         if (strpos($ret, ',') === false) {
             $desc = CRM_ContactsCommon::contact_format_no_company($ret, true);
         } else {
             $desc = __('Custom filter');
         }
     } elseif (is_numeric($prof)) {
         $cids = DB::GetAssoc('SELECT contact_id, contact_id FROM crm_filters_contacts');
         $c = DB::GetCol('SELECT p.contact_id FROM crm_filters_contacts p WHERE p.group_id=%d', array($prof));
         if ($c) {
             $ret = implode(',', $c);
         } else {
             $ret = '-1';
         }
         $desc = DB::GetOne('SELECT name FROM crm_filters_group WHERE id=%d', array($prof));
     } elseif ($prof == 'my') {
         $ret = CRM_FiltersCommon::get_my_profile();
         $desc = __('My records');
     } else {
         //all and undefined
         $ret = '';
         /*$contacts = Utils_RecordBrowserCommon::get_records('contact', array(), array(), array('last_name'=>'ASC'));
         		$contacts_select = array();
         		foreach($contacts as $v)
         			$contacts_select[] = $v['id'];
         		if($contacts_select)
         			$ret = implode(',',$contacts_select);
         		else
         			$ret = '-1';*/
         $desc = __('All records');
     }
     //		$this->set_module_variable('profile',$ret);
     $_SESSION['client']['filter_' . Acl::get_user()]['value'] = $ret;
     $_SESSION['client']['filter_' . Acl::get_user()]['desc'] = $desc;
     location(array());
 }
Example #19
0
 public static function new_autologin_id($old_autologin_id = null)
 {
     $uid = Acl::get_user();
     $user = Base_UserCommon::get_my_user_login();
     $autologin_id = md5(mt_rand() . md5($user . $uid) . mt_rand());
     setcookie('autologin_id', $user . ' ' . $autologin_id, time() + 60 * 60 * 24 * 30);
     $ip = get_client_ip_address();
     if ($old_autologin_id) {
         DB::Execute('DELETE FROM user_autologin WHERE user_login_id=%d AND autologin_id=%s', array($uid, $old_autologin_id));
     }
     DB::Execute('INSERT INTO user_autologin(user_login_id,autologin_id,description,last_log) VALUES(%d,%s,%s,%T)', array($uid, $autologin_id, $ip, time()));
     self::clean_old_autologins();
 }
Example #20
0
 public static function QFfield_login(&$form, $field, $label, $mode, $default, $desc, $rb = null)
 {
     $label = __('EPESI User');
     if (!Base_AclCommon::i_am_admin()) {
         return;
     }
     if ($mode == 'view') {
         if (!$default) {
             return;
         }
         if (Base_AclCommon::i_am_sa()) {
             Base_ActionBarCommon::add('settings', __('Log as user'), Module::create_href(array('log_as_user' => $default)));
             if (isset($_REQUEST['log_as_user']) && $_REQUEST['log_as_user'] == $default) {
                 Acl::set_user($default, true);
                 //tag who is logged
                 Epesi::redirect();
                 return;
             }
         }
         $form->addElement('static', $field, $label);
         $form->setDefaults(array($field => self::display_login(array('login' => $default), true, array('id' => 'login'))));
         return;
     }
     $ret = DB::Execute('SELECT id, login FROM user_login ORDER BY login');
     $users = array('' => '---', 'new' => '[' . __('Create new user') . ']');
     while ($row = $ret->FetchRow()) {
         $contact_id = Utils_RecordBrowserCommon::get_id('contact', 'login', $row['id']);
         if ($contact_id === false || $contact_id === null || $row['id'] === $default && $mode != 'add') {
             if (Base_AclCommon::i_am_admin() || $row['id'] == Acl::get_user()) {
                 $users[$row['id']] = $row['login'];
             }
         }
     }
     $form->addElement('select', $field, $label, $users, array('id' => 'crm_contacts_select_user'));
     $form->setDefaults(array($field => $default));
     if ($default !== '') {
         $form->freeze($field);
     } else {
         eval_js('new_user_textfield = function(){' . '($("crm_contacts_select_user").value=="new"?"":"none");' . '$("username").up("tr").style.display = $("set_password").up("tr").style.display = $("confirm_password").up("tr").style.display = $("_access__data").up("tr").style.display = ($("crm_contacts_select_user").value==""?"none":"");' . 'if ($("contact_admin")) $("contact_admin").up("tr").style.display = ($("crm_contacts_select_user").value==""?"none":"");' . '}');
         eval_js('new_user_textfield();');
         eval_js('Event.observe("crm_contacts_select_user","change",function(){new_user_textfield();});');
     }
     if ($default) {
         eval_js('$("_login__data").up("tr").style.display = "none";');
     }
 }
Example #21
0
    public static function save_google_docs($note_id) {
        $edit_url = DB::GetOne('SELECT doc_id FROM utils_attachment_googledocs WHERE note_id = %d', array($note_id));
        if (!$edit_url) {
            Base_StatusBarCommon::message(__('Document not found'), 'warning');
            return false;
        }
        if(!preg_match('/(spreadsheet|document)%3A(.+)$/i',$edit_url,$matches)) {
            Base_StatusBarCommon::message(__('Document not found'), 'warning');
            return false;
        }
        $edit_url = $matches[2];
        $doc = $matches[1]=='document';
        if ($doc)
            $export_url = 'https://docs.google.com/feeds/download/documents/Export?id='.$edit_url.'&exportFormat=doc';
        else
            $export_url = 'https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key='.$edit_url.'&exportFormat=xls';

        DB::Execute('DELETE FROM utils_attachment_googledocs WHERE note_id = %d', array($note_id));
        $g_auth = Utils_AttachmentCommon::get_google_auth(null, null, $doc?'writely':'wise');
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $headers = array(
            "Authorization: GoogleLogin auth=" . $g_auth,
            "If-Match: *",
            "GData-Version: 3.0",
        );
        curl_setopt($curl, CURLOPT_URL, $export_url);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_POST, false);
        $response = curl_exec_follow($curl);

        $row = DB::GetRow('SELECT f.*,l.f_crypted as crypted FROM utils_attachment_file f INNER JOIN utils_attachment_data_1 l ON l.id=f.attach_id WHERE f.id=%d',array($note_id));

        $local = DATA_DIR.'/Utils_Attachment/temp/'.Acl::get_user().'/gdocs';
        @mkdir($local,0777,true);
        $dest_file = $local.'/'.$row['id'];

        if($row['crypted']) {
            $password = $_SESSION['client']['cp'.$row['attach_id']];
            $response = Utils_AttachmentCommon::encrypt($response,$password);
        }
        file_put_contents($dest_file, $response);
        if($doc) {
            $ext = 'docx';
        } else $ext = 'xlsx';

        $row['original'] = substr($row['original'],0,strrpos($row['original'],'.')).'.'.$ext;

        Utils_AttachmentCommon::add_file($row['attach_id'], Acl::get_user(), $row['original'], $dest_file);
        DB::Execute('UPDATE utils_attachment_file SET deleted=1 WHERE id=%d',array($row['id']));

        $headers = array(
            "Authorization: GoogleLogin auth=" . $g_auth,
            "If-Match: *",
            "GData-Version: 3.0",
        );
        curl_setopt($curl, CURLOPT_URL, $edit_url);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_POST, false);
        $response = curl_exec($curl);

        Base_StatusBarCommon::message(__('Changes saved'));
    }
Example #22
0
<?php

if (!isset($_POST['acc_id']) || !is_numeric($_POST['acc_id'])) {
    die('Invalid request');
}
define('CID', false);
define('READ_ONLY_SESSION', true);
require_once '../../../include.php';
ModuleManager::load_modules();
if (!Acl::is_user()) {
    die('not logged');
}
@set_time_limit(0);
$rec = Utils_RecordBrowserCommon::get_record('rc_accounts', $_POST['acc_id']);
if ($rec['epesi_user'] !== Acl::get_user()) {
    die('invalid account id');
}
$port = $rec['security'] == 'ssl' ? 993 : 143;
$server_str = '{' . $rec['server'] . '/imap/readonly/novalidate-cert' . ($rec['security'] ? '/' . $rec['security'] : '') . ':' . $port . '}';
$mailbox = @imap_open(imap_utf7_encode($server_str), imap_utf7_encode($rec['login']), imap_utf7_encode($rec['password']), OP_READONLY || OP_SILENT);
$err = imap_errors();
if (!$mailbox || $err) {
    die(Utils_TooltipCommon::create(__('Connection error'), $err, false));
}
$uns = @imap_search($mailbox, 'UNSEEN ALL');
$unseen = array();
if ($uns) {
    $l = @imap_fetch_overview($mailbox, implode(',', $uns), 0);
    $err = imap_errors();
    if (!$l || $err) {
        die('error reading messages overview');
Example #23
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
Example #24
0
 public static function update()
 {
     if (isset($_SESSION['base_login_audit']) && isset($_SESSION['base_login_audit_user']) && $_SESSION['base_login_audit_user'] == Acl::get_user()) {
         DB::Execute('UPDATE base_login_audit SET end_time=%T WHERE id=%d', array(time(), $_SESSION['base_login_audit']));
     }
 }
Example #25
0
 public static function mobile_rb_view($tab, $id)
 {
     if (Utils_RecordBrowserCommon::get_access($tab, 'browse') === false) {
         print __('You are not authorised to browse this data.');
         return;
     }
     self::add_recent_entry($tab, Acl::get_user(), $id);
     $rec = self::get_record($tab, $id);
     $access = Utils_RecordBrowserCommon::get_access($tab, 'view', $rec);
     if (is_array($access)) {
         foreach ($access as $k => $v) {
             if (!$v) {
                 $rec[$k] = '';
             }
         }
     }
     $cols = Utils_RecordBrowserCommon::init($tab);
     if (IPHONE) {
         print '<ul class="field">';
         foreach ($cols as $k => $col) {
             $val = Utils_RecordBrowserCommon::get_val($tab, $k, $rec, true, $col);
             if ($val === '') {
                 continue;
             }
             print '<li>' . _V($col['name']) . ': ' . $val . '</li>';
             // TRSL
         }
         print '</ul>';
     } else {
         foreach ($cols as $k => $col) {
             $val = Utils_RecordBrowserCommon::get_val($tab, $k, $rec, true, $col);
             if ($val === '') {
                 continue;
             }
             print _V($col['name']) . ': ' . $val . '<br>';
             // TRSL
         }
     }
     if (Utils_RecordBrowserCommon::get_access($tab, 'edit', $rec)) {
         print '<a ' . (IPHONE ? 'class="button blue" ' : '') . mobile_stack_href(array('Utils_RecordBrowserCommon', 'mobile_rb_edit'), array($tab, $id), __('Record edition')) . '>' . __('Edit') . '</a>' . (IPHONE ? '' : '<br />');
     }
     if (Utils_RecordBrowserCommon::get_access($tab, 'delete', $rec)) {
         print '<a ' . (IPHONE ? 'class="button red" ' : '') . mobile_stack_href(array('Utils_RecordBrowserCommon', 'mobile_rb_delete'), array($tab, $id), __('Record deletion')) . '>' . __('Delete') . '</a>' . (IPHONE ? '' : '<br />');
     }
 }
Example #26
0
 /**
  * Adds new comment to current comment group.
  * You can also specify to which comment this was reply to.
  * 
  * @param string text message
  * @param integer id of a comment to which this one replies
  */
 public function add_post($post_text, $answer_to = -1)
 {
     //		$post_text = str_replace("\n",'<br>',$post_text);
     DB::Execute('INSERT INTO comment (text, user_login_id, topic, created_on, parent) VALUES (%s, %d, %s, %s, %d)', array($post_text, Acl::get_user(), $this->key, date('Y-m-d G:i:s'), $answer_to));
 }
Example #27
0
 public static function check_group_name_exists($name, $id)
 {
     if (isset($id)) {
         $ret = DB::GetOne('SELECT id FROM crm_filters_group WHERE id!=%d AND name=%s AND user_login_id=%d', array($id, $name, Acl::get_user()));
     } else {
         $ret = DB::GetOne('SELECT id FROM crm_filters_group WHERE name=%s AND user_login_id=%d', array($name, Acl::get_user()));
     }
     return $ret === false || $ret === null;
 }
Example #28
0
 public function translations()
 {
     global $translations;
     global $custom_translations;
     load_js('modules/Base/Lang/Administrator/js/main.js');
     eval_js('translate_init();');
     $lp = $this->init_module('Utils/LeightboxPrompt');
     $form = $this->init_module('Libs/QuickForm', null, 'translations_sending');
     $desc = '<div id="trans_sett_info" style="line-height:17px;">';
     $desc .= __('You have now option to contribute with your translations to help us deliver EPESI in various languages. You can opt in to send your translations to EPESI central database, allowing to deliver EPESI in your language to other users.') . '<br>';
     $desc .= __('Please note that the translations you submit aren\'t subject to copyright. EPESI Team will distribute the translations free of charge to the end users.') . '<br>';
     $desc .= __('The only data being sent is the values of the fields presented below and the translated strings, we do not receive any other information contained in EPESI.') . '<br>';
     $desc .= __('You can also change your Translations Contribution settings at later time.') . '<br>';
     $desc .= '</div>';
     eval_js('$("trans_sett_info").up("td").setAttribute("colspan",2);');
     eval_js('$("trans_sett_info").up("td").style.borderRadius="0";');
     // Not really nice, but will have to do for now
     eval_js('$("decription_label").up("td").hide();');
     eval_js('function update_credits(){$("contact_email").disabled=$("credits_website").disabled=!$("include_credits").checked||!$("allow").checked;}');
     eval_js('update_credits();');
     $ip = gethostbyname($_SERVER['SERVER_NAME']);
     $me = CRM_ContactsCommon::get_my_record();
     $form->addElement('static', 'header', '<div id="decription_label" />', $desc);
     $form->addElement('checkbox', 'allow', __('Enable sending translations'), null, array('id' => 'allow', 'onchange' => '$("include_credits").disabled=$("first_name").disabled=$("last_name").disabled=!this.checked;update_credits();'));
     $form->addElement('text', 'first_name', __('First Name'), array('id' => 'first_name'));
     $form->addElement('text', 'last_name', __('Last Name'), array('id' => 'last_name'));
     $form->addElement('checkbox', 'include_credits', __('Include in credits'), null, array('id' => 'include_credits', 'onchange' => 'update_credits();'));
     $form->addElement('text', 'credits_website', __('Credits website'), array('id' => 'credits_website'));
     $form->addElement('text', 'contact_email', __('Contact e-mail'), array('id' => 'contact_email'));
     $form->addElement('static', 'IP', __('IP'), $ip);
     $lp->add_option(null, null, null, $form);
     eval_js('$("first_name").disabled=$("last_name").disabled=!$("allow").checked;');
     $vals = $lp->export_values();
     if ($vals) {
         $values = $vals['form'];
         if (!isset($values['allow'])) {
             $values['allow'] = 0;
         }
         if (!isset($values['first_name'])) {
             $values['first_name'] = '';
         }
         if (!isset($values['last_name'])) {
             $values['last_name'] = '';
         }
         if (!isset($values['include_credits'])) {
             $values['include_credits'] = 0;
         }
         if (!isset($values['credits_website'])) {
             $values['credits_website'] = '';
         }
         if (!isset($values['contact_email'])) {
             $values['contact_email'] = '';
         }
         DB::Execute('DELETE FROM base_lang_trans_contrib WHERE user_id=%d', array(Acl::get_user()));
         DB::Execute('INSERT INTO base_lang_trans_contrib (user_id, allow, first_name, last_name, credits, credits_website, contact_email) VALUES (%d, %d, %s, %s, %d, %s, %s)', array(Acl::get_user(), $values['allow'], $values['first_name'], $values['last_name'], $values['include_credits'], $values['credits_website'], $values['contact_email']));
     }
     $allow_sending = Base_Lang_AdministratorCommon::allow_sending(true);
     if ($allow_sending === null || $allow_sending === false) {
         $form->setDefaults(array('allow' => 0, 'first_name' => $me['first_name'], 'last_name' => $me['last_name'], 'contact_email' => $me['email']));
     } else {
         $r = DB::GetRow('SELECT * FROM base_lang_trans_contrib WHERE user_id=%d', array(Acl::get_user()));
         if (!$r['first_name']) {
             $r['first_name'] = $me['first_name'];
         }
         if (!$r['last_name']) {
             $r['last_name'] = $me['last_name'];
         }
         if (!$r['contact_email']) {
             $r['contact_email'] = $me['email'];
         }
         $form->setDefaults(array('allow' => $r['allow'], 'first_name' => $r['first_name'], 'last_name' => $r['last_name'], 'contact_email' => $r['contact_email'], 'credits_website' => $r['credits_website'], 'include_credits' => $r['credits']));
     }
     Base_ActionBarCommon::add('settings', __('Translations Contributions'), $lp->get_href());
     $this->display_module($lp, array(__('Translations Contributions settings')));
     if (Base_AdminCommon::get_access('Base_Lang_Administrator', 'new_langpack')) {
         Base_ActionBarCommon::add('add', __('New langpack'), $this->create_callback_href(array($this, 'new_lang_pack')));
     }
     if (Base_AdminCommon::get_access('Base_Lang_Administrator', 'select_language')) {
         Base_ActionBarCommon::add('refresh', __('Refresh languages'), $this->create_callback_href(array('Base_LangCommon', 'refresh_cache')));
     }
     $form2 = $this->init_module('Libs/QuickForm', null, 'translaction_filter');
     $form2->addElement('select', 'lang_filter', __('Filter'), array(__('Show all'), __('Show with custom translation'), __('Show with translation'), __('Show without translation')), array('onchange' => $form2->get_submit_form_js()));
     if ($form2->validate()) {
         $vals = $form2->exportValues();
         $this->set_module_variable('filter', $vals['lang_filter']);
     }
     $filter = $this->get_module_variable('filter', 0);
     $form2->setDefaults(array('lang_filter' => $filter));
     ob_start();
     $form2->display_as_row();
     $trans_filter = ob_get_clean();
     if (!isset($_SESSION['client']['base_lang_administrator']['currently_translating'])) {
         $_SESSION['client']['base_lang_administrator']['currently_translating'] = Base_LangCommon::get_lang_code();
     }
     if (!isset($_SESSION['client']['base_lang_administrator']['notice'])) {
         print '<span class="important_notice">' . __('Please make sure the correct language is selected in the box below before you start translating') . ' <a style="float:right;" ' . $this->create_callback_href(array($this, 'hide_notice')) . '>' . __('Discard') . '</a>' . '</span>';
     }
     if (Base_AdminCommon::get_access('Base_Lang_Administrator', 'translate')) {
         $langs = Base_LangCommon::get_installed_langs();
         $form = $this->init_module('Libs/QuickForm', null, 'language_selected');
         $form->addElement('select', 'lang_code', __('Currently Translating'), $langs, array('onchange' => $form->get_submit_form_js()));
         $currently_translating = $_SESSION['client']['base_lang_administrator']['currently_translating'];
         $form->setDefaults(array('lang_code' => $currently_translating));
         if ($form->validate()) {
             $form->process(array($this, 'submit_language_select'));
         }
         if ($allow_sending) {
             $warning_mgs = __('All custom translations will be sent to our server right after you will input them. Use this mode only, if you wish to contribute your translations. If you are going to change meaning of any string, then please disable sending translations.');
             print "<h1 style=\"color:red; width: 70%\">{$warning_mgs}</h1>";
         } else {
             $contribution_mgs = __('If you wish to help us with translating EPESI to your language, then click Translation Contribution in the Action Bar.');
             print "<h3>{$contribution_mgs}</h3>";
         }
         $form->display_as_column();
         if ($allow_sending) {
             $href = $this->create_confirm_callback_href(__('Are you sure?'), array($this, 'send_lang_ajax'), array($currently_translating));
             print "<h4><a {$href}>" . __('Send all your custom translations for language %s', array($langs[$currently_translating])) . "</a></h4>";
         }
         $help_msg = __('You can open next string to translate with space button');
         print "<p>{$help_msg}</p>";
     }
     Base_LangCommon::load($_SESSION['client']['base_lang_administrator']['currently_translating']);
     $data = array();
     foreach ($custom_translations as $o => $t) {
         if ($t || !isset($translations[$o])) {
             $translations[$o] = $t;
         }
     }
     foreach ($translations as $o => $t) {
         if (isset($custom_translations[$o]) && $custom_translations[$o]) {
             $t = $custom_translations[$o];
         } else {
             if ($filter == 1) {
                 continue;
             }
         }
         if ($filter == 2 && !$t) {
             continue;
         }
         if ($filter == 3 && $t) {
             continue;
         }
         $span_id = 'trans__' . md5($o);
         if (Base_AdminCommon::get_access('Base_Lang_Administrator', 'translate')) {
             $org = '<a href="javascript:void(0);" onclick="lang_translate(\'' . Epesi::escapeJS(htmlspecialchars($o)) . '\',\'' . $span_id . '\');">' . $o . '</a>';
             $t = '<span id="' . $span_id . '">' . $t . '</span>';
         }
         eval_js('translate_add_id("' . $span_id . '","' . Epesi::escapeJS($o) . '");');
         $data[] = array($org, $t);
     }
     $gb = $this->init_module('Utils/GenericBrowser', null, 'lang_translations');
     $gb->set_custom_label($trans_filter);
     $gb->set_table_columns(array(array('name' => __('Original'), 'order_preg' => '/^<[^>]+>([^<]*)<[^>]+>$/i', 'search' => 'original'), array('name' => __('Translated'), 'search' => 'translated')));
     //$limit = $gb->get_limit(count($data));
     $id = 0;
     foreach ($data as $v) {
         //if ($id>=$limit['offset'] && $id<$limit['offset']+$limit['numrows'])
         $gb->add_row_array($v);
         $id++;
     }
     Base_LangCommon::load();
     $this->display_module($gb, array(true), 'automatic_display');
     Utils_ShortcutCommon::add(array(' '), 'translate_first_on_the_list', array('disable_in_input' => 1));
 }
Example #29
0
 public function file_history($attachment)
 {
     if ($this->is_back()) {
         $x = ModuleManager::get_instance('/Base_Box|0');
         if (!$x) {
             trigger_error('There is no base box module instance', E_USER_ERROR);
         }
         return $x->pop_main();
     }
     Base_ActionBarCommon::add('back', __('Back'), $this->create_back_href());
     $id = $attachment['id'];
     $tb =& $this->init_module(Utils_TabbedBrowser::module_name());
     $tb->start_tab('File history');
     $gb = $this->init_module(Utils_GenericBrowser::module_name(), null, 'hua' . $id);
     $gb->set_inline_display();
     $gb->set_table_columns(array(array('name' => __('Deleted'), 'order' => 'deleted', 'width' => 10), array('name' => __('Date'), 'order' => 'upload_on', 'width' => 25), array('name' => __('Who'), 'order' => 'upload_by', 'width' => 25), array('name' => __('Attachment'), 'order' => 'uaf.original')));
     $gb->set_default_order(array(__('Date') => 'DESC'));
     $ret = $gb->query_order_limit('SELECT uaf.id,uaf.deleted,uaf.filestorage_id,uaf.created_on as upload_on,uaf.created_by as upload_by,uaf.original FROM utils_attachment_file uaf WHERE uaf.attach_id=' . $id, 'SELECT count(*) FROM utils_attachment_file uaf WHERE uaf.attach_id=' . $id);
     while ($row = $ret->FetchRow()) {
         $r = $gb->get_new_row();
         if ($row['deleted']) {
             $r->add_action($this->create_confirm_callback_href(__('Are you sure you want to restore attached file?'), array($this, 'restore_file'), array($row['id'])), 'restore', __('Restore'));
         }
         $view_link = '';
         $lb = array();
         $lb['aid'] = $id;
         $lb['crypted'] = $attachment['crypted'];
         $lb['original'] = $row['original'];
         $lb['id'] = $row['id'];
         $lb['filestorage_id'] = $row['filestorage_id'];
         $file = '<a ' . Utils_AttachmentCommon::get_file_leightbox($lb, $view_link) . '>' . $row['original'] . '</a>';
         $r->add_data($row['deleted'] ? __('Yes') : __('No'), Base_RegionalSettingsCommon::time2reg($row['upload_on']), Base_UserCommon::get_user_label($row['upload_by']), $file);
     }
     $this->display_module($gb);
     $tb->end_tab();
     $tb->start_tab('File access history');
     $gb = $this->init_module(Utils_GenericBrowser::module_name(), null, 'hda' . $id);
     $gb->set_inline_display();
     $gb->set_table_columns(array(array('name' => __('Create date'), 'order' => 'created_on', 'width' => 15), array('name' => __('Download date'), 'order' => 'download_on', 'width' => 15), array('name' => __('Who'), 'order' => 'created_by', 'width' => 15), array('name' => __('IP Address'), 'order' => 'ip_address', 'width' => 15), array('name' => __('Host Name'), 'order' => 'host_name', 'width' => 15), array('name' => __('Method description'), 'order' => 'description', 'width' => 20), array('name' => __('Remote'), 'order' => 'remote', 'width' => 10)));
     $gb->set_default_order(array(__('Create date') => 'DESC'));
     $query = 'SELECT uad.created_on,uad.download_on,(SELECT l.login FROM user_login l WHERE uad.created_by=l.id) as created_by,uad.remote,uad.ip_address,uad.host_name,uad.description FROM utils_attachment_download uad INNER JOIN utils_attachment_file uaf ON uaf.id=uad.attach_file_id WHERE uaf.attach_id=' . $id;
     $query_qty = 'SELECT count(*) FROM utils_attachment_download uad INNER JOIN utils_attachment_file uaf ON uaf.id=uad.attach_file_id WHERE uaf.attach_id=' . $id;
     if (Base_AclCommon::check_permission('Attachments - view full download history')) {
         $ret = $gb->query_order_limit($query, $query_qty);
     } else {
         print 'You are allowed to see your own downloads only';
         $who = ' AND uad.created_by=' . Acl::get_user();
         $ret = $gb->query_order_limit($query . $who, $query_qty . $who);
     }
     while ($row = $ret->FetchRow()) {
         $r = $gb->get_new_row();
         $r->add_data(Base_RegionalSettingsCommon::time2reg($row['created_on']), $row['remote'] != 1 ? Base_RegionalSettingsCommon::time2reg($row['download_on']) : '', $row['created_by'], $row['ip_address'], $row['host_name'], $row['description'], $row['remote'] == 0 ? 'no' : 'yes');
     }
     $this->display_module($gb);
     $tb->end_tab();
     $this->display_module($tb);
     $this->caption = 'Note history';
     return true;
 }
Example #30
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);
 }