rcube.php 51 KB

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