您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

rcube.php 51KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2008-2014, The Roundcube Dev Team |
  6. | Copyright (C) 2011-2014, Kolab Systems AG |
  7. | |
  8. | Licensed under the GNU General Public License version 3 or |
  9. | any later version with exceptions for skins & plugins. |
  10. | See the README file for a full license statement. |
  11. | |
  12. | PURPOSE: |
  13. | Framework base class providing core functions and holding |
  14. | instances of all 'global' objects like db- and storage-connections |
  15. +-----------------------------------------------------------------------+
  16. | Author: Thomas Bruederli <roundcube@gmail.com> |
  17. +-----------------------------------------------------------------------+
  18. */
  19. /**
  20. * Base class of the Roundcube Framework
  21. * implemented as singleton
  22. *
  23. * @package Framework
  24. * @subpackage Core
  25. */
  26. class rcube
  27. {
  28. // Init options
  29. const INIT_WITH_DB = 1;
  30. const INIT_WITH_PLUGINS = 2;
  31. // Request status
  32. const REQUEST_VALID = 0;
  33. const REQUEST_ERROR_URL = 1;
  34. const REQUEST_ERROR_TOKEN = 2;
  35. const DEBUG_LINE_LENGTH = 4096;
  36. /**
  37. * Singleton instance of rcube
  38. *
  39. * @var rcube
  40. */
  41. static protected $instance;
  42. /**
  43. * Stores instance of rcube_config.
  44. *
  45. * @var rcube_config
  46. */
  47. public $config;
  48. /**
  49. * Instance of database class.
  50. *
  51. * @var rcube_db
  52. */
  53. public $db;
  54. /**
  55. * Instance of Memcache class.
  56. *
  57. * @var Memcache
  58. */
  59. public $memcache;
  60. /**
  61. * Instance of rcube_session class.
  62. *
  63. * @var rcube_session
  64. */
  65. public $session;
  66. /**
  67. * Instance of rcube_smtp class.
  68. *
  69. * @var rcube_smtp
  70. */
  71. public $smtp;
  72. /**
  73. * Instance of rcube_storage class.
  74. *
  75. * @var rcube_storage
  76. */
  77. public $storage;
  78. /**
  79. * Instance of rcube_output class.
  80. *
  81. * @var rcube_output
  82. */
  83. public $output;
  84. /**
  85. * Instance of rcube_plugin_api.
  86. *
  87. * @var rcube_plugin_api
  88. */
  89. public $plugins;
  90. /**
  91. * Instance of rcube_user class.
  92. *
  93. * @var rcube_user
  94. */
  95. public $user;
  96. /**
  97. * Request status
  98. *
  99. * @var int
  100. */
  101. public $request_status = 0;
  102. /* private/protected vars */
  103. protected $texts;
  104. protected $caches = array();
  105. protected $shutdown_functions = array();
  106. /**
  107. * This implements the 'singleton' design pattern
  108. *
  109. * @param integer $mode Options to initialize with this instance. See rcube::INIT_WITH_* constants
  110. * @param string $env Environment name to run (e.g. live, dev, test)
  111. *
  112. * @return rcube The one and only instance
  113. */
  114. static function get_instance($mode = 0, $env = '')
  115. {
  116. if (!self::$instance) {
  117. self::$instance = new rcube($env);
  118. self::$instance->init($mode);
  119. }
  120. return self::$instance;
  121. }
  122. /**
  123. * Private constructor
  124. */
  125. protected function __construct($env = '')
  126. {
  127. // load configuration
  128. $this->config = new rcube_config($env);
  129. $this->plugins = new rcube_dummy_plugin_api;
  130. register_shutdown_function(array($this, 'shutdown'));
  131. }
  132. /**
  133. * Initial startup function
  134. */
  135. protected function init($mode = 0)
  136. {
  137. // initialize syslog
  138. if ($this->config->get('log_driver') == 'syslog') {
  139. $syslog_id = $this->config->get('syslog_id', 'roundcube');
  140. $syslog_facility = $this->config->get('syslog_facility', LOG_USER);
  141. openlog($syslog_id, LOG_ODELAY, $syslog_facility);
  142. }
  143. // connect to database
  144. if ($mode & self::INIT_WITH_DB) {
  145. $this->get_dbh();
  146. }
  147. // create plugin API and load plugins
  148. if ($mode & self::INIT_WITH_PLUGINS) {
  149. $this->plugins = rcube_plugin_api::get_instance();
  150. }
  151. }
  152. /**
  153. * Get the current database connection
  154. *
  155. * @return rcube_db Database object
  156. */
  157. public function get_dbh()
  158. {
  159. if (!$this->db) {
  160. $this->db = rcube_db::factory(
  161. $this->config->get('db_dsnw'),
  162. $this->config->get('db_dsnr'),
  163. $this->config->get('db_persistent')
  164. );
  165. $this->db->set_debug((bool)$this->config->get('sql_debug'));
  166. }
  167. return $this->db;
  168. }
  169. /**
  170. * Get global handle for memcache access
  171. *
  172. * @return object Memcache
  173. */
  174. public function get_memcache()
  175. {
  176. if (!isset($this->memcache)) {
  177. // no memcache support in PHP
  178. if (!class_exists('Memcache')) {
  179. $this->memcache = false;
  180. return false;
  181. }
  182. $this->memcache = new Memcache;
  183. $this->memcache_init();
  184. // test connection and failover (will result in $this->mc_available == 0 on complete failure)
  185. $this->memcache->increment('__CONNECTIONTEST__', 1); // NOP if key doesn't exist
  186. if (!$this->mc_available) {
  187. $this->memcache = false;
  188. }
  189. }
  190. return $this->memcache;
  191. }
  192. /**
  193. * Get global handle for memcache access
  194. *
  195. * @return object Memcache
  196. */
  197. protected function memcache_init()
  198. {
  199. $this->mc_available = 0;
  200. // add all configured hosts to pool
  201. $pconnect = $this->config->get('memcache_pconnect', true);
  202. $timeout = $this->config->get('memcache_timeout', 1);
  203. $retry_interval = $this->config->get('memcache_retry_interval', 15);
  204. foreach ($this->config->get('memcache_hosts', array()) as $host) {
  205. if (substr($host, 0, 7) != 'unix://') {
  206. list($host, $port) = explode(':', $host);
  207. if (!$port) $port = 11211;
  208. }
  209. else {
  210. $port = 0;
  211. }
  212. $this->mc_available += intval($this->memcache->addServer(
  213. $host, $port, $pconnect, 1, $timeout, $retry_interval, false, array($this, 'memcache_failure')));
  214. }
  215. }
  216. /**
  217. * Callback for memcache failure
  218. */
  219. public function memcache_failure($host, $port)
  220. {
  221. static $seen = array();
  222. // only report once
  223. if (!$seen["$host:$port"]++) {
  224. $this->mc_available--;
  225. self::raise_error(array(
  226. 'code' => 604, 'type' => 'db',
  227. 'line' => __LINE__, 'file' => __FILE__,
  228. 'message' => "Memcache failure on host $host:$port"),
  229. true, false);
  230. }
  231. }
  232. /**
  233. * Initialize and get cache object
  234. *
  235. * @param string $name Cache identifier
  236. * @param string $type Cache type ('db', 'apc' or 'memcache')
  237. * @param string $ttl Expiration time for cache items
  238. * @param bool $packed Enables/disables data serialization
  239. *
  240. * @return rcube_cache Cache object
  241. */
  242. public function get_cache($name, $type='db', $ttl=0, $packed=true)
  243. {
  244. if (!isset($this->caches[$name]) && ($userid = $this->get_user_id())) {
  245. $this->caches[$name] = new rcube_cache($type, $userid, $name, $ttl, $packed);
  246. }
  247. return $this->caches[$name];
  248. }
  249. /**
  250. * Initialize and get shared cache object
  251. *
  252. * @param string $name Cache identifier
  253. * @param bool $packed Enables/disables data serialization
  254. *
  255. * @return rcube_cache_shared Cache object
  256. */
  257. public function get_cache_shared($name, $packed=true)
  258. {
  259. $shared_name = "shared_$name";
  260. if (!array_key_exists($shared_name, $this->caches)) {
  261. $opt = strtolower($name) . '_cache';
  262. $type = $this->config->get($opt);
  263. $ttl = $this->config->get($opt . '_ttl');
  264. if (!$type) {
  265. // cache is disabled
  266. return $this->caches[$shared_name] = null;
  267. }
  268. if ($ttl === null) {
  269. $ttl = $this->config->get('shared_cache_ttl', '10d');
  270. }
  271. $this->caches[$shared_name] = new rcube_cache_shared($type, $name, $ttl, $packed);
  272. }
  273. return $this->caches[$shared_name];
  274. }
  275. /**
  276. * Create SMTP object and connect to server
  277. *
  278. * @param boolean $connect True if connection should be established
  279. */
  280. public function smtp_init($connect = false)
  281. {
  282. $this->smtp = new rcube_smtp();
  283. if ($connect) {
  284. $this->smtp->connect();
  285. }
  286. }
  287. /**
  288. * Initialize and get storage object
  289. *
  290. * @return rcube_storage Storage object
  291. */
  292. public function get_storage()
  293. {
  294. // already initialized
  295. if (!is_object($this->storage)) {
  296. $this->storage_init();
  297. }
  298. return $this->storage;
  299. }
  300. /**
  301. * Initialize storage object
  302. */
  303. public function storage_init()
  304. {
  305. // already initialized
  306. if (is_object($this->storage)) {
  307. return;
  308. }
  309. $driver = $this->config->get('storage_driver', 'imap');
  310. $driver_class = "rcube_{$driver}";
  311. if (!class_exists($driver_class)) {
  312. self::raise_error(array(
  313. 'code' => 700, 'type' => 'php',
  314. 'file' => __FILE__, 'line' => __LINE__,
  315. 'message' => "Storage driver class ($driver) not found!"),
  316. true, true);
  317. }
  318. // Initialize storage object
  319. $this->storage = new $driver_class;
  320. // for backward compat. (deprecated, will be removed)
  321. $this->imap = $this->storage;
  322. // set class options
  323. $options = array(
  324. 'auth_type' => $this->config->get("{$driver}_auth_type", 'check'),
  325. 'auth_cid' => $this->config->get("{$driver}_auth_cid"),
  326. 'auth_pw' => $this->config->get("{$driver}_auth_pw"),
  327. 'debug' => (bool) $this->config->get("{$driver}_debug"),
  328. 'force_caps' => (bool) $this->config->get("{$driver}_force_caps"),
  329. 'disabled_caps' => $this->config->get("{$driver}_disabled_caps"),
  330. 'socket_options' => $this->config->get("{$driver}_conn_options"),
  331. 'timeout' => (int) $this->config->get("{$driver}_timeout"),
  332. 'skip_deleted' => (bool) $this->config->get('skip_deleted'),
  333. 'driver' => $driver,
  334. );
  335. if (!empty($_SESSION['storage_host'])) {
  336. $options['language'] = $_SESSION['language'];
  337. $options['host'] = $_SESSION['storage_host'];
  338. $options['user'] = $_SESSION['username'];
  339. $options['port'] = $_SESSION['storage_port'];
  340. $options['ssl'] = $_SESSION['storage_ssl'];
  341. $options['password'] = $this->decrypt($_SESSION['password']);
  342. $_SESSION[$driver.'_host'] = $_SESSION['storage_host'];
  343. }
  344. $options = $this->plugins->exec_hook("storage_init", $options);
  345. // for backward compat. (deprecated, to be removed)
  346. $options = $this->plugins->exec_hook("imap_init", $options);
  347. $this->storage->set_options($options);
  348. $this->set_storage_prop();
  349. // subscribe to 'storage_connected' hook for session logging
  350. if ($this->config->get('imap_log_session', false)) {
  351. $this->plugins->register_hook('storage_connected', array($this, 'storage_log_session'));
  352. }
  353. }
  354. /**
  355. * Set storage parameters.
  356. */
  357. protected function set_storage_prop()
  358. {
  359. $storage = $this->get_storage();
  360. // set pagesize from config
  361. $pagesize = $this->config->get('mail_pagesize');
  362. if (!$pagesize) {
  363. $pagesize = $this->config->get('pagesize', 50);
  364. }
  365. $storage->set_pagesize($pagesize);
  366. $storage->set_charset($this->config->get('default_charset', RCUBE_CHARSET));
  367. // enable caching of mail data
  368. $driver = $this->config->get('storage_driver', 'imap');
  369. $storage_cache = $this->config->get("{$driver}_cache");
  370. $messages_cache = $this->config->get('messages_cache');
  371. // for backward compatybility
  372. if ($storage_cache === null && $messages_cache === null && $this->config->get('enable_caching')) {
  373. $storage_cache = 'db';
  374. $messages_cache = true;
  375. }
  376. if ($storage_cache) {
  377. $storage->set_caching($storage_cache);
  378. }
  379. if ($messages_cache) {
  380. $storage->set_messages_caching(true);
  381. }
  382. }
  383. /**
  384. * Set special folders type association.
  385. * This must be done AFTER connecting to the server!
  386. */
  387. protected function set_special_folders()
  388. {
  389. $storage = $this->get_storage();
  390. $folders = $storage->get_special_folders(true);
  391. $prefs = array();
  392. // check SPECIAL-USE flags on IMAP folders
  393. foreach ($folders as $type => $folder) {
  394. $idx = $type . '_mbox';
  395. if ($folder !== $this->config->get($idx)) {
  396. $prefs[$idx] = $folder;
  397. }
  398. }
  399. // Some special folders differ, update user preferences
  400. if (!empty($prefs) && $this->user) {
  401. $this->user->save_prefs($prefs);
  402. }
  403. // create default folders (on login)
  404. if ($this->config->get('create_default_folders')) {
  405. $storage->create_default_folders();
  406. }
  407. }
  408. /**
  409. * Callback for IMAP connection events to log session identifiers
  410. */
  411. public function storage_log_session($args)
  412. {
  413. if (!empty($args['session']) && session_id()) {
  414. $this->write_log('imap_session', $args['session']);
  415. }
  416. }
  417. /**
  418. * Create session object and start the session.
  419. */
  420. public function session_init()
  421. {
  422. // session started (Installer?)
  423. if (session_id()) {
  424. return;
  425. }
  426. $sess_name = $this->config->get('session_name');
  427. $sess_domain = $this->config->get('session_domain');
  428. $sess_path = $this->config->get('session_path');
  429. $lifetime = $this->config->get('session_lifetime', 0) * 60;
  430. $is_secure = $this->config->get('use_https') || rcube_utils::https_check();
  431. // set session domain
  432. if ($sess_domain) {
  433. ini_set('session.cookie_domain', $sess_domain);
  434. }
  435. // set session path
  436. if ($sess_path) {
  437. ini_set('session.cookie_path', $sess_path);
  438. }
  439. // set session garbage collecting time according to session_lifetime
  440. if ($lifetime) {
  441. ini_set('session.gc_maxlifetime', $lifetime * 2);
  442. }
  443. // set session cookie lifetime so it never expires (#5961)
  444. ini_set('session.cookie_lifetime', 0);
  445. ini_set('session.cookie_secure', $is_secure);
  446. ini_set('session.name', $sess_name ?: 'roundcube_sessid');
  447. ini_set('session.use_cookies', 1);
  448. ini_set('session.use_only_cookies', 1);
  449. ini_set('session.cookie_httponly', 1);
  450. // get session driver instance
  451. $this->session = rcube_session::factory($this->config);
  452. $this->session->register_gc_handler(array($this, 'gc'));
  453. // start PHP session (if not in CLI mode)
  454. if ($_SERVER['REMOTE_ADDR']) {
  455. $this->session->start();
  456. }
  457. }
  458. /**
  459. * Garbage collector - cache/temp cleaner
  460. */
  461. public function gc()
  462. {
  463. rcube_cache::gc();
  464. rcube_cache_shared::gc();
  465. $this->get_storage()->cache_gc();
  466. $this->gc_temp();
  467. }
  468. /**
  469. * Garbage collector function for temp files.
  470. * Remove temp files older than two days
  471. */
  472. public function gc_temp()
  473. {
  474. $tmp = unslashify($this->config->get('temp_dir'));
  475. // expire in 48 hours by default
  476. $temp_dir_ttl = $this->config->get('temp_dir_ttl', '48h');
  477. $temp_dir_ttl = get_offset_sec($temp_dir_ttl);
  478. if ($temp_dir_ttl < 6*3600)
  479. $temp_dir_ttl = 6*3600; // 6 hours sensible lower bound.
  480. $expire = time() - $temp_dir_ttl;
  481. if ($tmp && ($dir = opendir($tmp))) {
  482. while (($fname = readdir($dir)) !== false) {
  483. if ($fname[0] == '.') {
  484. continue;
  485. }
  486. if (@filemtime($tmp.'/'.$fname) < $expire) {
  487. @unlink($tmp.'/'.$fname);
  488. }
  489. }
  490. closedir($dir);
  491. }
  492. }
  493. /**
  494. * Runs garbage collector with probability based on
  495. * session settings. This is intended for environments
  496. * without a session.
  497. */
  498. public function gc_run()
  499. {
  500. $probability = (int) ini_get('session.gc_probability');
  501. $divisor = (int) ini_get('session.gc_divisor');
  502. if ($divisor > 0 && $probability > 0) {
  503. $random = mt_rand(1, $divisor);
  504. if ($random <= $probability) {
  505. $this->gc();
  506. }
  507. }
  508. }
  509. /**
  510. * Get localized text in the desired language
  511. *
  512. * @param mixed $attrib Named parameters array or label name
  513. * @param string $domain Label domain (plugin) name
  514. *
  515. * @return string Localized text
  516. */
  517. public function gettext($attrib, $domain = null)
  518. {
  519. // load localization files if not done yet
  520. if (empty($this->texts)) {
  521. $this->load_language();
  522. }
  523. // extract attributes
  524. if (is_string($attrib)) {
  525. $attrib = array('name' => $attrib);
  526. }
  527. $name = (string) $attrib['name'];
  528. // attrib contain text values: use them from now
  529. if (($setval = $attrib[strtolower($_SESSION['language'])]) || ($setval = $attrib['en_us'])) {
  530. $this->texts[$name] = $setval;
  531. }
  532. // check for text with domain
  533. if ($domain && ($text = $this->texts[$domain.'.'.$name])) {
  534. }
  535. // text does not exist
  536. else if (!($text = $this->texts[$name])) {
  537. return "[$name]";
  538. }
  539. // replace vars in text
  540. if (is_array($attrib['vars'])) {
  541. foreach ($attrib['vars'] as $var_key => $var_value) {
  542. $text = str_replace($var_key[0] != '$' ? '$'.$var_key : $var_key, $var_value, $text);
  543. }
  544. }
  545. // replace \n with real line break
  546. $text = strtr($text, array('\n' => "\n"));
  547. // case folding
  548. if (($attrib['uppercase'] && strtolower($attrib['uppercase']) == 'first') || $attrib['ucfirst']) {
  549. $case_mode = MB_CASE_TITLE;
  550. }
  551. else if ($attrib['uppercase']) {
  552. $case_mode = MB_CASE_UPPER;
  553. }
  554. else if ($attrib['lowercase']) {
  555. $case_mode = MB_CASE_LOWER;
  556. }
  557. if (isset($case_mode)) {
  558. $text = mb_convert_case($text, $case_mode);
  559. }
  560. return $text;
  561. }
  562. /**
  563. * Check if the given text label exists
  564. *
  565. * @param string $name Label name
  566. * @param string $domain Label domain (plugin) name or '*' for all domains
  567. * @param string $ref_domain Sets domain name if label is found
  568. *
  569. * @return boolean True if text exists (either in the current language or in en_US)
  570. */
  571. public function text_exists($name, $domain = null, &$ref_domain = null)
  572. {
  573. // load localization files if not done yet
  574. if (empty($this->texts)) {
  575. $this->load_language();
  576. }
  577. if (isset($this->texts[$name])) {
  578. $ref_domain = '';
  579. return true;
  580. }
  581. // any of loaded domains (plugins)
  582. if ($domain == '*') {
  583. foreach ($this->plugins->loaded_plugins() as $domain) {
  584. if (isset($this->texts[$domain.'.'.$name])) {
  585. $ref_domain = $domain;
  586. return true;
  587. }
  588. }
  589. }
  590. // specified domain
  591. else if ($domain) {
  592. $ref_domain = $domain;
  593. return isset($this->texts[$domain.'.'.$name]);
  594. }
  595. return false;
  596. }
  597. /**
  598. * Load a localization package
  599. *
  600. * @param string $lang Language ID
  601. * @param array $add Additional text labels/messages
  602. * @param array $merge Additional text labels/messages to merge
  603. */
  604. public function load_language($lang = null, $add = array(), $merge = array())
  605. {
  606. $lang = $this->language_prop($lang ?: $_SESSION['language']);
  607. // load localized texts
  608. if (empty($this->texts) || $lang != $_SESSION['language']) {
  609. $this->texts = array();
  610. // handle empty lines after closing PHP tag in localization files
  611. ob_start();
  612. // get english labels (these should be complete)
  613. @include(RCUBE_LOCALIZATION_DIR . 'en_US/labels.inc');
  614. @include(RCUBE_LOCALIZATION_DIR . 'en_US/messages.inc');
  615. if (is_array($labels))
  616. $this->texts = $labels;
  617. if (is_array($messages))
  618. $this->texts = array_merge($this->texts, $messages);
  619. // include user language files
  620. if ($lang != 'en' && $lang != 'en_US' && is_dir(RCUBE_LOCALIZATION_DIR . $lang)) {
  621. include_once(RCUBE_LOCALIZATION_DIR . $lang . '/labels.inc');
  622. include_once(RCUBE_LOCALIZATION_DIR . $lang . '/messages.inc');
  623. if (is_array($labels))
  624. $this->texts = array_merge($this->texts, $labels);
  625. if (is_array($messages))
  626. $this->texts = array_merge($this->texts, $messages);
  627. }
  628. ob_end_clean();
  629. $_SESSION['language'] = $lang;
  630. }
  631. // append additional texts (from plugin)
  632. if (is_array($add) && !empty($add)) {
  633. $this->texts += $add;
  634. }
  635. // merge additional texts (from plugin)
  636. if (is_array($merge) && !empty($merge)) {
  637. $this->texts = array_merge($this->texts, $merge);
  638. }
  639. }
  640. /**
  641. * Check the given string and return a valid language code
  642. *
  643. * @param string $lang Language code
  644. *
  645. * @return string Valid language code
  646. */
  647. protected function language_prop($lang)
  648. {
  649. static $rcube_languages, $rcube_language_aliases;
  650. // user HTTP_ACCEPT_LANGUAGE if no language is specified
  651. if (empty($lang) || $lang == 'auto') {
  652. $accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
  653. $lang = $accept_langs[0];
  654. if (preg_match('/^([a-z]+)[_-]([a-z]+)$/i', $lang, $m)) {
  655. $lang = $m[1] . '_' . strtoupper($m[2]);
  656. }
  657. }
  658. if (empty($rcube_languages)) {
  659. @include(RCUBE_LOCALIZATION_DIR . 'index.inc');
  660. }
  661. // check if we have an alias for that language
  662. if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
  663. $lang = $rcube_language_aliases[$lang];
  664. }
  665. // try the first two chars
  666. else if (!isset($rcube_languages[$lang])) {
  667. $short = substr($lang, 0, 2);
  668. // check if we have an alias for the short language code
  669. if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
  670. $lang = $rcube_language_aliases[$short];
  671. }
  672. // expand 'nn' to 'nn_NN'
  673. else if (!isset($rcube_languages[$short])) {
  674. $lang = $short.'_'.strtoupper($short);
  675. }
  676. }
  677. if (!isset($rcube_languages[$lang]) || !is_dir(RCUBE_LOCALIZATION_DIR . $lang)) {
  678. $lang = 'en_US';
  679. }
  680. return $lang;
  681. }
  682. /**
  683. * Read directory program/localization and return a list of available languages
  684. *
  685. * @return array List of available localizations
  686. */
  687. public function list_languages()
  688. {
  689. static $sa_languages = array();
  690. if (!count($sa_languages)) {
  691. @include(RCUBE_LOCALIZATION_DIR . 'index.inc');
  692. if ($dh = @opendir(RCUBE_LOCALIZATION_DIR)) {
  693. while (($name = readdir($dh)) !== false) {
  694. if ($name[0] == '.' || !is_dir(RCUBE_LOCALIZATION_DIR . $name)) {
  695. continue;
  696. }
  697. if ($label = $rcube_languages[$name]) {
  698. $sa_languages[$name] = $label;
  699. }
  700. }
  701. closedir($dh);
  702. }
  703. }
  704. return $sa_languages;
  705. }
  706. /**
  707. * Encrypt a string
  708. *
  709. * @param string $clear Clear text input
  710. * @param string $key Encryption key to retrieve from the configuration, defaults to 'des_key'
  711. * @param boolean $base64 Whether or not to base64_encode() the result before returning
  712. *
  713. * @return string Encrypted text
  714. */
  715. public function encrypt($clear, $key = 'des_key', $base64 = true)
  716. {
  717. if (!is_string($clear) || !strlen($clear)) {
  718. return '';
  719. }
  720. $ckey = $this->config->get_crypto_key($key);
  721. $method = $this->config->get_crypto_method();
  722. $opts = defined('OPENSSL_RAW_DATA') ? OPENSSL_RAW_DATA : true;
  723. $iv = rcube_utils::random_bytes(openssl_cipher_iv_length($method), true);
  724. $cipher = $iv . openssl_encrypt($clear, $method, $ckey, $opts, $iv);
  725. return $base64 ? base64_encode($cipher) : $cipher;
  726. }
  727. /**
  728. * Decrypt a string
  729. *
  730. * @param string $cipher Encrypted text
  731. * @param string $key Encryption key to retrieve from the configuration, defaults to 'des_key'
  732. * @param boolean $base64 Whether or not input is base64-encoded
  733. *
  734. * @return string Decrypted text
  735. */
  736. public function decrypt($cipher, $key = 'des_key', $base64 = true)
  737. {
  738. if (!$cipher) {
  739. return '';
  740. }
  741. $cipher = $base64 ? base64_decode($cipher) : $cipher;
  742. $ckey = $this->config->get_crypto_key($key);
  743. $method = $this->config->get_crypto_method();
  744. $opts = defined('OPENSSL_RAW_DATA') ? OPENSSL_RAW_DATA : true;
  745. $iv_size = openssl_cipher_iv_length($method);
  746. $iv = substr($cipher, 0, $iv_size);
  747. // session corruption? (#1485970)
  748. if (strlen($iv) < $iv_size) {
  749. return '';
  750. }
  751. $cipher = substr($cipher, $iv_size);
  752. $clear = openssl_decrypt($cipher, $method, $ckey, $opts, $iv);
  753. return $clear;
  754. }
  755. /**
  756. * Returns session token for secure URLs
  757. *
  758. * @param bool $generate Generate token if not exists in session yet
  759. *
  760. * @return string|bool Token string, False when disabled
  761. */
  762. public function get_secure_url_token($generate = false)
  763. {
  764. if ($len = $this->config->get('use_secure_urls')) {
  765. if (empty($_SESSION['secure_token']) && $generate) {
  766. // generate x characters long token
  767. $length = $len > 1 ? $len : 16;
  768. $token = rcube_utils::random_bytes($length);
  769. $plugin = $this->plugins->exec_hook('secure_token',
  770. array('value' => $token, 'length' => $length));
  771. $_SESSION['secure_token'] = $plugin['value'];
  772. }
  773. return $_SESSION['secure_token'];
  774. }
  775. return false;
  776. }
  777. /**
  778. * Generate a unique token to be used in a form request
  779. *
  780. * @return string The request token
  781. */
  782. public function get_request_token()
  783. {
  784. if (empty($_SESSION['request_token'])) {
  785. $plugin = $this->plugins->exec_hook('request_token', array(
  786. 'value' => rcube_utils::random_bytes(32)));
  787. $_SESSION['request_token'] = $plugin['value'];
  788. }
  789. return $_SESSION['request_token'];
  790. }
  791. /**
  792. * Check if the current request contains a valid token.
  793. * Empty requests aren't checked until use_secure_urls is set.
  794. *
  795. * @param int $mode Request method
  796. *
  797. * @return boolean True if request token is valid false if not
  798. */
  799. public function check_request($mode = rcube_utils::INPUT_POST)
  800. {
  801. // check secure token in URL if enabled
  802. if ($token = $this->get_secure_url_token()) {
  803. foreach (explode('/', preg_replace('/[?#&].*$/', '', $_SERVER['REQUEST_URI'])) as $tok) {
  804. if ($tok == $token) {
  805. return true;
  806. }
  807. }
  808. $this->request_status = self::REQUEST_ERROR_URL;
  809. return false;
  810. }
  811. $sess_tok = $this->get_request_token();
  812. // ajax requests
  813. if (rcube_utils::request_header('X-Roundcube-Request') === $sess_tok) {
  814. return true;
  815. }
  816. // skip empty requests
  817. if (($mode == rcube_utils::INPUT_POST && empty($_POST))
  818. || ($mode == rcube_utils::INPUT_GET && empty($_GET))
  819. ) {
  820. return true;
  821. }
  822. // default method of securing requests
  823. $token = rcube_utils::get_input_value('_token', $mode);
  824. $sess_id = $_COOKIE[ini_get('session.name')];
  825. if (empty($sess_id) || $token !== $sess_tok) {
  826. $this->request_status = self::REQUEST_ERROR_TOKEN;
  827. return false;
  828. }
  829. return true;
  830. }
  831. /**
  832. * Build a valid URL to this instance of Roundcube
  833. *
  834. * @param mixed $p Either a string with the action or url parameters as key-value pairs
  835. *
  836. * @return string Valid application URL
  837. */
  838. public function url($p)
  839. {
  840. // STUB: should be overloaded by the application
  841. return '';
  842. }
  843. /**
  844. * Function to be executed in script shutdown
  845. * Registered with register_shutdown_function()
  846. */
  847. public function shutdown()
  848. {
  849. foreach ($this->shutdown_functions as $function) {
  850. call_user_func($function);
  851. }
  852. // write session data as soon as possible and before
  853. // closing database connection, don't do this before
  854. // registered shutdown functions, they may need the session
  855. // Note: this will run registered gc handlers (ie. cache gc)
  856. if ($_SERVER['REMOTE_ADDR'] && is_object($this->session)) {
  857. $this->session->write_close();
  858. }
  859. if (is_object($this->smtp)) {
  860. $this->smtp->disconnect();
  861. }
  862. foreach ($this->caches as $cache) {
  863. if (is_object($cache)) {
  864. $cache->close();
  865. }
  866. }
  867. if (is_object($this->storage)) {
  868. $this->storage->close();
  869. }
  870. if ($this->config->get('log_driver') == 'syslog') {
  871. closelog();
  872. }
  873. }
  874. /**
  875. * Registers shutdown function to be executed on shutdown.
  876. * The functions will be executed before destroying any
  877. * objects like smtp, imap, session, etc.
  878. *
  879. * @param callback $function Function callback
  880. */
  881. public function add_shutdown_function($function)
  882. {
  883. $this->shutdown_functions[] = $function;
  884. }
  885. /**
  886. * When you're going to sleep the script execution for a longer time
  887. * it is good to close all external connections (sql, memcache, SMTP, IMAP).
  888. *
  889. * No action is required on wake up, all connections will be
  890. * re-established automatically.
  891. */
  892. public function sleep()
  893. {
  894. foreach ($this->caches as $cache) {
  895. if (is_object($cache)) {
  896. $cache->close();
  897. }
  898. }
  899. if ($this->storage) {
  900. $this->storage->close();
  901. }
  902. if ($this->db) {
  903. $this->db->closeConnection();
  904. }
  905. if ($this->memcache) {
  906. $this->memcache->close();
  907. // after close() need to re-init memcache
  908. $this->memcache_init();
  909. }
  910. if ($this->smtp) {
  911. $this->smtp->disconnect();
  912. }
  913. }
  914. /**
  915. * Quote a given string.
  916. * Shortcut function for rcube_utils::rep_specialchars_output()
  917. *
  918. * @return string HTML-quoted string
  919. */
  920. public static function Q($str, $mode = 'strict', $newlines = true)
  921. {
  922. return rcube_utils::rep_specialchars_output($str, 'html', $mode, $newlines);
  923. }
  924. /**
  925. * Quote a given string for javascript output.
  926. * Shortcut function for rcube_utils::rep_specialchars_output()
  927. *
  928. * @return string JS-quoted string
  929. */
  930. public static function JQ($str)
  931. {
  932. return rcube_utils::rep_specialchars_output($str, 'js');
  933. }
  934. /**
  935. * Construct shell command, execute it and return output as string.
  936. * Keywords {keyword} are replaced with arguments
  937. *
  938. * @param $cmd Format string with {keywords} to be replaced
  939. * @param $values (zero, one or more arrays can be passed)
  940. *
  941. * @return output of command. shell errors not detectable
  942. */
  943. public static function exec(/* $cmd, $values1 = array(), ... */)
  944. {
  945. $args = func_get_args();
  946. $cmd = array_shift($args);
  947. $values = $replacements = array();
  948. // merge values into one array
  949. foreach ($args as $arg) {
  950. $values += (array)$arg;
  951. }
  952. preg_match_all('/({(-?)([a-z]\w*)})/', $cmd, $matches, PREG_SET_ORDER);
  953. foreach ($matches as $tags) {
  954. list(, $tag, $option, $key) = $tags;
  955. $parts = array();
  956. if ($option) {
  957. foreach ((array)$values["-$key"] as $key => $value) {
  958. if ($value === true || $value === false || $value === null) {
  959. $parts[] = $value ? $key : "";
  960. }
  961. else {
  962. foreach ((array)$value as $val) {
  963. $parts[] = "$key " . escapeshellarg($val);
  964. }
  965. }
  966. }
  967. }
  968. else {
  969. foreach ((array)$values[$key] as $value) {
  970. $parts[] = escapeshellarg($value);
  971. }
  972. }
  973. $replacements[$tag] = join(" ", $parts);
  974. }
  975. // use strtr behaviour of going through source string once
  976. $cmd = strtr($cmd, $replacements);
  977. return (string)shell_exec($cmd);
  978. }
  979. /**
  980. * Print or write debug messages
  981. *
  982. * @param mixed Debug message or data
  983. */
  984. public static function console()
  985. {
  986. $args = func_get_args();
  987. if (class_exists('rcube', false)) {
  988. $rcube = self::get_instance();
  989. $plugin = $rcube->plugins->exec_hook('console', array('args' => $args));
  990. if ($plugin['abort']) {
  991. return;
  992. }
  993. $args = $plugin['args'];
  994. }
  995. $msg = array();
  996. foreach ($args as $arg) {
  997. $msg[] = !is_string($arg) ? var_export($arg, true) : $arg;
  998. }
  999. self::write_log('console', join(";\n", $msg));
  1000. }
  1001. /**
  1002. * Append a line to a logfile in the logs directory.
  1003. * Date will be added automatically to the line.
  1004. *
  1005. * @param string $name Name of the log file
  1006. * @param mixed $line Line to append
  1007. *
  1008. * @return bool True on success, False on failure
  1009. */
  1010. public static function write_log($name, $line)
  1011. {
  1012. if (!is_string($line)) {
  1013. $line = var_export($line, true);
  1014. }
  1015. $date_format = $log_driver = $session_key = null;
  1016. if (self::$instance) {
  1017. $date_format = self::$instance->config->get('log_date_format');
  1018. $log_driver = self::$instance->config->get('log_driver');
  1019. $session_key = intval(self::$instance->config->get('log_session_id', 8));
  1020. }
  1021. $date = rcube_utils::date_format($date_format);
  1022. // trigger logging hook
  1023. if (is_object(self::$instance) && is_object(self::$instance->plugins)) {
  1024. $log = self::$instance->plugins->exec_hook('write_log',
  1025. array('name' => $name, 'date' => $date, 'line' => $line));
  1026. $name = $log['name'];
  1027. $line = $log['line'];
  1028. $date = $log['date'];
  1029. if ($log['abort']) {
  1030. return true;
  1031. }
  1032. }
  1033. // add session ID to the log
  1034. if ($session_key > 0 && ($sess = session_id())) {
  1035. $line = '<' . substr($sess, 0, $session_key) . '> ' . $line;
  1036. }
  1037. if ($log_driver == 'syslog') {
  1038. $prio = $name == 'errors' ? LOG_ERR : LOG_INFO;
  1039. return syslog($prio, $line);
  1040. }
  1041. // write message with file name when configured to log to STDOUT
  1042. if ($log_driver == 'stdout') {
  1043. $stdout = "php://stdout";
  1044. $line = "$name: $line";
  1045. return file_put_contents($stdout, $line, FILE_APPEND) !== false;
  1046. }
  1047. // log_driver == 'file' is assumed here
  1048. $line = sprintf("[%s]: %s\n", $date, $line);
  1049. // per-user logging is activated
  1050. if (self::$instance && self::$instance->config->get('per_user_logging') && self::$instance->get_user_id()) {
  1051. $log_dir = self::$instance->get_user_log_dir();
  1052. if (empty($log_dir) && !in_array($name, array('errors', 'userlogins', 'sendmail'))) {
  1053. return false;
  1054. }
  1055. }
  1056. if (empty($log_dir)) {
  1057. if (!empty($log['dir'])) {
  1058. $log_dir = $log['dir'];
  1059. }
  1060. else if (self::$instance) {
  1061. $log_dir = self::$instance->config->get('log_dir');
  1062. }
  1063. }
  1064. if (empty($log_dir)) {
  1065. $log_dir = RCUBE_INSTALL_PATH . 'logs';
  1066. }
  1067. return file_put_contents("$log_dir/$name", $line, FILE_APPEND) !== false;
  1068. }
  1069. /**
  1070. * Throw system error (and show error page).
  1071. *
  1072. * @param array $arg Named parameters
  1073. * - code: Error code (required)
  1074. * - type: Error type [php|db|imap|javascript]
  1075. * - message: Error message
  1076. * - file: File where error occurred
  1077. * - line: Line where error occurred
  1078. * @param boolean $log True to log the error
  1079. * @param boolean $terminate Terminate script execution
  1080. */
  1081. public static function raise_error($arg = array(), $log = false, $terminate = false)
  1082. {
  1083. // handle PHP exceptions
  1084. if (is_object($arg) && is_a($arg, 'Exception')) {
  1085. $arg = array(
  1086. 'code' => $arg->getCode(),
  1087. 'line' => $arg->getLine(),
  1088. 'file' => $arg->getFile(),
  1089. 'message' => $arg->getMessage(),
  1090. );
  1091. }
  1092. else if (is_string($arg)) {
  1093. $arg = array('message' => $arg);
  1094. }
  1095. if (empty($arg['code'])) {
  1096. $arg['code'] = 500;
  1097. }
  1098. $cli = php_sapi_name() == 'cli';
  1099. // installer
  1100. if (!$cli && class_exists('rcmail_install', false)) {
  1101. $rci = rcmail_install::get_instance();
  1102. $rci->raise_error($arg);
  1103. return;
  1104. }
  1105. if (($log || $terminate) && !$cli && $arg['message']) {
  1106. $arg['fatal'] = $terminate;
  1107. self::log_bug($arg);
  1108. }
  1109. // terminate script
  1110. if ($terminate) {
  1111. // display error page
  1112. if (is_object(self::$instance->output)) {
  1113. self::$instance->output->raise_error($arg['code'], $arg['message']);
  1114. }
  1115. else if ($cli) {
  1116. fwrite(STDERR, 'ERROR: ' . $arg['message']);
  1117. }
  1118. exit(1);
  1119. }
  1120. else if ($cli) {
  1121. fwrite(STDERR, 'ERROR: ' . $arg['message']);
  1122. }
  1123. }
  1124. /**
  1125. * Report error according to configured debug_level
  1126. *
  1127. * @param array $arg_arr Named parameters
  1128. * @see self::raise_error()
  1129. */
  1130. public static function log_bug($arg_arr)
  1131. {
  1132. $program = strtoupper($arg_arr['type'] ?: 'php');
  1133. $level = self::get_instance()->config->get('debug_level');
  1134. // disable errors for ajax requests, write to log instead (#1487831)
  1135. if (($level & 4) && !empty($_REQUEST['_remote'])) {
  1136. $level = ($level ^ 4) | 1;
  1137. }
  1138. // write error to local log file
  1139. if (($level & 1) || !empty($arg_arr['fatal'])) {
  1140. if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  1141. foreach (array('_task', '_action') as $arg) {
  1142. if ($_POST[$arg] && !$_GET[$arg]) {
  1143. $post_query[$arg] = $_POST[$arg];
  1144. }
  1145. }
  1146. if (!empty($post_query)) {
  1147. $post_query = (strpos($_SERVER['REQUEST_URI'], '?') != false ? '&' : '?')
  1148. . http_build_query($post_query, '', '&');
  1149. }
  1150. }
  1151. $log_entry = sprintf("%s Error: %s%s (%s %s)",
  1152. $program,
  1153. $arg_arr['message'],
  1154. $arg_arr['file'] ? sprintf(' in %s on line %d', $arg_arr['file'], $arg_arr['line']) : '',
  1155. $_SERVER['REQUEST_METHOD'],
  1156. $_SERVER['REQUEST_URI'] . $post_query);
  1157. if (!self::write_log('errors', $log_entry)) {
  1158. // send error to PHPs error handler if write_log didn't succeed
  1159. trigger_error($arg_arr['message'], E_USER_WARNING);
  1160. }
  1161. }
  1162. // report the bug to the global bug reporting system
  1163. if ($level & 2) {
  1164. // TODO: Send error via HTTP
  1165. }
  1166. // show error if debug_mode is on
  1167. if ($level & 4) {
  1168. print "<b>$program Error";
  1169. if (!empty($arg_arr['file']) && !empty($arg_arr['line'])) {
  1170. print " in $arg_arr[file] ($arg_arr[line])";
  1171. }
  1172. print ':</b>&nbsp;';
  1173. print nl2br($arg_arr['message']);
  1174. print '<br />';
  1175. flush();
  1176. }
  1177. }
  1178. /**
  1179. * Write debug info to the log
  1180. *
  1181. * @param string $engine Engine type - file name (memcache, apc)
  1182. * @param string $data Data string to log
  1183. * @param bool $result Operation result
  1184. */
  1185. public static function debug($engine, $data, $result = null)
  1186. {
  1187. static $debug_counter;
  1188. $line = '[' . (++$debug_counter[$engine]) . '] ' . $data;
  1189. if (($len = strlen($line)) > self::DEBUG_LINE_LENGTH) {
  1190. $diff = $len - self::DEBUG_LINE_LENGTH;
  1191. $line = substr($line, 0, self::DEBUG_LINE_LENGTH) . "... [truncated $diff bytes]";
  1192. }
  1193. if ($result !== null) {
  1194. $line .= ' [' . ($result ? 'TRUE' : 'FALSE') . ']';
  1195. }
  1196. self::write_log($engine, $line);
  1197. }
  1198. /**
  1199. * Returns current time (with microseconds).
  1200. *
  1201. * @return float Current time in seconds since the Unix
  1202. */
  1203. public static function timer()
  1204. {
  1205. return microtime(true);
  1206. }
  1207. /**
  1208. * Logs time difference according to provided timer
  1209. *
  1210. * @param float $timer Timer (self::timer() result)
  1211. * @param string $label Log line prefix
  1212. * @param string $dest Log file name
  1213. *
  1214. * @see self::timer()
  1215. */
  1216. public static function print_timer($timer, $label = 'Timer', $dest = 'console')
  1217. {
  1218. static $print_count = 0;
  1219. $print_count++;
  1220. $now = self::timer();
  1221. $diff = $now - $timer;
  1222. if (empty($label)) {
  1223. $label = 'Timer '.$print_count;
  1224. }
  1225. self::write_log($dest, sprintf("%s: %0.4f sec", $label, $diff));
  1226. }
  1227. /**
  1228. * Setter for system user object
  1229. *
  1230. * @param rcube_user Current user instance
  1231. */
  1232. public function set_user($user)
  1233. {
  1234. if (is_object($user)) {
  1235. $this->user = $user;
  1236. // overwrite config with user preferences
  1237. $this->config->set_user_prefs((array)$this->user->get_prefs());
  1238. }
  1239. }
  1240. /**
  1241. * Getter for logged user ID.
  1242. *
  1243. * @return mixed User identifier
  1244. */
  1245. public function get_user_id()
  1246. {
  1247. if (is_object($this->user)) {
  1248. return $this->user->ID;
  1249. }
  1250. else if (isset($_SESSION['user_id'])) {
  1251. return $_SESSION['user_id'];
  1252. }
  1253. return null;
  1254. }
  1255. /**
  1256. * Getter for logged user name.
  1257. *
  1258. * @return string User name
  1259. */
  1260. public function get_user_name()
  1261. {
  1262. if (is_object($this->user)) {
  1263. return $this->user->get_username();
  1264. }
  1265. else if (isset($_SESSION['username'])) {
  1266. return $_SESSION['username'];
  1267. }
  1268. }
  1269. /**
  1270. * Getter for logged user email (derived from user name not identity).
  1271. *
  1272. * @return string User email address
  1273. */
  1274. public function get_user_email()
  1275. {
  1276. if (is_object($this->user)) {
  1277. return $this->user->get_username('mail');
  1278. }
  1279. }
  1280. /**
  1281. * Getter for logged user password.
  1282. *
  1283. * @return string User password
  1284. */
  1285. public function get_user_password()
  1286. {
  1287. if ($this->password) {
  1288. return $this->password;
  1289. }
  1290. else if ($_SESSION['password']) {
  1291. return $this->decrypt($_SESSION['password']);
  1292. }
  1293. }
  1294. /**
  1295. * Get the per-user log directory
  1296. */
  1297. protected function get_user_log_dir()
  1298. {
  1299. $log_dir = $this->config->get('log_dir', RCUBE_INSTALL_PATH . 'logs');
  1300. $user_name = $this->get_user_name();
  1301. $user_log_dir = $log_dir . '/' . $user_name;
  1302. return !empty($user_name) && is_writable($user_log_dir) ? $user_log_dir : false;
  1303. }
  1304. /**
  1305. * Getter for logged user language code.
  1306. *
  1307. * @return string User language code
  1308. */
  1309. public function get_user_language()
  1310. {
  1311. if (is_object($this->user)) {
  1312. return $this->user->language;
  1313. }
  1314. else if (isset($_SESSION['language'])) {
  1315. return $_SESSION['language'];
  1316. }
  1317. }
  1318. /**
  1319. * Unique Message-ID generator.
  1320. *
  1321. * @param string $sender Optional sender e-mail address
  1322. *
  1323. * @return string Message-ID
  1324. */
  1325. public function gen_message_id($sender = null)
  1326. {
  1327. $local_part = md5(uniqid('rcube'.mt_rand(), true));
  1328. $domain_part = '';
  1329. if ($sender && preg_match('/@([^\s]+\.[a-z0-9-]+)/', $sender, $m)) {
  1330. $domain_part = $m[1];
  1331. }
  1332. else {
  1333. $domain_part = $this->user->get_username('domain');
  1334. }
  1335. // Try to find FQDN, some spamfilters doesn't like 'localhost' (#1486924)
  1336. if (!preg_match('/\.[a-z0-9-]+$/i', $domain_part)) {
  1337. foreach (array($_SERVER['HTTP_HOST'], $_SERVER['SERVER_NAME']) as $host) {
  1338. $host = preg_replace('/:[0-9]+$/', '', $host);
  1339. if ($host && preg_match('/\.[a-z]+$/i', $host)) {
  1340. $domain_part = $host;
  1341. break;
  1342. }
  1343. }
  1344. }
  1345. return sprintf('<%s@%s>', $local_part, $domain_part);
  1346. }
  1347. /**
  1348. * Send the given message using the configured method.
  1349. *
  1350. * @param object $message Reference to Mail_MIME object
  1351. * @param string $from Sender address string
  1352. * @param array $mailto Array of recipient address strings
  1353. * @param array $error SMTP error array (reference)
  1354. * @param string $body_file Location of file with saved message body (reference),
  1355. * used when delay_file_io is enabled
  1356. * @param array $options SMTP options (e.g. DSN request)
  1357. * @param bool $disconnect Close SMTP connection ASAP
  1358. *
  1359. * @return boolean Send status.
  1360. */
  1361. public function deliver_message(&$message, $from, $mailto, &$error,
  1362. &$body_file = null, $options = null, $disconnect = false)
  1363. {
  1364. $plugin = $this->plugins->exec_hook('message_before_send', array(
  1365. 'message' => $message,
  1366. 'from' => $from,
  1367. 'mailto' => $mailto,
  1368. 'options' => $options,
  1369. ));
  1370. if ($plugin['abort']) {
  1371. if (!empty($plugin['error'])) {
  1372. $error = $plugin['error'];
  1373. }
  1374. if (!empty($plugin['body_file'])) {
  1375. $body_file = $plugin['body_file'];
  1376. }
  1377. return isset($plugin['result']) ? $plugin['result'] : false;
  1378. }
  1379. $from = $plugin['from'];
  1380. $mailto = $plugin['mailto'];
  1381. $options = $plugin['options'];
  1382. $message = $plugin['message'];
  1383. $headers = $message->headers();
  1384. // generate list of recipients
  1385. $a_recipients = (array) $mailto;
  1386. if (strlen($headers['Cc'])) {
  1387. $a_recipients[] = $headers['Cc'];
  1388. }
  1389. if (strlen($headers['Bcc'])) {
  1390. $a_recipients[] = $headers['Bcc'];
  1391. }
  1392. // remove Bcc header and get the whole head of the message as string
  1393. $smtp_headers = $message->txtHeaders(array('Bcc' => null), true);
  1394. if ($message->getParam('delay_file_io')) {
  1395. // use common temp dir
  1396. $temp_dir = $this->config->get('temp_dir');
  1397. $body_file = tempnam($temp_dir, 'rcmMsg');
  1398. $mime_result = $message->saveMessageBody($body_file);
  1399. if (is_a($mime_result, 'PEAR_Error')) {
  1400. self::raise_error(array('code' => 650, 'type' => 'php',
  1401. 'file' => __FILE__, 'line' => __LINE__,
  1402. 'message' => "Could not create message: ".$mime_result->getMessage()),
  1403. true, false);
  1404. return false;
  1405. }
  1406. $msg_body = fopen($body_file, 'r');
  1407. }
  1408. else {
  1409. $msg_body = $message->get();
  1410. }
  1411. // initialize SMTP connection
  1412. if (!is_object($this->smtp)) {
  1413. $this->smtp_init(true);
  1414. }
  1415. // send message
  1416. $sent = $this->smtp->send_mail($from, $a_recipients, $smtp_headers, $msg_body, $options);
  1417. $response = $this->smtp->get_response();
  1418. $error = $this->smtp->get_error();
  1419. if (!$sent) {
  1420. self::raise_error(array('code' => 800, 'type' => 'smtp',
  1421. 'line' => __LINE__, 'file' => __FILE__,
  1422. 'message' => join("\n", $response)), true, false);
  1423. // allow plugins to catch sending errors with the same parameters as in 'message_before_send'
  1424. $this->plugins->exec_hook('message_send_error', $plugin + array('error' => $error));
  1425. }
  1426. else {
  1427. $this->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body, 'message' => $message));
  1428. // remove MDN headers after sending
  1429. unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
  1430. if ($this->config->get('smtp_log')) {
  1431. // get all recipient addresses
  1432. $mailto = implode(',', $a_recipients);
  1433. $mailto = rcube_mime::decode_address_list($mailto, null, false, null, true);
  1434. self::write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
  1435. $this->user->get_username(),
  1436. rcube_utils::remote_addr(),
  1437. implode(', ', $mailto),
  1438. !empty($response) ? join('; ', $response) : ''));
  1439. }
  1440. }
  1441. if (is_resource($msg_body)) {
  1442. fclose($msg_body);
  1443. }
  1444. if ($disconnect) {
  1445. $this->smtp->disconnect();
  1446. }
  1447. $message->headers($headers, true);
  1448. return $sent;
  1449. }
  1450. }
  1451. /**
  1452. * Lightweight plugin API class serving as a dummy if plugins are not enabled
  1453. *
  1454. * @package Framework
  1455. * @subpackage Core
  1456. */
  1457. class rcube_dummy_plugin_api
  1458. {
  1459. /**
  1460. * Triggers a plugin hook.
  1461. * @see rcube_plugin_api::exec_hook()
  1462. */
  1463. public function exec_hook($hook, $args = array())
  1464. {
  1465. return $args;
  1466. }
  1467. }