Import Ruty

This commit is contained in:
2024-03-11 00:58:34 +01:00
parent 34a31bb184
commit 985f1ab418
618 changed files with 225414 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| PURPOSE: |
| Setup the command line environment and provide some utility |
| functions. |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
*/
if (php_sapi_name() != 'cli') {
die('Not on the "shell" (php-cli).');
}
require_once INSTALL_PATH . 'program/include/iniset.php';
// Unset max. execution time limit, set to 120 seconds in iniset.php
@set_time_limit(0);
$rcmail = rcmail::get_instance();
+139
View File
@@ -0,0 +1,139 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| PURPOSE: |
| Setup the application environment required to process |
| any request. |
+-----------------------------------------------------------------------+
| Author: Till Klampaeckel <till@php.net> |
| Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
*/
if (PHP_VERSION_ID < 70300) {
die("Unsupported PHP version. Required PHP >= 7.3.");
}
// application constants
define('RCMAIL_VERSION', '1.6.3');
define('RCMAIL_START', microtime(true));
if (!defined('INSTALL_PATH')) {
define('INSTALL_PATH', dirname($_SERVER['SCRIPT_FILENAME']).'/');
}
if (!defined('RCMAIL_CONFIG_DIR')) {
define('RCMAIL_CONFIG_DIR', getenv('ROUNDCUBE_CONFIG_DIR') ?: (INSTALL_PATH . 'config'));
}
if (!defined('RCUBE_LOCALIZATION_DIR')) {
define('RCUBE_LOCALIZATION_DIR', INSTALL_PATH . 'program/localization/');
}
define('RCUBE_INSTALL_PATH', INSTALL_PATH);
define('RCUBE_CONFIG_DIR', RCMAIL_CONFIG_DIR.'/');
// Show basic error message on fatal PHP error
register_shutdown_function('rcmail_error_handler');
// RC include folders MUST be included FIRST to avoid other
// possible not compatible libraries (i.e PEAR) to be included
// instead the ones provided by RC
$include_path = INSTALL_PATH . 'program/lib' . PATH_SEPARATOR;
$include_path.= ini_get('include_path');
if (set_include_path($include_path) === false) {
die("Fatal error: ini_set/set_include_path does not work.");
}
// increase maximum execution time for php scripts
// (does not work in safe mode)
@set_time_limit(120);
// include composer autoloader (if available)
if (@file_exists(INSTALL_PATH . 'vendor/autoload.php')) {
require INSTALL_PATH . 'vendor/autoload.php';
}
// translate PATH_INFO to _task and _action GET parameters
if (!empty($_SERVER['PATH_INFO']) && preg_match('!^/([a-z]+)/([a-z]+)$!', $_SERVER['PATH_INFO'], $m)) {
if (!isset($_GET['_task'])) {
$_GET['_task'] = $m[1];
}
if (!isset($_GET['_action'])) {
$_GET['_action'] = $m[2];
}
}
// include Roundcube Framework
require_once 'Roundcube/bootstrap.php';
// register autoloader for rcmail app classes
spl_autoload_register('rcmail_autoload');
/**
* PHP5 autoloader routine for dynamic class loading
*/
function rcmail_autoload($classname)
{
if (strpos($classname, 'rcmail') === 0) {
if (preg_match('/^rcmail_action_([^_]+)_(.*)$/', $classname, $matches)) {
$filepath = INSTALL_PATH . "program/actions/{$matches[1]}/{$matches[2]}.php";
}
else {
$filepath = INSTALL_PATH . "program/include/$classname.php";
}
if (is_readable($filepath)) {
include_once $filepath;
return true;
}
}
return false;
}
/**
* Show a generic error message on fatal PHP error
*/
function rcmail_error_handler()
{
$error = error_get_last();
if ($error && ($error['type'] === E_ERROR || $error['type'] === E_PARSE)) {
rcmail_fatal_error();
}
}
/**
* Raise a generic error message on error
*/
function rcmail_fatal_error()
{
if (php_sapi_name() === 'cli') {
echo "Fatal error: Please check the Roundcube error log and/or server error logs for more information.\n";
}
elseif (!empty($_REQUEST['_remote'])) {
// Ajax request from UI
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(['code' => 500, 'message' => "Internal Server Error"]);
}
else {
if (!defined('RCUBE_FATAL_ERROR_MSG')) {
define('RCUBE_FATAL_ERROR_MSG', INSTALL_PATH . 'program/resources/error.html');
}
echo file_get_contents(RCUBE_FATAL_ERROR_MSG);
}
exit;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,393 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| Copyright (C) Kolab Systems AG |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| PURPOSE: |
| Unified access to attachment properties and body |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
| Author: Aleksander Machniak <alec@alec.pl> |
+-----------------------------------------------------------------------+
*/
/**
* Unified access to attachment properties and body
* Unified for message parts as well as uploaded attachments
*
* @package Webmail
*/
class rcmail_attachment_handler
{
public $filename;
public $size;
public $mimetype;
public $ident;
public $charset = RCUBE_CHARSET;
private $message;
private $part;
private $upload;
private $body;
private $body_file;
private $download = false;
/**
* Class constructor.
* Reads request parameters and initializes attachment/part props.
*/
public function __construct()
{
ob_end_clean();
$part_id = rcube_utils::get_input_string('_part', rcube_utils::INPUT_GET);
$file_id = rcube_utils::get_input_string('_file', rcube_utils::INPUT_GET);
$compose_id = rcube_utils::get_input_string('_id', rcube_utils::INPUT_GET);
$uid = rcube_utils::get_input_string('_uid', rcube_utils::INPUT_GET);
$rcube = rcube::get_instance();
$this->download = !empty($_GET['_download']);
// similar code as in program/steps/mail/show.inc
if (!empty($uid)) {
$rcube->config->set('prefer_html', true);
$this->message = new rcube_message($uid, null, !empty($_GET['_safe']));
if ($this->part = $this->message->mime_parts[$part_id]) {
$this->filename = rcmail_action_mail_index::attachment_name($this->part);
$this->mimetype = $this->part->mimetype;
$this->size = $this->part->size;
$this->ident = $this->message->headers->messageID . ':' . $this->part->mime_id . ':' . $this->size . ':' . $this->mimetype;
$this->charset = $this->part->charset ?: RCUBE_CHARSET;
if (empty($_GET['_frame'])) {
// allow post-processing of the attachment body
$plugin = $rcube->plugins->exec_hook('message_part_get', [
'uid' => $uid,
'id' => $this->part->mime_id,
'mimetype' => $this->mimetype,
'part' => $this->part,
'download' => $this->download,
]);
if ($plugin['abort']) {
exit;
}
// overwrite modified vars from plugin
$this->mimetype = $plugin['mimetype'];
if (!empty($plugin['body'])) {
$this->body = $plugin['body'];
$this->size = strlen($this->body);
}
}
}
}
else if ($file_id && $compose_id) {
$file_id = preg_replace('/^rcmfile/', '', $file_id);
if (($compose = $_SESSION['compose_data_' . $compose_id])
&& ($this->upload = $compose['attachments'][$file_id])
) {
$this->filename = $this->upload['name'];
$this->mimetype = $this->upload['mimetype'];
$this->size = $this->upload['size'];
$this->ident = sprintf('%s:%s%s', $compose_id, $file_id, $this->size);
$this->charset = !empty($this->upload['charset']) ? $this->upload['charset'] : RCUBE_CHARSET;
}
}
if (empty($this->part) && empty($this->upload)) {
header('HTTP/1.1 404 Not Found');
exit;
}
// check connection status
self::check_storage_status();
$this->mimetype = rcube_mime::fix_mimetype($this->mimetype);
}
/**
* Remove temp files, etc.
*/
public function __destruct()
{
if ($this->body_file) {
@unlink($this->body_file);
}
}
/**
* Check if the object is a message part not uploaded file
*
* @return bool True if the object is a message part
*/
public function is_message_part()
{
return !empty($this->message);
}
/**
* Object/request status
*
* @return bool Status
*/
public function is_valid()
{
return !empty($this->part) || !empty($this->upload);
}
/**
* Return attachment/part mimetype if this is an image
* of supported type.
*
* @return string Image mimetype
*/
public function image_type()
{
$part = (object) [
'filename' => $this->filename,
'mimetype' => $this->mimetype,
];
return rcmail_action_mail_index::part_image_type($part);
}
/**
* Formatted attachment/part size (with units)
*
* @return string Attachment/part size (with units)
*/
public function size()
{
$part = $this->part ?: ((object) ['size' => $this->size, 'exact_size' => true]);
return rcmail_action::message_part_size($part);
}
/**
* Returns, prints or saves the attachment/part body
*/
public function body($size = null, $fp = null)
{
// we may have the body in memory or file already
if ($this->body !== null) {
if ($fp == -1) {
echo $size ? substr($this->body, 0, $size) : $this->body;
}
else if ($fp) {
$result = fwrite($fp, $size ? substr($this->body, $size) : $this->body) !== false;
}
else {
$result = $size ? substr($this->body, 0, $size) : $this->body;
}
}
else if ($this->body_file) {
if ($size) {
$result = file_get_contents($this->body_file, false, null, 0, $size);
}
else {
$result = file_get_contents($this->body_file);
}
if ($fp == -1) {
echo $result;
}
else if ($fp) {
$result = fwrite($fp, $result) !== false;
}
}
else if ($this->message) {
$result = $this->message->get_part_body($this->part->mime_id, false, 0, $fp);
// check connection status
if (!$fp && $this->size && empty($result)) {
self::check_storage_status();
}
}
else if ($this->upload) {
// This hook retrieves the attachment contents from the file storage backend
$attachment = rcube::get_instance()->plugins->exec_hook('attachment_get', $this->upload);
if ($fp && $fp != -1) {
if ($attachment['data']) {
$result = fwrite($fp, $size ? substr($attachment['data'], 0, $size) : $attachment['data']) !== false;
}
else if ($attachment['path']) {
if ($fh = fopen($attachment['path'], 'rb')) {
$result = stream_copy_to_stream($fh, $fp, $size ? $size : -1);
}
}
}
else {
$data = $attachment['data'] ?? '';
if (!$data && $attachment['path']) {
$data = file_get_contents($attachment['path']);
}
if ($fp == -1) {
echo $size ? substr($data, 0, $size) : $data;
}
else {
$result = $size ? substr($data, 0, $size) : $data;
}
}
}
return $result ?? null;
}
/**
* Save the body to a file
*
* @param string $filename File name with path
*
* @return bool True on success, False on failure
*/
public function body_to_file($filename)
{
if ($filename && $this->size && ($fp = fopen($filename, 'w'))) {
$this->body(0, $fp);
$this->body_file = $filename;
fclose($fp);
@chmod($filename, 0600);
return true;
}
return false;
}
/**
* Output attachment body with content filtering
*/
public function output($mimetype)
{
if (!$this->size) {
return false;
}
$secure = stripos($mimetype, 'image/') === false || $this->download;
// Remove <script> in SVG images
if (!$secure && stripos($mimetype, 'image/svg') === 0) {
if (!$this->body) {
$this->body = $this->body();
if (empty($this->body)) {
return false;
}
}
echo self::svg_filter($this->body);
return true;
}
if ($this->body !== null && !$this->download) {
header("Content-Length: " . strlen($this->body));
echo $this->body;
return true;
}
// Don't be tempted to set Content-Length to $part->d_parameters['size'] (#1490482)
// RFC2183 says "The size parameter indicates an approximate size"
return $this->body(0, -1);
}
/**
* Returns formatted HTML if the attachment is HTML
*/
public function html()
{
list($type, $subtype) = explode('/', $this->mimetype);
$part = (object) [
'charset' => $this->charset,
'ctype_secondary' => $subtype,
];
// get part body if not available
// fix formatting and charset
$body = rcube_message::format_part_body($this->body(), $part);
// show images?
$is_safe = $this->is_safe();
return rcmail_action_mail_index::wash_html($body, ['safe' => $is_safe, 'inline_html' => false]);
}
/**
* Remove <script> in SVG images
*/
public static function svg_filter($body)
{
// clean SVG with washtml
$wash_opts = [
'show_washed' => false,
'allow_remote' => false,
'charset' => RCUBE_CHARSET,
'html_elements' => ['title'],
];
// initialize HTML washer
$washer = new rcube_washtml($wash_opts);
// allow CSS styles, will be sanitized by rcmail_washtml_callback()
$washer->add_callback('style', 'rcmail_action_mail_index::washtml_callback');
return $washer->wash($body);
}
/**
* Handles nicely storage connection errors
*/
public static function check_storage_status()
{
$error = rcmail::get_instance()->storage->get_error_code();
// Check if we have a connection error
if ($error == rcube_imap_generic::ERROR_BAD) {
ob_end_clean();
// Get action is often executed simultaneously.
// Some servers have MAXPERIP or other limits.
// To workaround this we'll wait for some time
// and try again (once).
// Note: Random sleep interval is used to minimize concurrency
// in getting message parts
if (!isset($_GET['_redirected'])) {
usleep(rand(10, 30) * 100000); // 1-3 sec.
header('Location: ' . $_SERVER['REQUEST_URI'] . '&_redirected=1');
}
else {
rcube::raise_error([
'code' => 500, 'file' => __FILE__, 'line' => __LINE__,
'message' => 'Unable to get/display message part. IMAP connection error'
],
true, true
);
}
// Don't kill session, just quit (#1486995)
exit;
}
}
public function is_safe()
{
if ($this->message) {
return rcmail_action_mail_index::check_safe($this->message);
}
return !empty($_GET['_safe']);
}
}
@@ -0,0 +1,87 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| PURPOSE: |
| Render a simple HTML page with the given contents |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
*/
/**
* Class to create an empty HTML page with some default styles
*
* @package Webmail
* @subpackage View
*/
class rcmail_html_page extends rcmail_output_html
{
protected $inline_warning;
/**
* Process the page content and write to stdOut
*
* @param string $contents HTML page content
*/
public function write($contents = '')
{
self::reset(true);
// load embed.css from skin folder (if exists)
$embed_css = $this->config->get('embed_css_location', '/embed.css');
if ($embed_css = $this->get_skin_file($embed_css, $path, null, true)) {
$this->include_css($embed_css);
}
else { // set default styles for warning blocks inside the attachment part frame
$this->add_header(html::tag('style', ['type' => 'text/css'],
".rcmail-inline-message { font-family: sans-serif; border:2px solid #ffdf0e;"
. "background:#fef893; padding:0.6em 1em; margin-bottom:0.6em }\n" .
".rcmail-inline-buttons { margin-bottom:0 }"
));
}
if (empty($contents)) {
$contents = '<html><body></body></html>';
}
if ($this->inline_warning) {
$body_start = 0;
if ($body_pos = strpos($contents, '<body')) {
$body_start = strpos($contents, '>', $body_pos) + 1;
}
$contents = substr_replace($contents, $this->inline_warning, $body_start, 0);
}
parent::write($contents);
}
/**
* Add inline warning with optional button
*
* @param string $text Warning content
* @param string $button_label Button label
* @param string $button_url Button URL
*/
public function register_inline_warning($text, $button_label = null, $button_url = null)
{
$text = html::span(null, $text);
if ($button_label) {
$onclick = "location.href = '$button_url'";
$button = html::tag('button', ['onclick' => $onclick], rcube::Q($button_label));
$text .= html::p(['class' => 'rcmail-inline-buttons'], $button);
}
$this->inline_warning = html::div(['class' => 'rcmail-inline-message rcmail-inline-warning'], $text);
}
}
@@ -0,0 +1,932 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| PURPOSE: |
| Roundcube Installer |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
| Author: Aleksander Machniak <alec@alec.pl> |
+-----------------------------------------------------------------------+
*/
/**
* Class to control the installation process of the Roundcube Webmail package
*
* @category Install
* @package Webmail
*/
class rcmail_install
{
public $step;
public $last_error;
public $is_post = false;
public $failures = 0;
public $config = [];
public $defaults = [];
public $comments = [];
public $configured = false;
public $legacy_config = false;
public $email_pattern = '([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9])';
public $bool_config_props = ['ip_check', 'enable_spellcheck', 'auto_create_user', 'smtp_log', 'prefer_html'];
public $local_config = ['db_dsnw', 'imap_host', 'support_url', 'des_key', 'plugins'];
public $obsolete_config = ['db_backend', 'db_max_length', 'double_auth', 'preview_pane', 'debug_level', 'referer_check'];
public $replaced_config = [
'skin_path' => 'skin',
'locale_string' => 'language',
'multiple_identities' => 'identities_level',
'addrbook_show_images' => 'show_images',
'imap_root' => 'imap_ns_personal',
'pagesize' => 'mail_pagesize',
'top_posting' => 'reply_mode',
'keep_alive' => 'refresh_interval',
'min_keep_alive' => 'min_refresh_interval',
'default_host' => 'imap_host',
'smtp_server' => 'smtp_host',
];
// List of configuration options supported by the Installer
public $supported_config = [
'product_name', 'support_url', 'temp_dir', 'des_key', 'ip_check', 'enable_spellcheck',
'spellcheck_engine', 'identities_level', 'log_driver', 'log_dir', 'syslog_id',
'syslog_facility', 'db_dsnw', 'db_prefix', 'imap_host', 'username_domain',
'auto_create_user', 'sent_mbox', 'trash_mbox', 'drafts_mbox', 'junk_mbox',
'smtp_host', 'smtp_user', 'smtp_pass', 'smtp_log', 'language', 'skin', 'mail_pagesize',
'addressbook_pagesize', 'prefer_html', 'htmleditor', 'draft_autosave', 'mdn_requests',
'mime_param_folding', 'plugins',
];
// list of supported database drivers
public $supported_dbs = [
'MySQL' => 'pdo_mysql',
'PostgreSQL' => 'pdo_pgsql',
'SQLite' => 'pdo_sqlite',
'SQLite (v2)' => 'pdo_sqlite2',
'SQL Server (SQLSRV)' => 'pdo_sqlsrv',
'SQL Server (DBLIB)' => 'pdo_dblib',
'Oracle' => 'oci8',
];
/** @var array List of config options with default value change per-release */
public $defaults_changes = [
'1.4.0' => ['skin', 'smtp_port', 'smtp_user', 'smtp_pass'],
'1.4.1' => ['jquery_ui_skin_map'],
];
/**
* Constructor
*/
public function __construct()
{
$this->step = isset($_REQUEST['_step']) ? intval($_REQUEST['_step']) : 0;
$this->is_post = isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'POST';
}
/**
* Singleton getter
*/
public static function get_instance()
{
static $inst;
if (!$inst) {
$inst = new rcmail_install();
}
return $inst;
}
/**
* Read the local config files and store properties
*/
public function load_config()
{
if ($this->configured) {
return;
}
// defaults
if ($config = $this->load_config_file(RCUBE_CONFIG_DIR . 'defaults.inc.php')) {
$this->config = (array) $config;
$this->defaults = $this->config;
}
$config = null;
// config
if ($config = $this->load_config_file(RCUBE_CONFIG_DIR . 'config.inc.php')) {
$this->config = array_merge($this->config, $config);
}
else {
if ($config = $this->load_config_file(RCUBE_CONFIG_DIR . 'main.inc.php')) {
$this->config = array_merge($this->config, $config);
$this->legacy_config = true;
}
if ($config = $this->load_config_file(RCUBE_CONFIG_DIR . 'db.inc.php')) {
$this->config = array_merge($this->config, $config);
$this->legacy_config = true;
}
}
$this->configured = !empty($config);
}
/**
* Read the default config file and store properties
*
* @param string $file File name with path
*/
public function load_config_file($file)
{
if (!is_readable($file)) {
return;
}
$config = [];
$rcmail_config = []; // deprecated var name
include $file;
// read comments from config file
if (function_exists('token_get_all')) {
$tokens = token_get_all(file_get_contents($file));
$in_config = false;
$buffer = '';
for ($i = 0; $i < count($tokens); $i++) {
$token = $tokens[$i];
if ($token[0] == T_VARIABLE && ($token[1] == '$config' || $token[1] == '$rcmail_config')) {
$in_config = true;
if ($buffer && $tokens[$i+1] == '[' && $tokens[$i+2][0] == T_CONSTANT_ENCAPSED_STRING) {
$propname = trim($tokens[$i+2][1], "'\"");
$this->comments[$propname] = preg_replace('/\n\n/', "\n", $buffer);
$buffer = '';
$i += 3;
}
}
else if ($in_config && $token[0] == T_COMMENT) {
$buffer .= strtr($token[1], ['\n' => "\n"]) . "\n";
}
}
}
return array_merge((array) $rcmail_config, (array) $config);
}
/**
* Getter for a certain config property
*
* @param string $name Property name
* @param string $default Default value
*
* @return mixed The property value
*/
public function getprop($name, $default = '')
{
$value = $this->config[$name] ?? null;
if ($name == 'des_key' && !$this->configured && !isset($_REQUEST["_$name"])) {
$value = rcube_utils::random_bytes(24);
}
return $value !== null && $value !== '' ? $value : $default;
}
/**
* Create configuration file that contains parameters
* that differ from default values.
*
* @param bool $use_post Use POSTed configuration values (of supported options)
*
* @return string The complete config file content
*/
public function create_config($use_post = true)
{
$config = [];
foreach ($this->config as $prop => $default) {
$post_value = $_POST["_$prop"] ?? null;
$value = $default;
if ($use_post && in_array($prop, $this->supported_config)
&& ($post_value !== null || in_array($prop, $this->bool_config_props))
) {
$value = $post_value;
}
// always disable installer
if ($prop == 'enable_installer') {
$value = false;
}
// generate new encryption key, never use the default value
if ($prop == 'des_key' && $value == $this->defaults[$prop]) {
$value = rcube_utils::random_bytes(24);
}
// convert some form data
if ($prop == 'db_dsnw' && !empty($_POST['_dbtype'])) {
if ($_POST['_dbtype'] == 'sqlite') {
$value = sprintf('%s://%s?mode=0646', $_POST['_dbtype'],
$_POST['_dbname'][0] == '/' ? '/' . $_POST['_dbname'] : $_POST['_dbname']);
}
else if ($_POST['_dbtype']) {
$value = sprintf('%s://%s:%s@%s/%s', $_POST['_dbtype'],
rawurlencode($_POST['_dbuser']), rawurlencode($_POST['_dbpass']), $_POST['_dbhost'], $_POST['_dbname']);
}
}
else if ($prop == 'imap_host' && is_array($value)) {
$value = self::_clean_array($value);
if (count($value) <= 1) {
$value = $value[0];
}
}
else if ($prop == 'mail_pagesize' || $prop == 'addressbook_pagesize') {
$value = max(2, intval($value));
}
else if ($prop == 'smtp_user' && !empty($_POST['_smtp_user_u'])) {
$value = '%u';
}
else if ($prop == 'smtp_pass' && !empty($_POST['_smtp_user_u'])) {
$value = '%p';
}
else if (is_bool($default)) {
$value = (bool) $value;
}
else if (is_numeric($value)) {
$value = intval($value);
}
else if ($prop == 'plugins' && !empty($_POST['submit'])) {
$value = [];
foreach (array_keys($_POST) as $key) {
if (preg_match('/^_plugins_*/', $key)) {
array_push($value, $_POST[$key]);
}
}
}
// skip this property
if ($value == ($this->defaults[$prop] ?? null)
&& (!in_array($prop, $this->local_config)
|| in_array($prop, array_merge($this->obsolete_config, array_keys($this->replaced_config)))
|| preg_match('/^db_(table|sequence)_/', $prop)
)
) {
continue;
}
// save change
$this->config[$prop] = $value;
$config[$prop] = $value;
}
$out = "<?php\n\n";
$out .= "/* Local configuration for Roundcube Webmail */\n\n";
foreach ($config as $prop => $value) {
// copy option descriptions from existing config or defaults.inc.php
$out .= $this->comments[$prop] ?? '';
$out .= "\$config['$prop'] = " . self::_dump_var($value, $prop) . ";\n\n";
}
return $out;
}
/**
* save generated config file in RCUBE_CONFIG_DIR
*
* @return boolean True if the file was saved successfully, false if not
*/
public function save_configfile($config)
{
if (is_writable(RCUBE_CONFIG_DIR)) {
return file_put_contents(RCUBE_CONFIG_DIR . 'config.inc.php', $config);
}
return false;
}
/**
* Check the current configuration for missing properties
* and deprecated or obsolete settings
*
* @param string $version Previous version on upgrade
*
* @return array List with problems detected
*/
public function check_config($version = null)
{
$this->load_config();
if (!$this->configured) {
return;
}
$out = $seen = [];
// iterate over the current configuration
foreach (array_keys($this->config) as $prop) {
if (!empty($this->replaced_config[$prop])) {
$replacement = $this->replaced_config[$prop];
$out['replaced'][] = ['prop' => $prop, 'replacement' => $replacement];
$seen[$replacement] = true;
}
else if (empty($seen[$prop]) && in_array($prop, $this->obsolete_config)) {
$out['obsolete'][] = ['prop' => $prop];
$seen[$prop] = true;
}
}
// the old default mime_magic reference is obsolete
if ($this->config['mime_magic'] == '/usr/share/misc/magic') {
$out['obsolete'][] = [
'prop' => 'mime_magic',
'explain' => "Set value to null in order to use system default"
];
}
// check config dependencies and contradictions
if (!empty($this->config['enable_spellcheck']) && $this->config['spellcheck_engine'] == 'pspell') {
if (!extension_loaded('pspell')) {
$out['dependencies'][] = [
'prop' => 'spellcheck_engine',
'explain' => "This requires the <tt>pspell</tt> extension which could not be loaded."
];
}
else if (!empty($this->config['spellcheck_languages'])) {
foreach ($this->config['spellcheck_languages'] as $lang => $descr) {
if (!@pspell_new($lang)) {
$out['dependencies'][] = [
'prop' => 'spellcheck_languages',
'explain' => "You are missing pspell support for language $lang ($descr)"
];
}
}
}
}
if ($this->config['log_driver'] == 'syslog') {
if (!function_exists('openlog')) {
$out['dependencies'][] = [
'prop' => 'log_driver',
'explain' => "This requires the <tt>syslog</tt> extension which could not be loaded."
];
}
if (empty($this->config['syslog_id'])) {
$out['dependencies'][] = [
'prop' => 'syslog_id',
'explain' => "Using <tt>syslog</tt> for logging requires a syslog ID to be configured"
];
}
}
// check ldap_public sources having global_search enabled
if (is_array($this->config['ldap_public']) && !is_array($this->config['autocomplete_addressbooks'])) {
foreach ($this->config['ldap_public'] as $ldap_public) {
if ($ldap_public['global_search']) {
$out['replaced'][] = [
'prop' => 'ldap_public::global_search',
'replacement' => 'autocomplete_addressbooks'
];
break;
}
}
}
if ($version) {
$out['defaults'] = [];
foreach ($this->defaults_changes as $v => $opts) {
if (version_compare($v, $version, '>')) {
$out['defaults'] = array_merge($out['defaults'], $opts);
}
}
$out['defaults'] = array_unique($out['defaults']);
}
return $out;
}
/**
* Merge the current configuration with the defaults
* and copy replaced values to the new options.
*/
public function merge_config()
{
$current = $this->config;
$this->config = [];
foreach ($this->replaced_config as $prop => $replacement) {
if (isset($current[$prop])) {
if ($prop == 'skin_path') {
$this->config[$replacement] = preg_replace('#skins/(\w+)/?$#', '\\1', $current[$prop]);
}
else if ($prop == 'multiple_identities') {
$this->config[$replacement] = $current[$prop] ? 2 : 0;
}
else {
$this->config[$replacement] = $current[$prop];
}
unset($current[$prop]);
unset($current[$replacement]);
}
}
// Merge old *_port options into the new *_host options, where possible
foreach (['default' => 'imap', 'smtp' => 'smtp'] as $prop => $type) {
$old_prop = "{$prop}_port";
$new_prop = "{$type}_host";
if (!empty($current[$old_prop]) && !empty($this->config[$new_prop])
&& is_string($this->config[$new_prop])
&& !preg_match('/:[0-9]+$/', $this->config[$new_prop])
) {
$this->config[$new_prop] .= ':' . $current[$old_prop];
}
unset($current[$old_prop]);
}
foreach ($this->obsolete_config as $prop) {
unset($current[$prop]);
}
// add all ldap_public sources having global_search enabled to autocomplete_addressbooks
if (!empty($current['ldap_public']) && is_array($current['ldap_public'])) {
foreach ($current['ldap_public'] as $key => $ldap_public) {
if (!empty($ldap_public['global_search'])) {
$this->config['autocomplete_addressbooks'][] = $key;
unset($current['ldap_public'][$key]['global_search']);
}
}
}
$this->config = array_merge($this->config, $current);
}
/**
* Compare the local database schema with the reference schema
* required for this version of Roundcube
*
* @param rcube_db $db Database object
*
* @return bool True if the schema is up-to-date, false if not or an error occurred
*/
public function db_schema_check($db)
{
if (!$this->configured) {
return false;
}
// read reference schema from mysql.initial.sql
$engine = $db->db_provider;
$db_schema = $this->db_read_schema(INSTALL_PATH . "SQL/$engine.initial.sql", $schema_version);
$errors = [];
// Just check the version
if ($schema_version) {
$version = rcmail_utils::db_version();
if (empty($version)) {
$errors[] = "Schema version not found";
}
else if ($schema_version != $version) {
$errors[] = "Schema version: {$version} (required: {$schema_version})";
}
return !empty($errors) ? $errors : false;
}
// check list of tables
$existing_tables = $db->list_tables();
foreach ($db_schema as $table => $cols) {
$table = $this->config['db_prefix'] . $table;
if (!in_array($table, $existing_tables)) {
$errors[] = "Missing table '".$table."'";
}
else { // compare cols
$db_cols = $db->list_cols($table);
$diff = array_diff(array_keys($cols), $db_cols);
if (!empty($diff)) {
$errors[] = "Missing columns in table '$table': " . implode(',', $diff);
}
}
}
return !empty($errors) ? $errors : false;
}
/**
* Utility function to read database schema from an .sql file
*/
private function db_read_schema($schemafile, &$version = null)
{
$lines = file($schemafile);
$schema = [];
$keywords = ['PRIMARY','KEY','INDEX','UNIQUE','CONSTRAINT','REFERENCES','FOREIGN'];
$table_name = null;
foreach ($lines as $line) {
if (preg_match('/^\s*create table ([\S]+)/i', $line, $m)) {
$table_name = explode('.', $m[1]);
$table_name = end($table_name);
$table_name = preg_replace('/[`"\[\]]/', '', $table_name);
}
else if (preg_match('/insert into/i', $line) && preg_match('/\'roundcube-version\',\s*\'([0-9]+)\'/', $line, $m)) {
$version = $m[1];
}
else if ($table_name && ($line = trim($line))) {
if ($line == 'GO' || $line[0] == ')' || $line[strlen($line)-1] == ';') {
$table_name = null;
}
else {
$items = explode(' ', $line);
$col = $items[0];
$col = preg_replace('/[`"\[\]]/', '', $col);
if (!in_array(strtoupper($col), $keywords)) {
$type = strtolower($items[1]);
$type = preg_replace('/[^a-zA-Z0-9()]/', '', $type);
$schema[$table_name][$col] = $type;
}
}
}
}
return $schema;
}
/**
* Try to detect some file's mimetypes to test the correct behavior of fileinfo
*/
public function check_mime_detection()
{
$errors = [];
$files = [
'program/resources/tinymce/video.png' => 'image/png',
'program/resources/blank.tiff' => 'image/tiff',
'program/resources/blocked.gif' => 'image/gif',
];
foreach ($files as $path => $expected) {
$mimetype = rcube_mime::file_content_type(INSTALL_PATH . $path, basename($path));
if ($mimetype != $expected) {
$errors[] = [$path, $mimetype, $expected];
}
}
return $errors;
}
/**
* Check the correct configuration of the 'mime_types' mapping option
*/
public function check_mime_extensions()
{
$errors = [];
$types = [
'application/zip' => 'zip',
'text/css' => 'css',
'application/pdf' => 'pdf',
'image/gif' => 'gif',
'image/svg+xml' => 'svg',
];
foreach ($types as $mimetype => $expected) {
$ext = rcube_mime::get_mime_extensions($mimetype);
if (!in_array($expected, (array) $ext)) {
$errors[] = [$mimetype, $ext, $expected];
}
}
return $errors;
}
/**
* Getter for the last error message
*
* @return string Error message or null if none exists
*/
public function get_error()
{
return $this->last_error['message'] ?? null;
}
/**
* Return a list with all imap/smtp hosts configured
*
* @return array Clean list with imap/smtp hosts
*/
public function get_hostlist($prop = 'imap_host')
{
$hosts = (array) $this->getprop($prop);
$out = [];
$imap_host = '';
if ($prop == 'smtp_host') {
// Set the imap host name for the %h macro
$default_hosts = $this->get_hostlist();
$imap_host = !empty($default_hosts) ? $default_hosts[0] : '';
}
foreach ($hosts as $key => $name) {
if (!empty($name)) {
if ($prop == 'smtp_host') {
// SMTP host array uses `IMAP host => SMTP host` format
$host = $name;
}
else {
$host = is_numeric($key) ? $name : $key;
}
$out[] = rcube_utils::parse_host($host, $imap_host);
}
}
return $out;
}
/**
* Create a HTML dropdown to select a previous version of Roundcube
*/
public function versions_select($attrib = [])
{
$select = new html_select($attrib);
$select->add([
'0.1-stable', '0.1.1',
'0.2-alpha', '0.2-beta', '0.2-stable',
'0.3-stable', '0.3.1',
'0.4-beta', '0.4.2',
'0.5-beta', '0.5', '0.5.1', '0.5.2', '0.5.3', '0.5.4',
'0.6-beta', '0.6',
'0.7-beta', '0.7', '0.7.1', '0.7.2', '0.7.3', '0.7.4',
'0.8-beta', '0.8-rc', '0.8.0', '0.8.1', '0.8.2', '0.8.3', '0.8.4', '0.8.5', '0.8.6',
'0.9-beta', '0.9-rc', '0.9-rc2',
// Note: Do not add newer versions here
]);
return $select;
}
/**
* Return a list with available subfolders of the skin directory
*
* @return array List of available skins
*/
public function list_skins()
{
$skins = [];
$skindir = INSTALL_PATH . 'skins/';
foreach (glob($skindir . '*') as $path) {
if (is_dir($path) && is_readable($path)) {
$skins[] = substr($path, strlen($skindir));
}
}
return $skins;
}
/**
* Return a list with available subfolders of the plugins directory
* (with their associated description in composer.json)
*
* @return array List of available plugins
*/
public function list_plugins()
{
$plugins = [];
$plugin_dir = INSTALL_PATH . 'plugins/';
$enabled = isset($this->config['plugins']) ? (array) $this->config['plugins'] : [];
foreach (glob($plugin_dir . '*') as $path) {
if (!is_dir($path)) {
continue;
}
if (is_readable($path . '/composer.json')) {
$file_json = json_decode(file_get_contents($path . '/composer.json'));
$plugin_desc = $file_json->description ?: 'N/A';
}
else {
$plugin_desc = 'N/A';
}
$name = substr($path, strlen($plugin_dir));
$plugins[] = [
'name' => $name,
'desc' => $plugin_desc,
'enabled' => in_array($name, $enabled)
];
}
return $plugins;
}
/**
* Display OK status
*
* @param string $name Test name
* @param string $message Confirm message
*/
public function pass($name, $message = '')
{
echo rcube::Q($name) . ':&nbsp; <span class="success">OK</span>';
$this->_showhint($message);
}
/**
* Display an error status and increase failure count
*
* @param string $name Test name
* @param string $message Error message
* @param string $url URL for details
* @param bool $optional Do not count this failure
*/
public function fail($name, $message = '', $url = '', $optional = false)
{
if (!$optional) {
$this->failures++;
}
echo rcube::Q($name) . ':&nbsp; <span class="fail">NOT OK</span>';
$this->_showhint($message, $url);
}
/**
* Display an error status for optional settings/features
*
* @param string $name Test name
* @param string $message Error message
* @param string $url URL for details
*/
public function optfail($name, $message = '', $url = '')
{
echo rcube::Q($name) . ':&nbsp; <span class="na">NOT OK</span>';
$this->_showhint($message, $url);
}
/**
* Display warning status
*
* @param string $name Test name
* @param string $message Warning message
* @param string $url URL for details
*/
public function na($name, $message = '', $url = '')
{
echo rcube::Q($name) . ':&nbsp; <span class="na">NOT AVAILABLE</span>';
$this->_showhint($message, $url);
}
private function _showhint($message, $url = '')
{
$hint = rcube::Q($message);
if ($url) {
$hint .= ($hint ? '; ' : '') . 'See <a href="' . rcube::Q($url) . '" target="_blank">' . rcube::Q($url) . '</a>';
}
if ($hint) {
echo '<span class="indent">(' . $hint . ')</span>';
}
}
private static function _clean_array($arr)
{
$out = [];
foreach (array_unique($arr) as $k => $val) {
if (!empty($val)) {
if (is_numeric($k)) {
$out[] = $val;
}
else {
$out[$k] = $val;
}
}
}
return $out;
}
private static function _dump_var($var, $name = null)
{
// special values
switch ($name) {
case 'syslog_facility':
$list = [
32 => 'LOG_AUTH', 80 => 'LOG_AUTHPRIV', 72 => ' LOG_CRON',
24 => 'LOG_DAEMON', 0 => 'LOG_KERN', 128 => 'LOG_LOCAL0',
136 => 'LOG_LOCAL1', 144 => 'LOG_LOCAL2', 152 => 'LOG_LOCAL3',
160 => 'LOG_LOCAL4', 168 => 'LOG_LOCAL5', 176 => 'LOG_LOCAL6',
184 => 'LOG_LOCAL7', 48 => 'LOG_LPR', 16 => 'LOG_MAIL',
56 => 'LOG_NEWS', 40 => 'LOG_SYSLOG', 8 => 'LOG_USER', 64 => 'LOG_UUCP'
];
if (!empty($list[$var])) {
return $list[$var];
}
break;
}
if (is_array($var)) {
if (empty($var)) {
return '[]';
}
// check if all keys are numeric
$isnum = true;
foreach (array_keys($var) as $key) {
if (!is_numeric($key)) {
$isnum = false;
break;
}
}
if ($isnum) {
return '[' . implode(', ', array_map(['rcmail_install', '_dump_var'], $var)) . ']';
}
}
return var_export($var, true);
}
/**
* Initialize the database with the according schema
*
* @param rcube_db $db Database connection
*
* @return bool True on success, False on error
*/
public function init_db($db)
{
$engine = $db->db_provider;
// read schema file from /SQL/*
$fname = INSTALL_PATH . "SQL/$engine.initial.sql";
if ($sql = @file_get_contents($fname)) {
$db->set_option('table_prefix', $this->config['db_prefix']);
$db->exec_script($sql);
}
else {
$this->fail('DB Schema', "Cannot read the schema file: $fname");
return false;
}
if ($err = $this->get_error()) {
$this->fail('DB Schema', "Error creating database schema: $err");
return false;
}
return true;
}
/**
* Update database schema
*
* @param string $version Version to update from
*
* @return boolean True on success, False on error
*/
public function update_db($version)
{
return rcmail_utils::db_update(INSTALL_PATH . 'SQL', 'roundcube', $version, ['quiet' => true]);
}
/**
* Handler for Roundcube errors
*/
public function raise_error($p)
{
$this->last_error = $p;
}
/**
* Check if vendor/autoload.php was created by Roundcube and left untouched
*
* @param string $target_dir The target installation dir
* @return string
*/
public static function vendor_dir_untouched($target_dir)
{
system('grep -q "generated by Roundcube" ' . escapeshellarg($target_dir . '/vendor/autoload.php') . ' 2>/dev/null', $exit_code);
return $exit_code === 0;
}
}
+588
View File
@@ -0,0 +1,588 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| CONTENTS: |
| Roundcube OAuth2 utilities |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
*/
use GuzzleHttp\Client;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Exception\RequestException;
/**
* Roundcube OAuth2 utilities
*
* @package Webmail
* @subpackage Utils
*/
class rcmail_oauth
{
/** @var rcmail */
protected $rcmail;
/** @var array */
protected $options = [];
/** @var string */
protected $last_error = null;
/** @var boolean */
protected $no_redirect = false;
/** @var rcmail_oauth */
static protected $instance;
/**
* Singleton factory
*
* @return rcmail_oauth The one and only instance
*/
static function get_instance($options = [])
{
if (!self::$instance) {
self::$instance = new rcmail_oauth($options);
self::$instance->init();
}
return self::$instance;
}
/**
* Object constructor
*
* @param array $options Config options:
*/
public function __construct($options = [])
{
$this->rcmail = rcmail::get_instance();
$this->options = (array) $options + [
'provider' => $this->rcmail->config->get('oauth_provider'),
'auth_uri' => $this->rcmail->config->get('oauth_auth_uri'),
'token_uri' => $this->rcmail->config->get('oauth_token_uri'),
'client_id' => $this->rcmail->config->get('oauth_client_id'),
'client_secret' => $this->rcmail->config->get('oauth_client_secret'),
'identity_uri' => $this->rcmail->config->get('oauth_identity_uri'),
'identity_fields' => $this->rcmail->config->get('oauth_identity_fields', ['email']),
'scope' => $this->rcmail->config->get('oauth_scope'),
'verify_peer' => $this->rcmail->config->get('oauth_verify_peer', true),
'auth_parameters' => $this->rcmail->config->get('oauth_auth_parameters', []),
'login_redirect' => $this->rcmail->config->get('oauth_login_redirect', false),
];
}
/**
* Initialize this instance
*
* @return void
*/
protected function init()
{
// subscribe to storage and smtp init events
if ($this->is_enabled()) {
$this->rcmail->plugins->register_hook('storage_init', [$this, 'storage_init']);
$this->rcmail->plugins->register_hook('smtp_connect', [$this, 'smtp_connect']);
$this->rcmail->plugins->register_hook('managesieve_connect', [$this, 'managesieve_connect']);
$this->rcmail->plugins->register_hook('logout_after', [$this, 'logout_after']);
$this->rcmail->plugins->register_hook('login_failed', [$this, 'login_failed']);
$this->rcmail->plugins->register_hook('unauthenticated', [$this, 'unauthenticated']);
$this->rcmail->plugins->register_hook('refresh', [$this, 'refresh']);
}
}
/**
* Check if OAuth is generally enabled in config
*
* @return boolean
*/
public function is_enabled()
{
return !empty($this->options['provider']) &&
!empty($this->options['token_uri']) &&
!empty($this->options['client_id']);
}
/**
* Compose a fully qualified redirect URI for auth requests
*
* @return string
*/
public function get_redirect_uri()
{
$url = $this->rcmail->url([], true, true);
// rewrite redirect URL to not contain query parameters because some providers do not support this
$url = preg_replace('/\?.*/', '', $url);
return slashify($url) . 'index.php/login/oauth';
}
/**
* Getter for the last error occurred
*
* @return mixed
*/
public function get_last_error()
{
return $this->last_error;
}
/**
* Helper method to decode a JWT
*
* @param string $jwt
* @return array Hash array with decoded body
*/
public function jwt_decode($jwt)
{
list($headb64, $bodyb64, $cryptob64) = explode('.', strtr($jwt, '-_', '+/'));
$header = json_decode(base64_decode($headb64), true);
$body = json_decode(base64_decode($bodyb64), true);
if (isset($body['azp']) && $body['azp'] !== $this->options['client_id']) {
throw new RuntimeException('Failed to validate JWT: invalid azp value');
}
else if (isset($body['aud']) && !in_array($this->options['client_id'], (array) $body['aud'])) {
throw new RuntimeException('Failed to validate JWT: invalid aud value');
}
else if (!isset($body['azp']) && !isset($body['aud'])) {
throw new RuntimeException('Failed to validate JWT: missing aud/azp value');
}
return $body;
}
/**
* Login action: redirect to `oauth_auth_uri`
*
* @return void
*/
public function login_redirect()
{
if (!empty($this->options['auth_uri']) && !empty($this->options['client_id'])) {
// create a secret string
$_SESSION['oauth_state'] = rcube_utils::random_bytes(12);
// compose full oauth login uri
$delimiter = strpos($this->options['auth_uri'], '?') > 0 ? '&' : '?';
$query = http_build_query([
'response_type' => 'code',
'client_id' => $this->options['client_id'],
'scope' => $this->options['scope'],
'redirect_uri' => $this->get_redirect_uri(),
'state' => $_SESSION['oauth_state'],
] + (array) $this->options['auth_parameters']);
$this->rcmail->output->redirect($this->options['auth_uri'] . $delimiter . $query); // exit
}
else {
// log error about missing config options
rcube::raise_error([
'message' => "Missing required OAuth config options 'oauth_auth_uri', 'oauth_client_id'",
'file' => __FILE__,
'line' => __LINE__,
], true, false
);
}
}
/**
* Request access token with auth code returned from oauth login
*
* @param string $auth_code
* @param string $state
*
* @return array Authorization data as hash array with entries
* `username` as the authentication user name
* `authorization` as the oauth authorization string "<type> <access-token>"
* `token` as the complete oauth response to be stored in session
*/
public function request_access_token($auth_code, $state = null)
{
$oauth_token_uri = $this->options['token_uri'];
$oauth_client_id = $this->options['client_id'];
$oauth_client_secret = $this->options['client_secret'];
$oauth_identity_uri = $this->options['identity_uri'];
if (!empty($oauth_token_uri) && !empty($oauth_client_secret)) {
try {
// validate state parameter against $_SESSION['oauth_state']
if (!empty($_SESSION['oauth_state']) && $_SESSION['oauth_state'] !== $state) {
throw new RuntimeException('Invalid state parameter');
}
// send token request to get a real access token for the given auth code
$client = new Client([
'timeout' => 10.0,
'verify' => $this->options['verify_peer'],
]);
$response = $client->post($oauth_token_uri, [
'form_params' => [
'code' => $auth_code,
'client_id' => $oauth_client_id,
'client_secret' => $oauth_client_secret,
'redirect_uri' => $this->get_redirect_uri(),
'grant_type' => 'authorization_code',
],
]);
$data = \GuzzleHttp\json_decode($response->getBody(), true);
// auth success
if (!empty($data['access_token'])) {
$username = null;
$identity = null;
$authorization = sprintf('%s %s', $data['token_type'], $data['access_token']);
// decode JWT id_token if provided
if (!empty($data['id_token'])) {
try {
$identity = $this->jwt_decode($data['id_token']);
foreach ($this->options['identity_fields'] as $field) {
if (isset($identity[$field])) {
$username = $identity[$field];
break;
}
}
} catch (\Exception $e) {
// log error
rcube::raise_error([
'message' => $e->getMessage(),
'file' => __FILE__,
'line' => __LINE__,
], true, false
);
}
}
// request user identity (email)
if (empty($username) && !empty($oauth_identity_uri)) {
$identity_response = $client->get($oauth_identity_uri, [
'headers' => [
'Authorization' => $authorization,
'Accept' => 'application/json',
],
]);
$identity = \GuzzleHttp\json_decode($identity_response->getBody(), true);
foreach ($this->options['identity_fields'] as $field) {
if (isset($identity[$field])) {
$username = $identity[$field];
break;
}
}
}
$data['identity'] = $username;
$this->mask_auth_data($data);
$this->rcmail->session->remove('oauth_state');
$this->rcmail->plugins->exec_hook('oauth_login', array_merge($data, [
'username' => $username,
'identity' => $identity,
]));
// remove some data we don't want to store in session
unset($data['id_token']);
// return auth data
return [
'username' => $username,
'authorization' => $authorization,
'token' => $data,
];
}
else {
throw new Exception('Unexpected response from OAuth service');
}
}
catch (RequestException $e) {
$this->last_error = "OAuth token request failed: " . $e->getMessage();
$this->no_redirect = true;
$formatter = new MessageFormatter();
rcube::raise_error([
'message' => $this->last_error . '; ' . $formatter->format($e->getRequest(), $e->getResponse()),
'file' => __FILE__,
'line' => __LINE__,
], true, false
);
return false;
}
catch (Exception $e) {
$this->last_error = "OAuth token request failed: " . $e->getMessage();
$this->no_redirect = true;
rcube::raise_error([
'message' => $this->last_error,
'file' => __FILE__,
'line' => __LINE__,
], true, false
);
return false;
}
}
else {
$this->last_error = "Missing required OAuth config options 'oauth_token_uri', 'oauth_client_id', 'oauth_client_secret'";
rcube::raise_error([
'message' => $this->last_error,
'file' => __FILE__,
'line' => __LINE__,
], true, false
);
return false;
}
}
/**
* Obtain a new access token using the refresh_token grant type
*
* If successful, this will update the `oauth_token` entry in
* session data.
*
* @param array $token
*
* @return array Updated authorization data
*/
public function refresh_access_token(array $token)
{
$oauth_token_uri = $this->options['token_uri'];
$oauth_client_id = $this->options['client_id'];
$oauth_client_secret = $this->options['client_secret'];
// send token request to get a real access token for the given auth code
try {
$client = new Client([
'timeout' => 10.0,
'verify' => $this->options['verify_peer'],
]);
$response = $client->post($oauth_token_uri, [
'form_params' => [
'client_id' => $oauth_client_id,
'client_secret' => $oauth_client_secret,
'refresh_token' => $this->rcmail->decrypt($token['refresh_token']),
'grant_type' => 'refresh_token',
],
]);
$data = \GuzzleHttp\json_decode($response->getBody(), true);
// auth success
if (!empty($data['access_token'])) {
// update access token stored as password
$authorization = sprintf('%s %s', $data['token_type'], $data['access_token']);
$_SESSION['password'] = $this->rcmail->encrypt($authorization);
$this->mask_auth_data($data);
// update session data
$_SESSION['oauth_token'] = array_merge($token, $data);
$this->rcmail->plugins->exec_hook('oauth_refresh_token', $data);
return [
'token' => $data,
'authorization' => $authorization,
];
}
}
catch (RequestException $e) {
$this->last_error = "OAuth refresh token request failed: " . $e->getMessage();
$formatter = new MessageFormatter();
rcube::raise_error([
'message' => $this->last_error . '; ' . $formatter->format($e->getRequest(), $e->getResponse()),
'file' => __FILE__,
'line' => __LINE__,
], true, false
);
// refrehsing token failed, mark session as expired
if ($e->getCode() >= 400 && $e->getCode() < 500) {
$this->rcmail->kill_session();
}
return false;
}
catch (Exception $e) {
$this->last_error = "OAuth refresh token request failed: " . $e->getMessage();
rcube::raise_error([
'message' => $this->last_error,
'file' => __FILE__,
'line' => __LINE__,
], true, false
);
return false;
}
}
/**
* Modify some properties of the received auth response
*
* @param array $token
* @return void
*/
protected function mask_auth_data(&$data)
{
// compute absolute token expiration date
$data['expires'] = time() + $data['expires_in'] - 10;
// encrypt refresh token if provided
if (isset($data['refresh_token'])) {
$data['refresh_token'] = $this->rcmail->encrypt($data['refresh_token']);
}
}
/**
* Check the given access token data if still valid
*
* ... and attempt to refresh if possible.
*
* @param array $token
* @return boolean
*/
protected function check_token_validity($token)
{
if ($token['expires'] < time() && isset($token['refresh_token']) && empty($this->last_error)) {
return $this->refresh_access_token($token) !== false;
}
return false;
}
/**
* Callback for 'storage_init' hook
*
* @param array $options
* @return array
*/
public function storage_init($options)
{
if (isset($_SESSION['oauth_token']) && $options['driver'] === 'imap') {
// check token validity
if ($this->check_token_validity($_SESSION['oauth_token'])) {
$options['password'] = $this->rcmail->decrypt($_SESSION['password']);
}
// enforce XOAUTH2 authorization type
$options['auth_type'] = 'XOAUTH2';
}
return $options;
}
/**
* Callback for 'smtp_connect' hook
*
* @param array $options
* @return array
*/
public function smtp_connect($options)
{
if (isset($_SESSION['oauth_token'])) {
// check token validity
$this->check_token_validity($_SESSION['oauth_token']);
// enforce XOAUTH2 authorization type
$options['smtp_user'] = '%u';
$options['smtp_pass'] = '%p';
$options['smtp_auth_type'] = 'XOAUTH2';
}
return $options;
}
/**
* Callback for 'managesieve_connect' hook
*
* @param array $options
* @return array
*/
public function managesieve_connect($options)
{
if (isset($_SESSION['oauth_token'])) {
// check token validity
$this->check_token_validity($_SESSION['oauth_token']);
// enforce XOAUTH2 authorization type
$options['auth_type'] = 'XOAUTH2';
}
return $options;
}
/**
* Callback for 'logout_after' hook
*
* @param array $options
* @return array
*/
public function logout_after($options)
{
$this->no_redirect = true;
}
/**
* Callback for 'login_failed' hook
*
* @param array $options
* @return array
*/
public function login_failed($options)
{
// no redirect on imap login failures
$this->no_redirect = true;
return $options;
}
/**
* Callback for 'unauthenticated' hook
*
* @param array $options
* @return array
*/
public function unauthenticated($options)
{
if (
$this->options['login_redirect']
&& !$this->rcmail->output->ajax_call
&& !$this->no_redirect
&& empty($options['error'])
&& $options['http_code'] === 200
) {
$this->login_redirect();
}
return $options;
}
/**
* Callback for 'refresh' hook
*
* @param array $options
* @return void
*/
public function refresh($options)
{
if (isset($_SESSION['oauth_token'])) {
$this->check_token_validity($_SESSION['oauth_token']);
}
}
}
@@ -0,0 +1,150 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| CONTENTS: |
| Abstract class for output generation |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
| Author: Aleksander Machniak <alec@alec.pl> |
+-----------------------------------------------------------------------+
*/
/**
* Class for output generation
*
* @package Webmail
* @subpackage View
*/
abstract class rcmail_output extends rcube_output
{
const JS_OBJECT_NAME = 'rcmail';
const BLANK_GIF = 'R0lGODlhDwAPAIAAAMDAwAAAACH5BAEAAAAALAAAAAAPAA8AQAINhI+py+0Po5y02otnAQA7';
public $type = 'html';
public $ajax_call = false;
public $framed = false;
protected $pagetitle = '';
protected $object_handlers = [];
protected $devel_mode = false;
/**
* Object constructor
*/
public function __construct()
{
parent::__construct();
$this->devel_mode = (bool) $this->config->get('devel_mode');
}
/**
* Setter for page title
*
* @param string $title Page title
*/
public function set_pagetitle($title)
{
$this->pagetitle = $title;
}
/**
* Getter for the current skin path property
*/
public function get_skin_path()
{
return $this->config->get('skin_path');
}
/**
* Delete all stored env variables and commands
*/
public function reset()
{
parent::reset();
$this->object_handlers = [];
$this->pagetitle = '';
}
/**
* Call a client method
*
* @param string $cmd Method to call
* @param mixed ...$args Method arguments
*/
abstract function command($cmd, ...$args);
/**
* Add a localized label(s) to the client environment
*
* @param mixed ...$args Labels (an array of strings, or many string arguments)
*/
abstract function add_label(...$args);
/**
* Register a template object handler
*
* @param string $name Object name
* @param callable $func Function name to call
*
* @return void
*/
public function add_handler($name, $func)
{
$this->object_handlers[$name] = $func;
}
/**
* Register a list of template object handlers
*
* @param array $handlers Hash array with object=>handler pairs
*
* @return void
*/
public function add_handlers($handlers)
{
$this->object_handlers = array_merge($this->object_handlers, $handlers);
}
/**
* A wrapper for header() function, so it can be replaced for automated tests
*
* @param string $header The header string
* @param bool $replace Replace previously set header?
*
* @return void
*/
public function header($header, $replace = true)
{
header($header, $replace);
}
/**
* A helper to send output to the browser and exit
*
* @param string $body The output body
* @param array $headers Headers
*
* @return void
*/
public function sendExit($body = '', $headers = [])
{
foreach ($headers as $header) {
header($header);
}
print $body;
exit;
}
}
@@ -0,0 +1,82 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| CONTENTS: |
| Abstract class for output generation |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
*/
/**
* Class for output generation
*
* @package Webmail
* @subpackage View
*/
class rcmail_output_cli extends rcmail_output
{
public $type = 'cli';
/**
* Call a client method
*
* @see rcube_output::command()
*/
function command($cmd, ...$args)
{
// NOP
}
/**
* Add a localized label to the client environment
*
* @see rcube_output::add_label()
*/
function add_label(...$args)
{
// NOP
}
/**
* Invoke display_message command
*
* @see rcube_output::show_message()
*/
function show_message($message, $type = 'notice', $vars = null, $override = true, $timeout = 0)
{
if ($this->app->text_exists($message)) {
$message = $this->app->gettext(['name' => $message, 'vars' => $vars]);
}
printf("[%s] %s\n", strtoupper($type), $message);
}
/**
* Redirect to a certain url.
*
* @see rcube_output::redirect()
*/
function redirect($p = [], $delay = 1)
{
// NOP
}
/**
* Send output to the client.
*/
function send()
{
// NOP
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,280 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| PURPOSE: |
| Class to handle JSON (AJAX) output |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
| Author: Aleksander Machniak <alec@alec.pl> |
+-----------------------------------------------------------------------+
*/
/**
* View class to produce JSON responses
*
* @package Webmail
* @subpackage View
*/
class rcmail_output_json extends rcmail_output
{
protected $texts = [];
protected $commands = [];
protected $callbacks = [];
protected $message = null;
protected $header_sent = false;
public $type = 'js';
public $ajax_call = true;
/**
* Object constructor
*/
public function __construct()
{
parent::__construct();
if (!empty($_SESSION['skin_config'])) {
foreach ($_SESSION['skin_config'] as $key => $value) {
$this->config->set($key, $value, true);
}
$value = array_merge((array) $this->config->get('dont_override'), array_keys($_SESSION['skin_config']));
$this->config->set('dont_override', $value, true);
}
}
/**
* Issue command to set page title
*
* @param string $title New page title
*/
public function set_pagetitle($title)
{
if ($this->config->get('devel_mode') && !empty($_SESSION['username'])) {
$name = $_SESSION['username'];
}
else {
$name = $this->config->get('product_name');
}
$this->command('set_pagetitle', empty($name) ? $title : $name . ' :: ' . $title);
}
/**
* Register a template object handler
*
* @param string $obj Object name
* @param callable $func Function name to call
*/
public function add_handler($obj, $func)
{
// ignore
}
/**
* Register a list of template object handlers
*
* @param array $arr Hash array with object=>handler pairs
*/
public function add_handlers($arr)
{
// ignore
}
/**
* Call a client method
*
* @param string $cmd Method to call
* @param mixed ...$args Additional arguments
*/
public function command($cmd, ...$args)
{
array_unshift($args, $cmd);
if (strpos($args[0], 'plugin.') === 0) {
$this->callbacks[] = $args;
}
else {
$this->commands[] = $args;
}
}
/**
* Add a localized label(s) to the client environment
*
* @param mixed ...$args Labels (an array of strings, or many string arguments)
*/
public function add_label(...$args)
{
if (count($args) == 1 && is_array($args[0])) {
$args = $args[0];
}
foreach ($args as $name) {
$this->texts[$name] = $this->app->gettext($name);
}
}
/**
* Invoke display_message command
*
* @param string $message Message to display
* @param string $type Message type [notice|confirm|error]
* @param array $vars Key-value pairs to be replaced in localized text
* @param bool $override Override last set message
* @param int $timeout Message displaying time in seconds
*
* @uses self::command()
*/
public function show_message($message, $type = 'notice', $vars = null, $override = true, $timeout = 0)
{
if ($override || !$this->message) {
if ($this->app->text_exists($message)) {
if (!empty($vars)) {
$vars = array_map(['rcmail', 'Q'], $vars);
}
$msgtext = $this->app->gettext(['name' => $message, 'vars' => $vars]);
}
else {
$msgtext = $message;
}
$this->message = $message;
$this->command('display_message', $msgtext, $type, $timeout * 1000);
}
}
/**
* Delete all stored env variables and commands
*/
public function reset()
{
parent::reset();
$this->texts = [];
$this->commands = [];
}
/**
* Redirect to a certain url
*
* @param mixed $p Either a string with the action or url parameters as key-value pairs
* @param int $delay Delay in seconds
*
* @see rcmail::url()
*/
public function redirect($p = [], $delay = 1)
{
$location = $this->app->url($p);
$this->remote_response(sprintf("window.setTimeout(function(){ %s.redirect('%s',true); }, %d);",
self::JS_OBJECT_NAME, $location, $delay));
exit;
}
/**
* Send an AJAX response to the client.
*/
public function send()
{
$this->remote_response();
exit;
}
/**
* Show error page and terminate script execution
*
* @param int $code Error code
* @param string $message Error message
*/
public function raise_error($code, $message)
{
if ($code == 403) {
$this->header('HTTP/1.1 403 Forbidden');
die("Invalid Request");
}
$this->show_message("Application Error ($code): $message", 'error');
$this->remote_response();
exit;
}
/**
* Send an AJAX response with executable JS code
*
* @param string $add Additional JS code
*/
protected function remote_response($add = '')
{
if (!$this->header_sent) {
$this->header_sent = true;
$this->nocacheing_headers();
$this->header('Content-Type: application/json; charset=' . $this->get_charset());
}
// unset default env vars
unset($this->env['task'], $this->env['action'], $this->env['comm_path']);
$rcmail = rcmail::get_instance();
$response['action'] = $rcmail->action;
if ($unlock = rcube_utils::get_input_string('_unlock', rcube_utils::INPUT_GPC)) {
$response['unlock'] = $unlock;
}
if (!empty($this->env)) {
$response['env'] = $this->env;
}
if (!empty($this->texts)) {
$response['texts'] = $this->texts;
}
// send function calls
$response['exec'] = $this->get_js_commands() . $add;
if (!empty($this->callbacks)) {
$response['callbacks'] = $this->callbacks;
}
// trigger generic hook where plugins can put additional content to the response
$hook = $this->app->plugins->exec_hook("render_response", ['response' => $response]);
// save some memory
$response = $hook['response'];
unset($hook['response']);
echo self::json_serialize($response, $this->devel_mode, false);
}
/**
* Return executable javascript code for all registered commands
*/
protected function get_js_commands()
{
$out = '';
foreach ($this->commands as $i => $args) {
$method = array_shift($args);
foreach ($args as $i => $arg) {
$args[$i] = self::json_serialize($arg, $this->devel_mode, false);
}
$out .= sprintf(
"this.%s(%s);\n",
preg_replace('/^parent\./', '', $method),
implode(',', $args)
);
}
return $out;
}
}
@@ -0,0 +1,196 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| PURPOSE: |
| Bounce/resend an email message |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
| Author: Aleksander Machniak <alec@alec.pl> |
+-----------------------------------------------------------------------+
*/
/**
* Mail_mime wrapper to handle mail resend/bounce
*
* @package Webmail
*/
class rcmail_resend_mail extends Mail_mime
{
protected $orig_head;
protected $orig_body;
/**
* Object constructor.
*
* @param array $params Class parameters derived from Mail_mime plus
* 'bounce_message' - rcube_message object of the original message
* 'bounce_headers' - An array of headers to be added to the original message
*/
public function __construct($params = [])
{
// To make the code simpler always use delay_file_io=true
$params['delay_file_io'] = true;
$params['eol'] = "\r\n";
if (!isset($params['bounce_headers'])) {
$params['bounce_headers'] = [];
}
parent::__construct($params);
}
/**
* Returns/Sets message headers
*/
public function headers($headers = [], $overwrite = false, $skip_content = false)
{
// headers() wrapper that returns Resent-Cc, Resent-Bcc instead of Cc,Bcc
// it's also called to re-add Resent-Bcc after it has been sent (to store in Sent)
if (array_key_exists('Bcc', $headers)) {
$this->build_params['bounce_headers']['Resent-Bcc'] = $headers['Bcc'];
}
foreach ($this->build_params['bounce_headers'] as $key => $val) {
$headers[str_replace('Resent-', '', $key)] = $val;
}
return $headers;
}
/**
* Returns all message headers as string
*/
public function txtHeaders($headers = [], $overwrite = false, $skip_content = false)
{
// i.e. add Resent-* headers on top of the original message head
$this->init_message();
$result = [];
foreach ($this->build_params['bounce_headers'] as $name => $value) {
$key = str_replace('Resent-', '', $name);
// txtHeaders() can be used to unset Bcc header
if (array_key_exists($key, $headers)) {
$value = $headers[$key];
$this->build_params['bounce_headers']['Resent-'.$key] = $value;
}
if ($value) {
$result[] = "$name: $value";
}
}
$result = implode($this->build_params['eol'], $result);
if (strlen($this->orig_head)) {
$result .= $this->build_params['eol'] . $this->orig_head;
}
return $result;
}
/**
* Save the message body to a file (if delay_file_io=true)
*/
public function saveMessageBody($file, $params = null)
{
$this->init_message();
// this will be called only once, so let just move the file
rename($this->orig_body, $file);
$this->orig_head = null;
}
/**
* Initialize the internal message. Fetches the message from the storage.
*/
protected function init_message()
{
if ($this->orig_head !== null) {
return;
}
$rcmail = rcmail::get_instance();
$storage = $rcmail->get_storage();
$message = $this->build_params['bounce_message'];
$path = rcube_utils::temp_filename('bounce');
// We'll write the body to the file and the headers to a variable
if ($fp = fopen($path, 'w')) {
stream_filter_register('bounce_source', 'rcmail_bounce_stream_filter');
stream_filter_append($fp, 'bounce_source');
// message part
if ($message->context) {
$message->get_part_body($message->context, false, 0, $fp);
}
// complete message
else {
$storage->set_folder($message->folder);
$storage->get_raw_body($message->uid, $fp);
}
fclose($fp);
$this->orig_head = rcmail_bounce_stream_filter::$headers;
$this->orig_body = $path;
}
}
}
/**
* Stream filter to remove message headers from the streamed
* message source (and store them in a variable)
*
* @package Webmail
*/
class rcmail_bounce_stream_filter extends php_user_filter
{
public static $headers;
protected $in_body = false;
public function onCreate(): bool
{
self::$headers = '';
return true;
}
#[ReturnTypeWillChange]
public function filter($in, $out, &$consumed, $closing)
{
while ($bucket = stream_bucket_make_writeable($in)) {
if (!$this->in_body) {
self::$headers .= $bucket->data;
if (($pos = strpos(self::$headers, "\r\n\r\n")) === false) {
continue;
}
$bucket->data = substr(self::$headers, $pos + 4);
$bucket->datalen = strlen($bucket->data);
self::$headers = substr(self::$headers, 0, $pos);
$this->in_body = true;
}
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,66 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| PURPOSE: |
| Turn URLs and email addresses into clickable links |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
*/
/**
* Helper class for turning URLs and email addresses in plaintext content
* into clickable links.
*
* @package Webmail
* @subpackage Utils
*/
class rcmail_string_replacer extends rcube_string_replacer
{
/**
* Callback function used to build mailto: links around e-mail strings
*
* This also adds an onclick-handler to open the Roundcube compose message screen on such links
*
* @param array $matches Matches result from preg_replace_callback
*
* @return int Index of saved string value
* @see rcube_string_replacer::mailto_callback()
*/
protected function mailto_callback($matches)
{
$href = $matches[1];
$suffix = $this->parse_url_brackets($href);
$email = $href;
if (strpos($email, '?')) {
list($email,) = explode('?', $email);
}
// skip invalid emails
if (!rcube_utils::check_email($email, false)) {
return $matches[1];
}
$attribs = [
'href' => 'mailto:' . $href,
'onclick' => sprintf("return %s.command('compose','%s',this)",
rcmail_output::JS_OBJECT_NAME,
rcube::JQ($href)
),
];
$i = $this->add(html::a($attribs, rcube::Q($href)) . $suffix);
return $i >= 0 ? $this->get_replacement($i) : '';
}
}
+375
View File
@@ -0,0 +1,375 @@
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| CONTENTS: |
| Roundcube utilities |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
| Author: Aleksander Machniak <alec@alec.pl> |
+-----------------------------------------------------------------------+
*/
/**
* Roundcube utilities
*
* @package Webmail
* @subpackage Utils
*/
class rcmail_utils
{
public static $db;
/**
* Initialize database object and connect
*
* @return rcube_db Database instance
*/
public static function db()
{
if (self::$db === null) {
$rc = rcube::get_instance();
$db = rcube_db::factory($rc->config->get('db_dsnw'));
$db->set_debug((bool)$rc->config->get('sql_debug'));
// Connect to database
$db->db_connect('w');
if (!$db->is_connected()) {
rcube::raise_error("Failed to connect to database", false, true);
}
self::$db = $db;
}
return self::$db;
}
/**
* Initialize database schema
*
* @param string $dir Directory with sql files
*/
public static function db_init($dir)
{
$db = self::db();
$error = null;
$file = $dir . '/' . $db->db_provider . '.initial.sql';
if (!file_exists($file)) {
rcube::raise_error("DDL file $file not found", false, true);
}
echo "Creating database schema... ";
if ($sql = file_get_contents($file)) {
if (!$db->exec_script($sql)) {
$error = $db->is_error();
}
}
else {
$error = "Unable to read file $file or it is empty";
}
if ($error) {
echo "[FAILED]\n";
rcube::raise_error($error, false, true);
}
else {
echo "[OK]\n";
}
}
/**
* Update database schema
*
* @param string $dir Directory with sql files
* @param string $package Component name
* @param string $ver Optional current version number
* @param array $opts Parameters (errors, quiet)
*
* @return True on success, False on failure
*/
public static function db_update($dir, $package, $ver = null, $opts = [])
{
// Check if directory exists
if (!file_exists($dir)) {
if (!empty($opts['errors'])) {
rcube::raise_error("Specified database schema directory doesn't exist.", false, true);
}
return false;
}
$db = self::db();
// Read DB schema version from database (if 'system' table exists)
if (in_array($db->table_name('system'), (array)$db->list_tables())) {
$version = self::db_version($package);
}
// DB version not found, but release version is specified
if (empty($version) && $ver) {
// Map old release version string to DB schema version
// Note: This is for backward compat. only, do not need to be updated
$map = [
'0.1-stable' => 1,
'0.1.1' => 2008030300,
'0.2-alpha' => 2008040500,
'0.2-beta' => 2008060900,
'0.2-stable' => 2008092100,
'0.2.1' => 2008092100,
'0.2.2' => 2008092100,
'0.3-stable' => 2008092100,
'0.3.1' => 2009090400,
'0.4-beta' => 2009103100,
'0.4' => 2010042300,
'0.4.1' => 2010042300,
'0.4.2' => 2010042300,
'0.5-beta' => 2010100600,
'0.5' => 2010100600,
'0.5.1' => 2010100600,
'0.5.2' => 2010100600,
'0.5.3' => 2010100600,
'0.5.4' => 2010100600,
'0.6-beta' => 2011011200,
'0.6' => 2011011200,
'0.7-beta' => 2011092800,
'0.7' => 2011111600,
'0.7.1' => 2011111600,
'0.7.2' => 2011111600,
'0.7.3' => 2011111600,
'0.7.4' => 2011111600,
'0.8-beta' => 2011121400,
'0.8-rc' => 2011121400,
'0.8.0' => 2011121400,
'0.8.1' => 2011121400,
'0.8.2' => 2011121400,
'0.8.3' => 2011121400,
'0.8.4' => 2011121400,
'0.8.5' => 2011121400,
'0.8.6' => 2011121400,
'0.9-beta' => 2012080700,
];
$version = $map[$ver];
}
// Assume last version before the 'system' table was added
if (empty($version)) {
$version = 2012080700;
}
$dir .= '/' . $db->db_provider;
if (!file_exists($dir)) {
if (!empty($opts['errors'])) {
rcube::raise_error("DDL Upgrade files for " . $db->db_provider . " driver not found.", false, true);
}
return false;
}
$dh = opendir($dir);
$result = [];
while ($file = readdir($dh)) {
if (preg_match('/^([0-9]+)\.sql$/', $file, $m) && $m[1] > $version) {
$result[] = $m[1];
}
}
sort($result, SORT_NUMERIC);
foreach ($result as $v) {
if (empty($opts['quiet'])) {
echo "Updating database schema ($v)... ";
}
// Ignore errors here to print the error only once
$db->set_option('ignore_errors', true);
$error = self::db_update_schema($package, $v, "$dir/$v.sql");
$db->set_option('ignore_errors', false);
if ($error) {
if (empty($opts['quiet'])) {
echo "[FAILED]\n";
}
if (!empty($opts['errors'])) {
rcube::raise_error("Error in DDL upgrade $v: $error", false, true);
}
return false;
}
else if (empty($opts['quiet'])) {
echo "[OK]\n";
}
}
return true;
}
/**
* Run database update from a single sql file
*/
protected static function db_update_schema($package, $version, $file)
{
$db = self::db();
// read DDL file
if ($sql = file_get_contents($file)) {
if (!$db->exec_script($sql)) {
return $db->is_error();
}
}
// escape if 'system' table does not exist
if ($version < 2013011000) {
return;
}
$system_table = $db->table_name('system', true);
$db->query("UPDATE " . $system_table
. " SET `value` = ?"
. " WHERE `name` = ?",
$version, $package . '-version');
if (!$db->is_error() && !$db->affected_rows()) {
$db->query("INSERT INTO " . $system_table
." (`name`, `value`) VALUES (?, ?)",
$package . '-version', $version);
}
return $db->is_error();
}
/**
* Get version string for the specified package
*
* @param string $package Package name
*
* @return null|string Version string
*/
public static function db_version($package = 'roundcube')
{
$db = self::db();
$db->query("SELECT `value`"
. " FROM " . $db->table_name('system', true)
. " WHERE `name` = ?",
$package . '-version');
$row = $db->fetch_array();
if ($row === false) {
return null;
}
$version = preg_replace('/[^0-9]/', '', $row[0]);
return $version;
}
/**
* Removes all deleted records older than X days
*
* @param int $days Number of days
*/
public static function db_clean($days)
{
$db = self::db();
$threshold = date('Y-m-d 00:00:00', time() - $days * 86400);
$tables = [
'contacts',
'contactgroups',
'identities',
'responses',
];
foreach ($tables as $table) {
$sqltable = $db->table_name($table, true);
// delete outdated records
$db->query("DELETE FROM $sqltable WHERE `del` = 1 AND `changed` < ?", $threshold);
echo $db->affected_rows() . " records deleted from '$table'\n";
}
}
/**
* Reindex contacts
*/
public static function indexcontacts()
{
$db = self::db();
// iterate over all users
$sql_result = $db->query("SELECT `user_id` FROM " . $db->table_name('users', true) . " ORDER BY `user_id`");
while ($sql_result && ($sql_arr = $db->fetch_assoc($sql_result))) {
echo "Indexing contacts for user " . $sql_arr['user_id'] . "...\n";
$contacts = new rcube_contacts($db, $sql_arr['user_id']);
$contacts->set_pagesize(9999);
$result = $contacts->list_records();
while ($result->count && ($row = $result->next())) {
unset($row['words']);
$contacts->update($row['ID'], $row);
}
}
echo "done.\n";
}
/**
* Modify user preferences
*
* @param string $name Option name
* @param string $value Option value
* @param int $userid Optional user identifier
* @param string $type Optional value type (bool, int, string)
*/
public static function mod_pref($name, $value, $userid = null, $type = 'string')
{
$db = self::db();
if ($userid) {
$query = '`user_id` = ' . intval($userid);
}
else {
$query = '1=1';
}
$type = strtolower($type);
if ($type == 'bool' || $type == 'boolean') {
$value = rcube_utils::get_boolean($value);
}
else if ($type == 'int' || $type == 'integer') {
$value = (int) $value;
}
// iterate over all users
$sql_result = $db->query("SELECT * FROM " . $db->table_name('users', true) . " WHERE $query");
while ($sql_result && ($sql_arr = $db->fetch_assoc($sql_result))) {
echo "Updating prefs for user " . $sql_arr['user_id'] . "...";
$user = new rcube_user($sql_arr['user_id'], $sql_arr);
$prefs = $old_prefs = $user->get_prefs();
$prefs[$name] = $value;
if ($prefs != $old_prefs) {
$user->save_prefs($prefs, true);
echo "saved.\n";
}
else {
echo "nothing changed.\n";
}
}
}
}