+
+/****** debugging and logging functions ********/
+
+/**
+ * Print or write debug messages
+ *
+ * @param mixed Debug message or data
+ * @return void
+ */
+function console()
+{
+ $args = func_get_args();
+
+ if (class_exists('rcmail', false)) {
+ $rcmail = rcmail::get_instance();
+ if (is_object($rcmail->plugins)) {
+ $plugin = $rcmail->plugins->exec_hook('console', array('args' => $args));
+ if ($plugin['abort'])
+ return;
+ $args = $plugin['args'];
+ }
+ }
+
+ $msg = array();
+ foreach ($args as $arg)
+ $msg[] = !is_string($arg) ? var_export($arg, true) : $arg;
+
+ write_log('console', join(";\n", $msg));
+}
+
+
+/**
+ * Append a line to a logfile in the logs directory.
+ * Date will be added automatically to the line.
+ *
+ * @param $name name of log file
+ * @param line Line to append
+ * @return void
+ */
+function write_log($name, $line)
+{
+ global $CONFIG, $RCMAIL;
+
+ if (!is_string($line))
+ $line = var_export($line, true);
+
+ if (empty($CONFIG['log_date_format']))
+ $CONFIG['log_date_format'] = 'd-M-Y H:i:s O';
+
+ $date = date($CONFIG['log_date_format']);
+
+ // trigger logging hook
+ if (is_object($RCMAIL) && is_object($RCMAIL->plugins)) {
+ $log = $RCMAIL->plugins->exec_hook('write_log', array('name' => $name, 'date' => $date, 'line' => $line));
+ $name = $log['name'];
+ $line = $log['line'];
+ $date = $log['date'];
+ if ($log['abort'])
+ return true;
+ }
+
+ if ($CONFIG['log_driver'] == 'syslog') {
+ $prio = $name == 'errors' ? LOG_ERR : LOG_INFO;
+ syslog($prio, $line);
+ return true;
+ }
+ else {
+ $line = sprintf("[%s]: %s\n", $date, $line);
+
+ // log_driver == 'file' is assumed here
+ if (empty($CONFIG['log_dir']))
+ $CONFIG['log_dir'] = INSTALL_PATH.'logs';
+
+ // try to open specific log file for writing
+ $logfile = $CONFIG['log_dir'].'/'.$name;
+ if ($fp = @fopen($logfile, 'a')) {
+ fwrite($fp, $line);
+ fflush($fp);
+ fclose($fp);
+ return true;
+ }
+ else
+ trigger_error("Error writing to log file $logfile; Please check permissions", E_USER_WARNING);
+ }
+
+ return false;
+}
+
+
+/**
+ * Write login data (name, ID, IP address) to the 'userlogins' log file.
+ *
+ * @return void
+ */
+function rcmail_log_login()
+{
+ global $RCMAIL;
+
+ if (!$RCMAIL->config->get('log_logins') || !$RCMAIL->user)
+ return;
+
+ write_log('userlogins', sprintf('Successful login for %s (ID: %d) from %s in session %s',
+ $RCMAIL->user->get_username(), $RCMAIL->user->ID, rcmail_remote_ip(), session_id()));
+}
+
+
+/**
+ * Returns remote IP address and forwarded addresses if found
+ *
+ * @return string Remote IP address(es)
+ */
+function rcmail_remote_ip()
+{
+ $address = $_SERVER['REMOTE_ADDR'];
+
+ // append the NGINX X-Real-IP header, if set
+ if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
+ $remote_ip[] = 'X-Real-IP: ' . $_SERVER['HTTP_X_REAL_IP'];
+ }
+ // append the X-Forwarded-For header, if set
+ if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
+ $remote_ip[] = 'X-Forwarded-For: ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
+ }
+
+ if (!empty($remote_ip))
+ $address .= '(' . implode(',', $remote_ip) . ')';
+
+ return $address;
+}
+
+
+/**
+ * Check whether the HTTP referer matches the current request
+ *
+ * @return boolean True if referer is the same host+path, false if not
+ */
+function rcube_check_referer()
+{
+ $uri = parse_url($_SERVER['REQUEST_URI']);
+ $referer = parse_url(rc_request_header('Referer'));
+ return $referer['host'] == rc_request_header('Host') && $referer['path'] == $uri['path'];
+}
+
+
+/**
+ * @access private
+ * @return mixed
+ */
+function rcube_timer()
+{
+ return microtime(true);
+}
+
+
+/**
+ * @access private
+ * @return void
+ */
+function rcube_print_time($timer, $label='Timer', $dest='console')
+{
+ static $print_count = 0;
+
+ $print_count++;
+ $now = rcube_timer();
+ $diff = $now-$timer;
+
+ if (empty($label))
+ $label = 'Timer '.$print_count;
+
+ write_log($dest, sprintf("%s: %0.4f sec", $label, $diff));
+}
+
+
+/**
+ * Throw system error and show error page
+ *
+ * @param array Named parameters
+ * - code: Error code (required)
+ * - type: Error type [php|db|imap|javascript] (required)
+ * - message: Error message
+ * - file: File where error occured
+ * - line: Line where error occured
+ * @param boolean True to log the error
+ * @param boolean Terminate script execution
+ */
+// may be defined in Installer
+if (!function_exists('raise_error')) {
+function raise_error($arg=array(), $log=false, $terminate=false)
+{
+ global $__page_content, $CONFIG, $OUTPUT, $ERROR_CODE, $ERROR_MESSAGE;
+
+ // report bug (if not incompatible browser)
+ if ($log && $arg['type'] && $arg['message'])
+ rcube_log_bug($arg);
+
+ // display error page and terminate script
+ if ($terminate) {
+ $ERROR_CODE = $arg['code'];
+ $ERROR_MESSAGE = $arg['message'];
+ include INSTALL_PATH . 'program/steps/utils/error.inc';
+ exit;
+ }
+}
+}
+
+
+/**
+ * Report error according to configured debug_level
+ *
+ * @param array Named parameters
+ * @return void
+ * @see raise_error()
+ */
+function rcube_log_bug($arg_arr)
+{
+ global $CONFIG;
+
+ $program = strtoupper($arg_arr['type']);
+ $level = $CONFIG['debug_level'];
+
+ // disable errors for ajax requests, write to log instead (#1487831)
+ if (($level & 4) && !empty($_REQUEST['_remote'])) {
+ $level = ($level ^ 4) | 1;
+ }
+
+ // write error to local log file
+ if ($level & 1) {
+ $post_query = ($_SERVER['REQUEST_METHOD'] == 'POST' ? '?_task='.urlencode($_POST['_task']).'&_action='.urlencode($_POST['_action']) : '');
+ $log_entry = sprintf("%s Error: %s%s (%s %s)",
+ $program,
+ $arg_arr['message'],
+ $arg_arr['file'] ? sprintf(' in %s on line %d', $arg_arr['file'], $arg_arr['line']) : '',
+ $_SERVER['REQUEST_METHOD'],
+ $_SERVER['REQUEST_URI'] . $post_query);
+
+ if (!write_log('errors', $log_entry)) {
+ // send error to PHPs error handler if write_log didn't succeed
+ trigger_error($arg_arr['message']);
+ }
+ }
+
+ // report the bug to the global bug reporting system
+ if ($level & 2) {
+ // TODO: Send error via HTTP
+ }
+
+ // show error if debug_mode is on
+ if ($level & 4) {
+ print "<b>$program Error";
+
+ if (!empty($arg_arr['file']) && !empty($arg_arr['line']))
+ print " in $arg_arr[file] ($arg_arr[line])";
+
+ print ':</b> ';
+ print nl2br($arg_arr['message']);
+ print '<br />';
+ flush();
+ }
+}
+
+function rcube_upload_progress()
+{
+ global $RCMAIL;
+
+ $prefix = ini_get('apc.rfc1867_prefix');
+ $params = array(
+ 'action' => $RCMAIL->action,
+ 'name' => get_input_value('_progress', RCUBE_INPUT_GET),
+ );
+
+ if (function_exists('apc_fetch')) {
+ $status = apc_fetch($prefix . $params['name']);
+
+ if (!empty($status)) {
+ $status['percent'] = round($status['current']/$status['total']*100);
+ $params = array_merge($status, $params);
+ }
+ }
+
+ if (isset($params['percent']))
+ $params['text'] = rcube_label(array('name' => 'uploadprogress', 'vars' => array(
+ 'percent' => $params['percent'] . '%',
+ 'current' => show_bytes($params['current']),
+ 'total' => show_bytes($params['total'])
+ )));
+
+ $RCMAIL->output->command('upload_progress_update', $params);
+ $RCMAIL->output->send();
+}
+
+function rcube_upload_init()
+{
+ global $RCMAIL;
+
+ // Enable upload progress bar
+ if (($seconds = $RCMAIL->config->get('upload_progress')) && ini_get('apc.rfc1867')) {
+ if ($field_name = ini_get('apc.rfc1867_name')) {
+ $RCMAIL->output->set_env('upload_progress_name', $field_name);
+ $RCMAIL->output->set_env('upload_progress_time', (int) $seconds);
+ }
+ }
+
+ // find max filesize value
+ $max_filesize = parse_bytes(ini_get('upload_max_filesize'));
+ $max_postsize = parse_bytes(ini_get('post_max_size'));
+ if ($max_postsize && $max_postsize < $max_filesize)
+ $max_filesize = $max_postsize;
+
+ $RCMAIL->output->set_env('max_filesize', $max_filesize);
+ $max_filesize = show_bytes($max_filesize);
+ $RCMAIL->output->set_env('filesizeerror', rcube_label(array(
+ 'name' => 'filesizeerror', 'vars' => array('size' => $max_filesize))));
+
+ return $max_filesize;
+}
+
+/**
+ * Initializes client-side autocompletion
+ */
+function rcube_autocomplete_init()
+{
+ global $RCMAIL;
+ static $init;
+
+ if ($init)
+ return;
+
+ $init = 1;
+
+ if (($threads = (int)$RCMAIL->config->get('autocomplete_threads')) > 0) {
+ $book_types = (array) $RCMAIL->config->get('autocomplete_addressbooks', 'sql');
+ if (count($book_types) > 1) {
+ $RCMAIL->output->set_env('autocomplete_threads', $threads);
+ $RCMAIL->output->set_env('autocomplete_sources', $book_types);
+ }
+ }
+
+ $RCMAIL->output->set_env('autocomplete_max', (int)$RCMAIL->config->get('autocomplete_max', 15));
+ $RCMAIL->output->set_env('autocomplete_min_length', $RCMAIL->config->get('autocomplete_min_length'));
+ $RCMAIL->output->add_label('autocompletechars');
+}