You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rcube.php 53KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
  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. // format output
  543. if (($attrib['uppercase'] && strtolower($attrib['uppercase'] == 'first')) || $attrib['ucfirst']) {
  544. return ucfirst($text);
  545. }
  546. else if ($attrib['uppercase']) {
  547. return mb_strtoupper($text);
  548. }
  549. else if ($attrib['lowercase']) {
  550. return mb_strtolower($text);
  551. }
  552. return strtr($text, array('\n' => "\n"));
  553. }
  554. /**
  555. * Check if the given text label exists
  556. *
  557. * @param string $name Label name
  558. * @param string $domain Label domain (plugin) name or '*' for all domains
  559. * @param string $ref_domain Sets domain name if label is found
  560. *
  561. * @return boolean True if text exists (either in the current language or in en_US)
  562. */
  563. public function text_exists($name, $domain = null, &$ref_domain = null)
  564. {
  565. // load localization files if not done yet
  566. if (empty($this->texts)) {
  567. $this->load_language();
  568. }
  569. if (isset($this->texts[$name])) {
  570. $ref_domain = '';
  571. return true;
  572. }
  573. // any of loaded domains (plugins)
  574. if ($domain == '*') {
  575. foreach ($this->plugins->loaded_plugins() as $domain) {
  576. if (isset($this->texts[$domain.'.'.$name])) {
  577. $ref_domain = $domain;
  578. return true;
  579. }
  580. }
  581. }
  582. // specified domain
  583. else if ($domain) {
  584. $ref_domain = $domain;
  585. return isset($this->texts[$domain.'.'.$name]);
  586. }
  587. return false;
  588. }
  589. /**
  590. * Load a localization package
  591. *
  592. * @param string $lang Language ID
  593. * @param array $add Additional text labels/messages
  594. * @param array $merge Additional text labels/messages to merge
  595. */
  596. public function load_language($lang = null, $add = array(), $merge = array())
  597. {
  598. $lang = $this->language_prop($lang ?: $_SESSION['language']);
  599. // load localized texts
  600. if (empty($this->texts) || $lang != $_SESSION['language']) {
  601. $this->texts = array();
  602. // handle empty lines after closing PHP tag in localization files
  603. ob_start();
  604. // get english labels (these should be complete)
  605. @include(RCUBE_LOCALIZATION_DIR . 'en_US/labels.inc');
  606. @include(RCUBE_LOCALIZATION_DIR . 'en_US/messages.inc');
  607. if (is_array($labels))
  608. $this->texts = $labels;
  609. if (is_array($messages))
  610. $this->texts = array_merge($this->texts, $messages);
  611. // include user language files
  612. if ($lang != 'en' && $lang != 'en_US' && is_dir(RCUBE_LOCALIZATION_DIR . $lang)) {
  613. include_once(RCUBE_LOCALIZATION_DIR . $lang . '/labels.inc');
  614. include_once(RCUBE_LOCALIZATION_DIR . $lang . '/messages.inc');
  615. if (is_array($labels))
  616. $this->texts = array_merge($this->texts, $labels);
  617. if (is_array($messages))
  618. $this->texts = array_merge($this->texts, $messages);
  619. }
  620. ob_end_clean();
  621. $_SESSION['language'] = $lang;
  622. }
  623. // append additional texts (from plugin)
  624. if (is_array($add) && !empty($add)) {
  625. $this->texts += $add;
  626. }
  627. // merge additional texts (from plugin)
  628. if (is_array($merge) && !empty($merge)) {
  629. $this->texts = array_merge($this->texts, $merge);
  630. }
  631. }
  632. /**
  633. * Check the given string and return a valid language code
  634. *
  635. * @param string $lang Language code
  636. *
  637. * @return string Valid language code
  638. */
  639. protected function language_prop($lang)
  640. {
  641. static $rcube_languages, $rcube_language_aliases;
  642. // user HTTP_ACCEPT_LANGUAGE if no language is specified
  643. if (empty($lang) || $lang == 'auto') {
  644. $accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
  645. $lang = $accept_langs[0];
  646. if (preg_match('/^([a-z]+)[_-]([a-z]+)$/i', $lang, $m)) {
  647. $lang = $m[1] . '_' . strtoupper($m[2]);
  648. }
  649. }
  650. if (empty($rcube_languages)) {
  651. @include(RCUBE_LOCALIZATION_DIR . 'index.inc');
  652. }
  653. // check if we have an alias for that language
  654. if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
  655. $lang = $rcube_language_aliases[$lang];
  656. }
  657. // try the first two chars
  658. else if (!isset($rcube_languages[$lang])) {
  659. $short = substr($lang, 0, 2);
  660. // check if we have an alias for the short language code
  661. if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
  662. $lang = $rcube_language_aliases[$short];
  663. }
  664. // expand 'nn' to 'nn_NN'
  665. else if (!isset($rcube_languages[$short])) {
  666. $lang = $short.'_'.strtoupper($short);
  667. }
  668. }
  669. if (!isset($rcube_languages[$lang]) || !is_dir(RCUBE_LOCALIZATION_DIR . $lang)) {
  670. $lang = 'en_US';
  671. }
  672. return $lang;
  673. }
  674. /**
  675. * Read directory program/localization and return a list of available languages
  676. *
  677. * @return array List of available localizations
  678. */
  679. public function list_languages()
  680. {
  681. static $sa_languages = array();
  682. if (!sizeof($sa_languages)) {
  683. @include(RCUBE_LOCALIZATION_DIR . 'index.inc');
  684. if ($dh = @opendir(RCUBE_LOCALIZATION_DIR)) {
  685. while (($name = readdir($dh)) !== false) {
  686. if ($name[0] == '.' || !is_dir(RCUBE_LOCALIZATION_DIR . $name)) {
  687. continue;
  688. }
  689. if ($label = $rcube_languages[$name]) {
  690. $sa_languages[$name] = $label;
  691. }
  692. }
  693. closedir($dh);
  694. }
  695. }
  696. return $sa_languages;
  697. }
  698. /**
  699. * Encrypt a string
  700. *
  701. * @param string $clear Clear text input
  702. * @param string $key Encryption key to retrieve from the configuration, defaults to 'des_key'
  703. * @param boolean $base64 Whether or not to base64_encode() the result before returning
  704. *
  705. * @return string Encrypted text
  706. */
  707. public function encrypt($clear, $key = 'des_key', $base64 = true)
  708. {
  709. if (!is_string($clear) || !strlen($clear)) {
  710. return '';
  711. }
  712. $ckey = $this->config->get_crypto_key($key);
  713. $method = $this->config->get_crypto_method();
  714. $opts = defined('OPENSSL_RAW_DATA') ? OPENSSL_RAW_DATA : true;
  715. $iv = rcube_utils::random_bytes(openssl_cipher_iv_length($method), true);
  716. $cipher = $iv . openssl_encrypt($clear, $method, $ckey, $opts, $iv);
  717. return $base64 ? base64_encode($cipher) : $cipher;
  718. }
  719. /**
  720. * Decrypt a string
  721. *
  722. * @param string $cipher Encrypted text
  723. * @param string $key Encryption key to retrieve from the configuration, defaults to 'des_key'
  724. * @param boolean $base64 Whether or not input is base64-encoded
  725. *
  726. * @return string Decrypted text
  727. */
  728. public function decrypt($cipher, $key = 'des_key', $base64 = true)
  729. {
  730. if (!$cipher) {
  731. return '';
  732. }
  733. $cipher = $base64 ? base64_decode($cipher) : $cipher;
  734. $ckey = $this->config->get_crypto_key($key);
  735. $method = $this->config->get_crypto_method();
  736. $opts = defined('OPENSSL_RAW_DATA') ? OPENSSL_RAW_DATA : true;
  737. $iv_size = openssl_cipher_iv_length($method);
  738. $iv = substr($cipher, 0, $iv_size);
  739. // session corruption? (#1485970)
  740. if (strlen($iv) < $iv_size) {
  741. return '';
  742. }
  743. $cipher = substr($cipher, $iv_size);
  744. $clear = openssl_decrypt($cipher, $method, $ckey, $opts, $iv);
  745. return $clear;
  746. }
  747. /**
  748. * Returns session token for secure URLs
  749. *
  750. * @param bool $generate Generate token if not exists in session yet
  751. *
  752. * @return string|bool Token string, False when disabled
  753. */
  754. public function get_secure_url_token($generate = false)
  755. {
  756. if ($len = $this->config->get('use_secure_urls')) {
  757. if (empty($_SESSION['secure_token']) && $generate) {
  758. // generate x characters long token
  759. $length = $len > 1 ? $len : 16;
  760. $token = rcube_utils::random_bytes($length);
  761. $plugin = $this->plugins->exec_hook('secure_token',
  762. array('value' => $token, 'length' => $length));
  763. $_SESSION['secure_token'] = $plugin['value'];
  764. }
  765. return $_SESSION['secure_token'];
  766. }
  767. return false;
  768. }
  769. /**
  770. * Generate a unique token to be used in a form request
  771. *
  772. * @return string The request token
  773. */
  774. public function get_request_token()
  775. {
  776. if (empty($_SESSION['request_token'])) {
  777. $plugin = $this->plugins->exec_hook('request_token', array(
  778. 'value' => rcube_utils::random_bytes(32)));
  779. $_SESSION['request_token'] = $plugin['value'];
  780. }
  781. return $_SESSION['request_token'];
  782. }
  783. /**
  784. * Check if the current request contains a valid token.
  785. * Empty requests aren't checked until use_secure_urls is set.
  786. *
  787. * @param int $mode Request method
  788. *
  789. * @return boolean True if request token is valid false if not
  790. */
  791. public function check_request($mode = rcube_utils::INPUT_POST)
  792. {
  793. // check secure token in URL if enabled
  794. if ($token = $this->get_secure_url_token()) {
  795. foreach (explode('/', preg_replace('/[?#&].*$/', '', $_SERVER['REQUEST_URI'])) as $tok) {
  796. if ($tok == $token) {
  797. return true;
  798. }
  799. }
  800. $this->request_status = self::REQUEST_ERROR_URL;
  801. return false;
  802. }
  803. $sess_tok = $this->get_request_token();
  804. // ajax requests
  805. if (rcube_utils::request_header('X-Roundcube-Request') == $sess_tok) {
  806. return true;
  807. }
  808. // skip empty requests
  809. if (($mode == rcube_utils::INPUT_POST && empty($_POST))
  810. || ($mode == rcube_utils::INPUT_GET && empty($_GET))
  811. ) {
  812. return true;
  813. }
  814. // default method of securing requests
  815. $token = rcube_utils::get_input_value('_token', $mode);
  816. $sess_id = $_COOKIE[ini_get('session.name')];
  817. if (empty($sess_id) || $token != $sess_tok) {
  818. $this->request_status = self::REQUEST_ERROR_TOKEN;
  819. return false;
  820. }
  821. return true;
  822. }
  823. /**
  824. * Build a valid URL to this instance of Roundcube
  825. *
  826. * @param mixed $p Either a string with the action or url parameters as key-value pairs
  827. *
  828. * @return string Valid application URL
  829. */
  830. public function url($p)
  831. {
  832. // STUB: should be overloaded by the application
  833. return '';
  834. }
  835. /**
  836. * Function to be executed in script shutdown
  837. * Registered with register_shutdown_function()
  838. */
  839. public function shutdown()
  840. {
  841. foreach ($this->shutdown_functions as $function) {
  842. call_user_func($function);
  843. }
  844. // write session data as soon as possible and before
  845. // closing database connection, don't do this before
  846. // registered shutdown functions, they may need the session
  847. // Note: this will run registered gc handlers (ie. cache gc)
  848. if ($_SERVER['REMOTE_ADDR'] && is_object($this->session)) {
  849. $this->session->write_close();
  850. }
  851. if (is_object($this->smtp)) {
  852. $this->smtp->disconnect();
  853. }
  854. foreach ($this->caches as $cache) {
  855. if (is_object($cache)) {
  856. $cache->close();
  857. }
  858. }
  859. if (is_object($this->storage)) {
  860. $this->storage->close();
  861. }
  862. if ($this->config->get('log_driver') == 'syslog') {
  863. closelog();
  864. }
  865. }
  866. /**
  867. * Registers shutdown function to be executed on shutdown.
  868. * The functions will be executed before destroying any
  869. * objects like smtp, imap, session, etc.
  870. *
  871. * @param callback Function callback
  872. */
  873. public function add_shutdown_function($function)
  874. {
  875. $this->shutdown_functions[] = $function;
  876. }
  877. /**
  878. * When you're going to sleep the script execution for a longer time
  879. * it is good to close all external connections (sql, memcache, SMTP, IMAP).
  880. *
  881. * No action is required on wake up, all connections will be
  882. * re-established automatically.
  883. */
  884. public function sleep()
  885. {
  886. foreach ($this->caches as $cache) {
  887. if (is_object($cache)) {
  888. $cache->close();
  889. }
  890. }
  891. if ($this->storage) {
  892. $this->storage->close();
  893. }
  894. if ($this->db) {
  895. $this->db->closeConnection();
  896. }
  897. if ($this->memcache) {
  898. $this->memcache->close();
  899. // after close() need to re-init memcache
  900. $this->memcache_init();
  901. }
  902. if ($this->smtp) {
  903. $this->smtp->disconnect();
  904. }
  905. }
  906. /**
  907. * Quote a given string.
  908. * Shortcut function for rcube_utils::rep_specialchars_output()
  909. *
  910. * @return string HTML-quoted string
  911. */
  912. public static function Q($str, $mode = 'strict', $newlines = true)
  913. {
  914. return rcube_utils::rep_specialchars_output($str, 'html', $mode, $newlines);
  915. }
  916. /**
  917. * Quote a given string for javascript output.
  918. * Shortcut function for rcube_utils::rep_specialchars_output()
  919. *
  920. * @return string JS-quoted string
  921. */
  922. public static function JQ($str)
  923. {
  924. return rcube_utils::rep_specialchars_output($str, 'js');
  925. }
  926. /**
  927. * Construct shell command, execute it and return output as string.
  928. * Keywords {keyword} are replaced with arguments
  929. *
  930. * @param $cmd Format string with {keywords} to be replaced
  931. * @param $values (zero, one or more arrays can be passed)
  932. *
  933. * @return output of command. shell errors not detectable
  934. */
  935. public static function exec(/* $cmd, $values1 = array(), ... */)
  936. {
  937. $args = func_get_args();
  938. $cmd = array_shift($args);
  939. $values = $replacements = array();
  940. // merge values into one array
  941. foreach ($args as $arg) {
  942. $values += (array)$arg;
  943. }
  944. preg_match_all('/({(-?)([a-z]\w*)})/', $cmd, $matches, PREG_SET_ORDER);
  945. foreach ($matches as $tags) {
  946. list(, $tag, $option, $key) = $tags;
  947. $parts = array();
  948. if ($option) {
  949. foreach ((array)$values["-$key"] as $key => $value) {
  950. if ($value === true || $value === false || $value === null) {
  951. $parts[] = $value ? $key : "";
  952. }
  953. else {
  954. foreach ((array)$value as $val) {
  955. $parts[] = "$key " . escapeshellarg($val);
  956. }
  957. }
  958. }
  959. }
  960. else {
  961. foreach ((array)$values[$key] as $value) {
  962. $parts[] = escapeshellarg($value);
  963. }
  964. }
  965. $replacements[$tag] = join(" ", $parts);
  966. }
  967. // use strtr behaviour of going through source string once
  968. $cmd = strtr($cmd, $replacements);
  969. return (string)shell_exec($cmd);
  970. }
  971. /**
  972. * Print or write debug messages
  973. *
  974. * @param mixed Debug message or data
  975. */
  976. public static function console()
  977. {
  978. $args = func_get_args();
  979. if (class_exists('rcube', false)) {
  980. $rcube = self::get_instance();
  981. $plugin = $rcube->plugins->exec_hook('console', array('args' => $args));
  982. if ($plugin['abort']) {
  983. return;
  984. }
  985. $args = $plugin['args'];
  986. }
  987. $msg = array();
  988. foreach ($args as $arg) {
  989. $msg[] = !is_string($arg) ? var_export($arg, true) : $arg;
  990. }
  991. self::write_log('console', join(";\n", $msg));
  992. }
  993. /**
  994. * Append a line to a logfile in the logs directory.
  995. * Date will be added automatically to the line.
  996. *
  997. * @param string $name Name of the log file
  998. * @param mixed $line Line to append
  999. */
  1000. public static function write_log($name, $line)
  1001. {
  1002. if (!is_string($line)) {
  1003. $line = var_export($line, true);
  1004. }
  1005. $date_format = $log_driver = $session_key = null;
  1006. if (self::$instance) {
  1007. $date_format = self::$instance->config->get('log_date_format');
  1008. $log_driver = self::$instance->config->get('log_driver');
  1009. $session_key = intval(self::$instance->config->get('log_session_id', 8));
  1010. }
  1011. $date = rcube_utils::date_format($date_format);
  1012. // trigger logging hook
  1013. if (is_object(self::$instance) && is_object(self::$instance->plugins)) {
  1014. $log = self::$instance->plugins->exec_hook('write_log',
  1015. array('name' => $name, 'date' => $date, 'line' => $line));
  1016. $name = $log['name'];
  1017. $line = $log['line'];
  1018. $date = $log['date'];
  1019. if ($log['abort']) {
  1020. return true;
  1021. }
  1022. }
  1023. // add session ID to the log
  1024. if ($session_key > 0 && ($sess = session_id())) {
  1025. $line = '<' . substr($sess, 0, $session_key) . '> ' . $line;
  1026. }
  1027. if ($log_driver == 'syslog') {
  1028. $prio = $name == 'errors' ? LOG_ERR : LOG_INFO;
  1029. syslog($prio, $line);
  1030. return true;
  1031. }
  1032. // log_driver == 'file' is assumed here
  1033. $line = sprintf("[%s]: %s\n", $date, $line);
  1034. $log_dir = null;
  1035. // per-user logging is activated
  1036. if (self::$instance && self::$instance->config->get('per_user_logging', false) && self::$instance->get_user_id()) {
  1037. $log_dir = self::$instance->get_user_log_dir();
  1038. if (empty($log_dir) && $name != 'errors') {
  1039. return false;
  1040. }
  1041. }
  1042. if (empty($log_dir)) {
  1043. if (!empty($log['dir'])) {
  1044. $log_dir = $log['dir'];
  1045. }
  1046. else if (self::$instance) {
  1047. $log_dir = self::$instance->config->get('log_dir');
  1048. }
  1049. }
  1050. if (empty($log_dir)) {
  1051. $log_dir = RCUBE_INSTALL_PATH . 'logs';
  1052. }
  1053. return file_put_contents("$log_dir/$name", $line, FILE_APPEND) !== false;
  1054. }
  1055. /**
  1056. * Throw system error (and show error page).
  1057. *
  1058. * @param array $arg Named parameters
  1059. * - code: Error code (required)
  1060. * - type: Error type [php|db|imap|javascript] (required)
  1061. * - message: Error message
  1062. * - file: File where error occurred
  1063. * - line: Line where error occurred
  1064. * @param boolean $log True to log the error
  1065. * @param boolean $terminate Terminate script execution
  1066. */
  1067. public static function raise_error($arg = array(), $log = false, $terminate = false)
  1068. {
  1069. // handle PHP exceptions
  1070. if (is_object($arg) && is_a($arg, 'Exception')) {
  1071. $arg = array(
  1072. 'code' => $arg->getCode(),
  1073. 'line' => $arg->getLine(),
  1074. 'file' => $arg->getFile(),
  1075. 'message' => $arg->getMessage(),
  1076. );
  1077. }
  1078. else if (is_string($arg)) {
  1079. $arg = array('message' => $arg);
  1080. }
  1081. if (empty($arg['code'])) {
  1082. $arg['code'] = 500;
  1083. }
  1084. // installer
  1085. if (class_exists('rcmail_install', false)) {
  1086. $rci = rcmail_install::get_instance();
  1087. $rci->raise_error($arg);
  1088. return;
  1089. }
  1090. $cli = php_sapi_name() == 'cli';
  1091. if (($log || $terminate) && !$cli && $arg['message']) {
  1092. $arg['fatal'] = $terminate;
  1093. self::log_bug($arg);
  1094. }
  1095. // terminate script
  1096. if ($terminate) {
  1097. // display error page
  1098. if (is_object(self::$instance->output)) {
  1099. self::$instance->output->raise_error($arg['code'], $arg['message']);
  1100. }
  1101. else if ($cli) {
  1102. fwrite(STDERR, 'ERROR: ' . $arg['message']);
  1103. }
  1104. exit(1);
  1105. }
  1106. else if ($cli) {
  1107. fwrite(STDERR, 'ERROR: ' . $arg['message']);
  1108. }
  1109. }
  1110. /**
  1111. * Report error according to configured debug_level
  1112. *
  1113. * @param array $arg_arr Named parameters
  1114. * @see self::raise_error()
  1115. */
  1116. public static function log_bug($arg_arr)
  1117. {
  1118. $program = strtoupper($arg_arr['type'] ?: 'php');
  1119. $level = self::get_instance()->config->get('debug_level');
  1120. // disable errors for ajax requests, write to log instead (#1487831)
  1121. if (($level & 4) && !empty($_REQUEST['_remote'])) {
  1122. $level = ($level ^ 4) | 1;
  1123. }
  1124. // write error to local log file
  1125. if (($level & 1) || !empty($arg_arr['fatal'])) {
  1126. $post_query = '';
  1127. if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  1128. foreach (array('_task', '_action') as $arg) {
  1129. if ($_POST[$arg] && !$_GET[$arg]) {
  1130. $post_query[$arg] = $_POST[$arg];
  1131. }
  1132. }
  1133. if (!empty($post_query)) {
  1134. $post_query = (strpos($_SERVER['REQUEST_URI'], '?') != false ? '&' : '?')
  1135. . http_build_query($post_query, '', '&');
  1136. }
  1137. }
  1138. $log_entry = sprintf("%s Error: %s%s (%s %s)",
  1139. $program,
  1140. $arg_arr['message'],
  1141. $arg_arr['file'] ? sprintf(' in %s on line %d', $arg_arr['file'], $arg_arr['line']) : '',
  1142. $_SERVER['REQUEST_METHOD'],
  1143. $_SERVER['REQUEST_URI'] . $post_query);
  1144. if (!self::write_log('errors', $log_entry)) {
  1145. // send error to PHPs error handler if write_log didn't succeed
  1146. trigger_error($arg_arr['message'], E_USER_WARNING);
  1147. }
  1148. }
  1149. // report the bug to the global bug reporting system
  1150. if ($level & 2) {
  1151. // TODO: Send error via HTTP
  1152. }
  1153. // show error if debug_mode is on
  1154. if ($level & 4) {
  1155. print "<b>$program Error";
  1156. if (!empty($arg_arr['file']) && !empty($arg_arr['line'])) {
  1157. print " in $arg_arr[file] ($arg_arr[line])";
  1158. }
  1159. print ':</b>&nbsp;';
  1160. print nl2br($arg_arr['message']);
  1161. print '<br />';
  1162. flush();
  1163. }
  1164. }
  1165. /**
  1166. * Write debug info to the log
  1167. *
  1168. * @param string $engine Engine type - file name (memcache, apc)
  1169. * @param string $data Data string to log
  1170. * @param bool $result Operation result
  1171. */
  1172. public static function debug($engine, $data, $result = null)
  1173. {
  1174. static $debug_counter;
  1175. $line = '[' . (++$debug_counter[$engine]) . '] ' . $data;
  1176. if (($len = strlen($line)) > self::DEBUG_LINE_LENGTH) {
  1177. $diff = $len - self::DEBUG_LINE_LENGTH;
  1178. $line = substr($line, 0, self::DEBUG_LINE_LENGTH) . "... [truncated $diff bytes]";
  1179. }
  1180. if ($result !== null) {
  1181. $line .= ' [' . ($result ? 'TRUE' : 'FALSE') . ']';
  1182. }
  1183. self::write_log($engine, $line);
  1184. }
  1185. /**
  1186. * Returns current time (with microseconds).
  1187. *
  1188. * @return float Current time in seconds since the Unix
  1189. */
  1190. public static function timer()
  1191. {
  1192. return microtime(true);
  1193. }
  1194. /**
  1195. * Logs time difference according to provided timer
  1196. *
  1197. * @param float $timer Timer (self::timer() result)
  1198. * @param string $label Log line prefix
  1199. * @param string $dest Log file name
  1200. *
  1201. * @see self::timer()
  1202. */
  1203. public static function print_timer($timer, $label = 'Timer', $dest = 'console')
  1204. {
  1205. static $print_count = 0;
  1206. $print_count++;
  1207. $now = self::timer();
  1208. $diff = $now - $timer;
  1209. if (empty($label)) {
  1210. $label = 'Timer '.$print_count;
  1211. }
  1212. self::write_log($dest, sprintf("%s: %0.4f sec", $label, $diff));
  1213. }
  1214. /**
  1215. * Setter for system user object
  1216. *
  1217. * @param rcube_user Current user instance
  1218. */
  1219. public function set_user($user)
  1220. {
  1221. if (is_object($user)) {
  1222. $this->user = $user;
  1223. // overwrite config with user preferences
  1224. $this->config->set_user_prefs((array)$this->user->get_prefs());
  1225. }
  1226. }
  1227. /**
  1228. * Getter for logged user ID.
  1229. *
  1230. * @return mixed User identifier
  1231. */
  1232. public function get_user_id()
  1233. {
  1234. if (is_object($this->user)) {
  1235. return $this->user->ID;
  1236. }
  1237. else if (isset($_SESSION['user_id'])) {
  1238. return $_SESSION['user_id'];
  1239. }
  1240. return null;
  1241. }
  1242. /**
  1243. * Getter for logged user name.
  1244. *
  1245. * @return string User name
  1246. */
  1247. public function get_user_name()
  1248. {
  1249. if (is_object($this->user)) {
  1250. return $this->user->get_username();
  1251. }
  1252. else if (isset($_SESSION['username'])) {
  1253. return $_SESSION['username'];
  1254. }
  1255. }
  1256. /**
  1257. * Getter for logged user email (derived from user name not identity).
  1258. *
  1259. * @return string User email address
  1260. */
  1261. public function get_user_email()
  1262. {
  1263. if (is_object($this->user)) {
  1264. return $this->user->get_username('mail');
  1265. }
  1266. }
  1267. /**
  1268. * Getter for logged user password.
  1269. *
  1270. * @return string User password
  1271. */
  1272. public function get_user_password()
  1273. {
  1274. if ($this->password) {
  1275. return $this->password;
  1276. }
  1277. else if ($_SESSION['password']) {
  1278. return $this->decrypt($_SESSION['password']);
  1279. }
  1280. }
  1281. /**
  1282. * Get the per-user log directory
  1283. */
  1284. protected function get_user_log_dir()
  1285. {
  1286. $log_dir = $this->config->get('log_dir', RCUBE_INSTALL_PATH . 'logs');
  1287. $user_name = $this->get_user_name();
  1288. $user_log_dir = $log_dir . '/' . $user_name;
  1289. return !empty($user_name) && is_writable($user_log_dir) ? $user_log_dir : false;
  1290. }
  1291. /**
  1292. * Getter for logged user language code.
  1293. *
  1294. * @return string User language code
  1295. */
  1296. public function get_user_language()
  1297. {
  1298. if (is_object($this->user)) {
  1299. return $this->user->language;
  1300. }
  1301. else if (isset($_SESSION['language'])) {
  1302. return $_SESSION['language'];
  1303. }
  1304. }
  1305. /**
  1306. * Unique Message-ID generator.
  1307. *
  1308. * @param string $sender Optional sender e-mail address
  1309. *
  1310. * @return string Message-ID
  1311. */
  1312. public function gen_message_id($sender = null)
  1313. {
  1314. $local_part = md5(uniqid('rcube'.mt_rand(), true));
  1315. $domain_part = '';
  1316. if ($sender && preg_match('/@([^\s]+\.[a-z0-9-]+)/', $sender, $m)) {
  1317. $domain_part = $m[1];
  1318. }
  1319. else {
  1320. $domain_part = $this->user->get_username('domain');
  1321. }
  1322. // Try to find FQDN, some spamfilters doesn't like 'localhost' (#1486924)
  1323. if (!preg_match('/\.[a-z0-9-]+$/i', $domain_part)) {
  1324. foreach (array($_SERVER['HTTP_HOST'], $_SERVER['SERVER_NAME']) as $host) {
  1325. $host = preg_replace('/:[0-9]+$/', '', $host);
  1326. if ($host && preg_match('/\.[a-z]+$/i', $host)) {
  1327. $domain_part = $host;
  1328. break;
  1329. }
  1330. }
  1331. }
  1332. return sprintf('<%s@%s>', $local_part, $domain_part);
  1333. }
  1334. /**
  1335. * Send the given message using the configured method.
  1336. *
  1337. * @param object $message Reference to Mail_MIME object
  1338. * @param string $from Sender address string
  1339. * @param array $mailto Array of recipient address strings
  1340. * @param array $error SMTP error array (reference)
  1341. * @param string $body_file Location of file with saved message body (reference),
  1342. * used when delay_file_io is enabled
  1343. * @param array $options SMTP options (e.g. DSN request)
  1344. *
  1345. * @return boolean Send status.
  1346. */
  1347. public function deliver_message(&$message, $from, $mailto, &$error, &$body_file = null, $options = null)
  1348. {
  1349. $plugin = $this->plugins->exec_hook('message_before_send', array(
  1350. 'message' => $message,
  1351. 'from' => $from,
  1352. 'mailto' => $mailto,
  1353. 'options' => $options,
  1354. ));
  1355. if ($plugin['abort']) {
  1356. if (!empty($plugin['error'])) {
  1357. $error = $plugin['error'];
  1358. }
  1359. if (!empty($plugin['body_file'])) {
  1360. $body_file = $plugin['body_file'];
  1361. }
  1362. return isset($plugin['result']) ? $plugin['result'] : false;
  1363. }
  1364. $from = $plugin['from'];
  1365. $mailto = $plugin['mailto'];
  1366. $options = $plugin['options'];
  1367. $message = $plugin['message'];
  1368. $headers = $message->headers();
  1369. // send thru SMTP server using custom SMTP library
  1370. if ($this->config->get('smtp_server')) {
  1371. // generate list of recipients
  1372. $a_recipients = (array) $mailto;
  1373. if (strlen($headers['Cc']))
  1374. $a_recipients[] = $headers['Cc'];
  1375. if (strlen($headers['Bcc']))
  1376. $a_recipients[] = $headers['Bcc'];
  1377. // remove Bcc header and get the whole head of the message as string
  1378. $smtp_headers = $this->message_head($message, array('Bcc'));
  1379. if ($message->getParam('delay_file_io')) {
  1380. // use common temp dir
  1381. $temp_dir = $this->config->get('temp_dir');
  1382. $body_file = tempnam($temp_dir, 'rcmMsg');
  1383. $mime_result = $message->saveMessageBody($body_file);
  1384. if (is_a($mime_result, 'PEAR_Error')) {
  1385. self::raise_error(array('code' => 650, 'type' => 'php',
  1386. 'file' => __FILE__, 'line' => __LINE__,
  1387. 'message' => "Could not create message: ".$mime_result->getMessage()),
  1388. true, false);
  1389. return false;
  1390. }
  1391. $msg_body = fopen($body_file, 'r');
  1392. }
  1393. else {
  1394. $msg_body = $message->get();
  1395. }
  1396. // send message
  1397. if (!is_object($this->smtp)) {
  1398. $this->smtp_init(true);
  1399. }
  1400. $sent = $this->smtp->send_mail($from, $a_recipients, $smtp_headers, $msg_body, $options);
  1401. $response = $this->smtp->get_response();
  1402. $error = $this->smtp->get_error();
  1403. // log error
  1404. if (!$sent) {
  1405. self::raise_error(array('code' => 800, 'type' => 'smtp',
  1406. 'line' => __LINE__, 'file' => __FILE__,
  1407. 'message' => join("\n", $response)), true, false);
  1408. }
  1409. }
  1410. // send mail using PHP's mail() function
  1411. else {
  1412. // unset To,Subject headers because they will be added by the mail() function
  1413. $header_str = $this->message_head($message, array('To', 'Subject'));
  1414. if (is_array($mailto)) {
  1415. $mailto = implode(', ', $mailto);
  1416. }
  1417. // #1485779
  1418. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  1419. if (preg_match_all('/<([^@]+@[^>]+)>/', $mailto, $m)) {
  1420. $mailto = implode(', ', $m[1]);
  1421. }
  1422. }
  1423. $msg_body = $message->get();
  1424. if (is_a($msg_body, 'PEAR_Error')) {
  1425. self::raise_error(array('code' => 650, 'type' => 'php',
  1426. 'file' => __FILE__, 'line' => __LINE__,
  1427. 'message' => "Could not create message: ".$msg_body->getMessage()),
  1428. true, false);
  1429. }
  1430. else {
  1431. $delim = $this->config->header_delimiter();
  1432. $to = $mailto;
  1433. $subject = $headers['Subject'];
  1434. $header_str = rtrim($header_str);
  1435. if ($delim != "\r\n") {
  1436. $header_str = str_replace("\r\n", $delim, $header_str);
  1437. $msg_body = str_replace("\r\n", $delim, $msg_body);
  1438. $to = str_replace("\r\n", $delim, $to);
  1439. $subject = str_replace("\r\n", $delim, $subject);
  1440. }
  1441. if (filter_var(ini_get('safe_mode'), FILTER_VALIDATE_BOOLEAN))
  1442. $sent = mail($to, $subject, $msg_body, $header_str);
  1443. else
  1444. $sent = mail($to, $subject, $msg_body, $header_str, "-f$from");
  1445. }
  1446. }
  1447. if ($sent) {
  1448. $this->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body));
  1449. // remove MDN headers after sending
  1450. unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
  1451. if ($this->config->get('smtp_log')) {
  1452. // get all recipient addresses
  1453. if (is_array($mailto)) {
  1454. $mailto = implode(',', $mailto);
  1455. }
  1456. if ($headers['Cc']) {
  1457. $mailto .= ',' . $headers['Cc'];
  1458. }
  1459. if ($headers['Bcc']) {
  1460. $mailto .= ',' . $headers['Bcc'];
  1461. }
  1462. $mailto = rcube_mime::decode_address_list($mailto, null, false, null, true);
  1463. self::write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
  1464. $this->user->get_username(),
  1465. rcube_utils::remote_addr(),
  1466. implode(', ', $mailto),
  1467. !empty($response) ? join('; ', $response) : ''));
  1468. }
  1469. }
  1470. else {
  1471. // allow plugins to catch sending errors with the same parameters as in 'message_before_send'
  1472. $this->plugins->exec_hook('message_send_error', $plugin + array('error' => $error));
  1473. }
  1474. if (is_resource($msg_body)) {
  1475. fclose($msg_body);
  1476. }
  1477. $message->headers($headers, true);
  1478. return $sent;
  1479. }
  1480. /**
  1481. * Return message headers as a string
  1482. */
  1483. protected function message_head($message, $unset = array())
  1484. {
  1485. // requires Mail_mime >= 1.9.0
  1486. $headers = array();
  1487. foreach ((array) $unset as $header) {
  1488. $headers[$header] = null;
  1489. }
  1490. return $message->txtHeaders($headers, true);
  1491. }
  1492. }
  1493. /**
  1494. * Lightweight plugin API class serving as a dummy if plugins are not enabled
  1495. *
  1496. * @package Framework
  1497. * @subpackage Core
  1498. */
  1499. class rcube_dummy_plugin_api
  1500. {
  1501. /**
  1502. * Triggers a plugin hook.
  1503. * @see rcube_plugin_api::exec_hook()
  1504. */
  1505. public function exec_hook($hook, $args = array())
  1506. {
  1507. return $args;
  1508. }
  1509. }